vis.js 1.8 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936
  1. /**
  2. * vis.js
  3. * https://github.com/almende/vis
  4. *
  5. * A dynamic, browser-based visualization library.
  6. *
  7. * @version 4.21.0
  8. * @date 2017-10-12
  9. *
  10. * @license
  11. * Copyright (C) 2011-2017 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. /******/
  40. /******/ // The require function
  41. /******/ function __webpack_require__(moduleId) {
  42. /******/
  43. /******/ // Check if module is in cache
  44. /******/ if(installedModules[moduleId]) {
  45. /******/ return installedModules[moduleId].exports;
  46. /******/ }
  47. /******/ // Create a new module (and put it into the cache)
  48. /******/ var module = installedModules[moduleId] = {
  49. /******/ i: moduleId,
  50. /******/ l: false,
  51. /******/ exports: {}
  52. /******/ };
  53. /******/
  54. /******/ // Execute the module function
  55. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  56. /******/
  57. /******/ // Flag the module as loaded
  58. /******/ module.l = true;
  59. /******/
  60. /******/ // Return the exports of the module
  61. /******/ return module.exports;
  62. /******/ }
  63. /******/
  64. /******/
  65. /******/ // expose the modules object (__webpack_modules__)
  66. /******/ __webpack_require__.m = modules;
  67. /******/
  68. /******/ // expose the module cache
  69. /******/ __webpack_require__.c = installedModules;
  70. /******/
  71. /******/ // define getter function for harmony exports
  72. /******/ __webpack_require__.d = function(exports, name, getter) {
  73. /******/ if(!__webpack_require__.o(exports, name)) {
  74. /******/ Object.defineProperty(exports, name, {
  75. /******/ configurable: false,
  76. /******/ enumerable: true,
  77. /******/ get: getter
  78. /******/ });
  79. /******/ }
  80. /******/ };
  81. /******/
  82. /******/ // getDefaultExport function for compatibility with non-harmony modules
  83. /******/ __webpack_require__.n = function(module) {
  84. /******/ var getter = module && module.__esModule ?
  85. /******/ function getDefault() { return module['default']; } :
  86. /******/ function getModuleExports() { return module; };
  87. /******/ __webpack_require__.d(getter, 'a', getter);
  88. /******/ return getter;
  89. /******/ };
  90. /******/
  91. /******/ // Object.prototype.hasOwnProperty.call
  92. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  93. /******/
  94. /******/ // __webpack_public_path__
  95. /******/ __webpack_require__.p = "";
  96. /******/
  97. /******/ // Load entry module and return exports
  98. /******/ return __webpack_require__(__webpack_require__.s = 123);
  99. /******/ })
  100. /************************************************************************/
  101. /******/ ([
  102. /* 0 */
  103. /***/ (function(module, exports, __webpack_require__) {
  104. "use strict";
  105. exports.__esModule = true;
  106. exports.default = function (instance, Constructor) {
  107. if (!(instance instanceof Constructor)) {
  108. throw new TypeError("Cannot call a class as a function");
  109. }
  110. };
  111. /***/ }),
  112. /* 1 */
  113. /***/ (function(module, exports, __webpack_require__) {
  114. "use strict";
  115. exports.__esModule = true;
  116. var _defineProperty = __webpack_require__(169);
  117. var _defineProperty2 = _interopRequireDefault(_defineProperty);
  118. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  119. exports.default = function () {
  120. function defineProperties(target, props) {
  121. for (var i = 0; i < props.length; i++) {
  122. var descriptor = props[i];
  123. descriptor.enumerable = descriptor.enumerable || false;
  124. descriptor.configurable = true;
  125. if ("value" in descriptor) descriptor.writable = true;
  126. (0, _defineProperty2.default)(target, descriptor.key, descriptor);
  127. }
  128. }
  129. return function (Constructor, protoProps, staticProps) {
  130. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  131. if (staticProps) defineProperties(Constructor, staticProps);
  132. return Constructor;
  133. };
  134. }();
  135. /***/ }),
  136. /* 2 */
  137. /***/ (function(module, exports, __webpack_require__) {
  138. "use strict";
  139. var _getIterator2 = __webpack_require__(77);
  140. var _getIterator3 = _interopRequireDefault(_getIterator2);
  141. var _create = __webpack_require__(29);
  142. var _create2 = _interopRequireDefault(_create);
  143. var _keys = __webpack_require__(8);
  144. var _keys2 = _interopRequireDefault(_keys);
  145. var _typeof2 = __webpack_require__(6);
  146. var _typeof3 = _interopRequireDefault(_typeof2);
  147. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  148. // utility functions
  149. // first check if moment.js is already loaded in the browser window, if so,
  150. // use this instance. Else, load via commonjs.
  151. var moment = __webpack_require__(9);
  152. var uuid = __webpack_require__(157);
  153. /**
  154. * Test whether given object is a number
  155. * @param {*} object
  156. * @return {Boolean} isNumber
  157. */
  158. exports.isNumber = function (object) {
  159. return object instanceof Number || typeof object == 'number';
  160. };
  161. /**
  162. * Remove everything in the DOM object
  163. * @param {Element} DOMobject
  164. */
  165. exports.recursiveDOMDelete = function (DOMobject) {
  166. if (DOMobject) {
  167. while (DOMobject.hasChildNodes() === true) {
  168. exports.recursiveDOMDelete(DOMobject.firstChild);
  169. DOMobject.removeChild(DOMobject.firstChild);
  170. }
  171. }
  172. };
  173. /**
  174. * 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.
  175. *
  176. * @param {number} min
  177. * @param {number} max
  178. * @param {number} total
  179. * @param {number} value
  180. * @returns {number}
  181. */
  182. exports.giveRange = function (min, max, total, value) {
  183. if (max == min) {
  184. return 0.5;
  185. } else {
  186. var scale = 1 / (max - min);
  187. return Math.max(0, (value - min) * scale);
  188. }
  189. };
  190. /**
  191. * Test whether given object is a string
  192. * @param {*} object
  193. * @return {Boolean} isString
  194. */
  195. exports.isString = function (object) {
  196. return object instanceof String || typeof object == 'string';
  197. };
  198. /**
  199. * Test whether given object is a Date, or a String containing a Date
  200. * @param {Date | String} object
  201. * @return {Boolean} isDate
  202. */
  203. exports.isDate = function (object) {
  204. if (object instanceof Date) {
  205. return true;
  206. } else if (exports.isString(object)) {
  207. // test whether this string contains a date
  208. var match = ASPDateRegex.exec(object);
  209. if (match) {
  210. return true;
  211. } else if (!isNaN(Date.parse(object))) {
  212. return true;
  213. }
  214. }
  215. return false;
  216. };
  217. /**
  218. * Create a semi UUID
  219. * source: http://stackoverflow.com/a/105074/1262753
  220. * @return {string} uuid
  221. */
  222. exports.randomUUID = function () {
  223. return uuid.v4();
  224. };
  225. /**
  226. * assign all keys of an object that are not nested objects to a certain value (used for color objects).
  227. * @param {object} obj
  228. * @param {number} value
  229. */
  230. exports.assignAllKeys = function (obj, value) {
  231. for (var prop in obj) {
  232. if (obj.hasOwnProperty(prop)) {
  233. if ((0, _typeof3['default'])(obj[prop]) !== 'object') {
  234. obj[prop] = value;
  235. }
  236. }
  237. }
  238. };
  239. /**
  240. * Copy property from b to a if property present in a.
  241. * If property in b explicitly set to null, delete it if `allowDeletion` set.
  242. *
  243. * Internal helper routine, should not be exported. Not added to `exports` for that reason.
  244. *
  245. * @param {object} a target object
  246. * @param {object} b source object
  247. * @param {string} prop name of property to copy to a
  248. * @param {boolean} allowDeletion if true, delete property in a if explicitly set to null in b
  249. * @private
  250. */
  251. function copyOrDelete(a, b, prop, allowDeletion) {
  252. var doDeletion = false;
  253. if (allowDeletion === true) {
  254. doDeletion = b[prop] === null && a[prop] !== undefined;
  255. }
  256. if (doDeletion) {
  257. delete a[prop];
  258. } else {
  259. a[prop] = b[prop]; // Remember, this is a reference copy!
  260. }
  261. }
  262. /**
  263. * Fill an object with a possibly partially defined other object.
  264. *
  265. * Only copies values for the properties already present in a.
  266. * That means an object is not created on a property if only the b object has it.
  267. *
  268. * @param {object} a
  269. * @param {object} b
  270. * @param {boolean} [allowDeletion=false] if true, delete properties in a that are explicitly set to null in b
  271. */
  272. exports.fillIfDefined = function (a, b) {
  273. var allowDeletion = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  274. // NOTE: iteration of properties of a
  275. // NOTE: prototype properties iterated over as well
  276. for (var prop in a) {
  277. if (b[prop] !== undefined) {
  278. if (b[prop] === null || (0, _typeof3['default'])(b[prop]) !== 'object') {
  279. // Note: typeof null === 'object'
  280. copyOrDelete(a, b, prop, allowDeletion);
  281. } else {
  282. if ((0, _typeof3['default'])(a[prop]) === 'object') {
  283. exports.fillIfDefined(a[prop], b[prop], allowDeletion);
  284. }
  285. }
  286. }
  287. }
  288. };
  289. /**
  290. * Extend object a with the properties of object b or a series of objects
  291. * Only properties with defined values are copied
  292. * @param {Object} a
  293. * @param {...Object} b
  294. * @return {Object} a
  295. */
  296. exports.extend = function (a, b) {
  297. // eslint-disable-line no-unused-vars
  298. for (var i = 1; i < arguments.length; i++) {
  299. var other = arguments[i];
  300. for (var prop in other) {
  301. if (other.hasOwnProperty(prop)) {
  302. a[prop] = other[prop];
  303. }
  304. }
  305. }
  306. return a;
  307. };
  308. /**
  309. * Extend object a with selected properties of object b or a series of objects
  310. * Only properties with defined values are copied
  311. * @param {Array.<string>} props
  312. * @param {Object} a
  313. * @param {Object} b
  314. * @return {Object} a
  315. */
  316. exports.selectiveExtend = function (props, a, b) {
  317. // eslint-disable-line no-unused-vars
  318. if (!Array.isArray(props)) {
  319. throw new Error('Array with property names expected as first argument');
  320. }
  321. for (var i = 2; i < arguments.length; i++) {
  322. var other = arguments[i];
  323. for (var p = 0; p < props.length; p++) {
  324. var prop = props[p];
  325. if (other && other.hasOwnProperty(prop)) {
  326. a[prop] = other[prop];
  327. }
  328. }
  329. }
  330. return a;
  331. };
  332. /**
  333. * Extend object a with selected properties of object b.
  334. * Only properties with defined values are copied.
  335. *
  336. * **Note:** Previous version of this routine implied that multiple source objects
  337. * could be used; however, the implementation was **wrong**.
  338. * Since multiple (>1) sources weren't used anywhere in the `vis.js` code,
  339. * this has been removed
  340. *
  341. * @param {Array.<string>} props names of first-level properties to copy over
  342. * @param {object} a target object
  343. * @param {object} b source object
  344. * @param {boolean} [allowDeletion=false] if true, delete property in a if explicitly set to null in b
  345. * @returns {Object} a
  346. */
  347. exports.selectiveDeepExtend = function (props, a, b) {
  348. var allowDeletion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  349. // TODO: add support for Arrays to deepExtend
  350. if (Array.isArray(b)) {
  351. throw new TypeError('Arrays are not supported by deepExtend');
  352. }
  353. for (var p = 0; p < props.length; p++) {
  354. var prop = props[p];
  355. if (b.hasOwnProperty(prop)) {
  356. if (b[prop] && b[prop].constructor === Object) {
  357. if (a[prop] === undefined) {
  358. a[prop] = {};
  359. }
  360. if (a[prop].constructor === Object) {
  361. exports.deepExtend(a[prop], b[prop], false, allowDeletion);
  362. } else {
  363. copyOrDelete(a, b, prop, allowDeletion);
  364. }
  365. } else if (Array.isArray(b[prop])) {
  366. throw new TypeError('Arrays are not supported by deepExtend');
  367. } else {
  368. copyOrDelete(a, b, prop, allowDeletion);
  369. }
  370. }
  371. }
  372. return a;
  373. };
  374. /**
  375. * Extend object `a` with properties of object `b`, ignoring properties which are explicitly
  376. * specified to be excluded.
  377. *
  378. * The properties of `b` are considered for copying.
  379. * Properties which are themselves objects are are also extended.
  380. * Only properties with defined values are copied
  381. *
  382. * @param {Array.<string>} propsToExclude names of properties which should *not* be copied
  383. * @param {Object} a object to extend
  384. * @param {Object} b object to take properties from for extension
  385. * @param {boolean} [allowDeletion=false] if true, delete properties in a that are explicitly set to null in b
  386. * @return {Object} a
  387. */
  388. exports.selectiveNotDeepExtend = function (propsToExclude, a, b) {
  389. var allowDeletion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  390. // TODO: add support for Arrays to deepExtend
  391. // NOTE: array properties have an else-below; apparently, there is a problem here.
  392. if (Array.isArray(b)) {
  393. throw new TypeError('Arrays are not supported by deepExtend');
  394. }
  395. for (var prop in b) {
  396. if (!b.hasOwnProperty(prop)) continue; // Handle local properties only
  397. if (propsToExclude.indexOf(prop) !== -1) continue; // In exclusion list, skip
  398. if (b[prop] && b[prop].constructor === Object) {
  399. if (a[prop] === undefined) {
  400. a[prop] = {};
  401. }
  402. if (a[prop].constructor === Object) {
  403. exports.deepExtend(a[prop], b[prop]); // NOTE: allowDeletion not propagated!
  404. } else {
  405. copyOrDelete(a, b, prop, allowDeletion);
  406. }
  407. } else if (Array.isArray(b[prop])) {
  408. a[prop] = [];
  409. for (var i = 0; i < b[prop].length; i++) {
  410. a[prop].push(b[prop][i]);
  411. }
  412. } else {
  413. copyOrDelete(a, b, prop, allowDeletion);
  414. }
  415. }
  416. return a;
  417. };
  418. /**
  419. * Deep extend an object a with the properties of object b
  420. *
  421. * @param {Object} a
  422. * @param {Object} b
  423. * @param {boolean} [protoExtend=false] If true, the prototype values will also be extended.
  424. * (ie. the options objects that inherit from others will also get the inherited options)
  425. * @param {boolean} [allowDeletion=false] If true, the values of fields that are null will be deleted
  426. * @returns {Object}
  427. */
  428. exports.deepExtend = function (a, b) {
  429. var protoExtend = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  430. var allowDeletion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  431. for (var prop in b) {
  432. if (b.hasOwnProperty(prop) || protoExtend === true) {
  433. if (b[prop] && b[prop].constructor === Object) {
  434. if (a[prop] === undefined) {
  435. a[prop] = {};
  436. }
  437. if (a[prop].constructor === Object) {
  438. exports.deepExtend(a[prop], b[prop], protoExtend); // NOTE: allowDeletion not propagated!
  439. } else {
  440. copyOrDelete(a, b, prop, allowDeletion);
  441. }
  442. } else if (Array.isArray(b[prop])) {
  443. a[prop] = [];
  444. for (var i = 0; i < b[prop].length; i++) {
  445. a[prop].push(b[prop][i]);
  446. }
  447. } else {
  448. copyOrDelete(a, b, prop, allowDeletion);
  449. }
  450. }
  451. }
  452. return a;
  453. };
  454. /**
  455. * Test whether all elements in two arrays are equal.
  456. * @param {Array} a
  457. * @param {Array} b
  458. * @return {boolean} Returns true if both arrays have the same length and same
  459. * elements.
  460. */
  461. exports.equalArray = function (a, b) {
  462. if (a.length != b.length) return false;
  463. for (var i = 0, len = a.length; i < len; i++) {
  464. if (a[i] != b[i]) return false;
  465. }
  466. return true;
  467. };
  468. /**
  469. * Convert an object to another type
  470. * @param {boolean | number | string | Date | Moment | Null | undefined} object
  471. * @param {string | undefined} type Name of the type. Available types:
  472. * 'Boolean', 'Number', 'String',
  473. * 'Date', 'Moment', ISODate', 'ASPDate'.
  474. * @return {*} object
  475. * @throws Error
  476. */
  477. exports.convert = function (object, type) {
  478. var match;
  479. if (object === undefined) {
  480. return undefined;
  481. }
  482. if (object === null) {
  483. return null;
  484. }
  485. if (!type) {
  486. return object;
  487. }
  488. if (!(typeof type === 'string') && !(type instanceof String)) {
  489. throw new Error('Type must be a string');
  490. }
  491. //noinspection FallthroughInSwitchStatementJS
  492. switch (type) {
  493. case 'boolean':
  494. case 'Boolean':
  495. return Boolean(object);
  496. case 'number':
  497. case 'Number':
  498. if (exports.isString(object) && !isNaN(Date.parse(object))) {
  499. return moment(object).valueOf();
  500. } else {
  501. return Number(object.valueOf());
  502. }
  503. case 'string':
  504. case 'String':
  505. return String(object);
  506. case 'Date':
  507. if (exports.isNumber(object)) {
  508. return new Date(object);
  509. }
  510. if (object instanceof Date) {
  511. return new Date(object.valueOf());
  512. } else if (moment.isMoment(object)) {
  513. return new Date(object.valueOf());
  514. }
  515. if (exports.isString(object)) {
  516. match = ASPDateRegex.exec(object);
  517. if (match) {
  518. // object is an ASP date
  519. return new Date(Number(match[1])); // parse number
  520. } else {
  521. return moment(new Date(object)).toDate(); // parse string
  522. }
  523. } else {
  524. throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type Date');
  525. }
  526. case 'Moment':
  527. if (exports.isNumber(object)) {
  528. return moment(object);
  529. }
  530. if (object instanceof Date) {
  531. return moment(object.valueOf());
  532. } else if (moment.isMoment(object)) {
  533. return moment(object);
  534. }
  535. if (exports.isString(object)) {
  536. match = ASPDateRegex.exec(object);
  537. if (match) {
  538. // object is an ASP date
  539. return moment(Number(match[1])); // parse number
  540. } else {
  541. return moment(object); // parse string
  542. }
  543. } else {
  544. throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type Date');
  545. }
  546. case 'ISODate':
  547. if (exports.isNumber(object)) {
  548. return new Date(object);
  549. } else if (object instanceof Date) {
  550. return object.toISOString();
  551. } else if (moment.isMoment(object)) {
  552. return object.toDate().toISOString();
  553. } else if (exports.isString(object)) {
  554. match = ASPDateRegex.exec(object);
  555. if (match) {
  556. // object is an ASP date
  557. return new Date(Number(match[1])).toISOString(); // parse number
  558. } else {
  559. return moment(object).format(); // ISO 8601
  560. }
  561. } else {
  562. throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type ISODate');
  563. }
  564. case 'ASPDate':
  565. if (exports.isNumber(object)) {
  566. return '/Date(' + object + ')/';
  567. } else if (object instanceof Date) {
  568. return '/Date(' + object.valueOf() + ')/';
  569. } else if (exports.isString(object)) {
  570. match = ASPDateRegex.exec(object);
  571. var value;
  572. if (match) {
  573. // object is an ASP date
  574. value = new Date(Number(match[1])).valueOf(); // parse number
  575. } else {
  576. value = new Date(object).valueOf(); // parse string
  577. }
  578. return '/Date(' + value + ')/';
  579. } else {
  580. throw new Error('Cannot convert object of type ' + exports.getType(object) + ' to type ASPDate');
  581. }
  582. default:
  583. throw new Error('Unknown type "' + type + '"');
  584. }
  585. };
  586. // parse ASP.Net Date pattern,
  587. // for example '/Date(1198908717056)/' or '/Date(1198908717056-0700)/'
  588. // code from http://momentjs.com/
  589. var ASPDateRegex = /^\/?Date\((\-?\d+)/i;
  590. /**
  591. * Get the type of an object, for example exports.getType([]) returns 'Array'
  592. * @param {*} object
  593. * @return {string} type
  594. */
  595. exports.getType = function (object) {
  596. var type = typeof object === 'undefined' ? 'undefined' : (0, _typeof3['default'])(object);
  597. if (type == 'object') {
  598. if (object === null) {
  599. return 'null';
  600. }
  601. if (object instanceof Boolean) {
  602. return 'Boolean';
  603. }
  604. if (object instanceof Number) {
  605. return 'Number';
  606. }
  607. if (object instanceof String) {
  608. return 'String';
  609. }
  610. if (Array.isArray(object)) {
  611. return 'Array';
  612. }
  613. if (object instanceof Date) {
  614. return 'Date';
  615. }
  616. return 'Object';
  617. } else if (type == 'number') {
  618. return 'Number';
  619. } else if (type == 'boolean') {
  620. return 'Boolean';
  621. } else if (type == 'string') {
  622. return 'String';
  623. } else if (type === undefined) {
  624. return 'undefined';
  625. }
  626. return type;
  627. };
  628. /**
  629. * Used to extend an array and copy it. This is used to propagate paths recursively.
  630. *
  631. * @param {Array} arr
  632. * @param {*} newValue
  633. * @returns {Array}
  634. */
  635. exports.copyAndExtendArray = function (arr, newValue) {
  636. var newArr = [];
  637. for (var i = 0; i < arr.length; i++) {
  638. newArr.push(arr[i]);
  639. }
  640. newArr.push(newValue);
  641. return newArr;
  642. };
  643. /**
  644. * Used to extend an array and copy it. This is used to propagate paths recursively.
  645. *
  646. * @param {Array} arr
  647. * @returns {Array}
  648. */
  649. exports.copyArray = function (arr) {
  650. var newArr = [];
  651. for (var i = 0; i < arr.length; i++) {
  652. newArr.push(arr[i]);
  653. }
  654. return newArr;
  655. };
  656. /**
  657. * Retrieve the absolute left value of a DOM element
  658. * @param {Element} elem A dom element, for example a div
  659. * @return {number} left The absolute left position of this element
  660. * in the browser page.
  661. */
  662. exports.getAbsoluteLeft = function (elem) {
  663. return elem.getBoundingClientRect().left;
  664. };
  665. exports.getAbsoluteRight = function (elem) {
  666. return elem.getBoundingClientRect().right;
  667. };
  668. /**
  669. * Retrieve the absolute top value of a DOM element
  670. * @param {Element} elem A dom element, for example a div
  671. * @return {number} top The absolute top position of this element
  672. * in the browser page.
  673. */
  674. exports.getAbsoluteTop = function (elem) {
  675. return elem.getBoundingClientRect().top;
  676. };
  677. /**
  678. * add a className to the given elements style
  679. * @param {Element} elem
  680. * @param {string} classNames
  681. */
  682. exports.addClassName = function (elem, classNames) {
  683. var classes = elem.className.split(' ');
  684. var newClasses = classNames.split(' ');
  685. classes = classes.concat(newClasses.filter(function (className) {
  686. return classes.indexOf(className) < 0;
  687. }));
  688. elem.className = classes.join(' ');
  689. };
  690. /**
  691. * add a className to the given elements style
  692. * @param {Element} elem
  693. * @param {string} classNames
  694. */
  695. exports.removeClassName = function (elem, classNames) {
  696. var classes = elem.className.split(' ');
  697. var oldClasses = classNames.split(' ');
  698. classes = classes.filter(function (className) {
  699. return oldClasses.indexOf(className) < 0;
  700. });
  701. elem.className = classes.join(' ');
  702. };
  703. /**
  704. * For each method for both arrays and objects.
  705. * In case of an array, the built-in Array.forEach() is applied. (**No, it's not!**)
  706. * In case of an Object, the method loops over all properties of the object.
  707. * @param {Object | Array} object An Object or Array
  708. * @param {function} callback Callback method, called for each item in
  709. * the object or array with three parameters:
  710. * callback(value, index, object)
  711. */
  712. exports.forEach = function (object, callback) {
  713. var i, len;
  714. if (Array.isArray(object)) {
  715. // array
  716. for (i = 0, len = object.length; i < len; i++) {
  717. callback(object[i], i, object);
  718. }
  719. } else {
  720. // object
  721. for (i in object) {
  722. if (object.hasOwnProperty(i)) {
  723. callback(object[i], i, object);
  724. }
  725. }
  726. }
  727. };
  728. /**
  729. * Convert an object into an array: all objects properties are put into the
  730. * array. The resulting array is unordered.
  731. * @param {Object} object
  732. * @returns {Array} array
  733. */
  734. exports.toArray = function (object) {
  735. var array = [];
  736. for (var prop in object) {
  737. if (object.hasOwnProperty(prop)) array.push(object[prop]);
  738. }
  739. return array;
  740. };
  741. /**
  742. * Update a property in an object
  743. * @param {Object} object
  744. * @param {string} key
  745. * @param {*} value
  746. * @return {Boolean} changed
  747. */
  748. exports.updateProperty = function (object, key, value) {
  749. if (object[key] !== value) {
  750. object[key] = value;
  751. return true;
  752. } else {
  753. return false;
  754. }
  755. };
  756. /**
  757. * Throttle the given function to be only executed once per animation frame
  758. * @param {function} fn
  759. * @returns {function} Returns the throttled function
  760. */
  761. exports.throttle = function (fn) {
  762. var scheduled = false;
  763. return function throttled() {
  764. if (!scheduled) {
  765. scheduled = true;
  766. requestAnimationFrame(function () {
  767. scheduled = false;
  768. fn();
  769. });
  770. }
  771. };
  772. };
  773. /**
  774. * Add and event listener. Works for all browsers
  775. * @param {Element} element An html element
  776. * @param {string} action The action, for example "click",
  777. * without the prefix "on"
  778. * @param {function} listener The callback function to be executed
  779. * @param {boolean} [useCapture]
  780. */
  781. exports.addEventListener = function (element, action, listener, useCapture) {
  782. if (element.addEventListener) {
  783. if (useCapture === undefined) useCapture = false;
  784. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  785. action = "DOMMouseScroll"; // For Firefox
  786. }
  787. element.addEventListener(action, listener, useCapture);
  788. } else {
  789. element.attachEvent("on" + action, listener); // IE browsers
  790. }
  791. };
  792. /**
  793. * Remove an event listener from an element
  794. * @param {Element} element An html dom element
  795. * @param {string} action The name of the event, for example "mousedown"
  796. * @param {function} listener The listener function
  797. * @param {boolean} [useCapture]
  798. */
  799. exports.removeEventListener = function (element, action, listener, useCapture) {
  800. if (element.removeEventListener) {
  801. // non-IE browsers
  802. if (useCapture === undefined) useCapture = false;
  803. if (action === "mousewheel" && navigator.userAgent.indexOf("Firefox") >= 0) {
  804. action = "DOMMouseScroll"; // For Firefox
  805. }
  806. element.removeEventListener(action, listener, useCapture);
  807. } else {
  808. // IE browsers
  809. element.detachEvent("on" + action, listener);
  810. }
  811. };
  812. /**
  813. * Cancels the event if it is cancelable, without stopping further propagation of the event.
  814. * @param {Event} event
  815. */
  816. exports.preventDefault = function (event) {
  817. if (!event) event = window.event;
  818. if (event.preventDefault) {
  819. event.preventDefault(); // non-IE browsers
  820. } else {
  821. event.returnValue = false; // IE browsers
  822. }
  823. };
  824. /**
  825. * Get HTML element which is the target of the event
  826. * @param {Event} event
  827. * @return {Element} target element
  828. */
  829. exports.getTarget = function (event) {
  830. // code from http://www.quirksmode.org/js/events_properties.html
  831. if (!event) {
  832. event = window.event;
  833. }
  834. var target;
  835. if (event.target) {
  836. target = event.target;
  837. } else if (event.srcElement) {
  838. target = event.srcElement;
  839. }
  840. if (target.nodeType != undefined && target.nodeType == 3) {
  841. // defeat Safari bug
  842. target = target.parentNode;
  843. }
  844. return target;
  845. };
  846. /**
  847. * Check if given element contains given parent somewhere in the DOM tree
  848. * @param {Element} element
  849. * @param {Element} parent
  850. * @returns {boolean}
  851. */
  852. exports.hasParent = function (element, parent) {
  853. var e = element;
  854. while (e) {
  855. if (e === parent) {
  856. return true;
  857. }
  858. e = e.parentNode;
  859. }
  860. return false;
  861. };
  862. exports.option = {};
  863. /**
  864. * Convert a value into a boolean
  865. * @param {Boolean | function | undefined} value
  866. * @param {boolean} [defaultValue]
  867. * @returns {Boolean} bool
  868. */
  869. exports.option.asBoolean = function (value, defaultValue) {
  870. if (typeof value == 'function') {
  871. value = value();
  872. }
  873. if (value != null) {
  874. return value != false;
  875. }
  876. return defaultValue || null;
  877. };
  878. /**
  879. * Convert a value into a number
  880. * @param {Boolean | function | undefined} value
  881. * @param {number} [defaultValue]
  882. * @returns {number} number
  883. */
  884. exports.option.asNumber = function (value, defaultValue) {
  885. if (typeof value == 'function') {
  886. value = value();
  887. }
  888. if (value != null) {
  889. return Number(value) || defaultValue || null;
  890. }
  891. return defaultValue || null;
  892. };
  893. /**
  894. * Convert a value into a string
  895. * @param {string | function | undefined} value
  896. * @param {string} [defaultValue]
  897. * @returns {String} str
  898. */
  899. exports.option.asString = function (value, defaultValue) {
  900. if (typeof value == 'function') {
  901. value = value();
  902. }
  903. if (value != null) {
  904. return String(value);
  905. }
  906. return defaultValue || null;
  907. };
  908. /**
  909. * Convert a size or location into a string with pixels or a percentage
  910. * @param {string | number | function | undefined} value
  911. * @param {string} [defaultValue]
  912. * @returns {String} size
  913. */
  914. exports.option.asSize = function (value, defaultValue) {
  915. if (typeof value == 'function') {
  916. value = value();
  917. }
  918. if (exports.isString(value)) {
  919. return value;
  920. } else if (exports.isNumber(value)) {
  921. return value + 'px';
  922. } else {
  923. return defaultValue || null;
  924. }
  925. };
  926. /**
  927. * Convert a value into a DOM element
  928. * @param {HTMLElement | function | undefined} value
  929. * @param {HTMLElement} [defaultValue]
  930. * @returns {HTMLElement | null} dom
  931. */
  932. exports.option.asElement = function (value, defaultValue) {
  933. if (typeof value == 'function') {
  934. value = value();
  935. }
  936. return value || defaultValue || null;
  937. };
  938. /**
  939. * http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
  940. *
  941. * @param {string} hex
  942. * @returns {{r: *, g: *, b: *}} | 255 range
  943. */
  944. exports.hexToRGB = function (hex) {
  945. // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  946. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  947. hex = hex.replace(shorthandRegex, function (m, r, g, b) {
  948. return r + r + g + g + b + b;
  949. });
  950. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  951. return result ? {
  952. r: parseInt(result[1], 16),
  953. g: parseInt(result[2], 16),
  954. b: parseInt(result[3], 16)
  955. } : null;
  956. };
  957. /**
  958. * This function takes color in hex format or rgb() or rgba() format and overrides the opacity. Returns rgba() string.
  959. * @param {string} color
  960. * @param {number} opacity
  961. * @returns {String}
  962. */
  963. exports.overrideOpacity = function (color, opacity) {
  964. var rgb;
  965. if (color.indexOf("rgba") != -1) {
  966. return color;
  967. } else if (color.indexOf("rgb") != -1) {
  968. rgb = color.substr(color.indexOf("(") + 1).replace(")", "").split(",");
  969. return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + opacity + ")";
  970. } else {
  971. rgb = exports.hexToRGB(color);
  972. if (rgb == null) {
  973. return color;
  974. } else {
  975. return "rgba(" + rgb.r + "," + rgb.g + "," + rgb.b + "," + opacity + ")";
  976. }
  977. }
  978. };
  979. /**
  980. *
  981. * @param {number} red 0 -- 255
  982. * @param {number} green 0 -- 255
  983. * @param {number} blue 0 -- 255
  984. * @returns {String}
  985. * @constructor
  986. */
  987. exports.RGBToHex = function (red, green, blue) {
  988. return "#" + ((1 << 24) + (red << 16) + (green << 8) + blue).toString(16).slice(1);
  989. };
  990. /**
  991. * Parse a color property into an object with border, background, and
  992. * highlight colors
  993. * @param {Object | String} color
  994. * @return {Object} colorObject
  995. */
  996. exports.parseColor = function (color) {
  997. var c;
  998. if (exports.isString(color) === true) {
  999. if (exports.isValidRGB(color) === true) {
  1000. var rgb = color.substr(4).substr(0, color.length - 5).split(',').map(function (value) {
  1001. return parseInt(value);
  1002. });
  1003. color = exports.RGBToHex(rgb[0], rgb[1], rgb[2]);
  1004. }
  1005. if (exports.isValidHex(color) === true) {
  1006. var hsv = exports.hexToHSV(color);
  1007. var lighterColorHSV = { h: hsv.h, s: hsv.s * 0.8, v: Math.min(1, hsv.v * 1.02) };
  1008. var darkerColorHSV = { h: hsv.h, s: Math.min(1, hsv.s * 1.25), v: hsv.v * 0.8 };
  1009. var darkerColorHex = exports.HSVToHex(darkerColorHSV.h, darkerColorHSV.s, darkerColorHSV.v);
  1010. var lighterColorHex = exports.HSVToHex(lighterColorHSV.h, lighterColorHSV.s, lighterColorHSV.v);
  1011. c = {
  1012. background: color,
  1013. border: darkerColorHex,
  1014. highlight: {
  1015. background: lighterColorHex,
  1016. border: darkerColorHex
  1017. },
  1018. hover: {
  1019. background: lighterColorHex,
  1020. border: darkerColorHex
  1021. }
  1022. };
  1023. } else {
  1024. c = {
  1025. background: color,
  1026. border: color,
  1027. highlight: {
  1028. background: color,
  1029. border: color
  1030. },
  1031. hover: {
  1032. background: color,
  1033. border: color
  1034. }
  1035. };
  1036. }
  1037. } else {
  1038. c = {};
  1039. c.background = color.background || undefined;
  1040. c.border = color.border || undefined;
  1041. if (exports.isString(color.highlight)) {
  1042. c.highlight = {
  1043. border: color.highlight,
  1044. background: color.highlight
  1045. };
  1046. } else {
  1047. c.highlight = {};
  1048. c.highlight.background = color.highlight && color.highlight.background || undefined;
  1049. c.highlight.border = color.highlight && color.highlight.border || undefined;
  1050. }
  1051. if (exports.isString(color.hover)) {
  1052. c.hover = {
  1053. border: color.hover,
  1054. background: color.hover
  1055. };
  1056. } else {
  1057. c.hover = {};
  1058. c.hover.background = color.hover && color.hover.background || undefined;
  1059. c.hover.border = color.hover && color.hover.border || undefined;
  1060. }
  1061. }
  1062. return c;
  1063. };
  1064. /**
  1065. * http://www.javascripter.net/faq/rgb2hsv.htm
  1066. *
  1067. * @param {number} red
  1068. * @param {number} green
  1069. * @param {number} blue
  1070. * @returns {{h: number, s: number, v: number}}
  1071. * @constructor
  1072. */
  1073. exports.RGBToHSV = function (red, green, blue) {
  1074. red = red / 255;green = green / 255;blue = blue / 255;
  1075. var minRGB = Math.min(red, Math.min(green, blue));
  1076. var maxRGB = Math.max(red, Math.max(green, blue));
  1077. // Black-gray-white
  1078. if (minRGB == maxRGB) {
  1079. return { h: 0, s: 0, v: minRGB };
  1080. }
  1081. // Colors other than black-gray-white:
  1082. var d = red == minRGB ? green - blue : blue == minRGB ? red - green : blue - red;
  1083. var h = red == minRGB ? 3 : blue == minRGB ? 1 : 5;
  1084. var hue = 60 * (h - d / (maxRGB - minRGB)) / 360;
  1085. var saturation = (maxRGB - minRGB) / maxRGB;
  1086. var value = maxRGB;
  1087. return { h: hue, s: saturation, v: value };
  1088. };
  1089. var cssUtil = {
  1090. // split a string with css styles into an object with key/values
  1091. split: function split(cssText) {
  1092. var styles = {};
  1093. cssText.split(';').forEach(function (style) {
  1094. if (style.trim() != '') {
  1095. var parts = style.split(':');
  1096. var key = parts[0].trim();
  1097. var value = parts[1].trim();
  1098. styles[key] = value;
  1099. }
  1100. });
  1101. return styles;
  1102. },
  1103. // build a css text string from an object with key/values
  1104. join: function join(styles) {
  1105. return (0, _keys2['default'])(styles).map(function (key) {
  1106. return key + ': ' + styles[key];
  1107. }).join('; ');
  1108. }
  1109. };
  1110. /**
  1111. * Append a string with css styles to an element
  1112. * @param {Element} element
  1113. * @param {string} cssText
  1114. */
  1115. exports.addCssText = function (element, cssText) {
  1116. var currentStyles = cssUtil.split(element.style.cssText);
  1117. var newStyles = cssUtil.split(cssText);
  1118. var styles = exports.extend(currentStyles, newStyles);
  1119. element.style.cssText = cssUtil.join(styles);
  1120. };
  1121. /**
  1122. * Remove a string with css styles from an element
  1123. * @param {Element} element
  1124. * @param {string} cssText
  1125. */
  1126. exports.removeCssText = function (element, cssText) {
  1127. var styles = cssUtil.split(element.style.cssText);
  1128. var removeStyles = cssUtil.split(cssText);
  1129. for (var key in removeStyles) {
  1130. if (removeStyles.hasOwnProperty(key)) {
  1131. delete styles[key];
  1132. }
  1133. }
  1134. element.style.cssText = cssUtil.join(styles);
  1135. };
  1136. /**
  1137. * https://gist.github.com/mjijackson/5311256
  1138. * @param {number} h
  1139. * @param {number} s
  1140. * @param {number} v
  1141. * @returns {{r: number, g: number, b: number}}
  1142. * @constructor
  1143. */
  1144. exports.HSVToRGB = function (h, s, v) {
  1145. var r, g, b;
  1146. var i = Math.floor(h * 6);
  1147. var f = h * 6 - i;
  1148. var p = v * (1 - s);
  1149. var q = v * (1 - f * s);
  1150. var t = v * (1 - (1 - f) * s);
  1151. switch (i % 6) {
  1152. case 0:
  1153. r = v, g = t, b = p;break;
  1154. case 1:
  1155. r = q, g = v, b = p;break;
  1156. case 2:
  1157. r = p, g = v, b = t;break;
  1158. case 3:
  1159. r = p, g = q, b = v;break;
  1160. case 4:
  1161. r = t, g = p, b = v;break;
  1162. case 5:
  1163. r = v, g = p, b = q;break;
  1164. }
  1165. return { r: Math.floor(r * 255), g: Math.floor(g * 255), b: Math.floor(b * 255) };
  1166. };
  1167. exports.HSVToHex = function (h, s, v) {
  1168. var rgb = exports.HSVToRGB(h, s, v);
  1169. return exports.RGBToHex(rgb.r, rgb.g, rgb.b);
  1170. };
  1171. exports.hexToHSV = function (hex) {
  1172. var rgb = exports.hexToRGB(hex);
  1173. return exports.RGBToHSV(rgb.r, rgb.g, rgb.b);
  1174. };
  1175. exports.isValidHex = function (hex) {
  1176. var isOk = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex);
  1177. return isOk;
  1178. };
  1179. exports.isValidRGB = function (rgb) {
  1180. rgb = rgb.replace(" ", "");
  1181. var isOk = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/i.test(rgb);
  1182. return isOk;
  1183. };
  1184. exports.isValidRGBA = function (rgba) {
  1185. rgba = rgba.replace(" ", "");
  1186. var isOk = /rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),(.{1,3})\)/i.test(rgba);
  1187. return isOk;
  1188. };
  1189. /**
  1190. * This recursively redirects the prototype of JSON objects to the referenceObject
  1191. * This is used for default options.
  1192. *
  1193. * @param {Array.<string>} fields
  1194. * @param {Object} referenceObject
  1195. * @returns {*}
  1196. */
  1197. exports.selectiveBridgeObject = function (fields, referenceObject) {
  1198. if (referenceObject !== null && (typeof referenceObject === 'undefined' ? 'undefined' : (0, _typeof3['default'])(referenceObject)) === "object") {
  1199. // !!! typeof null === 'object'
  1200. var objectTo = (0, _create2['default'])(referenceObject);
  1201. for (var i = 0; i < fields.length; i++) {
  1202. if (referenceObject.hasOwnProperty(fields[i])) {
  1203. if ((0, _typeof3['default'])(referenceObject[fields[i]]) == "object") {
  1204. objectTo[fields[i]] = exports.bridgeObject(referenceObject[fields[i]]);
  1205. }
  1206. }
  1207. }
  1208. return objectTo;
  1209. } else {
  1210. return null;
  1211. }
  1212. };
  1213. /**
  1214. * This recursively redirects the prototype of JSON objects to the referenceObject
  1215. * This is used for default options.
  1216. *
  1217. * @param {Object} referenceObject
  1218. * @returns {*}
  1219. */
  1220. exports.bridgeObject = function (referenceObject) {
  1221. if (referenceObject !== null && (typeof referenceObject === 'undefined' ? 'undefined' : (0, _typeof3['default'])(referenceObject)) === "object") {
  1222. // !!! typeof null === 'object'
  1223. var objectTo = (0, _create2['default'])(referenceObject);
  1224. if (referenceObject instanceof Element) {
  1225. // Avoid bridging DOM objects
  1226. objectTo = referenceObject;
  1227. } else {
  1228. objectTo = (0, _create2['default'])(referenceObject);
  1229. for (var i in referenceObject) {
  1230. if (referenceObject.hasOwnProperty(i)) {
  1231. if ((0, _typeof3['default'])(referenceObject[i]) == "object") {
  1232. objectTo[i] = exports.bridgeObject(referenceObject[i]);
  1233. }
  1234. }
  1235. }
  1236. }
  1237. return objectTo;
  1238. } else {
  1239. return null;
  1240. }
  1241. };
  1242. /**
  1243. * This method provides a stable sort implementation, very fast for presorted data
  1244. *
  1245. * @param {Array} a the array
  1246. * @param {function} compare an order comparator
  1247. * @returns {Array}
  1248. */
  1249. exports.insertSort = function (a, compare) {
  1250. for (var i = 0; i < a.length; i++) {
  1251. var k = a[i];
  1252. for (var j = i; j > 0 && compare(k, a[j - 1]) < 0; j--) {
  1253. a[j] = a[j - 1];
  1254. }
  1255. a[j] = k;
  1256. }
  1257. return a;
  1258. };
  1259. /**
  1260. * This is used to set the options of subobjects in the options object.
  1261. *
  1262. * A requirement of these subobjects is that they have an 'enabled' element
  1263. * which is optional for the user but mandatory for the program.
  1264. *
  1265. * The added value here of the merge is that option 'enabled' is set as required.
  1266. *
  1267. *
  1268. * @param {object} mergeTarget | either this.options or the options used for the groups.
  1269. * @param {object} options | options
  1270. * @param {string} option | option key in the options argument
  1271. * @param {object} globalOptions | global options, passed in to determine value of option 'enabled'
  1272. */
  1273. exports.mergeOptions = function (mergeTarget, options, option) {
  1274. var globalOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  1275. // Local helpers
  1276. var isPresent = function isPresent(obj) {
  1277. return obj !== null && obj !== undefined;
  1278. };
  1279. var isObject = function isObject(obj) {
  1280. return obj !== null && (typeof obj === 'undefined' ? 'undefined' : (0, _typeof3['default'])(obj)) === 'object';
  1281. };
  1282. // https://stackoverflow.com/a/34491287/1223531
  1283. var isEmpty = function isEmpty(obj) {
  1284. for (var x in obj) {
  1285. if (obj.hasOwnProperty(x)) return false;
  1286. }
  1287. return true;
  1288. };
  1289. // Guards
  1290. if (!isObject(mergeTarget)) {
  1291. throw new Error('Parameter mergeTarget must be an object');
  1292. }
  1293. if (!isObject(options)) {
  1294. throw new Error('Parameter options must be an object');
  1295. }
  1296. if (!isPresent(option)) {
  1297. throw new Error('Parameter option must have a value');
  1298. }
  1299. if (!isObject(globalOptions)) {
  1300. throw new Error('Parameter globalOptions must be an object');
  1301. }
  1302. //
  1303. // Actual merge routine, separated from main logic
  1304. // Only a single level of options is merged. Deeper levels are ref'd. This may actually be an issue.
  1305. //
  1306. var doMerge = function doMerge(target, options, option) {
  1307. if (!isObject(target[option])) {
  1308. target[option] = {};
  1309. }
  1310. var src = options[option];
  1311. var dst = target[option];
  1312. for (var prop in src) {
  1313. if (src.hasOwnProperty(prop)) {
  1314. dst[prop] = src[prop];
  1315. }
  1316. }
  1317. };
  1318. // Local initialization
  1319. var srcOption = options[option];
  1320. var globalPassed = isObject(globalOptions) && !isEmpty(globalOptions);
  1321. var globalOption = globalPassed ? globalOptions[option] : undefined;
  1322. var globalEnabled = globalOption ? globalOption.enabled : undefined;
  1323. /////////////////////////////////////////
  1324. // Main routine
  1325. /////////////////////////////////////////
  1326. if (srcOption === undefined) {
  1327. return; // Nothing to do
  1328. }
  1329. if (typeof srcOption === 'boolean') {
  1330. if (!isObject(mergeTarget[option])) {
  1331. mergeTarget[option] = {};
  1332. }
  1333. mergeTarget[option].enabled = srcOption;
  1334. return;
  1335. }
  1336. if (srcOption === null && !isObject(mergeTarget[option])) {
  1337. // If possible, explicit copy from globals
  1338. if (isPresent(globalOption)) {
  1339. mergeTarget[option] = (0, _create2['default'])(globalOption);
  1340. } else {
  1341. return; // Nothing to do
  1342. }
  1343. }
  1344. if (!isObject(srcOption)) {
  1345. return;
  1346. }
  1347. //
  1348. // Ensure that 'enabled' is properly set. It is required internally
  1349. // Note that the value from options will always overwrite the existing value
  1350. //
  1351. var enabled = true; // default value
  1352. if (srcOption.enabled !== undefined) {
  1353. enabled = srcOption.enabled;
  1354. } else {
  1355. // Take from globals, if present
  1356. if (globalEnabled !== undefined) {
  1357. enabled = globalOption.enabled;
  1358. }
  1359. }
  1360. doMerge(mergeTarget, options, option);
  1361. mergeTarget[option].enabled = enabled;
  1362. };
  1363. /**
  1364. * This function does a binary search for a visible item in a sorted list. If we find a visible item, the code that uses
  1365. * this function will then iterate in both directions over this sorted list to find all visible items.
  1366. *
  1367. * @param {Item[]} orderedItems | Items ordered by start
  1368. * @param {function} comparator | -1 is lower, 0 is equal, 1 is higher
  1369. * @param {string} field
  1370. * @param {string} field2
  1371. * @returns {number}
  1372. * @private
  1373. */
  1374. exports.binarySearchCustom = function (orderedItems, comparator, field, field2) {
  1375. var maxIterations = 10000;
  1376. var iteration = 0;
  1377. var low = 0;
  1378. var high = orderedItems.length - 1;
  1379. while (low <= high && iteration < maxIterations) {
  1380. var middle = Math.floor((low + high) / 2);
  1381. var item = orderedItems[middle];
  1382. var value = field2 === undefined ? item[field] : item[field][field2];
  1383. var searchResult = comparator(value);
  1384. if (searchResult == 0) {
  1385. // jihaa, found a visible item!
  1386. return middle;
  1387. } else if (searchResult == -1) {
  1388. // it is too small --> increase low
  1389. low = middle + 1;
  1390. } else {
  1391. // it is too big --> decrease high
  1392. high = middle - 1;
  1393. }
  1394. iteration++;
  1395. }
  1396. return -1;
  1397. };
  1398. /**
  1399. * This function does a binary search for a specific value in a sorted array. If it does not exist but is in between of
  1400. * two values, we return either the one before or the one after, depending on user input
  1401. * If it is found, we return the index, else -1.
  1402. *
  1403. * @param {Array} orderedItems
  1404. * @param {{start: number, end: number}} target
  1405. * @param {string} field
  1406. * @param {string} sidePreference 'before' or 'after'
  1407. * @param {function} comparator an optional comparator, returning -1,0,1 for <,==,>.
  1408. * @returns {number}
  1409. * @private
  1410. */
  1411. exports.binarySearchValue = function (orderedItems, target, field, sidePreference, comparator) {
  1412. var maxIterations = 10000;
  1413. var iteration = 0;
  1414. var low = 0;
  1415. var high = orderedItems.length - 1;
  1416. var prevValue, value, nextValue, middle;
  1417. comparator = comparator != undefined ? comparator : function (a, b) {
  1418. return a == b ? 0 : a < b ? -1 : 1;
  1419. };
  1420. while (low <= high && iteration < maxIterations) {
  1421. // get a new guess
  1422. middle = Math.floor(0.5 * (high + low));
  1423. prevValue = orderedItems[Math.max(0, middle - 1)][field];
  1424. value = orderedItems[middle][field];
  1425. nextValue = orderedItems[Math.min(orderedItems.length - 1, middle + 1)][field];
  1426. if (comparator(value, target) == 0) {
  1427. // we found the target
  1428. return middle;
  1429. } else if (comparator(prevValue, target) < 0 && comparator(value, target) > 0) {
  1430. // target is in between of the previous and the current
  1431. return sidePreference == 'before' ? Math.max(0, middle - 1) : middle;
  1432. } else if (comparator(value, target) < 0 && comparator(nextValue, target) > 0) {
  1433. // target is in between of the current and the next
  1434. return sidePreference == 'before' ? middle : Math.min(orderedItems.length - 1, middle + 1);
  1435. } else {
  1436. // didnt find the target, we need to change our boundaries.
  1437. if (comparator(value, target) < 0) {
  1438. // it is too small --> increase low
  1439. low = middle + 1;
  1440. } else {
  1441. // it is too big --> decrease high
  1442. high = middle - 1;
  1443. }
  1444. }
  1445. iteration++;
  1446. }
  1447. // didnt find anything. Return -1.
  1448. return -1;
  1449. };
  1450. /*
  1451. * Easing Functions - inspired from http://gizma.com/easing/
  1452. * only considering the t value for the range [0, 1] => [0, 1]
  1453. * https://gist.github.com/gre/1650294
  1454. */
  1455. exports.easingFunctions = {
  1456. // no easing, no acceleration
  1457. linear: function linear(t) {
  1458. return t;
  1459. },
  1460. // accelerating from zero velocity
  1461. easeInQuad: function easeInQuad(t) {
  1462. return t * t;
  1463. },
  1464. // decelerating to zero velocity
  1465. easeOutQuad: function easeOutQuad(t) {
  1466. return t * (2 - t);
  1467. },
  1468. // acceleration until halfway, then deceleration
  1469. easeInOutQuad: function easeInOutQuad(t) {
  1470. return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
  1471. },
  1472. // accelerating from zero velocity
  1473. easeInCubic: function easeInCubic(t) {
  1474. return t * t * t;
  1475. },
  1476. // decelerating to zero velocity
  1477. easeOutCubic: function easeOutCubic(t) {
  1478. return --t * t * t + 1;
  1479. },
  1480. // acceleration until halfway, then deceleration
  1481. easeInOutCubic: function easeInOutCubic(t) {
  1482. return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
  1483. },
  1484. // accelerating from zero velocity
  1485. easeInQuart: function easeInQuart(t) {
  1486. return t * t * t * t;
  1487. },
  1488. // decelerating to zero velocity
  1489. easeOutQuart: function easeOutQuart(t) {
  1490. return 1 - --t * t * t * t;
  1491. },
  1492. // acceleration until halfway, then deceleration
  1493. easeInOutQuart: function easeInOutQuart(t) {
  1494. return t < .5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t;
  1495. },
  1496. // accelerating from zero velocity
  1497. easeInQuint: function easeInQuint(t) {
  1498. return t * t * t * t * t;
  1499. },
  1500. // decelerating to zero velocity
  1501. easeOutQuint: function easeOutQuint(t) {
  1502. return 1 + --t * t * t * t * t;
  1503. },
  1504. // acceleration until halfway, then deceleration
  1505. easeInOutQuint: function easeInOutQuint(t) {
  1506. return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t;
  1507. }
  1508. };
  1509. exports.getScrollBarWidth = function () {
  1510. var inner = document.createElement('p');
  1511. inner.style.width = "100%";
  1512. inner.style.height = "200px";
  1513. var outer = document.createElement('div');
  1514. outer.style.position = "absolute";
  1515. outer.style.top = "0px";
  1516. outer.style.left = "0px";
  1517. outer.style.visibility = "hidden";
  1518. outer.style.width = "200px";
  1519. outer.style.height = "150px";
  1520. outer.style.overflow = "hidden";
  1521. outer.appendChild(inner);
  1522. document.body.appendChild(outer);
  1523. var w1 = inner.offsetWidth;
  1524. outer.style.overflow = 'scroll';
  1525. var w2 = inner.offsetWidth;
  1526. if (w1 == w2) w2 = outer.clientWidth;
  1527. document.body.removeChild(outer);
  1528. return w1 - w2;
  1529. };
  1530. exports.topMost = function (pile, accessors) {
  1531. var candidate = void 0;
  1532. if (!Array.isArray(accessors)) {
  1533. accessors = [accessors];
  1534. }
  1535. var _iteratorNormalCompletion = true;
  1536. var _didIteratorError = false;
  1537. var _iteratorError = undefined;
  1538. try {
  1539. for (var _iterator = (0, _getIterator3['default'])(pile), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  1540. var member = _step.value;
  1541. if (member) {
  1542. candidate = member[accessors[0]];
  1543. for (var i = 1; i < accessors.length; i++) {
  1544. if (candidate) {
  1545. candidate = candidate[accessors[i]];
  1546. } else {
  1547. continue;
  1548. }
  1549. }
  1550. if (typeof candidate != 'undefined') {
  1551. break;
  1552. }
  1553. }
  1554. }
  1555. } catch (err) {
  1556. _didIteratorError = true;
  1557. _iteratorError = err;
  1558. } finally {
  1559. try {
  1560. if (!_iteratorNormalCompletion && _iterator['return']) {
  1561. _iterator['return']();
  1562. }
  1563. } finally {
  1564. if (_didIteratorError) {
  1565. throw _iteratorError;
  1566. }
  1567. }
  1568. }
  1569. return candidate;
  1570. };
  1571. /***/ }),
  1572. /* 3 */
  1573. /***/ (function(module, exports, __webpack_require__) {
  1574. module.exports = { "default": __webpack_require__(194), __esModule: true };
  1575. /***/ }),
  1576. /* 4 */
  1577. /***/ (function(module, exports, __webpack_require__) {
  1578. "use strict";
  1579. exports.__esModule = true;
  1580. var _typeof2 = __webpack_require__(6);
  1581. var _typeof3 = _interopRequireDefault(_typeof2);
  1582. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1583. exports.default = function (self, call) {
  1584. if (!self) {
  1585. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  1586. }
  1587. return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self;
  1588. };
  1589. /***/ }),
  1590. /* 5 */
  1591. /***/ (function(module, exports, __webpack_require__) {
  1592. "use strict";
  1593. exports.__esModule = true;
  1594. var _setPrototypeOf = __webpack_require__(196);
  1595. var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);
  1596. var _create = __webpack_require__(29);
  1597. var _create2 = _interopRequireDefault(_create);
  1598. var _typeof2 = __webpack_require__(6);
  1599. var _typeof3 = _interopRequireDefault(_typeof2);
  1600. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1601. exports.default = function (subClass, superClass) {
  1602. if (typeof superClass !== "function" && superClass !== null) {
  1603. throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass)));
  1604. }
  1605. subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {
  1606. constructor: {
  1607. value: subClass,
  1608. enumerable: false,
  1609. writable: true,
  1610. configurable: true
  1611. }
  1612. });
  1613. if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass;
  1614. };
  1615. /***/ }),
  1616. /* 6 */
  1617. /***/ (function(module, exports, __webpack_require__) {
  1618. "use strict";
  1619. exports.__esModule = true;
  1620. var _iterator = __webpack_require__(142);
  1621. var _iterator2 = _interopRequireDefault(_iterator);
  1622. var _symbol = __webpack_require__(144);
  1623. var _symbol2 = _interopRequireDefault(_symbol);
  1624. var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };
  1625. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1626. exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
  1627. return typeof obj === "undefined" ? "undefined" : _typeof(obj);
  1628. } : function (obj) {
  1629. return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
  1630. };
  1631. /***/ }),
  1632. /* 7 */
  1633. /***/ (function(module, exports) {
  1634. var core = module.exports = { version: '2.5.1' };
  1635. if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef
  1636. /***/ }),
  1637. /* 8 */
  1638. /***/ (function(module, exports, __webpack_require__) {
  1639. module.exports = { "default": __webpack_require__(140), __esModule: true };
  1640. /***/ }),
  1641. /* 9 */
  1642. /***/ (function(module, exports, __webpack_require__) {
  1643. "use strict";
  1644. // first check if moment.js is already loaded in the browser window, if so,
  1645. // use this instance. Else, load via commonjs.
  1646. module.exports = typeof window !== 'undefined' && window['moment'] || __webpack_require__(154);
  1647. /***/ }),
  1648. /* 10 */
  1649. /***/ (function(module, exports, __webpack_require__) {
  1650. "use strict";
  1651. /**
  1652. * Setup a mock hammer.js object, for unit testing.
  1653. *
  1654. * Inspiration: https://github.com/uber/deck.gl/pull/658
  1655. *
  1656. * @returns {{on: noop, off: noop, destroy: noop, emit: noop, get: get}}
  1657. */
  1658. function hammerMock() {
  1659. var noop = function noop() {};
  1660. return {
  1661. on: noop,
  1662. off: noop,
  1663. destroy: noop,
  1664. emit: noop,
  1665. get: function get(m) {
  1666. //eslint-disable-line no-unused-vars
  1667. return {
  1668. set: noop
  1669. };
  1670. }
  1671. };
  1672. }
  1673. if (typeof window !== 'undefined') {
  1674. var propagating = __webpack_require__(175);
  1675. var Hammer = window['Hammer'] || __webpack_require__(176);
  1676. module.exports = propagating(Hammer, {
  1677. preventDefault: 'mouse'
  1678. });
  1679. } else {
  1680. module.exports = function () {
  1681. // hammer.js is only available in a browser, not in node.js. Replacing it with a mock object.
  1682. return hammerMock();
  1683. };
  1684. }
  1685. /***/ }),
  1686. /* 11 */
  1687. /***/ (function(module, exports, __webpack_require__) {
  1688. "use strict";
  1689. var _stringify = __webpack_require__(19);
  1690. var _stringify2 = _interopRequireDefault(_stringify);
  1691. var _typeof2 = __webpack_require__(6);
  1692. var _typeof3 = _interopRequireDefault(_typeof2);
  1693. var _keys = __webpack_require__(8);
  1694. var _keys2 = _interopRequireDefault(_keys);
  1695. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  1696. var util = __webpack_require__(2);
  1697. var Queue = __webpack_require__(43);
  1698. /**
  1699. * DataSet
  1700. * // TODO: add a DataSet constructor DataSet(data, options)
  1701. *
  1702. * Usage:
  1703. * var dataSet = new DataSet({
  1704. * fieldId: '_id',
  1705. * type: {
  1706. * // ...
  1707. * }
  1708. * });
  1709. *
  1710. * dataSet.add(item);
  1711. * dataSet.add(data);
  1712. * dataSet.update(item);
  1713. * dataSet.update(data);
  1714. * dataSet.remove(id);
  1715. * dataSet.remove(ids);
  1716. * var data = dataSet.get();
  1717. * var data = dataSet.get(id);
  1718. * var data = dataSet.get(ids);
  1719. * var data = dataSet.get(ids, options, data);
  1720. * dataSet.clear();
  1721. *
  1722. * A data set can:
  1723. * - add/remove/update data
  1724. * - gives triggers upon changes in the data
  1725. * - can import/export data in various data formats
  1726. *
  1727. * @param {Array} [data] Optional array with initial data
  1728. * @param {Object} [options] Available options:
  1729. * {string} fieldId Field name of the id in the
  1730. * items, 'id' by default.
  1731. * {Object.<string, string} type
  1732. * A map with field names as key,
  1733. * and the field type as value.
  1734. * {Object} queue Queue changes to the DataSet,
  1735. * flush them all at once.
  1736. * Queue options:
  1737. * - {number} delay Delay in ms, null by default
  1738. * - {number} max Maximum number of entries in the queue, Infinity by default
  1739. * @constructor DataSet
  1740. */
  1741. function DataSet(data, options) {
  1742. // correctly read optional arguments
  1743. if (data && !Array.isArray(data)) {
  1744. options = data;
  1745. data = null;
  1746. }
  1747. this._options = options || {};
  1748. this._data = {}; // map with data indexed by id
  1749. this.length = 0; // number of items in the DataSet
  1750. this._fieldId = this._options.fieldId || 'id'; // name of the field containing id
  1751. this._type = {}; // internal field types (NOTE: this can differ from this._options.type)
  1752. // all variants of a Date are internally stored as Date, so we can convert
  1753. // from everything to everything (also from ISODate to Number for example)
  1754. if (this._options.type) {
  1755. var fields = (0, _keys2['default'])(this._options.type);
  1756. for (var i = 0, len = fields.length; i < len; i++) {
  1757. var field = fields[i];
  1758. var value = this._options.type[field];
  1759. if (value == 'Date' || value == 'ISODate' || value == 'ASPDate') {
  1760. this._type[field] = 'Date';
  1761. } else {
  1762. this._type[field] = value;
  1763. }
  1764. }
  1765. }
  1766. this._subscribers = {}; // event subscribers
  1767. // add initial data when provided
  1768. if (data) {
  1769. this.add(data);
  1770. }
  1771. this.setOptions(options);
  1772. }
  1773. /**
  1774. * @param {Object} options Available options:
  1775. * {Object} queue Queue changes to the DataSet,
  1776. * flush them all at once.
  1777. * Queue options:
  1778. * - {number} delay Delay in ms, null by default
  1779. * - {number} max Maximum number of entries in the queue, Infinity by default
  1780. */
  1781. DataSet.prototype.setOptions = function (options) {
  1782. if (options && options.queue !== undefined) {
  1783. if (options.queue === false) {
  1784. // delete queue if loaded
  1785. if (this._queue) {
  1786. this._queue.destroy();
  1787. delete this._queue;
  1788. }
  1789. } else {
  1790. // create queue and update its options
  1791. if (!this._queue) {
  1792. this._queue = Queue.extend(this, {
  1793. replace: ['add', 'update', 'remove']
  1794. });
  1795. }
  1796. if ((0, _typeof3['default'])(options.queue) === 'object') {
  1797. this._queue.setOptions(options.queue);
  1798. }
  1799. }
  1800. }
  1801. };
  1802. /**
  1803. * Subscribe to an event, add an event listener
  1804. * @param {string} event Event name. Available events: 'add', 'update',
  1805. * 'remove'
  1806. * @param {function} callback Callback method. Called with three parameters:
  1807. * {string} event
  1808. * {Object | null} params
  1809. * {string | number} senderId
  1810. */
  1811. DataSet.prototype.on = function (event, callback) {
  1812. var subscribers = this._subscribers[event];
  1813. if (!subscribers) {
  1814. subscribers = [];
  1815. this._subscribers[event] = subscribers;
  1816. }
  1817. subscribers.push({
  1818. callback: callback
  1819. });
  1820. };
  1821. /**
  1822. * Unsubscribe from an event, remove an event listener
  1823. * @param {string} event
  1824. * @param {function} callback
  1825. */
  1826. DataSet.prototype.off = function (event, callback) {
  1827. var subscribers = this._subscribers[event];
  1828. if (subscribers) {
  1829. this._subscribers[event] = subscribers.filter(function (listener) {
  1830. return listener.callback != callback;
  1831. });
  1832. }
  1833. };
  1834. /**
  1835. * Trigger an event
  1836. * @param {string} event
  1837. * @param {Object | null} params
  1838. * @param {string} [senderId] Optional id of the sender.
  1839. * @private
  1840. */
  1841. DataSet.prototype._trigger = function (event, params, senderId) {
  1842. if (event == '*') {
  1843. throw new Error('Cannot trigger event *');
  1844. }
  1845. var subscribers = [];
  1846. if (event in this._subscribers) {
  1847. subscribers = subscribers.concat(this._subscribers[event]);
  1848. }
  1849. if ('*' in this._subscribers) {
  1850. subscribers = subscribers.concat(this._subscribers['*']);
  1851. }
  1852. for (var i = 0, len = subscribers.length; i < len; i++) {
  1853. var subscriber = subscribers[i];
  1854. if (subscriber.callback) {
  1855. subscriber.callback(event, params, senderId || null);
  1856. }
  1857. }
  1858. };
  1859. /**
  1860. * Add data.
  1861. * Adding an item will fail when there already is an item with the same id.
  1862. * @param {Object | Array} data
  1863. * @param {string} [senderId] Optional sender id
  1864. * @return {Array.<string|number>} addedIds Array with the ids of the added items
  1865. */
  1866. DataSet.prototype.add = function (data, senderId) {
  1867. var addedIds = [],
  1868. id,
  1869. me = this;
  1870. if (Array.isArray(data)) {
  1871. // Array
  1872. for (var i = 0, len = data.length; i < len; i++) {
  1873. id = me._addItem(data[i]);
  1874. addedIds.push(id);
  1875. }
  1876. } else if (data && (typeof data === 'undefined' ? 'undefined' : (0, _typeof3['default'])(data)) === 'object') {
  1877. // Single item
  1878. id = me._addItem(data);
  1879. addedIds.push(id);
  1880. } else {
  1881. throw new Error('Unknown dataType');
  1882. }
  1883. if (addedIds.length) {
  1884. this._trigger('add', { items: addedIds }, senderId);
  1885. }
  1886. return addedIds;
  1887. };
  1888. /**
  1889. * Update existing items. When an item does not exist, it will be created
  1890. * @param {Object | Array} data
  1891. * @param {string} [senderId] Optional sender id
  1892. * @return {Array.<string|number>} updatedIds The ids of the added or updated items
  1893. * @throws {Error} Unknown Datatype
  1894. */
  1895. DataSet.prototype.update = function (data, senderId) {
  1896. var addedIds = [];
  1897. var updatedIds = [];
  1898. var oldData = [];
  1899. var updatedData = [];
  1900. var me = this;
  1901. var fieldId = me._fieldId;
  1902. var addOrUpdate = function addOrUpdate(item) {
  1903. var id = item[fieldId];
  1904. if (me._data[id]) {
  1905. var oldItem = util.extend({}, me._data[id]);
  1906. // update item
  1907. id = me._updateItem(item);
  1908. updatedIds.push(id);
  1909. updatedData.push(item);
  1910. oldData.push(oldItem);
  1911. } else {
  1912. // add new item
  1913. id = me._addItem(item);
  1914. addedIds.push(id);
  1915. }
  1916. };
  1917. if (Array.isArray(data)) {
  1918. // Array
  1919. for (var i = 0, len = data.length; i < len; i++) {
  1920. if (data[i] && (0, _typeof3['default'])(data[i]) === 'object') {
  1921. addOrUpdate(data[i]);
  1922. } else {
  1923. console.warn('Ignoring input item, which is not an object at index ' + i);
  1924. }
  1925. }
  1926. } else if (data && (typeof data === 'undefined' ? 'undefined' : (0, _typeof3['default'])(data)) === 'object') {
  1927. // Single item
  1928. addOrUpdate(data);
  1929. } else {
  1930. throw new Error('Unknown dataType');
  1931. }
  1932. if (addedIds.length) {
  1933. this._trigger('add', { items: addedIds }, senderId);
  1934. }
  1935. if (updatedIds.length) {
  1936. var props = { items: updatedIds, oldData: oldData, data: updatedData };
  1937. // TODO: remove deprecated property 'data' some day
  1938. //Object.defineProperty(props, 'data', {
  1939. // 'get': (function() {
  1940. // 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');
  1941. // return updatedData;
  1942. // }).bind(this)
  1943. //});
  1944. this._trigger('update', props, senderId);
  1945. }
  1946. return addedIds.concat(updatedIds);
  1947. };
  1948. /**
  1949. * Get a data item or multiple items.
  1950. *
  1951. * Usage:
  1952. *
  1953. * get()
  1954. * get(options: Object)
  1955. *
  1956. * get(id: number | string)
  1957. * get(id: number | string, options: Object)
  1958. *
  1959. * get(ids: number[] | string[])
  1960. * get(ids: number[] | string[], options: Object)
  1961. *
  1962. * Where:
  1963. *
  1964. * {number | string} id The id of an item
  1965. * {number[] | string{}} ids An array with ids of items
  1966. * {Object} options An Object with options. Available options:
  1967. * {string} [returnType] Type of data to be returned.
  1968. * Can be 'Array' (default) or 'Object'.
  1969. * {Object.<string, string>} [type]
  1970. * {string[]} [fields] field names to be returned
  1971. * {function} [filter] filter items
  1972. * {string | function} [order] Order the items by a field name or custom sort function.
  1973. * @param {Array} args
  1974. * @returns {DataSet}
  1975. * @throws Error
  1976. */
  1977. DataSet.prototype.get = function (args) {
  1978. // eslint-disable-line no-unused-vars
  1979. var me = this;
  1980. // parse the arguments
  1981. var id, ids, options;
  1982. var firstType = util.getType(arguments[0]);
  1983. if (firstType == 'String' || firstType == 'Number') {
  1984. // get(id [, options])
  1985. id = arguments[0];
  1986. options = arguments[1];
  1987. } else if (firstType == 'Array') {
  1988. // get(ids [, options])
  1989. ids = arguments[0];
  1990. options = arguments[1];
  1991. } else {
  1992. // get([, options])
  1993. options = arguments[0];
  1994. }
  1995. // determine the return type
  1996. var returnType;
  1997. if (options && options.returnType) {
  1998. var allowedValues = ['Array', 'Object'];
  1999. returnType = allowedValues.indexOf(options.returnType) == -1 ? 'Array' : options.returnType;
  2000. } else {
  2001. returnType = 'Array';
  2002. }
  2003. // build options
  2004. var type = options && options.type || this._options.type;
  2005. var filter = options && options.filter;
  2006. var items = [],
  2007. item,
  2008. itemIds,
  2009. itemId,
  2010. i,
  2011. len;
  2012. // convert items
  2013. if (id != undefined) {
  2014. // return a single item
  2015. item = me._getItem(id, type);
  2016. if (item && filter && !filter(item)) {
  2017. item = null;
  2018. }
  2019. } else if (ids != undefined) {
  2020. // return a subset of items
  2021. for (i = 0, len = ids.length; i < len; i++) {
  2022. item = me._getItem(ids[i], type);
  2023. if (!filter || filter(item)) {
  2024. items.push(item);
  2025. }
  2026. }
  2027. } else {
  2028. // return all items
  2029. itemIds = (0, _keys2['default'])(this._data);
  2030. for (i = 0, len = itemIds.length; i < len; i++) {
  2031. itemId = itemIds[i];
  2032. item = me._getItem(itemId, type);
  2033. if (!filter || filter(item)) {
  2034. items.push(item);
  2035. }
  2036. }
  2037. }
  2038. // order the results
  2039. if (options && options.order && id == undefined) {
  2040. this._sort(items, options.order);
  2041. }
  2042. // filter fields of the items
  2043. if (options && options.fields) {
  2044. var fields = options.fields;
  2045. if (id != undefined) {
  2046. item = this._filterFields(item, fields);
  2047. } else {
  2048. for (i = 0, len = items.length; i < len; i++) {
  2049. items[i] = this._filterFields(items[i], fields);
  2050. }
  2051. }
  2052. }
  2053. // return the results
  2054. if (returnType == 'Object') {
  2055. var result = {},
  2056. resultant;
  2057. for (i = 0, len = items.length; i < len; i++) {
  2058. resultant = items[i];
  2059. result[resultant.id] = resultant;
  2060. }
  2061. return result;
  2062. } else {
  2063. if (id != undefined) {
  2064. // a single item
  2065. return item;
  2066. } else {
  2067. // just return our array
  2068. return items;
  2069. }
  2070. }
  2071. };
  2072. /**
  2073. * Get ids of all items or from a filtered set of items.
  2074. * @param {Object} [options] An Object with options. Available options:
  2075. * {function} [filter] filter items
  2076. * {string | function} [order] Order the items by
  2077. * a field name or custom sort function.
  2078. * @return {Array.<string|number>} ids
  2079. */
  2080. DataSet.prototype.getIds = function (options) {
  2081. var data = this._data,
  2082. filter = options && options.filter,
  2083. order = options && options.order,
  2084. type = options && options.type || this._options.type,
  2085. itemIds = (0, _keys2['default'])(data),
  2086. i,
  2087. len,
  2088. id,
  2089. item,
  2090. items,
  2091. ids = [];
  2092. if (filter) {
  2093. // get filtered items
  2094. if (order) {
  2095. // create ordered list
  2096. items = [];
  2097. for (i = 0, len = itemIds.length; i < len; i++) {
  2098. id = itemIds[i];
  2099. item = this._getItem(id, type);
  2100. if (filter(item)) {
  2101. items.push(item);
  2102. }
  2103. }
  2104. this._sort(items, order);
  2105. for (i = 0, len = items.length; i < len; i++) {
  2106. ids.push(items[i][this._fieldId]);
  2107. }
  2108. } else {
  2109. // create unordered list
  2110. for (i = 0, len = itemIds.length; i < len; i++) {
  2111. id = itemIds[i];
  2112. item = this._getItem(id, type);
  2113. if (filter(item)) {
  2114. ids.push(item[this._fieldId]);
  2115. }
  2116. }
  2117. }
  2118. } else {
  2119. // get all items
  2120. if (order) {
  2121. // create an ordered list
  2122. items = [];
  2123. for (i = 0, len = itemIds.length; i < len; i++) {
  2124. id = itemIds[i];
  2125. items.push(data[id]);
  2126. }
  2127. this._sort(items, order);
  2128. for (i = 0, len = items.length; i < len; i++) {
  2129. ids.push(items[i][this._fieldId]);
  2130. }
  2131. } else {
  2132. // create unordered list
  2133. for (i = 0, len = itemIds.length; i < len; i++) {
  2134. id = itemIds[i];
  2135. item = data[id];
  2136. ids.push(item[this._fieldId]);
  2137. }
  2138. }
  2139. }
  2140. return ids;
  2141. };
  2142. /**
  2143. * Returns the DataSet itself. Is overwritten for example by the DataView,
  2144. * which returns the DataSet it is connected to instead.
  2145. * @returns {DataSet}
  2146. */
  2147. DataSet.prototype.getDataSet = function () {
  2148. return this;
  2149. };
  2150. /**
  2151. * Execute a callback function for every item in the dataset.
  2152. * @param {function} callback
  2153. * @param {Object} [options] Available options:
  2154. * {Object.<string, string>} [type]
  2155. * {string[]} [fields] filter fields
  2156. * {function} [filter] filter items
  2157. * {string | function} [order] Order the items by
  2158. * a field name or custom sort function.
  2159. */
  2160. DataSet.prototype.forEach = function (callback, options) {
  2161. var filter = options && options.filter,
  2162. type = options && options.type || this._options.type,
  2163. data = this._data,
  2164. itemIds = (0, _keys2['default'])(data),
  2165. i,
  2166. len,
  2167. item,
  2168. id;
  2169. if (options && options.order) {
  2170. // execute forEach on ordered list
  2171. var items = this.get(options);
  2172. for (i = 0, len = items.length; i < len; i++) {
  2173. item = items[i];
  2174. id = item[this._fieldId];
  2175. callback(item, id);
  2176. }
  2177. } else {
  2178. // unordered
  2179. for (i = 0, len = itemIds.length; i < len; i++) {
  2180. id = itemIds[i];
  2181. item = this._getItem(id, type);
  2182. if (!filter || filter(item)) {
  2183. callback(item, id);
  2184. }
  2185. }
  2186. }
  2187. };
  2188. /**
  2189. * Map every item in the dataset.
  2190. * @param {function} callback
  2191. * @param {Object} [options] Available options:
  2192. * {Object.<string, string>} [type]
  2193. * {string[]} [fields] filter fields
  2194. * {function} [filter] filter items
  2195. * {string | function} [order] Order the items by
  2196. * a field name or custom sort function.
  2197. * @return {Object[]} mappedItems
  2198. */
  2199. DataSet.prototype.map = function (callback, options) {
  2200. var filter = options && options.filter,
  2201. type = options && options.type || this._options.type,
  2202. mappedItems = [],
  2203. data = this._data,
  2204. itemIds = (0, _keys2['default'])(data),
  2205. i,
  2206. len,
  2207. id,
  2208. item;
  2209. // convert and filter items
  2210. for (i = 0, len = itemIds.length; i < len; i++) {
  2211. id = itemIds[i];
  2212. item = this._getItem(id, type);
  2213. if (!filter || filter(item)) {
  2214. mappedItems.push(callback(item, id));
  2215. }
  2216. }
  2217. // order items
  2218. if (options && options.order) {
  2219. this._sort(mappedItems, options.order);
  2220. }
  2221. return mappedItems;
  2222. };
  2223. /**
  2224. * Filter the fields of an item
  2225. * @param {Object | null} item
  2226. * @param {string[]} fields Field names
  2227. * @return {Object | null} filteredItem or null if no item is provided
  2228. * @private
  2229. */
  2230. DataSet.prototype._filterFields = function (item, fields) {
  2231. if (!item) {
  2232. // item is null
  2233. return item;
  2234. }
  2235. var filteredItem = {},
  2236. itemFields = (0, _keys2['default'])(item),
  2237. len = itemFields.length,
  2238. i,
  2239. field;
  2240. if (Array.isArray(fields)) {
  2241. for (i = 0; i < len; i++) {
  2242. field = itemFields[i];
  2243. if (fields.indexOf(field) != -1) {
  2244. filteredItem[field] = item[field];
  2245. }
  2246. }
  2247. } else {
  2248. for (i = 0; i < len; i++) {
  2249. field = itemFields[i];
  2250. if (fields.hasOwnProperty(field)) {
  2251. filteredItem[fields[field]] = item[field];
  2252. }
  2253. }
  2254. }
  2255. return filteredItem;
  2256. };
  2257. /**
  2258. * Sort the provided array with items
  2259. * @param {Object[]} items
  2260. * @param {string | function} order A field name or custom sort function.
  2261. * @private
  2262. */
  2263. DataSet.prototype._sort = function (items, order) {
  2264. if (util.isString(order)) {
  2265. // order by provided field name
  2266. var name = order; // field name
  2267. items.sort(function (a, b) {
  2268. var av = a[name];
  2269. var bv = b[name];
  2270. return av > bv ? 1 : av < bv ? -1 : 0;
  2271. });
  2272. } else if (typeof order === 'function') {
  2273. // order by sort function
  2274. items.sort(order);
  2275. }
  2276. // TODO: extend order by an Object {field:string, direction:string}
  2277. // where direction can be 'asc' or 'desc'
  2278. else {
  2279. throw new TypeError('Order must be a function or a string');
  2280. }
  2281. };
  2282. /**
  2283. * Remove an object by pointer or by id
  2284. * @param {string | number | Object | Array.<string|number>} id Object or id, or an array with
  2285. * objects or ids to be removed
  2286. * @param {string} [senderId] Optional sender id
  2287. * @return {Array.<string|number>} removedIds
  2288. */
  2289. DataSet.prototype.remove = function (id, senderId) {
  2290. var removedIds = [],
  2291. removedItems = [],
  2292. ids = [],
  2293. i,
  2294. len,
  2295. itemId,
  2296. item;
  2297. // force everything to be an array for simplicity
  2298. ids = Array.isArray(id) ? id : [id];
  2299. for (i = 0, len = ids.length; i < len; i++) {
  2300. item = this._remove(ids[i]);
  2301. if (item) {
  2302. itemId = item[this._fieldId];
  2303. if (itemId != undefined) {
  2304. removedIds.push(itemId);
  2305. removedItems.push(item);
  2306. }
  2307. }
  2308. }
  2309. if (removedIds.length) {
  2310. this._trigger('remove', { items: removedIds, oldData: removedItems }, senderId);
  2311. }
  2312. return removedIds;
  2313. };
  2314. /**
  2315. * Remove an item by its id
  2316. * @param {number | string | Object} id id or item
  2317. * @returns {number | string | null} id
  2318. * @private
  2319. */
  2320. DataSet.prototype._remove = function (id) {
  2321. var item, ident;
  2322. // confirm the id to use based on the args type
  2323. if (util.isNumber(id) || util.isString(id)) {
  2324. ident = id;
  2325. } else if (id && (typeof id === 'undefined' ? 'undefined' : (0, _typeof3['default'])(id)) === 'object') {
  2326. ident = id[this._fieldId]; // look for the identifier field using _fieldId
  2327. }
  2328. // do the remove if the item is found
  2329. if (ident !== undefined && this._data[ident]) {
  2330. item = this._data[ident];
  2331. delete this._data[ident];
  2332. this.length--;
  2333. return item;
  2334. }
  2335. return null;
  2336. };
  2337. /**
  2338. * Clear the data
  2339. * @param {string} [senderId] Optional sender id
  2340. * @return {Array.<string|number>} removedIds The ids of all removed items
  2341. */
  2342. DataSet.prototype.clear = function (senderId) {
  2343. var i, len;
  2344. var ids = (0, _keys2['default'])(this._data);
  2345. var items = [];
  2346. for (i = 0, len = ids.length; i < len; i++) {
  2347. items.push(this._data[ids[i]]);
  2348. }
  2349. this._data = {};
  2350. this.length = 0;
  2351. this._trigger('remove', { items: ids, oldData: items }, senderId);
  2352. return ids;
  2353. };
  2354. /**
  2355. * Find the item with maximum value of a specified field
  2356. * @param {string} field
  2357. * @return {Object | null} item Item containing max value, or null if no items
  2358. */
  2359. DataSet.prototype.max = function (field) {
  2360. var data = this._data,
  2361. itemIds = (0, _keys2['default'])(data),
  2362. max = null,
  2363. maxField = null,
  2364. i,
  2365. len;
  2366. for (i = 0, len = itemIds.length; i < len; i++) {
  2367. var id = itemIds[i];
  2368. var item = data[id];
  2369. var itemField = item[field];
  2370. if (itemField != null && (!max || itemField > maxField)) {
  2371. max = item;
  2372. maxField = itemField;
  2373. }
  2374. }
  2375. return max;
  2376. };
  2377. /**
  2378. * Find the item with minimum value of a specified field
  2379. * @param {string} field
  2380. * @return {Object | null} item Item containing max value, or null if no items
  2381. */
  2382. DataSet.prototype.min = function (field) {
  2383. var data = this._data,
  2384. itemIds = (0, _keys2['default'])(data),
  2385. min = null,
  2386. minField = null,
  2387. i,
  2388. len;
  2389. for (i = 0, len = itemIds.length; i < len; i++) {
  2390. var id = itemIds[i];
  2391. var item = data[id];
  2392. var itemField = item[field];
  2393. if (itemField != null && (!min || itemField < minField)) {
  2394. min = item;
  2395. minField = itemField;
  2396. }
  2397. }
  2398. return min;
  2399. };
  2400. /**
  2401. * Find all distinct values of a specified field
  2402. * @param {string} field
  2403. * @return {Array} values Array containing all distinct values. If data items
  2404. * do not contain the specified field are ignored.
  2405. * The returned array is unordered.
  2406. */
  2407. DataSet.prototype.distinct = function (field) {
  2408. var data = this._data;
  2409. var itemIds = (0, _keys2['default'])(data);
  2410. var values = [];
  2411. var fieldType = this._options.type && this._options.type[field] || null;
  2412. var count = 0;
  2413. var i, j, len;
  2414. for (i = 0, len = itemIds.length; i < len; i++) {
  2415. var id = itemIds[i];
  2416. var item = data[id];
  2417. var value = item[field];
  2418. var exists = false;
  2419. for (j = 0; j < count; j++) {
  2420. if (values[j] == value) {
  2421. exists = true;
  2422. break;
  2423. }
  2424. }
  2425. if (!exists && value !== undefined) {
  2426. values[count] = value;
  2427. count++;
  2428. }
  2429. }
  2430. if (fieldType) {
  2431. for (i = 0, len = values.length; i < len; i++) {
  2432. values[i] = util.convert(values[i], fieldType);
  2433. }
  2434. }
  2435. return values;
  2436. };
  2437. /**
  2438. * Add a single item. Will fail when an item with the same id already exists.
  2439. * @param {Object} item
  2440. * @return {string} id
  2441. * @private
  2442. */
  2443. DataSet.prototype._addItem = function (item) {
  2444. var id = item[this._fieldId];
  2445. if (id != undefined) {
  2446. // check whether this id is already taken
  2447. if (this._data[id]) {
  2448. // item already exists
  2449. throw new Error('Cannot add item: item with id ' + id + ' already exists');
  2450. }
  2451. } else {
  2452. // generate an id
  2453. id = util.randomUUID();
  2454. item[this._fieldId] = id;
  2455. }
  2456. var d = {},
  2457. fields = (0, _keys2['default'])(item),
  2458. i,
  2459. len;
  2460. for (i = 0, len = fields.length; i < len; i++) {
  2461. var field = fields[i];
  2462. var fieldType = this._type[field]; // type may be undefined
  2463. d[field] = util.convert(item[field], fieldType);
  2464. }
  2465. this._data[id] = d;
  2466. this.length++;
  2467. return id;
  2468. };
  2469. /**
  2470. * Get an item. Fields can be converted to a specific type
  2471. * @param {string} id
  2472. * @param {Object.<string, string>} [types] field types to convert
  2473. * @return {Object | null} item
  2474. * @private
  2475. */
  2476. DataSet.prototype._getItem = function (id, types) {
  2477. var field, value, i, len;
  2478. // get the item from the dataset
  2479. var raw = this._data[id];
  2480. if (!raw) {
  2481. return null;
  2482. }
  2483. // convert the items field types
  2484. var converted = {},
  2485. fields = (0, _keys2['default'])(raw);
  2486. if (types) {
  2487. for (i = 0, len = fields.length; i < len; i++) {
  2488. field = fields[i];
  2489. value = raw[field];
  2490. converted[field] = util.convert(value, types[field]);
  2491. }
  2492. } else {
  2493. // no field types specified, no converting needed
  2494. for (i = 0, len = fields.length; i < len; i++) {
  2495. field = fields[i];
  2496. value = raw[field];
  2497. converted[field] = value;
  2498. }
  2499. }
  2500. if (!converted[this._fieldId]) {
  2501. converted[this._fieldId] = raw.id;
  2502. }
  2503. return converted;
  2504. };
  2505. /**
  2506. * Update a single item: merge with existing item.
  2507. * Will fail when the item has no id, or when there does not exist an item
  2508. * with the same id.
  2509. * @param {Object} item
  2510. * @return {string} id
  2511. * @private
  2512. */
  2513. DataSet.prototype._updateItem = function (item) {
  2514. var id = item[this._fieldId];
  2515. if (id == undefined) {
  2516. throw new Error('Cannot update item: item has no id (item: ' + (0, _stringify2['default'])(item) + ')');
  2517. }
  2518. var d = this._data[id];
  2519. if (!d) {
  2520. // item doesn't exist
  2521. throw new Error('Cannot update item: no item with id ' + id + ' found');
  2522. }
  2523. // merge with current item
  2524. var fields = (0, _keys2['default'])(item);
  2525. for (var i = 0, len = fields.length; i < len; i++) {
  2526. var field = fields[i];
  2527. var fieldType = this._type[field]; // type may be undefined
  2528. d[field] = util.convert(item[field], fieldType);
  2529. }
  2530. return id;
  2531. };
  2532. module.exports = DataSet;
  2533. /***/ }),
  2534. /* 12 */
  2535. /***/ (function(module, exports, __webpack_require__) {
  2536. "use strict";
  2537. var _keys = __webpack_require__(8);
  2538. var _keys2 = _interopRequireDefault(_keys);
  2539. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  2540. var util = __webpack_require__(2);
  2541. var DataSet = __webpack_require__(11);
  2542. /**
  2543. * DataView
  2544. *
  2545. * a dataview offers a filtered view on a dataset or an other dataview.
  2546. *
  2547. * @param {DataSet | DataView} data
  2548. * @param {Object} [options] Available options: see method get
  2549. *
  2550. * @constructor DataView
  2551. */
  2552. function DataView(data, options) {
  2553. this._data = null;
  2554. this._ids = {}; // ids of the items currently in memory (just contains a boolean true)
  2555. this.length = 0; // number of items in the DataView
  2556. this._options = options || {};
  2557. this._fieldId = 'id'; // name of the field containing id
  2558. this._subscribers = {}; // event subscribers
  2559. var me = this;
  2560. this.listener = function () {
  2561. me._onEvent.apply(me, arguments);
  2562. };
  2563. this.setData(data);
  2564. }
  2565. // TODO: implement a function .config() to dynamically update things like configured filter
  2566. // and trigger changes accordingly
  2567. /**
  2568. * Set a data source for the view
  2569. * @param {DataSet | DataView} data
  2570. */
  2571. DataView.prototype.setData = function (data) {
  2572. var ids, id, i, len, items;
  2573. if (this._data) {
  2574. // unsubscribe from current dataset
  2575. if (this._data.off) {
  2576. this._data.off('*', this.listener);
  2577. }
  2578. // trigger a remove of all items in memory
  2579. ids = this._data.getIds({ filter: this._options && this._options.filter });
  2580. items = [];
  2581. for (i = 0, len = ids.length; i < len; i++) {
  2582. items.push(this._data._data[ids[i]]);
  2583. }
  2584. this._ids = {};
  2585. this.length = 0;
  2586. this._trigger('remove', { items: ids, oldData: items });
  2587. }
  2588. this._data = data;
  2589. if (this._data) {
  2590. // update fieldId
  2591. this._fieldId = this._options.fieldId || this._data && this._data.options && this._data.options.fieldId || 'id';
  2592. // trigger an add of all added items
  2593. ids = this._data.getIds({ filter: this._options && this._options.filter });
  2594. for (i = 0, len = ids.length; i < len; i++) {
  2595. id = ids[i];
  2596. this._ids[id] = true;
  2597. }
  2598. this.length = ids.length;
  2599. this._trigger('add', { items: ids });
  2600. // subscribe to new dataset
  2601. if (this._data.on) {
  2602. this._data.on('*', this.listener);
  2603. }
  2604. }
  2605. };
  2606. /**
  2607. * Refresh the DataView. Useful when the DataView has a filter function
  2608. * containing a variable parameter.
  2609. */
  2610. DataView.prototype.refresh = function () {
  2611. var id, i, len;
  2612. var ids = this._data.getIds({ filter: this._options && this._options.filter }),
  2613. oldIds = (0, _keys2['default'])(this._ids),
  2614. newIds = {},
  2615. addedIds = [],
  2616. removedIds = [],
  2617. removedItems = [];
  2618. // check for additions
  2619. for (i = 0, len = ids.length; i < len; i++) {
  2620. id = ids[i];
  2621. newIds[id] = true;
  2622. if (!this._ids[id]) {
  2623. addedIds.push(id);
  2624. this._ids[id] = true;
  2625. }
  2626. }
  2627. // check for removals
  2628. for (i = 0, len = oldIds.length; i < len; i++) {
  2629. id = oldIds[i];
  2630. if (!newIds[id]) {
  2631. removedIds.push(id);
  2632. removedItems.push(this._data._data[id]);
  2633. delete this._ids[id];
  2634. }
  2635. }
  2636. this.length += addedIds.length - removedIds.length;
  2637. // trigger events
  2638. if (addedIds.length) {
  2639. this._trigger('add', { items: addedIds });
  2640. }
  2641. if (removedIds.length) {
  2642. this._trigger('remove', { items: removedIds, oldData: removedItems });
  2643. }
  2644. };
  2645. /**
  2646. * Get data from the data view
  2647. *
  2648. * Usage:
  2649. *
  2650. * get()
  2651. * get(options: Object)
  2652. * get(options: Object, data: Array | DataTable)
  2653. *
  2654. * get(id: Number)
  2655. * get(id: Number, options: Object)
  2656. * get(id: Number, options: Object, data: Array | DataTable)
  2657. *
  2658. * get(ids: Number[])
  2659. * get(ids: Number[], options: Object)
  2660. * get(ids: Number[], options: Object, data: Array | DataTable)
  2661. *
  2662. * Where:
  2663. *
  2664. * {number | string} id The id of an item
  2665. * {number[] | string{}} ids An array with ids of items
  2666. * {Object} options An Object with options. Available options:
  2667. * {string} [type] Type of data to be returned. Can
  2668. * be 'DataTable' or 'Array' (default)
  2669. * {Object.<string, string>} [convert]
  2670. * {string[]} [fields] field names to be returned
  2671. * {function} [filter] filter items
  2672. * {string | function} [order] Order the items by
  2673. * a field name or custom sort function.
  2674. * {Array | DataTable} [data] If provided, items will be appended to this
  2675. * array or table. Required in case of Google
  2676. * DataTable.
  2677. * @param {Array} args
  2678. * @return {DataSet|DataView}
  2679. */
  2680. DataView.prototype.get = function (args) {
  2681. // eslint-disable-line no-unused-vars
  2682. var me = this;
  2683. // parse the arguments
  2684. var ids, options, data;
  2685. var firstType = util.getType(arguments[0]);
  2686. if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {
  2687. // get(id(s) [, options] [, data])
  2688. ids = arguments[0]; // can be a single id or an array with ids
  2689. options = arguments[1];
  2690. data = arguments[2];
  2691. } else {
  2692. // get([, options] [, data])
  2693. options = arguments[0];
  2694. data = arguments[1];
  2695. }
  2696. // extend the options with the default options and provided options
  2697. var viewOptions = util.extend({}, this._options, options);
  2698. // create a combined filter method when needed
  2699. if (this._options.filter && options && options.filter) {
  2700. viewOptions.filter = function (item) {
  2701. return me._options.filter(item) && options.filter(item);
  2702. };
  2703. }
  2704. // build up the call to the linked data set
  2705. var getArguments = [];
  2706. if (ids != undefined) {
  2707. getArguments.push(ids);
  2708. }
  2709. getArguments.push(viewOptions);
  2710. getArguments.push(data);
  2711. return this._data && this._data.get.apply(this._data, getArguments);
  2712. };
  2713. /**
  2714. * Get ids of all items or from a filtered set of items.
  2715. * @param {Object} [options] An Object with options. Available options:
  2716. * {function} [filter] filter items
  2717. * {string | function} [order] Order the items by
  2718. * a field name or custom sort function.
  2719. * @return {Array.<string|number>} ids
  2720. */
  2721. DataView.prototype.getIds = function (options) {
  2722. var ids;
  2723. if (this._data) {
  2724. var defaultFilter = this._options.filter;
  2725. var filter;
  2726. if (options && options.filter) {
  2727. if (defaultFilter) {
  2728. filter = function filter(item) {
  2729. return defaultFilter(item) && options.filter(item);
  2730. };
  2731. } else {
  2732. filter = options.filter;
  2733. }
  2734. } else {
  2735. filter = defaultFilter;
  2736. }
  2737. ids = this._data.getIds({
  2738. filter: filter,
  2739. order: options && options.order
  2740. });
  2741. } else {
  2742. ids = [];
  2743. }
  2744. return ids;
  2745. };
  2746. /**
  2747. * Map every item in the dataset.
  2748. * @param {function} callback
  2749. * @param {Object} [options] Available options:
  2750. * {Object.<string, string>} [type]
  2751. * {string[]} [fields] filter fields
  2752. * {function} [filter] filter items
  2753. * {string | function} [order] Order the items by
  2754. * a field name or custom sort function.
  2755. * @return {Object[]} mappedItems
  2756. */
  2757. DataView.prototype.map = function (callback, options) {
  2758. var mappedItems = [];
  2759. if (this._data) {
  2760. var defaultFilter = this._options.filter;
  2761. var filter;
  2762. if (options && options.filter) {
  2763. if (defaultFilter) {
  2764. filter = function filter(item) {
  2765. return defaultFilter(item) && options.filter(item);
  2766. };
  2767. } else {
  2768. filter = options.filter;
  2769. }
  2770. } else {
  2771. filter = defaultFilter;
  2772. }
  2773. mappedItems = this._data.map(callback, {
  2774. filter: filter,
  2775. order: options && options.order
  2776. });
  2777. } else {
  2778. mappedItems = [];
  2779. }
  2780. return mappedItems;
  2781. };
  2782. /**
  2783. * Get the DataSet to which this DataView is connected. In case there is a chain
  2784. * of multiple DataViews, the root DataSet of this chain is returned.
  2785. * @return {DataSet} dataSet
  2786. */
  2787. DataView.prototype.getDataSet = function () {
  2788. var dataSet = this;
  2789. while (dataSet instanceof DataView) {
  2790. dataSet = dataSet._data;
  2791. }
  2792. return dataSet || null;
  2793. };
  2794. /**
  2795. * Event listener. Will propagate all events from the connected data set to
  2796. * the subscribers of the DataView, but will filter the items and only trigger
  2797. * when there are changes in the filtered data set.
  2798. * @param {string} event
  2799. * @param {Object | null} params
  2800. * @param {string} senderId
  2801. * @private
  2802. */
  2803. DataView.prototype._onEvent = function (event, params, senderId) {
  2804. var i, len, id, item;
  2805. var ids = params && params.items;
  2806. var addedIds = [],
  2807. updatedIds = [],
  2808. removedIds = [],
  2809. oldItems = [],
  2810. updatedItems = [],
  2811. removedItems = [];
  2812. if (ids && this._data) {
  2813. switch (event) {
  2814. case 'add':
  2815. // filter the ids of the added items
  2816. for (i = 0, len = ids.length; i < len; i++) {
  2817. id = ids[i];
  2818. item = this.get(id);
  2819. if (item) {
  2820. this._ids[id] = true;
  2821. addedIds.push(id);
  2822. }
  2823. }
  2824. break;
  2825. case 'update':
  2826. // determine the event from the views viewpoint: an updated
  2827. // item can be added, updated, or removed from this view.
  2828. for (i = 0, len = ids.length; i < len; i++) {
  2829. id = ids[i];
  2830. item = this.get(id);
  2831. if (item) {
  2832. if (this._ids[id]) {
  2833. updatedIds.push(id);
  2834. updatedItems.push(params.data[i]);
  2835. oldItems.push(params.oldData[i]);
  2836. } else {
  2837. this._ids[id] = true;
  2838. addedIds.push(id);
  2839. }
  2840. } else {
  2841. if (this._ids[id]) {
  2842. delete this._ids[id];
  2843. removedIds.push(id);
  2844. removedItems.push(params.oldData[i]);
  2845. } else {
  2846. // nothing interesting for me :-(
  2847. }
  2848. }
  2849. }
  2850. break;
  2851. case 'remove':
  2852. // filter the ids of the removed items
  2853. for (i = 0, len = ids.length; i < len; i++) {
  2854. id = ids[i];
  2855. if (this._ids[id]) {
  2856. delete this._ids[id];
  2857. removedIds.push(id);
  2858. removedItems.push(params.oldData[i]);
  2859. }
  2860. }
  2861. break;
  2862. }
  2863. this.length += addedIds.length - removedIds.length;
  2864. if (addedIds.length) {
  2865. this._trigger('add', { items: addedIds }, senderId);
  2866. }
  2867. if (updatedIds.length) {
  2868. this._trigger('update', { items: updatedIds, oldData: oldItems, data: updatedItems }, senderId);
  2869. }
  2870. if (removedIds.length) {
  2871. this._trigger('remove', { items: removedIds, oldData: removedItems }, senderId);
  2872. }
  2873. }
  2874. };
  2875. // copy subscription functionality from DataSet
  2876. DataView.prototype.on = DataSet.prototype.on;
  2877. DataView.prototype.off = DataSet.prototype.off;
  2878. DataView.prototype._trigger = DataSet.prototype._trigger;
  2879. // TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)
  2880. DataView.prototype.subscribe = DataView.prototype.on;
  2881. DataView.prototype.unsubscribe = DataView.prototype.off;
  2882. module.exports = DataView;
  2883. /***/ }),
  2884. /* 13 */
  2885. /***/ (function(module, exports, __webpack_require__) {
  2886. var store = __webpack_require__(57)('wks');
  2887. var uid = __webpack_require__(40);
  2888. var Symbol = __webpack_require__(18).Symbol;
  2889. var USE_SYMBOL = typeof Symbol == 'function';
  2890. var $exports = module.exports = function (name) {
  2891. return store[name] || (store[name] =
  2892. USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
  2893. };
  2894. $exports.store = store;
  2895. /***/ }),
  2896. /* 14 */
  2897. /***/ (function(module, exports, __webpack_require__) {
  2898. "use strict";
  2899. // DOM utility methods
  2900. /**
  2901. * this prepares the JSON container for allocating SVG elements
  2902. * @param {Object} JSONcontainer
  2903. * @private
  2904. */
  2905. exports.prepareElements = function (JSONcontainer) {
  2906. // cleanup the redundant svgElements;
  2907. for (var elementType in JSONcontainer) {
  2908. if (JSONcontainer.hasOwnProperty(elementType)) {
  2909. JSONcontainer[elementType].redundant = JSONcontainer[elementType].used;
  2910. JSONcontainer[elementType].used = [];
  2911. }
  2912. }
  2913. };
  2914. /**
  2915. * this cleans up all the unused SVG elements. By asking for the parentNode, we only need to supply the JSON container from
  2916. * which to remove the redundant elements.
  2917. *
  2918. * @param {Object} JSONcontainer
  2919. * @private
  2920. */
  2921. exports.cleanupElements = function (JSONcontainer) {
  2922. // cleanup the redundant svgElements;
  2923. for (var elementType in JSONcontainer) {
  2924. if (JSONcontainer.hasOwnProperty(elementType)) {
  2925. if (JSONcontainer[elementType].redundant) {
  2926. for (var i = 0; i < JSONcontainer[elementType].redundant.length; i++) {
  2927. JSONcontainer[elementType].redundant[i].parentNode.removeChild(JSONcontainer[elementType].redundant[i]);
  2928. }
  2929. JSONcontainer[elementType].redundant = [];
  2930. }
  2931. }
  2932. }
  2933. };
  2934. /**
  2935. * Ensures that all elements are removed first up so they can be recreated cleanly
  2936. * @param {Object} JSONcontainer
  2937. */
  2938. exports.resetElements = function (JSONcontainer) {
  2939. exports.prepareElements(JSONcontainer);
  2940. exports.cleanupElements(JSONcontainer);
  2941. exports.prepareElements(JSONcontainer);
  2942. };
  2943. /**
  2944. * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
  2945. * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
  2946. *
  2947. * @param {string} elementType
  2948. * @param {Object} JSONcontainer
  2949. * @param {Object} svgContainer
  2950. * @returns {Element}
  2951. * @private
  2952. */
  2953. exports.getSVGElement = function (elementType, JSONcontainer, svgContainer) {
  2954. var element;
  2955. // allocate SVG element, if it doesnt yet exist, create one.
  2956. if (JSONcontainer.hasOwnProperty(elementType)) {
  2957. // this element has been created before
  2958. // check if there is an redundant element
  2959. if (JSONcontainer[elementType].redundant.length > 0) {
  2960. element = JSONcontainer[elementType].redundant[0];
  2961. JSONcontainer[elementType].redundant.shift();
  2962. } else {
  2963. // create a new element and add it to the SVG
  2964. element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
  2965. svgContainer.appendChild(element);
  2966. }
  2967. } else {
  2968. // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
  2969. element = document.createElementNS('http://www.w3.org/2000/svg', elementType);
  2970. JSONcontainer[elementType] = { used: [], redundant: [] };
  2971. svgContainer.appendChild(element);
  2972. }
  2973. JSONcontainer[elementType].used.push(element);
  2974. return element;
  2975. };
  2976. /**
  2977. * Allocate or generate an SVG element if needed. Store a reference to it in the JSON container and draw it in the svgContainer
  2978. * the JSON container and the SVG container have to be supplied so other svg containers (like the legend) can use this.
  2979. *
  2980. * @param {string} elementType
  2981. * @param {Object} JSONcontainer
  2982. * @param {Element} DOMContainer
  2983. * @param {Element} insertBefore
  2984. * @returns {*}
  2985. */
  2986. exports.getDOMElement = function (elementType, JSONcontainer, DOMContainer, insertBefore) {
  2987. var element;
  2988. // allocate DOM element, if it doesnt yet exist, create one.
  2989. if (JSONcontainer.hasOwnProperty(elementType)) {
  2990. // this element has been created before
  2991. // check if there is an redundant element
  2992. if (JSONcontainer[elementType].redundant.length > 0) {
  2993. element = JSONcontainer[elementType].redundant[0];
  2994. JSONcontainer[elementType].redundant.shift();
  2995. } else {
  2996. // create a new element and add it to the SVG
  2997. element = document.createElement(elementType);
  2998. if (insertBefore !== undefined) {
  2999. DOMContainer.insertBefore(element, insertBefore);
  3000. } else {
  3001. DOMContainer.appendChild(element);
  3002. }
  3003. }
  3004. } else {
  3005. // create a new element and add it to the SVG, also create a new object in the svgElements to keep track of it.
  3006. element = document.createElement(elementType);
  3007. JSONcontainer[elementType] = { used: [], redundant: [] };
  3008. if (insertBefore !== undefined) {
  3009. DOMContainer.insertBefore(element, insertBefore);
  3010. } else {
  3011. DOMContainer.appendChild(element);
  3012. }
  3013. }
  3014. JSONcontainer[elementType].used.push(element);
  3015. return element;
  3016. };
  3017. /**
  3018. * Draw a point object. This is a separate function because it can also be called by the legend.
  3019. * The reason the JSONcontainer and the target SVG svgContainer have to be supplied is so the legend can use these functions
  3020. * as well.
  3021. *
  3022. * @param {number} x
  3023. * @param {number} y
  3024. * @param {Object} groupTemplate: A template containing the necessary information to draw the datapoint e.g., {style: 'circle', size: 5, className: 'className' }
  3025. * @param {Object} JSONcontainer
  3026. * @param {Object} svgContainer
  3027. * @param {Object} labelObj
  3028. * @returns {vis.PointItem}
  3029. */
  3030. exports.drawPoint = function (x, y, groupTemplate, JSONcontainer, svgContainer, labelObj) {
  3031. var point;
  3032. if (groupTemplate.style == 'circle') {
  3033. point = exports.getSVGElement('circle', JSONcontainer, svgContainer);
  3034. point.setAttributeNS(null, "cx", x);
  3035. point.setAttributeNS(null, "cy", y);
  3036. point.setAttributeNS(null, "r", 0.5 * groupTemplate.size);
  3037. } else {
  3038. point = exports.getSVGElement('rect', JSONcontainer, svgContainer);
  3039. point.setAttributeNS(null, "x", x - 0.5 * groupTemplate.size);
  3040. point.setAttributeNS(null, "y", y - 0.5 * groupTemplate.size);
  3041. point.setAttributeNS(null, "width", groupTemplate.size);
  3042. point.setAttributeNS(null, "height", groupTemplate.size);
  3043. }
  3044. if (groupTemplate.styles !== undefined) {
  3045. point.setAttributeNS(null, "style", groupTemplate.styles);
  3046. }
  3047. point.setAttributeNS(null, "class", groupTemplate.className + " vis-point");
  3048. //handle label
  3049. if (labelObj) {
  3050. var label = exports.getSVGElement('text', JSONcontainer, svgContainer);
  3051. if (labelObj.xOffset) {
  3052. x = x + labelObj.xOffset;
  3053. }
  3054. if (labelObj.yOffset) {
  3055. y = y + labelObj.yOffset;
  3056. }
  3057. if (labelObj.content) {
  3058. label.textContent = labelObj.content;
  3059. }
  3060. if (labelObj.className) {
  3061. label.setAttributeNS(null, "class", labelObj.className + " vis-label");
  3062. }
  3063. label.setAttributeNS(null, "x", x);
  3064. label.setAttributeNS(null, "y", y);
  3065. }
  3066. return point;
  3067. };
  3068. /**
  3069. * draw a bar SVG element centered on the X coordinate
  3070. *
  3071. * @param {number} x
  3072. * @param {number} y
  3073. * @param {number} width
  3074. * @param {number} height
  3075. * @param {string} className
  3076. * @param {Object} JSONcontainer
  3077. * @param {Object} svgContainer
  3078. * @param {string} style
  3079. */
  3080. exports.drawBar = function (x, y, width, height, className, JSONcontainer, svgContainer, style) {
  3081. if (height != 0) {
  3082. if (height < 0) {
  3083. height *= -1;
  3084. y -= height;
  3085. }
  3086. var rect = exports.getSVGElement('rect', JSONcontainer, svgContainer);
  3087. rect.setAttributeNS(null, "x", x - 0.5 * width);
  3088. rect.setAttributeNS(null, "y", y);
  3089. rect.setAttributeNS(null, "width", width);
  3090. rect.setAttributeNS(null, "height", height);
  3091. rect.setAttributeNS(null, "class", className);
  3092. if (style) {
  3093. rect.setAttributeNS(null, "style", style);
  3094. }
  3095. }
  3096. };
  3097. /***/ }),
  3098. /* 15 */
  3099. /***/ (function(module, exports, __webpack_require__) {
  3100. "use strict";
  3101. Object.defineProperty(exports, "__esModule", {
  3102. value: true
  3103. });
  3104. exports.printStyle = undefined;
  3105. var _stringify = __webpack_require__(19);
  3106. var _stringify2 = _interopRequireDefault(_stringify);
  3107. var _typeof2 = __webpack_require__(6);
  3108. var _typeof3 = _interopRequireDefault(_typeof2);
  3109. var _keys = __webpack_require__(8);
  3110. var _keys2 = _interopRequireDefault(_keys);
  3111. var _classCallCheck2 = __webpack_require__(0);
  3112. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  3113. var _createClass2 = __webpack_require__(1);
  3114. var _createClass3 = _interopRequireDefault(_createClass2);
  3115. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  3116. var util = __webpack_require__(2);
  3117. var errorFound = false;
  3118. var allOptions = void 0;
  3119. var printStyle = 'background: #FFeeee; color: #dd0000';
  3120. /**
  3121. * Used to validate options.
  3122. */
  3123. var Validator = function () {
  3124. /**
  3125. * @ignore
  3126. */
  3127. function Validator() {
  3128. (0, _classCallCheck3['default'])(this, Validator);
  3129. }
  3130. /**
  3131. * Main function to be called
  3132. * @param {Object} options
  3133. * @param {Object} referenceOptions
  3134. * @param {Object} subObject
  3135. * @returns {boolean}
  3136. * @static
  3137. */
  3138. (0, _createClass3['default'])(Validator, null, [{
  3139. key: 'validate',
  3140. value: function validate(options, referenceOptions, subObject) {
  3141. errorFound = false;
  3142. allOptions = referenceOptions;
  3143. var usedOptions = referenceOptions;
  3144. if (subObject !== undefined) {
  3145. usedOptions = referenceOptions[subObject];
  3146. }
  3147. Validator.parse(options, usedOptions, []);
  3148. return errorFound;
  3149. }
  3150. /**
  3151. * Will traverse an object recursively and check every value
  3152. * @param {Object} options
  3153. * @param {Object} referenceOptions
  3154. * @param {array} path | where to look for the actual option
  3155. * @static
  3156. */
  3157. }, {
  3158. key: 'parse',
  3159. value: function parse(options, referenceOptions, path) {
  3160. for (var option in options) {
  3161. if (options.hasOwnProperty(option)) {
  3162. Validator.check(option, options, referenceOptions, path);
  3163. }
  3164. }
  3165. }
  3166. /**
  3167. * Check every value. If the value is an object, call the parse function on that object.
  3168. * @param {string} option
  3169. * @param {Object} options
  3170. * @param {Object} referenceOptions
  3171. * @param {array} path | where to look for the actual option
  3172. * @static
  3173. */
  3174. }, {
  3175. key: 'check',
  3176. value: function check(option, options, referenceOptions, path) {
  3177. if (referenceOptions[option] === undefined && referenceOptions.__any__ === undefined) {
  3178. Validator.getSuggestion(option, referenceOptions, path);
  3179. return;
  3180. }
  3181. var referenceOption = option;
  3182. var is_object = true;
  3183. if (referenceOptions[option] === undefined && referenceOptions.__any__ !== undefined) {
  3184. // NOTE: This only triggers if the __any__ is in the top level of the options object.
  3185. // THAT'S A REALLY BAD PLACE TO ALLOW IT!!!!
  3186. // TODO: Examine if needed, remove if possible
  3187. // __any__ is a wildcard. Any value is accepted and will be further analysed by reference.
  3188. referenceOption = '__any__';
  3189. // if the any-subgroup is not a predefined object in the configurator,
  3190. // we do not look deeper into the object.
  3191. is_object = Validator.getType(options[option]) === 'object';
  3192. } else {
  3193. // Since all options in the reference are objects, we can check whether
  3194. // they are supposed to be the object to look for the __type__ field.
  3195. // if this is an object, we check if the correct type has been supplied to account for shorthand options.
  3196. }
  3197. var refOptionObj = referenceOptions[referenceOption];
  3198. if (is_object && refOptionObj.__type__ !== undefined) {
  3199. refOptionObj = refOptionObj.__type__;
  3200. }
  3201. Validator.checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path);
  3202. }
  3203. /**
  3204. *
  3205. * @param {string} option | the option property
  3206. * @param {Object} options | The supplied options object
  3207. * @param {Object} referenceOptions | The reference options containing all options and their allowed formats
  3208. * @param {string} referenceOption | Usually this is the same as option, except when handling an __any__ tag.
  3209. * @param {string} refOptionObj | This is the type object from the reference options
  3210. * @param {Array} path | where in the object is the option
  3211. * @static
  3212. */
  3213. }, {
  3214. key: 'checkFields',
  3215. value: function checkFields(option, options, referenceOptions, referenceOption, refOptionObj, path) {
  3216. var log = function log(message) {
  3217. console.log('%c' + message + Validator.printLocation(path, option), printStyle);
  3218. };
  3219. var optionType = Validator.getType(options[option]);
  3220. var refOptionType = refOptionObj[optionType];
  3221. if (refOptionType !== undefined) {
  3222. // if the type is correct, we check if it is supposed to be one of a few select values
  3223. if (Validator.getType(refOptionType) === 'array' && refOptionType.indexOf(options[option]) === -1) {
  3224. log('Invalid option detected in "' + option + '".' + ' Allowed values are:' + Validator.print(refOptionType) + ' not "' + options[option] + '". ');
  3225. errorFound = true;
  3226. } else if (optionType === 'object' && referenceOption !== "__any__") {
  3227. path = util.copyAndExtendArray(path, option);
  3228. Validator.parse(options[option], referenceOptions[referenceOption], path);
  3229. }
  3230. } else if (refOptionObj['any'] === undefined) {
  3231. // type of the field is incorrect and the field cannot be any
  3232. log('Invalid type received for "' + option + '". Expected: ' + Validator.print((0, _keys2['default'])(refOptionObj)) + '. Received [' + optionType + '] "' + options[option] + '"');
  3233. errorFound = true;
  3234. }
  3235. }
  3236. /**
  3237. *
  3238. * @param {Object|boolean|number|string|Array.<number>|Date|Node|Moment|undefined|null} object
  3239. * @returns {string}
  3240. * @static
  3241. */
  3242. }, {
  3243. key: 'getType',
  3244. value: function getType(object) {
  3245. var type = typeof object === 'undefined' ? 'undefined' : (0, _typeof3['default'])(object);
  3246. if (type === 'object') {
  3247. if (object === null) {
  3248. return 'null';
  3249. }
  3250. if (object instanceof Boolean) {
  3251. return 'boolean';
  3252. }
  3253. if (object instanceof Number) {
  3254. return 'number';
  3255. }
  3256. if (object instanceof String) {
  3257. return 'string';
  3258. }
  3259. if (Array.isArray(object)) {
  3260. return 'array';
  3261. }
  3262. if (object instanceof Date) {
  3263. return 'date';
  3264. }
  3265. if (object.nodeType !== undefined) {
  3266. return 'dom';
  3267. }
  3268. if (object._isAMomentObject === true) {
  3269. return 'moment';
  3270. }
  3271. return 'object';
  3272. } else if (type === 'number') {
  3273. return 'number';
  3274. } else if (type === 'boolean') {
  3275. return 'boolean';
  3276. } else if (type === 'string') {
  3277. return 'string';
  3278. } else if (type === undefined) {
  3279. return 'undefined';
  3280. }
  3281. return type;
  3282. }
  3283. /**
  3284. * @param {string} option
  3285. * @param {Object} options
  3286. * @param {Array.<string>} path
  3287. * @static
  3288. */
  3289. }, {
  3290. key: 'getSuggestion',
  3291. value: function getSuggestion(option, options, path) {
  3292. var localSearch = Validator.findInOptions(option, options, path, false);
  3293. var globalSearch = Validator.findInOptions(option, allOptions, [], true);
  3294. var localSearchThreshold = 8;
  3295. var globalSearchThreshold = 4;
  3296. var msg = void 0;
  3297. if (localSearch.indexMatch !== undefined) {
  3298. msg = ' in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was incomplete? Did you mean: "' + localSearch.indexMatch + '"?\n\n';
  3299. } else if (globalSearch.distance <= globalSearchThreshold && localSearch.distance > globalSearch.distance) {
  3300. msg = ' in ' + Validator.printLocation(localSearch.path, option, '') + 'Perhaps it was misplaced? Matching option found at: ' + Validator.printLocation(globalSearch.path, globalSearch.closestMatch, '');
  3301. } else if (localSearch.distance <= localSearchThreshold) {
  3302. msg = '. Did you mean "' + localSearch.closestMatch + '"?' + Validator.printLocation(localSearch.path, option);
  3303. } else {
  3304. msg = '. Did you mean one of these: ' + Validator.print((0, _keys2['default'])(options)) + Validator.printLocation(path, option);
  3305. }
  3306. console.log('%cUnknown option detected: "' + option + '"' + msg, printStyle);
  3307. errorFound = true;
  3308. }
  3309. /**
  3310. * traverse the options in search for a match.
  3311. * @param {string} option
  3312. * @param {Object} options
  3313. * @param {Array} path | where to look for the actual option
  3314. * @param {boolean} [recursive=false]
  3315. * @returns {{closestMatch: string, path: Array, distance: number}}
  3316. * @static
  3317. */
  3318. }, {
  3319. key: 'findInOptions',
  3320. value: function findInOptions(option, options, path) {
  3321. var recursive = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  3322. var min = 1e9;
  3323. var closestMatch = '';
  3324. var closestMatchPath = [];
  3325. var lowerCaseOption = option.toLowerCase();
  3326. var indexMatch = undefined;
  3327. for (var op in options) {
  3328. // eslint-disable-line guard-for-in
  3329. var distance = void 0;
  3330. if (options[op].__type__ !== undefined && recursive === true) {
  3331. var result = Validator.findInOptions(option, options[op], util.copyAndExtendArray(path, op));
  3332. if (min > result.distance) {
  3333. closestMatch = result.closestMatch;
  3334. closestMatchPath = result.path;
  3335. min = result.distance;
  3336. indexMatch = result.indexMatch;
  3337. }
  3338. } else {
  3339. if (op.toLowerCase().indexOf(lowerCaseOption) !== -1) {
  3340. indexMatch = op;
  3341. }
  3342. distance = Validator.levenshteinDistance(option, op);
  3343. if (min > distance) {
  3344. closestMatch = op;
  3345. closestMatchPath = util.copyArray(path);
  3346. min = distance;
  3347. }
  3348. }
  3349. }
  3350. return { closestMatch: closestMatch, path: closestMatchPath, distance: min, indexMatch: indexMatch };
  3351. }
  3352. /**
  3353. * @param {Array.<string>} path
  3354. * @param {Object} option
  3355. * @param {string} prefix
  3356. * @returns {String}
  3357. * @static
  3358. */
  3359. }, {
  3360. key: 'printLocation',
  3361. value: function printLocation(path, option) {
  3362. var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'Problem value found at: \n';
  3363. var str = '\n\n' + prefix + 'options = {\n';
  3364. for (var i = 0; i < path.length; i++) {
  3365. for (var j = 0; j < i + 1; j++) {
  3366. str += ' ';
  3367. }
  3368. str += path[i] + ': {\n';
  3369. }
  3370. for (var _j = 0; _j < path.length + 1; _j++) {
  3371. str += ' ';
  3372. }
  3373. str += option + '\n';
  3374. for (var _i = 0; _i < path.length + 1; _i++) {
  3375. for (var _j2 = 0; _j2 < path.length - _i; _j2++) {
  3376. str += ' ';
  3377. }
  3378. str += '}\n';
  3379. }
  3380. return str + '\n\n';
  3381. }
  3382. /**
  3383. * @param {Object} options
  3384. * @returns {String}
  3385. * @static
  3386. */
  3387. }, {
  3388. key: 'print',
  3389. value: function print(options) {
  3390. return (0, _stringify2['default'])(options).replace(/(\")|(\[)|(\])|(,"__type__")/g, "").replace(/(\,)/g, ', ');
  3391. }
  3392. /**
  3393. * Compute the edit distance between the two given strings
  3394. * http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#JavaScript
  3395. *
  3396. * Copyright (c) 2011 Andrei Mackenzie
  3397. *
  3398. * 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:
  3399. *
  3400. * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  3401. *
  3402. * 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.
  3403. *
  3404. * @param {string} a
  3405. * @param {string} b
  3406. * @returns {Array.<Array.<number>>}}
  3407. * @static
  3408. */
  3409. }, {
  3410. key: 'levenshteinDistance',
  3411. value: function levenshteinDistance(a, b) {
  3412. if (a.length === 0) return b.length;
  3413. if (b.length === 0) return a.length;
  3414. var matrix = [];
  3415. // increment along the first column of each row
  3416. var i;
  3417. for (i = 0; i <= b.length; i++) {
  3418. matrix[i] = [i];
  3419. }
  3420. // increment each column in the first row
  3421. var j;
  3422. for (j = 0; j <= a.length; j++) {
  3423. matrix[0][j] = j;
  3424. }
  3425. // Fill in the rest of the matrix
  3426. for (i = 1; i <= b.length; i++) {
  3427. for (j = 1; j <= a.length; j++) {
  3428. if (b.charAt(i - 1) == a.charAt(j - 1)) {
  3429. matrix[i][j] = matrix[i - 1][j - 1];
  3430. } else {
  3431. matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
  3432. Math.min(matrix[i][j - 1] + 1, // insertion
  3433. matrix[i - 1][j] + 1)); // deletion
  3434. }
  3435. }
  3436. }
  3437. return matrix[b.length][a.length];
  3438. }
  3439. }]);
  3440. return Validator;
  3441. }();
  3442. exports['default'] = Validator;
  3443. exports.printStyle = printStyle;
  3444. /***/ }),
  3445. /* 16 */
  3446. /***/ (function(module, exports, __webpack_require__) {
  3447. "use strict";
  3448. var util = __webpack_require__(2);
  3449. /**
  3450. * Prototype for visual components
  3451. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} [body]
  3452. * @param {Object} [options]
  3453. */
  3454. function Component(body, options) {
  3455. // eslint-disable-line no-unused-vars
  3456. this.options = null;
  3457. this.props = null;
  3458. }
  3459. /**
  3460. * Set options for the component. The new options will be merged into the
  3461. * current options.
  3462. * @param {Object} options
  3463. */
  3464. Component.prototype.setOptions = function (options) {
  3465. if (options) {
  3466. util.extend(this.options, options);
  3467. }
  3468. };
  3469. /**
  3470. * Repaint the component
  3471. * @return {boolean} Returns true if the component is resized
  3472. */
  3473. Component.prototype.redraw = function () {
  3474. // should be implemented by the component
  3475. return false;
  3476. };
  3477. /**
  3478. * Destroy the component. Cleanup DOM and event listeners
  3479. */
  3480. Component.prototype.destroy = function () {
  3481. // should be implemented by the component
  3482. };
  3483. /**
  3484. * Test whether the component is resized since the last time _isResized() was
  3485. * called.
  3486. * @return {Boolean} Returns true if the component is resized
  3487. * @protected
  3488. */
  3489. Component.prototype._isResized = function () {
  3490. var resized = this.props._previousWidth !== this.props.width || this.props._previousHeight !== this.props.height;
  3491. this.props._previousWidth = this.props.width;
  3492. this.props._previousHeight = this.props.height;
  3493. return resized;
  3494. };
  3495. module.exports = Component;
  3496. /***/ }),
  3497. /* 17 */
  3498. /***/ (function(module, exports, __webpack_require__) {
  3499. var global = __webpack_require__(18);
  3500. var core = __webpack_require__(7);
  3501. var ctx = __webpack_require__(80);
  3502. var hide = __webpack_require__(26);
  3503. var PROTOTYPE = 'prototype';
  3504. var $export = function (type, name, source) {
  3505. var IS_FORCED = type & $export.F;
  3506. var IS_GLOBAL = type & $export.G;
  3507. var IS_STATIC = type & $export.S;
  3508. var IS_PROTO = type & $export.P;
  3509. var IS_BIND = type & $export.B;
  3510. var IS_WRAP = type & $export.W;
  3511. var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
  3512. var expProto = exports[PROTOTYPE];
  3513. var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
  3514. var key, own, out;
  3515. if (IS_GLOBAL) source = name;
  3516. for (key in source) {
  3517. // contains in native
  3518. own = !IS_FORCED && target && target[key] !== undefined;
  3519. if (own && key in exports) continue;
  3520. // export native or passed
  3521. out = own ? target[key] : source[key];
  3522. // prevent global pollution for namespaces
  3523. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  3524. // bind timers to global for call from export context
  3525. : IS_BIND && own ? ctx(out, global)
  3526. // wrap global constructors for prevent change them in library
  3527. : IS_WRAP && target[key] == out ? (function (C) {
  3528. var F = function (a, b, c) {
  3529. if (this instanceof C) {
  3530. switch (arguments.length) {
  3531. case 0: return new C();
  3532. case 1: return new C(a);
  3533. case 2: return new C(a, b);
  3534. } return new C(a, b, c);
  3535. } return C.apply(this, arguments);
  3536. };
  3537. F[PROTOTYPE] = C[PROTOTYPE];
  3538. return F;
  3539. // make static versions for prototype methods
  3540. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  3541. // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
  3542. if (IS_PROTO) {
  3543. (exports.virtual || (exports.virtual = {}))[key] = out;
  3544. // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
  3545. if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
  3546. }
  3547. }
  3548. };
  3549. // type bitmap
  3550. $export.F = 1; // forced
  3551. $export.G = 2; // global
  3552. $export.S = 4; // static
  3553. $export.P = 8; // proto
  3554. $export.B = 16; // bind
  3555. $export.W = 32; // wrap
  3556. $export.U = 64; // safe
  3557. $export.R = 128; // real proto method for `library`
  3558. module.exports = $export;
  3559. /***/ }),
  3560. /* 18 */
  3561. /***/ (function(module, exports) {
  3562. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  3563. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  3564. ? window : typeof self != 'undefined' && self.Math == Math ? self
  3565. // eslint-disable-next-line no-new-func
  3566. : Function('return this')();
  3567. if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
  3568. /***/ }),
  3569. /* 19 */
  3570. /***/ (function(module, exports, __webpack_require__) {
  3571. module.exports = { "default": __webpack_require__(160), __esModule: true };
  3572. /***/ }),
  3573. /* 20 */
  3574. /***/ (function(module, exports, __webpack_require__) {
  3575. var anObject = __webpack_require__(27);
  3576. var IE8_DOM_DEFINE = __webpack_require__(81);
  3577. var toPrimitive = __webpack_require__(53);
  3578. var dP = Object.defineProperty;
  3579. exports.f = __webpack_require__(21) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
  3580. anObject(O);
  3581. P = toPrimitive(P, true);
  3582. anObject(Attributes);
  3583. if (IE8_DOM_DEFINE) try {
  3584. return dP(O, P, Attributes);
  3585. } catch (e) { /* empty */ }
  3586. if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
  3587. if ('value' in Attributes) O[P] = Attributes.value;
  3588. return O;
  3589. };
  3590. /***/ }),
  3591. /* 21 */
  3592. /***/ (function(module, exports, __webpack_require__) {
  3593. // Thank's IE8 for his funny defineProperty
  3594. module.exports = !__webpack_require__(28)(function () {
  3595. return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
  3596. });
  3597. /***/ }),
  3598. /* 22 */
  3599. /***/ (function(module, exports) {
  3600. var hasOwnProperty = {}.hasOwnProperty;
  3601. module.exports = function (it, key) {
  3602. return hasOwnProperty.call(it, key);
  3603. };
  3604. /***/ }),
  3605. /* 23 */
  3606. /***/ (function(module, exports, __webpack_require__) {
  3607. "use strict";
  3608. Object.defineProperty(exports, "__esModule", {
  3609. value: true
  3610. });
  3611. var _typeof2 = __webpack_require__(6);
  3612. var _typeof3 = _interopRequireDefault(_typeof2);
  3613. var _classCallCheck2 = __webpack_require__(0);
  3614. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  3615. var _createClass2 = __webpack_require__(1);
  3616. var _createClass3 = _interopRequireDefault(_createClass2);
  3617. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  3618. /**
  3619. * The Base class for all Nodes.
  3620. */
  3621. var NodeBase = function () {
  3622. /**
  3623. * @param {Object} options
  3624. * @param {Object} body
  3625. * @param {Label} labelModule
  3626. */
  3627. function NodeBase(options, body, labelModule) {
  3628. (0, _classCallCheck3['default'])(this, NodeBase);
  3629. this.body = body;
  3630. this.labelModule = labelModule;
  3631. this.setOptions(options);
  3632. this.top = undefined;
  3633. this.left = undefined;
  3634. this.height = undefined;
  3635. this.width = undefined;
  3636. this.radius = undefined;
  3637. this.margin = undefined;
  3638. this.refreshNeeded = true;
  3639. this.boundingBox = { top: 0, left: 0, right: 0, bottom: 0 };
  3640. }
  3641. /**
  3642. *
  3643. * @param {Object} options
  3644. */
  3645. (0, _createClass3['default'])(NodeBase, [{
  3646. key: 'setOptions',
  3647. value: function setOptions(options) {
  3648. this.options = options;
  3649. }
  3650. /**
  3651. *
  3652. * @param {Label} labelModule
  3653. * @private
  3654. */
  3655. }, {
  3656. key: '_setMargins',
  3657. value: function _setMargins(labelModule) {
  3658. this.margin = {};
  3659. if (this.options.margin) {
  3660. if ((0, _typeof3['default'])(this.options.margin) == 'object') {
  3661. this.margin.top = this.options.margin.top;
  3662. this.margin.right = this.options.margin.right;
  3663. this.margin.bottom = this.options.margin.bottom;
  3664. this.margin.left = this.options.margin.left;
  3665. } else {
  3666. this.margin.top = this.options.margin;
  3667. this.margin.right = this.options.margin;
  3668. this.margin.bottom = this.options.margin;
  3669. this.margin.left = this.options.margin;
  3670. }
  3671. }
  3672. labelModule.adjustSizes(this.margin);
  3673. }
  3674. /**
  3675. *
  3676. * @param {CanvasRenderingContext2D} ctx
  3677. * @param {number} angle
  3678. * @returns {number}
  3679. * @private
  3680. */
  3681. }, {
  3682. key: '_distanceToBorder',
  3683. value: function _distanceToBorder(ctx, angle) {
  3684. var borderWidth = this.options.borderWidth;
  3685. this.resize(ctx);
  3686. return Math.min(Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  3687. }
  3688. /**
  3689. *
  3690. * @param {CanvasRenderingContext2D} ctx
  3691. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  3692. */
  3693. }, {
  3694. key: 'enableShadow',
  3695. value: function enableShadow(ctx, values) {
  3696. if (values.shadow) {
  3697. ctx.shadowColor = values.shadowColor;
  3698. ctx.shadowBlur = values.shadowSize;
  3699. ctx.shadowOffsetX = values.shadowX;
  3700. ctx.shadowOffsetY = values.shadowY;
  3701. }
  3702. }
  3703. /**
  3704. *
  3705. * @param {CanvasRenderingContext2D} ctx
  3706. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  3707. */
  3708. }, {
  3709. key: 'disableShadow',
  3710. value: function disableShadow(ctx, values) {
  3711. if (values.shadow) {
  3712. ctx.shadowColor = 'rgba(0,0,0,0)';
  3713. ctx.shadowBlur = 0;
  3714. ctx.shadowOffsetX = 0;
  3715. ctx.shadowOffsetY = 0;
  3716. }
  3717. }
  3718. /**
  3719. *
  3720. * @param {CanvasRenderingContext2D} ctx
  3721. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  3722. */
  3723. }, {
  3724. key: 'enableBorderDashes',
  3725. value: function enableBorderDashes(ctx, values) {
  3726. if (values.borderDashes !== false) {
  3727. if (ctx.setLineDash !== undefined) {
  3728. var dashes = values.borderDashes;
  3729. if (dashes === true) {
  3730. dashes = [5, 15];
  3731. }
  3732. ctx.setLineDash(dashes);
  3733. } else {
  3734. console.warn("setLineDash is not supported in this browser. The dashed borders cannot be used.");
  3735. this.options.shapeProperties.borderDashes = false;
  3736. values.borderDashes = false;
  3737. }
  3738. }
  3739. }
  3740. /**
  3741. *
  3742. * @param {CanvasRenderingContext2D} ctx
  3743. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  3744. */
  3745. }, {
  3746. key: 'disableBorderDashes',
  3747. value: function disableBorderDashes(ctx, values) {
  3748. if (values.borderDashes !== false) {
  3749. if (ctx.setLineDash !== undefined) {
  3750. ctx.setLineDash([0]);
  3751. } else {
  3752. console.warn("setLineDash is not supported in this browser. The dashed borders cannot be used.");
  3753. this.options.shapeProperties.borderDashes = false;
  3754. values.borderDashes = false;
  3755. }
  3756. }
  3757. }
  3758. /**
  3759. * Determine if the shape of a node needs to be recalculated.
  3760. *
  3761. * @param {boolean} selected
  3762. * @param {boolean} hover
  3763. * @returns {boolean}
  3764. * @protected
  3765. */
  3766. }, {
  3767. key: 'needsRefresh',
  3768. value: function needsRefresh(selected, hover) {
  3769. if (this.refreshNeeded === true) {
  3770. // This is probably not the best location to reset this member.
  3771. // However, in the current logic, it is the most convenient one.
  3772. this.refreshNeeded = false;
  3773. return true;
  3774. }
  3775. return this.width === undefined || this.labelModule.differentState(selected, hover);
  3776. }
  3777. /**
  3778. *
  3779. * @param {CanvasRenderingContext2D} ctx
  3780. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  3781. */
  3782. }, {
  3783. key: 'initContextForDraw',
  3784. value: function initContextForDraw(ctx, values) {
  3785. var borderWidth = values.borderWidth / this.body.view.scale;
  3786. ctx.lineWidth = Math.min(this.width, borderWidth);
  3787. ctx.strokeStyle = values.borderColor;
  3788. ctx.fillStyle = values.color;
  3789. }
  3790. /**
  3791. *
  3792. * @param {CanvasRenderingContext2D} ctx
  3793. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  3794. */
  3795. }, {
  3796. key: 'performStroke',
  3797. value: function performStroke(ctx, values) {
  3798. var borderWidth = values.borderWidth / this.body.view.scale;
  3799. //draw dashed border if enabled, save and restore is required for firefox not to crash on unix.
  3800. ctx.save();
  3801. // if borders are zero width, they will be drawn with width 1 by default. This prevents that
  3802. if (borderWidth > 0) {
  3803. this.enableBorderDashes(ctx, values);
  3804. //draw the border
  3805. ctx.stroke();
  3806. //disable dashed border for other elements
  3807. this.disableBorderDashes(ctx, values);
  3808. }
  3809. ctx.restore();
  3810. }
  3811. /**
  3812. *
  3813. * @param {CanvasRenderingContext2D} ctx
  3814. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  3815. */
  3816. }, {
  3817. key: 'performFill',
  3818. value: function performFill(ctx, values) {
  3819. // draw shadow if enabled
  3820. this.enableShadow(ctx, values);
  3821. // draw the background
  3822. ctx.fill();
  3823. // disable shadows for other elements.
  3824. this.disableShadow(ctx, values);
  3825. this.performStroke(ctx, values);
  3826. }
  3827. /**
  3828. *
  3829. * @param {number} margin
  3830. * @private
  3831. */
  3832. }, {
  3833. key: '_addBoundingBoxMargin',
  3834. value: function _addBoundingBoxMargin(margin) {
  3835. this.boundingBox.left -= margin;
  3836. this.boundingBox.top -= margin;
  3837. this.boundingBox.bottom += margin;
  3838. this.boundingBox.right += margin;
  3839. }
  3840. /**
  3841. * Actual implementation of this method call.
  3842. *
  3843. * Doing it like this makes it easier to override
  3844. * in the child classes.
  3845. *
  3846. * @param {number} x width
  3847. * @param {number} y height
  3848. * @param {CanvasRenderingContext2D} ctx
  3849. * @param {boolean} selected
  3850. * @param {boolean} hover
  3851. * @private
  3852. */
  3853. }, {
  3854. key: '_updateBoundingBox',
  3855. value: function _updateBoundingBox(x, y, ctx, selected, hover) {
  3856. if (ctx !== undefined) {
  3857. this.resize(ctx, selected, hover);
  3858. }
  3859. this.left = x - this.width / 2;
  3860. this.top = y - this.height / 2;
  3861. this.boundingBox.left = this.left;
  3862. this.boundingBox.top = this.top;
  3863. this.boundingBox.bottom = this.top + this.height;
  3864. this.boundingBox.right = this.left + this.width;
  3865. }
  3866. /**
  3867. * Default implementation of this method call.
  3868. * This acts as a stub which can be overridden.
  3869. *
  3870. * @param {number} x width
  3871. * @param {number} y height
  3872. * @param {CanvasRenderingContext2D} ctx
  3873. * @param {boolean} selected
  3874. * @param {boolean} hover
  3875. */
  3876. }, {
  3877. key: 'updateBoundingBox',
  3878. value: function updateBoundingBox(x, y, ctx, selected, hover) {
  3879. this._updateBoundingBox(x, y, ctx, selected, hover);
  3880. }
  3881. /**
  3882. * Determine the dimensions to use for nodes with an internal label
  3883. *
  3884. * Currently, these are: Circle, Ellipse, Database, Box
  3885. * The other nodes have external labels, and will not call this method
  3886. *
  3887. * If there is no label, decent default values are supplied.
  3888. *
  3889. * @param {CanvasRenderingContext2D} ctx
  3890. * @param {boolean} [selected]
  3891. * @param {boolean} [hover]
  3892. * @returns {{width:number, height:number}}
  3893. */
  3894. }, {
  3895. key: 'getDimensionsFromLabel',
  3896. value: function getDimensionsFromLabel(ctx, selected, hover) {
  3897. // NOTE: previously 'textSize' was not put in 'this' for Ellipse
  3898. // TODO: examine the consequences.
  3899. this.textSize = this.labelModule.getTextSize(ctx, selected, hover);
  3900. var width = this.textSize.width;
  3901. var height = this.textSize.height;
  3902. var DEFAULT_SIZE = 14;
  3903. if (width === 0) {
  3904. // This happens when there is no label text set
  3905. width = DEFAULT_SIZE; // use a decent default
  3906. height = DEFAULT_SIZE; // if width zero, then height also always zero
  3907. }
  3908. return { width: width, height: height };
  3909. }
  3910. }]);
  3911. return NodeBase;
  3912. }();
  3913. exports['default'] = NodeBase;
  3914. /***/ }),
  3915. /* 24 */
  3916. /***/ (function(module, exports, __webpack_require__) {
  3917. "use strict";
  3918. Object.defineProperty(exports, "__esModule", {
  3919. value: true
  3920. });
  3921. var _getPrototypeOf = __webpack_require__(3);
  3922. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  3923. var _classCallCheck2 = __webpack_require__(0);
  3924. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  3925. var _createClass2 = __webpack_require__(1);
  3926. var _createClass3 = _interopRequireDefault(_createClass2);
  3927. var _possibleConstructorReturn2 = __webpack_require__(4);
  3928. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  3929. var _inherits2 = __webpack_require__(5);
  3930. var _inherits3 = _interopRequireDefault(_inherits2);
  3931. var _NodeBase2 = __webpack_require__(23);
  3932. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  3933. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  3934. /**
  3935. * Base class for constructing Node/Cluster Shapes.
  3936. *
  3937. * @extends NodeBase
  3938. */
  3939. var ShapeBase = function (_NodeBase) {
  3940. (0, _inherits3['default'])(ShapeBase, _NodeBase);
  3941. /**
  3942. * @param {Object} options
  3943. * @param {Object} body
  3944. * @param {Label} labelModule
  3945. */
  3946. function ShapeBase(options, body, labelModule) {
  3947. (0, _classCallCheck3['default'])(this, ShapeBase);
  3948. return (0, _possibleConstructorReturn3['default'])(this, (ShapeBase.__proto__ || (0, _getPrototypeOf2['default'])(ShapeBase)).call(this, options, body, labelModule));
  3949. }
  3950. /**
  3951. *
  3952. * @param {CanvasRenderingContext2D} ctx
  3953. * @param {boolean} [selected]
  3954. * @param {boolean} [hover]
  3955. * @param {Object} [values={size: this.options.size}]
  3956. */
  3957. (0, _createClass3['default'])(ShapeBase, [{
  3958. key: 'resize',
  3959. value: function resize(ctx) {
  3960. var selected = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.selected;
  3961. var hover = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.hover;
  3962. var values = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { size: this.options.size };
  3963. if (this.needsRefresh(selected, hover)) {
  3964. this.labelModule.getTextSize(ctx, selected, hover);
  3965. var size = 2 * values.size;
  3966. this.width = size;
  3967. this.height = size;
  3968. this.radius = 0.5 * this.width;
  3969. }
  3970. }
  3971. /**
  3972. *
  3973. * @param {CanvasRenderingContext2D} ctx
  3974. * @param {string} shape
  3975. * @param {number} sizeMultiplier - Unused! TODO: Remove next major release
  3976. * @param {number} x
  3977. * @param {number} y
  3978. * @param {boolean} selected
  3979. * @param {boolean} hover
  3980. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  3981. * @private
  3982. */
  3983. }, {
  3984. key: '_drawShape',
  3985. value: function _drawShape(ctx, shape, sizeMultiplier, x, y, selected, hover, values) {
  3986. this.resize(ctx, selected, hover, values);
  3987. this.left = x - this.width / 2;
  3988. this.top = y - this.height / 2;
  3989. this.initContextForDraw(ctx, values);
  3990. ctx[shape](x, y, values.size);
  3991. this.performFill(ctx, values);
  3992. if (this.options.label !== undefined) {
  3993. // Need to call following here in order to ensure value for `this.labelModule.size.height`
  3994. this.labelModule.calculateLabelSize(ctx, selected, hover, x, y, 'hanging');
  3995. var yLabel = y + 0.5 * this.height + 0.5 * this.labelModule.size.height;
  3996. this.labelModule.draw(ctx, x, yLabel, selected, hover, 'hanging');
  3997. }
  3998. this.updateBoundingBox(x, y);
  3999. }
  4000. /**
  4001. *
  4002. * @param {number} x
  4003. * @param {number} y
  4004. */
  4005. }, {
  4006. key: 'updateBoundingBox',
  4007. value: function updateBoundingBox(x, y) {
  4008. this.boundingBox.top = y - this.options.size;
  4009. this.boundingBox.left = x - this.options.size;
  4010. this.boundingBox.right = x + this.options.size;
  4011. this.boundingBox.bottom = y + this.options.size;
  4012. if (this.options.label !== undefined && this.labelModule.size.width > 0) {
  4013. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left);
  4014. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width);
  4015. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelModule.size.height);
  4016. }
  4017. }
  4018. }]);
  4019. return ShapeBase;
  4020. }(_NodeBase3['default']);
  4021. exports['default'] = ShapeBase;
  4022. /***/ }),
  4023. /* 25 */
  4024. /***/ (function(module, exports, __webpack_require__) {
  4025. // to indexed object, toObject with fallback for non-array-like ES3 strings
  4026. var IObject = __webpack_require__(78);
  4027. var defined = __webpack_require__(51);
  4028. module.exports = function (it) {
  4029. return IObject(defined(it));
  4030. };
  4031. /***/ }),
  4032. /* 26 */
  4033. /***/ (function(module, exports, __webpack_require__) {
  4034. var dP = __webpack_require__(20);
  4035. var createDesc = __webpack_require__(39);
  4036. module.exports = __webpack_require__(21) ? function (object, key, value) {
  4037. return dP.f(object, key, createDesc(1, value));
  4038. } : function (object, key, value) {
  4039. object[key] = value;
  4040. return object;
  4041. };
  4042. /***/ }),
  4043. /* 27 */
  4044. /***/ (function(module, exports, __webpack_require__) {
  4045. var isObject = __webpack_require__(32);
  4046. module.exports = function (it) {
  4047. if (!isObject(it)) throw TypeError(it + ' is not an object!');
  4048. return it;
  4049. };
  4050. /***/ }),
  4051. /* 28 */
  4052. /***/ (function(module, exports) {
  4053. module.exports = function (exec) {
  4054. try {
  4055. return !!exec();
  4056. } catch (e) {
  4057. return true;
  4058. }
  4059. };
  4060. /***/ }),
  4061. /* 29 */
  4062. /***/ (function(module, exports, __webpack_require__) {
  4063. module.exports = { "default": __webpack_require__(138), __esModule: true };
  4064. /***/ }),
  4065. /* 30 */
  4066. /***/ (function(module, exports, __webpack_require__) {
  4067. "use strict";
  4068. exports.__esModule = true;
  4069. var _isIterable2 = __webpack_require__(188);
  4070. var _isIterable3 = _interopRequireDefault(_isIterable2);
  4071. var _getIterator2 = __webpack_require__(77);
  4072. var _getIterator3 = _interopRequireDefault(_getIterator2);
  4073. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  4074. exports.default = function () {
  4075. function sliceIterator(arr, i) {
  4076. var _arr = [];
  4077. var _n = true;
  4078. var _d = false;
  4079. var _e = undefined;
  4080. try {
  4081. for (var _i = (0, _getIterator3.default)(arr), _s; !(_n = (_s = _i.next()).done); _n = true) {
  4082. _arr.push(_s.value);
  4083. if (i && _arr.length === i) break;
  4084. }
  4085. } catch (err) {
  4086. _d = true;
  4087. _e = err;
  4088. } finally {
  4089. try {
  4090. if (!_n && _i["return"]) _i["return"]();
  4091. } finally {
  4092. if (_d) throw _e;
  4093. }
  4094. }
  4095. return _arr;
  4096. }
  4097. return function (arr, i) {
  4098. if (Array.isArray(arr)) {
  4099. return arr;
  4100. } else if ((0, _isIterable3.default)(Object(arr))) {
  4101. return sliceIterator(arr, i);
  4102. } else {
  4103. throw new TypeError("Invalid attempt to destructure non-iterable instance");
  4104. }
  4105. };
  4106. }();
  4107. /***/ }),
  4108. /* 31 */
  4109. /***/ (function(module, exports) {
  4110. module.exports = {};
  4111. /***/ }),
  4112. /* 32 */
  4113. /***/ (function(module, exports) {
  4114. module.exports = function (it) {
  4115. return typeof it === 'object' ? it !== null : typeof it === 'function';
  4116. };
  4117. /***/ }),
  4118. /* 33 */
  4119. /***/ (function(module, exports, __webpack_require__) {
  4120. // 19.1.2.14 / 15.2.3.14 Object.keys(O)
  4121. var $keys = __webpack_require__(84);
  4122. var enumBugKeys = __webpack_require__(58);
  4123. module.exports = Object.keys || function keys(O) {
  4124. return $keys(O, enumBugKeys);
  4125. };
  4126. /***/ }),
  4127. /* 34 */
  4128. /***/ (function(module, exports, __webpack_require__) {
  4129. "use strict";
  4130. /**
  4131. * @prototype Point3d
  4132. * @param {number} [x]
  4133. * @param {number} [y]
  4134. * @param {number} [z]
  4135. */
  4136. function Point3d(x, y, z) {
  4137. this.x = x !== undefined ? x : 0;
  4138. this.y = y !== undefined ? y : 0;
  4139. this.z = z !== undefined ? z : 0;
  4140. }
  4141. /**
  4142. * Subtract the two provided points, returns a-b
  4143. * @param {Point3d} a
  4144. * @param {Point3d} b
  4145. * @return {Point3d} a-b
  4146. */
  4147. Point3d.subtract = function (a, b) {
  4148. var sub = new Point3d();
  4149. sub.x = a.x - b.x;
  4150. sub.y = a.y - b.y;
  4151. sub.z = a.z - b.z;
  4152. return sub;
  4153. };
  4154. /**
  4155. * Add the two provided points, returns a+b
  4156. * @param {Point3d} a
  4157. * @param {Point3d} b
  4158. * @return {Point3d} a+b
  4159. */
  4160. Point3d.add = function (a, b) {
  4161. var sum = new Point3d();
  4162. sum.x = a.x + b.x;
  4163. sum.y = a.y + b.y;
  4164. sum.z = a.z + b.z;
  4165. return sum;
  4166. };
  4167. /**
  4168. * Calculate the average of two 3d points
  4169. * @param {Point3d} a
  4170. * @param {Point3d} b
  4171. * @return {Point3d} The average, (a+b)/2
  4172. */
  4173. Point3d.avg = function (a, b) {
  4174. return new Point3d((a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2);
  4175. };
  4176. /**
  4177. * Calculate the cross product of the two provided points, returns axb
  4178. * Documentation: http://en.wikipedia.org/wiki/Cross_product
  4179. * @param {Point3d} a
  4180. * @param {Point3d} b
  4181. * @return {Point3d} cross product axb
  4182. */
  4183. Point3d.crossProduct = function (a, b) {
  4184. var crossproduct = new Point3d();
  4185. crossproduct.x = a.y * b.z - a.z * b.y;
  4186. crossproduct.y = a.z * b.x - a.x * b.z;
  4187. crossproduct.z = a.x * b.y - a.y * b.x;
  4188. return crossproduct;
  4189. };
  4190. /**
  4191. * Rtrieve the length of the vector (or the distance from this point to the origin
  4192. * @return {number} length
  4193. */
  4194. Point3d.prototype.length = function () {
  4195. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  4196. };
  4197. module.exports = Point3d;
  4198. /***/ }),
  4199. /* 35 */
  4200. /***/ (function(module, exports, __webpack_require__) {
  4201. "use strict";
  4202. var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
  4203. /**
  4204. * Created by Alex on 11/6/2014.
  4205. */
  4206. // https://github.com/umdjs/umd/blob/master/returnExports.js#L40-L60
  4207. // if the module has no dependencies, the above pattern can be simplified to
  4208. (function (root, factory) {
  4209. if (true) {
  4210. // AMD. Register as an anonymous module.
  4211. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
  4212. __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
  4213. (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
  4214. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  4215. } else if (typeof exports === 'object') {
  4216. // Node. Does not work with strict CommonJS, but
  4217. // only CommonJS-like environments that support module.exports,
  4218. // like Node.
  4219. module.exports = factory();
  4220. } else {
  4221. // Browser globals (root is window)
  4222. root.keycharm = factory();
  4223. }
  4224. }(this, function () {
  4225. function keycharm(options) {
  4226. var preventDefault = options && options.preventDefault || false;
  4227. var container = options && options.container || window;
  4228. var _exportFunctions = {};
  4229. var _bound = {keydown:{}, keyup:{}};
  4230. var _keys = {};
  4231. var i;
  4232. // a - z
  4233. for (i = 97; i <= 122; i++) {_keys[String.fromCharCode(i)] = {code:65 + (i - 97), shift: false};}
  4234. // A - Z
  4235. for (i = 65; i <= 90; i++) {_keys[String.fromCharCode(i)] = {code:i, shift: true};}
  4236. // 0 - 9
  4237. for (i = 0; i <= 9; i++) {_keys['' + i] = {code:48 + i, shift: false};}
  4238. // F1 - F12
  4239. for (i = 1; i <= 12; i++) {_keys['F' + i] = {code:111 + i, shift: false};}
  4240. // num0 - num9
  4241. for (i = 0; i <= 9; i++) {_keys['num' + i] = {code:96 + i, shift: false};}
  4242. // numpad misc
  4243. _keys['num*'] = {code:106, shift: false};
  4244. _keys['num+'] = {code:107, shift: false};
  4245. _keys['num-'] = {code:109, shift: false};
  4246. _keys['num/'] = {code:111, shift: false};
  4247. _keys['num.'] = {code:110, shift: false};
  4248. // arrows
  4249. _keys['left'] = {code:37, shift: false};
  4250. _keys['up'] = {code:38, shift: false};
  4251. _keys['right'] = {code:39, shift: false};
  4252. _keys['down'] = {code:40, shift: false};
  4253. // extra keys
  4254. _keys['space'] = {code:32, shift: false};
  4255. _keys['enter'] = {code:13, shift: false};
  4256. _keys['shift'] = {code:16, shift: undefined};
  4257. _keys['esc'] = {code:27, shift: false};
  4258. _keys['backspace'] = {code:8, shift: false};
  4259. _keys['tab'] = {code:9, shift: false};
  4260. _keys['ctrl'] = {code:17, shift: false};
  4261. _keys['alt'] = {code:18, shift: false};
  4262. _keys['delete'] = {code:46, shift: false};
  4263. _keys['pageup'] = {code:33, shift: false};
  4264. _keys['pagedown'] = {code:34, shift: false};
  4265. // symbols
  4266. _keys['='] = {code:187, shift: false};
  4267. _keys['-'] = {code:189, shift: false};
  4268. _keys[']'] = {code:221, shift: false};
  4269. _keys['['] = {code:219, shift: false};
  4270. var down = function(event) {handleEvent(event,'keydown');};
  4271. var up = function(event) {handleEvent(event,'keyup');};
  4272. // handle the actualy bound key with the event
  4273. var handleEvent = function(event,type) {
  4274. if (_bound[type][event.keyCode] !== undefined) {
  4275. var bound = _bound[type][event.keyCode];
  4276. for (var i = 0; i < bound.length; i++) {
  4277. if (bound[i].shift === undefined) {
  4278. bound[i].fn(event);
  4279. }
  4280. else if (bound[i].shift == true && event.shiftKey == true) {
  4281. bound[i].fn(event);
  4282. }
  4283. else if (bound[i].shift == false && event.shiftKey == false) {
  4284. bound[i].fn(event);
  4285. }
  4286. }
  4287. if (preventDefault == true) {
  4288. event.preventDefault();
  4289. }
  4290. }
  4291. };
  4292. // bind a key to a callback
  4293. _exportFunctions.bind = function(key, callback, type) {
  4294. if (type === undefined) {
  4295. type = 'keydown';
  4296. }
  4297. if (_keys[key] === undefined) {
  4298. throw new Error("unsupported key: " + key);
  4299. }
  4300. if (_bound[type][_keys[key].code] === undefined) {
  4301. _bound[type][_keys[key].code] = [];
  4302. }
  4303. _bound[type][_keys[key].code].push({fn:callback, shift:_keys[key].shift});
  4304. };
  4305. // bind all keys to a call back (demo purposes)
  4306. _exportFunctions.bindAll = function(callback, type) {
  4307. if (type === undefined) {
  4308. type = 'keydown';
  4309. }
  4310. for (var key in _keys) {
  4311. if (_keys.hasOwnProperty(key)) {
  4312. _exportFunctions.bind(key,callback,type);
  4313. }
  4314. }
  4315. };
  4316. // get the key label from an event
  4317. _exportFunctions.getKey = function(event) {
  4318. for (var key in _keys) {
  4319. if (_keys.hasOwnProperty(key)) {
  4320. if (event.shiftKey == true && _keys[key].shift == true && event.keyCode == _keys[key].code) {
  4321. return key;
  4322. }
  4323. else if (event.shiftKey == false && _keys[key].shift == false && event.keyCode == _keys[key].code) {
  4324. return key;
  4325. }
  4326. else if (event.keyCode == _keys[key].code && key == 'shift') {
  4327. return key;
  4328. }
  4329. }
  4330. }
  4331. return "unknown key, currently not supported";
  4332. };
  4333. // unbind either a specific callback from a key or all of them (by leaving callback undefined)
  4334. _exportFunctions.unbind = function(key, callback, type) {
  4335. if (type === undefined) {
  4336. type = 'keydown';
  4337. }
  4338. if (_keys[key] === undefined) {
  4339. throw new Error("unsupported key: " + key);
  4340. }
  4341. if (callback !== undefined) {
  4342. var newBindings = [];
  4343. var bound = _bound[type][_keys[key].code];
  4344. if (bound !== undefined) {
  4345. for (var i = 0; i < bound.length; i++) {
  4346. if (!(bound[i].fn == callback && bound[i].shift == _keys[key].shift)) {
  4347. newBindings.push(_bound[type][_keys[key].code][i]);
  4348. }
  4349. }
  4350. }
  4351. _bound[type][_keys[key].code] = newBindings;
  4352. }
  4353. else {
  4354. _bound[type][_keys[key].code] = [];
  4355. }
  4356. };
  4357. // reset all bound variables.
  4358. _exportFunctions.reset = function() {
  4359. _bound = {keydown:{}, keyup:{}};
  4360. };
  4361. // unbind all listeners and reset all variables.
  4362. _exportFunctions.destroy = function() {
  4363. _bound = {keydown:{}, keyup:{}};
  4364. container.removeEventListener('keydown', down, true);
  4365. container.removeEventListener('keyup', up, true);
  4366. };
  4367. // create listeners.
  4368. container.addEventListener('keydown',down,true);
  4369. container.addEventListener('keyup',up,true);
  4370. // return the public functions.
  4371. return _exportFunctions;
  4372. }
  4373. return keycharm;
  4374. }));
  4375. /***/ }),
  4376. /* 36 */
  4377. /***/ (function(module, exports, __webpack_require__) {
  4378. "use strict";
  4379. /**
  4380. * used in Core to convert the options into a volatile variable
  4381. *
  4382. * @param {function} moment
  4383. * @param {Object} body
  4384. * @param {Array | Object} hiddenDates
  4385. * @returns {number}
  4386. */
  4387. exports.convertHiddenOptions = function (moment, body, hiddenDates) {
  4388. if (hiddenDates && !Array.isArray(hiddenDates)) {
  4389. return exports.convertHiddenOptions(moment, body, [hiddenDates]);
  4390. }
  4391. body.hiddenDates = [];
  4392. if (hiddenDates) {
  4393. if (Array.isArray(hiddenDates) == true) {
  4394. for (var i = 0; i < hiddenDates.length; i++) {
  4395. if (hiddenDates[i].repeat === undefined) {
  4396. var dateItem = {};
  4397. dateItem.start = moment(hiddenDates[i].start).toDate().valueOf();
  4398. dateItem.end = moment(hiddenDates[i].end).toDate().valueOf();
  4399. body.hiddenDates.push(dateItem);
  4400. }
  4401. }
  4402. body.hiddenDates.sort(function (a, b) {
  4403. return a.start - b.start;
  4404. }); // sort by start time
  4405. }
  4406. }
  4407. };
  4408. /**
  4409. * create new entrees for the repeating hidden dates
  4410. *
  4411. * @param {function} moment
  4412. * @param {Object} body
  4413. * @param {Array | Object} hiddenDates
  4414. * @returns {null}
  4415. */
  4416. exports.updateHiddenDates = function (moment, body, hiddenDates) {
  4417. if (hiddenDates && !Array.isArray(hiddenDates)) {
  4418. return exports.updateHiddenDates(moment, body, [hiddenDates]);
  4419. }
  4420. if (hiddenDates && body.domProps.centerContainer.width !== undefined) {
  4421. exports.convertHiddenOptions(moment, body, hiddenDates);
  4422. var start = moment(body.range.start);
  4423. var end = moment(body.range.end);
  4424. var totalRange = body.range.end - body.range.start;
  4425. var pixelTime = totalRange / body.domProps.centerContainer.width;
  4426. for (var i = 0; i < hiddenDates.length; i++) {
  4427. if (hiddenDates[i].repeat !== undefined) {
  4428. var startDate = moment(hiddenDates[i].start);
  4429. var endDate = moment(hiddenDates[i].end);
  4430. if (startDate._d == "Invalid Date") {
  4431. throw new Error("Supplied start date is not valid: " + hiddenDates[i].start);
  4432. }
  4433. if (endDate._d == "Invalid Date") {
  4434. throw new Error("Supplied end date is not valid: " + hiddenDates[i].end);
  4435. }
  4436. var duration = endDate - startDate;
  4437. if (duration >= 4 * pixelTime) {
  4438. var offset = 0;
  4439. var runUntil = end.clone();
  4440. switch (hiddenDates[i].repeat) {
  4441. case "daily":
  4442. // case of time
  4443. if (startDate.day() != endDate.day()) {
  4444. offset = 1;
  4445. }
  4446. startDate.dayOfYear(start.dayOfYear());
  4447. startDate.year(start.year());
  4448. startDate.subtract(7, 'days');
  4449. endDate.dayOfYear(start.dayOfYear());
  4450. endDate.year(start.year());
  4451. endDate.subtract(7 - offset, 'days');
  4452. runUntil.add(1, 'weeks');
  4453. break;
  4454. case "weekly":
  4455. var dayOffset = endDate.diff(startDate, 'days');
  4456. var day = startDate.day();
  4457. // set the start date to the range.start
  4458. startDate.date(start.date());
  4459. startDate.month(start.month());
  4460. startDate.year(start.year());
  4461. endDate = startDate.clone();
  4462. // force
  4463. startDate.day(day);
  4464. endDate.day(day);
  4465. endDate.add(dayOffset, 'days');
  4466. startDate.subtract(1, 'weeks');
  4467. endDate.subtract(1, 'weeks');
  4468. runUntil.add(1, 'weeks');
  4469. break;
  4470. case "monthly":
  4471. if (startDate.month() != endDate.month()) {
  4472. offset = 1;
  4473. }
  4474. startDate.month(start.month());
  4475. startDate.year(start.year());
  4476. startDate.subtract(1, 'months');
  4477. endDate.month(start.month());
  4478. endDate.year(start.year());
  4479. endDate.subtract(1, 'months');
  4480. endDate.add(offset, 'months');
  4481. runUntil.add(1, 'months');
  4482. break;
  4483. case "yearly":
  4484. if (startDate.year() != endDate.year()) {
  4485. offset = 1;
  4486. }
  4487. startDate.year(start.year());
  4488. startDate.subtract(1, 'years');
  4489. endDate.year(start.year());
  4490. endDate.subtract(1, 'years');
  4491. endDate.add(offset, 'years');
  4492. runUntil.add(1, 'years');
  4493. break;
  4494. default:
  4495. console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
  4496. return;
  4497. }
  4498. while (startDate < runUntil) {
  4499. body.hiddenDates.push({ start: startDate.valueOf(), end: endDate.valueOf() });
  4500. switch (hiddenDates[i].repeat) {
  4501. case "daily":
  4502. startDate.add(1, 'days');
  4503. endDate.add(1, 'days');
  4504. break;
  4505. case "weekly":
  4506. startDate.add(1, 'weeks');
  4507. endDate.add(1, 'weeks');
  4508. break;
  4509. case "monthly":
  4510. startDate.add(1, 'months');
  4511. endDate.add(1, 'months');
  4512. break;
  4513. case "yearly":
  4514. startDate.add(1, 'y');
  4515. endDate.add(1, 'y');
  4516. break;
  4517. default:
  4518. console.log("Wrong repeat format, allowed are: daily, weekly, monthly, yearly. Given:", hiddenDates[i].repeat);
  4519. return;
  4520. }
  4521. }
  4522. body.hiddenDates.push({ start: startDate.valueOf(), end: endDate.valueOf() });
  4523. }
  4524. }
  4525. }
  4526. // remove duplicates, merge where possible
  4527. exports.removeDuplicates(body);
  4528. // ensure the new positions are not on hidden dates
  4529. var startHidden = exports.isHidden(body.range.start, body.hiddenDates);
  4530. var endHidden = exports.isHidden(body.range.end, body.hiddenDates);
  4531. var rangeStart = body.range.start;
  4532. var rangeEnd = body.range.end;
  4533. if (startHidden.hidden == true) {
  4534. rangeStart = body.range.startToFront == true ? startHidden.startDate - 1 : startHidden.endDate + 1;
  4535. }
  4536. if (endHidden.hidden == true) {
  4537. rangeEnd = body.range.endToFront == true ? endHidden.startDate - 1 : endHidden.endDate + 1;
  4538. }
  4539. if (startHidden.hidden == true || endHidden.hidden == true) {
  4540. body.range._applyRange(rangeStart, rangeEnd);
  4541. }
  4542. }
  4543. };
  4544. /**
  4545. * remove duplicates from the hidden dates list. Duplicates are evil. They mess everything up.
  4546. * Scales with N^2
  4547. *
  4548. * @param {Object} body
  4549. */
  4550. exports.removeDuplicates = function (body) {
  4551. var hiddenDates = body.hiddenDates;
  4552. var safeDates = [];
  4553. for (var i = 0; i < hiddenDates.length; i++) {
  4554. for (var j = 0; j < hiddenDates.length; j++) {
  4555. if (i != j && hiddenDates[j].remove != true && hiddenDates[i].remove != true) {
  4556. // j inside i
  4557. if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
  4558. hiddenDates[j].remove = true;
  4559. }
  4560. // j start inside i
  4561. else if (hiddenDates[j].start >= hiddenDates[i].start && hiddenDates[j].start <= hiddenDates[i].end) {
  4562. hiddenDates[i].end = hiddenDates[j].end;
  4563. hiddenDates[j].remove = true;
  4564. }
  4565. // j end inside i
  4566. else if (hiddenDates[j].end >= hiddenDates[i].start && hiddenDates[j].end <= hiddenDates[i].end) {
  4567. hiddenDates[i].start = hiddenDates[j].start;
  4568. hiddenDates[j].remove = true;
  4569. }
  4570. }
  4571. }
  4572. }
  4573. for (i = 0; i < hiddenDates.length; i++) {
  4574. if (hiddenDates[i].remove !== true) {
  4575. safeDates.push(hiddenDates[i]);
  4576. }
  4577. }
  4578. body.hiddenDates = safeDates;
  4579. body.hiddenDates.sort(function (a, b) {
  4580. return a.start - b.start;
  4581. }); // sort by start time
  4582. };
  4583. exports.printDates = function (dates) {
  4584. for (var i = 0; i < dates.length; i++) {
  4585. console.log(i, new Date(dates[i].start), new Date(dates[i].end), dates[i].start, dates[i].end, dates[i].remove);
  4586. }
  4587. };
  4588. /**
  4589. * Used in TimeStep to avoid the hidden times.
  4590. * @param {function} moment
  4591. * @param {TimeStep} timeStep
  4592. * @param {Date} previousTime
  4593. */
  4594. exports.stepOverHiddenDates = function (moment, timeStep, previousTime) {
  4595. var stepInHidden = false;
  4596. var currentValue = timeStep.current.valueOf();
  4597. for (var i = 0; i < timeStep.hiddenDates.length; i++) {
  4598. var startDate = timeStep.hiddenDates[i].start;
  4599. var endDate = timeStep.hiddenDates[i].end;
  4600. if (currentValue >= startDate && currentValue < endDate) {
  4601. stepInHidden = true;
  4602. break;
  4603. }
  4604. }
  4605. if (stepInHidden == true && currentValue < timeStep._end.valueOf() && currentValue != previousTime) {
  4606. var prevValue = moment(previousTime);
  4607. var newValue = moment(endDate);
  4608. //check if the next step should be major
  4609. if (prevValue.year() != newValue.year()) {
  4610. timeStep.switchedYear = true;
  4611. } else if (prevValue.month() != newValue.month()) {
  4612. timeStep.switchedMonth = true;
  4613. } else if (prevValue.dayOfYear() != newValue.dayOfYear()) {
  4614. timeStep.switchedDay = true;
  4615. }
  4616. timeStep.current = newValue;
  4617. }
  4618. };
  4619. ///**
  4620. // * Used in TimeStep to avoid the hidden times.
  4621. // * @param timeStep
  4622. // * @param previousTime
  4623. // */
  4624. //exports.checkFirstStep = function(timeStep) {
  4625. // var stepInHidden = false;
  4626. // var currentValue = timeStep.current.valueOf();
  4627. // for (var i = 0; i < timeStep.hiddenDates.length; i++) {
  4628. // var startDate = timeStep.hiddenDates[i].start;
  4629. // var endDate = timeStep.hiddenDates[i].end;
  4630. // if (currentValue >= startDate && currentValue < endDate) {
  4631. // stepInHidden = true;
  4632. // break;
  4633. // }
  4634. // }
  4635. //
  4636. // if (stepInHidden == true && currentValue <= timeStep._end.valueOf()) {
  4637. // var newValue = moment(endDate);
  4638. // timeStep.current = newValue.toDate();
  4639. // }
  4640. //};
  4641. /**
  4642. * replaces the Core toScreen methods
  4643. *
  4644. * @param {vis.Core} Core
  4645. * @param {Date} time
  4646. * @param {number} width
  4647. * @returns {number}
  4648. */
  4649. exports.toScreen = function (Core, time, width) {
  4650. var conversion;
  4651. if (Core.body.hiddenDates.length == 0) {
  4652. conversion = Core.range.conversion(width);
  4653. return (time.valueOf() - conversion.offset) * conversion.scale;
  4654. } else {
  4655. var hidden = exports.isHidden(time, Core.body.hiddenDates);
  4656. if (hidden.hidden == true) {
  4657. time = hidden.startDate;
  4658. }
  4659. var duration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
  4660. if (time < Core.range.start) {
  4661. conversion = Core.range.conversion(width, duration);
  4662. var hiddenBeforeStart = exports.getHiddenDurationBeforeStart(Core.body.hiddenDates, time, conversion.offset);
  4663. time = Core.options.moment(time).toDate().valueOf();
  4664. time = time + hiddenBeforeStart;
  4665. return -(conversion.offset - time.valueOf()) * conversion.scale;
  4666. } else if (time > Core.range.end) {
  4667. var rangeAfterEnd = { start: Core.range.start, end: time };
  4668. time = exports.correctTimeForHidden(Core.options.moment, Core.body.hiddenDates, rangeAfterEnd, time);
  4669. conversion = Core.range.conversion(width, duration);
  4670. return (time.valueOf() - conversion.offset) * conversion.scale;
  4671. } else {
  4672. time = exports.correctTimeForHidden(Core.options.moment, Core.body.hiddenDates, Core.range, time);
  4673. conversion = Core.range.conversion(width, duration);
  4674. return (time.valueOf() - conversion.offset) * conversion.scale;
  4675. }
  4676. }
  4677. };
  4678. /**
  4679. * Replaces the core toTime methods
  4680. *
  4681. * @param {vis.Core} Core
  4682. * @param {number} x
  4683. * @param {number} width
  4684. * @returns {Date}
  4685. */
  4686. exports.toTime = function (Core, x, width) {
  4687. if (Core.body.hiddenDates.length == 0) {
  4688. var conversion = Core.range.conversion(width);
  4689. return new Date(x / conversion.scale + conversion.offset);
  4690. } else {
  4691. var hiddenDuration = exports.getHiddenDurationBetween(Core.body.hiddenDates, Core.range.start, Core.range.end);
  4692. var totalDuration = Core.range.end - Core.range.start - hiddenDuration;
  4693. var partialDuration = totalDuration * x / width;
  4694. var accumulatedHiddenDuration = exports.getAccumulatedHiddenDuration(Core.body.hiddenDates, Core.range, partialDuration);
  4695. return new Date(accumulatedHiddenDuration + partialDuration + Core.range.start);
  4696. }
  4697. };
  4698. /**
  4699. * Support function
  4700. *
  4701. * @param {Array.<{start: Window.start, end: *}>} hiddenDates
  4702. * @param {number} start
  4703. * @param {number} end
  4704. * @returns {number}
  4705. */
  4706. exports.getHiddenDurationBetween = function (hiddenDates, start, end) {
  4707. var duration = 0;
  4708. for (var i = 0; i < hiddenDates.length; i++) {
  4709. var startDate = hiddenDates[i].start;
  4710. var endDate = hiddenDates[i].end;
  4711. // if time after the cutout, and the
  4712. if (startDate >= start && endDate < end) {
  4713. duration += endDate - startDate;
  4714. }
  4715. }
  4716. return duration;
  4717. };
  4718. /**
  4719. * Support function
  4720. *
  4721. * @param {Array.<{start: Window.start, end: *}>} hiddenDates
  4722. * @param {number} start
  4723. * @param {number} end
  4724. * @returns {number}
  4725. */
  4726. exports.getHiddenDurationBeforeStart = function (hiddenDates, start, end) {
  4727. var duration = 0;
  4728. for (var i = 0; i < hiddenDates.length; i++) {
  4729. var startDate = hiddenDates[i].start;
  4730. var endDate = hiddenDates[i].end;
  4731. if (startDate >= start && endDate <= end) {
  4732. duration += endDate - startDate;
  4733. }
  4734. }
  4735. return duration;
  4736. };
  4737. /**
  4738. * Support function
  4739. * @param {function} moment
  4740. * @param {Array.<{start: Window.start, end: *}>} hiddenDates
  4741. * @param {{start: number, end: number}} range
  4742. * @param {Date} time
  4743. * @returns {number}
  4744. */
  4745. exports.correctTimeForHidden = function (moment, hiddenDates, range, time) {
  4746. time = moment(time).toDate().valueOf();
  4747. time -= exports.getHiddenDurationBefore(moment, hiddenDates, range, time);
  4748. return time;
  4749. };
  4750. exports.getHiddenDurationBefore = function (moment, hiddenDates, range, time) {
  4751. var timeOffset = 0;
  4752. time = moment(time).toDate().valueOf();
  4753. for (var i = 0; i < hiddenDates.length; i++) {
  4754. var startDate = hiddenDates[i].start;
  4755. var endDate = hiddenDates[i].end;
  4756. // if time after the cutout, and the
  4757. if (startDate >= range.start && endDate < range.end) {
  4758. if (time >= endDate) {
  4759. timeOffset += endDate - startDate;
  4760. }
  4761. }
  4762. }
  4763. return timeOffset;
  4764. };
  4765. /**
  4766. * sum the duration from start to finish, including the hidden duration,
  4767. * until the required amount has been reached, return the accumulated hidden duration
  4768. * @param {Array.<{start: Window.start, end: *}>} hiddenDates
  4769. * @param {{start: number, end: number}} range
  4770. * @param {number} [requiredDuration=0]
  4771. * @returns {number}
  4772. */
  4773. exports.getAccumulatedHiddenDuration = function (hiddenDates, range, requiredDuration) {
  4774. var hiddenDuration = 0;
  4775. var duration = 0;
  4776. var previousPoint = range.start;
  4777. //exports.printDates(hiddenDates)
  4778. for (var i = 0; i < hiddenDates.length; i++) {
  4779. var startDate = hiddenDates[i].start;
  4780. var endDate = hiddenDates[i].end;
  4781. // if time after the cutout, and the
  4782. if (startDate >= range.start && endDate < range.end) {
  4783. duration += startDate - previousPoint;
  4784. previousPoint = endDate;
  4785. if (duration >= requiredDuration) {
  4786. break;
  4787. } else {
  4788. hiddenDuration += endDate - startDate;
  4789. }
  4790. }
  4791. }
  4792. return hiddenDuration;
  4793. };
  4794. /**
  4795. * used to step over to either side of a hidden block. Correction is disabled on tablets, might be set to true
  4796. * @param {Array.<{start: Window.start, end: *}>} hiddenDates
  4797. * @param {Date} time
  4798. * @param {number} direction
  4799. * @param {boolean} correctionEnabled
  4800. * @returns {Date|number}
  4801. */
  4802. exports.snapAwayFromHidden = function (hiddenDates, time, direction, correctionEnabled) {
  4803. var isHidden = exports.isHidden(time, hiddenDates);
  4804. if (isHidden.hidden == true) {
  4805. if (direction < 0) {
  4806. if (correctionEnabled == true) {
  4807. return isHidden.startDate - (isHidden.endDate - time) - 1;
  4808. } else {
  4809. return isHidden.startDate - 1;
  4810. }
  4811. } else {
  4812. if (correctionEnabled == true) {
  4813. return isHidden.endDate + (time - isHidden.startDate) + 1;
  4814. } else {
  4815. return isHidden.endDate + 1;
  4816. }
  4817. }
  4818. } else {
  4819. return time;
  4820. }
  4821. };
  4822. /**
  4823. * Check if a time is hidden
  4824. *
  4825. * @param {Date} time
  4826. * @param {Array.<{start: Window.start, end: *}>} hiddenDates
  4827. * @returns {{hidden: boolean, startDate: Window.start, endDate: *}}
  4828. */
  4829. exports.isHidden = function (time, hiddenDates) {
  4830. for (var i = 0; i < hiddenDates.length; i++) {
  4831. var startDate = hiddenDates[i].start;
  4832. var endDate = hiddenDates[i].end;
  4833. if (time >= startDate && time < endDate) {
  4834. // if the start is entering a hidden zone
  4835. return { hidden: true, startDate: startDate, endDate: endDate };
  4836. }
  4837. }
  4838. return { hidden: false, startDate: startDate, endDate: endDate };
  4839. };
  4840. /***/ }),
  4841. /* 37 */
  4842. /***/ (function(module, exports, __webpack_require__) {
  4843. "use strict";
  4844. /**
  4845. * Register a touch event, taking place before a gesture
  4846. * @param {Hammer} hammer A hammer instance
  4847. * @param {function} callback Callback, called as callback(event)
  4848. */
  4849. exports.onTouch = function (hammer, callback) {
  4850. callback.inputHandler = function (event) {
  4851. if (event.isFirst) {
  4852. callback(event);
  4853. }
  4854. };
  4855. hammer.on('hammer.input', callback.inputHandler);
  4856. };
  4857. /**
  4858. * Register a release event, taking place after a gesture
  4859. * @param {Hammer} hammer A hammer instance
  4860. * @param {function} callback Callback, called as callback(event)
  4861. * @returns {*}
  4862. */
  4863. exports.onRelease = function (hammer, callback) {
  4864. callback.inputHandler = function (event) {
  4865. if (event.isFinal) {
  4866. callback(event);
  4867. }
  4868. };
  4869. return hammer.on('hammer.input', callback.inputHandler);
  4870. };
  4871. /**
  4872. * Unregister a touch event, taking place before a gesture
  4873. * @param {Hammer} hammer A hammer instance
  4874. * @param {function} callback Callback, called as callback(event)
  4875. */
  4876. exports.offTouch = function (hammer, callback) {
  4877. hammer.off('hammer.input', callback.inputHandler);
  4878. };
  4879. /**
  4880. * Unregister a release event, taking place before a gesture
  4881. * @param {Hammer} hammer A hammer instance
  4882. * @param {function} callback Callback, called as callback(event)
  4883. */
  4884. exports.offRelease = exports.offTouch;
  4885. /**
  4886. * Hack the PinchRecognizer such that it doesn't prevent default behavior
  4887. * for vertical panning.
  4888. *
  4889. * Yeah ... this is quite a hack ... see https://github.com/hammerjs/hammer.js/issues/932
  4890. *
  4891. * @param {Hammer.Pinch} pinchRecognizer
  4892. * @return {Hammer.Pinch} returns the pinchRecognizer
  4893. */
  4894. exports.disablePreventDefaultVertically = function (pinchRecognizer) {
  4895. var TOUCH_ACTION_PAN_Y = 'pan-y';
  4896. pinchRecognizer.getTouchAction = function () {
  4897. // default method returns [TOUCH_ACTION_NONE]
  4898. return [TOUCH_ACTION_PAN_Y];
  4899. };
  4900. return pinchRecognizer;
  4901. };
  4902. /***/ }),
  4903. /* 38 */
  4904. /***/ (function(module, exports, __webpack_require__) {
  4905. "use strict";
  4906. var _typeof2 = __webpack_require__(6);
  4907. var _typeof3 = _interopRequireDefault(_typeof2);
  4908. var _keys = __webpack_require__(8);
  4909. var _keys2 = _interopRequireDefault(_keys);
  4910. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  4911. var Hammer = __webpack_require__(10);
  4912. var util = __webpack_require__(2);
  4913. var moment = __webpack_require__(9);
  4914. /**
  4915. * @constructor Item
  4916. * @param {Object} data Object containing (optional) parameters type,
  4917. * start, end, content, group, className.
  4918. * @param {{toScreen: function, toTime: function}} conversion
  4919. * Conversion functions from time to screen and vice versa
  4920. * @param {Object} options Configuration options
  4921. * // TODO: describe available options
  4922. */
  4923. function Item(data, conversion, options) {
  4924. this.id = null;
  4925. this.parent = null;
  4926. this.data = data;
  4927. this.dom = null;
  4928. this.conversion = conversion || {};
  4929. this.options = options || {};
  4930. this.selected = false;
  4931. this.displayed = false;
  4932. this.groupShowing = true;
  4933. this.dirty = true;
  4934. this.top = null;
  4935. this.right = null;
  4936. this.left = null;
  4937. this.width = null;
  4938. this.height = null;
  4939. this.editable = null;
  4940. this._updateEditStatus();
  4941. }
  4942. Item.prototype.stack = true;
  4943. /**
  4944. * Select current item
  4945. */
  4946. Item.prototype.select = function () {
  4947. this.selected = true;
  4948. this.dirty = true;
  4949. if (this.displayed) this.redraw();
  4950. };
  4951. /**
  4952. * Unselect current item
  4953. */
  4954. Item.prototype.unselect = function () {
  4955. this.selected = false;
  4956. this.dirty = true;
  4957. if (this.displayed) this.redraw();
  4958. };
  4959. /**
  4960. * Set data for the item. Existing data will be updated. The id should not
  4961. * be changed. When the item is displayed, it will be redrawn immediately.
  4962. * @param {Object} data
  4963. */
  4964. Item.prototype.setData = function (data) {
  4965. var groupChanged = data.group != undefined && this.data.group != data.group;
  4966. if (groupChanged && this.parent != null) {
  4967. this.parent.itemSet._moveToGroup(this, data.group);
  4968. }
  4969. if (this.parent) {
  4970. this.parent.stackDirty = true;
  4971. }
  4972. var subGroupChanged = data.subgroup != undefined && this.data.subgroup != data.subgroup;
  4973. if (subGroupChanged && this.parent != null) {
  4974. this.parent.changeSubgroup(this, this.data.subgroup, data.subgroup);
  4975. }
  4976. this.data = data;
  4977. this._updateEditStatus();
  4978. this.dirty = true;
  4979. if (this.displayed) this.redraw();
  4980. };
  4981. /**
  4982. * Set a parent for the item
  4983. * @param {Group} parent
  4984. */
  4985. Item.prototype.setParent = function (parent) {
  4986. if (this.displayed) {
  4987. this.hide();
  4988. this.parent = parent;
  4989. if (this.parent) {
  4990. this.show();
  4991. }
  4992. } else {
  4993. this.parent = parent;
  4994. }
  4995. };
  4996. /**
  4997. * Check whether this item is visible inside given range
  4998. * @param {vis.Range} range with a timestamp for start and end
  4999. * @returns {boolean} True if visible
  5000. */
  5001. Item.prototype.isVisible = function (range) {
  5002. // eslint-disable-line no-unused-vars
  5003. return false;
  5004. };
  5005. /**
  5006. * Show the Item in the DOM (when not already visible)
  5007. * @return {Boolean} changed
  5008. */
  5009. Item.prototype.show = function () {
  5010. return false;
  5011. };
  5012. /**
  5013. * Hide the Item from the DOM (when visible)
  5014. * @return {Boolean} changed
  5015. */
  5016. Item.prototype.hide = function () {
  5017. return false;
  5018. };
  5019. /**
  5020. * Repaint the item
  5021. */
  5022. Item.prototype.redraw = function () {
  5023. // should be implemented by the item
  5024. };
  5025. /**
  5026. * Reposition the Item horizontally
  5027. */
  5028. Item.prototype.repositionX = function () {
  5029. // should be implemented by the item
  5030. };
  5031. /**
  5032. * Reposition the Item vertically
  5033. */
  5034. Item.prototype.repositionY = function () {
  5035. // should be implemented by the item
  5036. };
  5037. /**
  5038. * Repaint a drag area on the center of the item when the item is selected
  5039. * @protected
  5040. */
  5041. Item.prototype._repaintDragCenter = function () {
  5042. if (this.selected && this.options.editable.updateTime && !this.dom.dragCenter) {
  5043. var me = this;
  5044. // create and show drag area
  5045. var dragCenter = document.createElement('div');
  5046. dragCenter.className = 'vis-drag-center';
  5047. dragCenter.dragCenterItem = this;
  5048. var hammer = new Hammer(dragCenter);
  5049. hammer.on('tap', function (event) {
  5050. me.parent.itemSet.body.emitter.emit('click', {
  5051. event: event,
  5052. item: me.id
  5053. });
  5054. });
  5055. hammer.on('doubletap', function (event) {
  5056. event.stopPropagation();
  5057. me.parent.itemSet._onUpdateItem(me);
  5058. me.parent.itemSet.body.emitter.emit('doubleClick', {
  5059. event: event,
  5060. item: me.id
  5061. });
  5062. });
  5063. if (this.dom.box) {
  5064. if (this.dom.dragLeft) {
  5065. this.dom.box.insertBefore(dragCenter, this.dom.dragLeft);
  5066. } else {
  5067. this.dom.box.appendChild(dragCenter);
  5068. }
  5069. } else if (this.dom.point) {
  5070. this.dom.point.appendChild(dragCenter);
  5071. }
  5072. this.dom.dragCenter = dragCenter;
  5073. } else if (!this.selected && this.dom.dragCenter) {
  5074. // delete drag area
  5075. if (this.dom.dragCenter.parentNode) {
  5076. this.dom.dragCenter.parentNode.removeChild(this.dom.dragCenter);
  5077. }
  5078. this.dom.dragCenter = null;
  5079. }
  5080. };
  5081. /**
  5082. * Repaint a delete button on the top right of the item when the item is selected
  5083. * @param {HTMLElement} anchor
  5084. * @protected
  5085. */
  5086. Item.prototype._repaintDeleteButton = function (anchor) {
  5087. var editable = (this.options.editable.overrideItems || this.editable == null) && this.options.editable.remove || !this.options.editable.overrideItems && this.editable != null && this.editable.remove;
  5088. if (this.selected && editable && !this.dom.deleteButton) {
  5089. // create and show button
  5090. var me = this;
  5091. var deleteButton = document.createElement('div');
  5092. if (this.options.rtl) {
  5093. deleteButton.className = 'vis-delete-rtl';
  5094. } else {
  5095. deleteButton.className = 'vis-delete';
  5096. }
  5097. deleteButton.title = 'Delete this item';
  5098. // TODO: be able to destroy the delete button
  5099. new Hammer(deleteButton).on('tap', function (event) {
  5100. event.stopPropagation();
  5101. me.parent.removeFromDataSet(me);
  5102. });
  5103. anchor.appendChild(deleteButton);
  5104. this.dom.deleteButton = deleteButton;
  5105. } else if (!this.selected && this.dom.deleteButton) {
  5106. // remove button
  5107. if (this.dom.deleteButton.parentNode) {
  5108. this.dom.deleteButton.parentNode.removeChild(this.dom.deleteButton);
  5109. }
  5110. this.dom.deleteButton = null;
  5111. }
  5112. };
  5113. /**
  5114. * Repaint a onChange tooltip on the top right of the item when the item is selected
  5115. * @param {HTMLElement} anchor
  5116. * @protected
  5117. */
  5118. Item.prototype._repaintOnItemUpdateTimeTooltip = function (anchor) {
  5119. if (!this.options.tooltipOnItemUpdateTime) return;
  5120. var editable = (this.options.editable.updateTime || this.data.editable === true) && this.data.editable !== false;
  5121. if (this.selected && editable && !this.dom.onItemUpdateTimeTooltip) {
  5122. var onItemUpdateTimeTooltip = document.createElement('div');
  5123. onItemUpdateTimeTooltip.className = 'vis-onUpdateTime-tooltip';
  5124. anchor.appendChild(onItemUpdateTimeTooltip);
  5125. this.dom.onItemUpdateTimeTooltip = onItemUpdateTimeTooltip;
  5126. } else if (!this.selected && this.dom.onItemUpdateTimeTooltip) {
  5127. // remove button
  5128. if (this.dom.onItemUpdateTimeTooltip.parentNode) {
  5129. this.dom.onItemUpdateTimeTooltip.parentNode.removeChild(this.dom.onItemUpdateTimeTooltip);
  5130. }
  5131. this.dom.onItemUpdateTimeTooltip = null;
  5132. }
  5133. // position onChange tooltip
  5134. if (this.dom.onItemUpdateTimeTooltip) {
  5135. // only show when editing
  5136. this.dom.onItemUpdateTimeTooltip.style.visibility = this.parent.itemSet.touchParams.itemIsDragging ? 'visible' : 'hidden';
  5137. // position relative to item's content
  5138. if (this.options.rtl) {
  5139. this.dom.onItemUpdateTimeTooltip.style.right = this.dom.content.style.right;
  5140. } else {
  5141. this.dom.onItemUpdateTimeTooltip.style.left = this.dom.content.style.left;
  5142. }
  5143. // position above or below the item depending on the item's position in the window
  5144. var tooltipOffset = 50; // TODO: should be tooltip height (depends on template)
  5145. var scrollTop = this.parent.itemSet.body.domProps.scrollTop;
  5146. // TODO: this.top for orientation:true is actually the items distance from the bottom...
  5147. // (should be this.bottom)
  5148. var itemDistanceFromTop;
  5149. if (this.options.orientation.item == 'top') {
  5150. itemDistanceFromTop = this.top;
  5151. } else {
  5152. itemDistanceFromTop = this.parent.height - this.top - this.height;
  5153. }
  5154. var isCloseToTop = itemDistanceFromTop + this.parent.top - tooltipOffset < -scrollTop;
  5155. if (isCloseToTop) {
  5156. this.dom.onItemUpdateTimeTooltip.style.bottom = "";
  5157. this.dom.onItemUpdateTimeTooltip.style.top = this.height + 2 + "px";
  5158. } else {
  5159. this.dom.onItemUpdateTimeTooltip.style.top = "";
  5160. this.dom.onItemUpdateTimeTooltip.style.bottom = this.height + 2 + "px";
  5161. }
  5162. // handle tooltip content
  5163. var content;
  5164. var templateFunction;
  5165. if (this.options.tooltipOnItemUpdateTime && this.options.tooltipOnItemUpdateTime.template) {
  5166. templateFunction = this.options.tooltipOnItemUpdateTime.template.bind(this);
  5167. content = templateFunction(this.data);
  5168. } else {
  5169. content = 'start: ' + moment(this.data.start).format('MM/DD/YYYY hh:mm');
  5170. if (this.data.end) {
  5171. content += '<br> end: ' + moment(this.data.end).format('MM/DD/YYYY hh:mm');
  5172. }
  5173. }
  5174. this.dom.onItemUpdateTimeTooltip.innerHTML = content;
  5175. }
  5176. };
  5177. /**
  5178. * Set HTML contents for the item
  5179. * @param {Element} element HTML element to fill with the contents
  5180. * @private
  5181. */
  5182. Item.prototype._updateContents = function (element) {
  5183. var content;
  5184. var changed;
  5185. var templateFunction;
  5186. var itemVisibleFrameContent;
  5187. var visibleFrameTemplateFunction;
  5188. var itemData = this.parent.itemSet.itemsData.get(this.id); // get a clone of the data from the dataset
  5189. var frameElement = this.dom.box || this.dom.point;
  5190. var itemVisibleFrameContentElement = frameElement.getElementsByClassName('vis-item-visible-frame')[0];
  5191. if (this.options.visibleFrameTemplate) {
  5192. visibleFrameTemplateFunction = this.options.visibleFrameTemplate.bind(this);
  5193. itemVisibleFrameContent = visibleFrameTemplateFunction(itemData, frameElement);
  5194. } else {
  5195. itemVisibleFrameContent = '';
  5196. }
  5197. if (itemVisibleFrameContentElement) {
  5198. if (itemVisibleFrameContent instanceof Object && !(itemVisibleFrameContent instanceof Element)) {
  5199. visibleFrameTemplateFunction(itemData, itemVisibleFrameContentElement);
  5200. } else {
  5201. changed = this._contentToString(this.itemVisibleFrameContent) !== this._contentToString(itemVisibleFrameContent);
  5202. if (changed) {
  5203. // only replace the content when changed
  5204. if (itemVisibleFrameContent instanceof Element) {
  5205. itemVisibleFrameContentElement.innerHTML = '';
  5206. itemVisibleFrameContentElement.appendChild(itemVisibleFrameContent);
  5207. } else if (itemVisibleFrameContent != undefined) {
  5208. itemVisibleFrameContentElement.innerHTML = itemVisibleFrameContent;
  5209. } else {
  5210. if (!(this.data.type == 'background' && this.data.content === undefined)) {
  5211. throw new Error('Property "content" missing in item ' + this.id);
  5212. }
  5213. }
  5214. this.itemVisibleFrameContent = itemVisibleFrameContent;
  5215. }
  5216. }
  5217. }
  5218. if (this.options.template) {
  5219. templateFunction = this.options.template.bind(this);
  5220. content = templateFunction(itemData, element, this.data);
  5221. } else {
  5222. content = this.data.content;
  5223. }
  5224. if (content instanceof Object && !(content instanceof Element)) {
  5225. templateFunction(itemData, element);
  5226. } else {
  5227. changed = this._contentToString(this.content) !== this._contentToString(content);
  5228. if (changed) {
  5229. // only replace the content when changed
  5230. if (content instanceof Element) {
  5231. element.innerHTML = '';
  5232. element.appendChild(content);
  5233. } else if (content != undefined) {
  5234. element.innerHTML = content;
  5235. } else {
  5236. if (!(this.data.type == 'background' && this.data.content === undefined)) {
  5237. throw new Error('Property "content" missing in item ' + this.id);
  5238. }
  5239. }
  5240. this.content = content;
  5241. }
  5242. }
  5243. };
  5244. /**
  5245. * Process dataAttributes timeline option and set as data- attributes on dom.content
  5246. * @param {Element} element HTML element to which the attributes will be attached
  5247. * @private
  5248. */
  5249. Item.prototype._updateDataAttributes = function (element) {
  5250. if (this.options.dataAttributes && this.options.dataAttributes.length > 0) {
  5251. var attributes = [];
  5252. if (Array.isArray(this.options.dataAttributes)) {
  5253. attributes = this.options.dataAttributes;
  5254. } else if (this.options.dataAttributes == 'all') {
  5255. attributes = (0, _keys2['default'])(this.data);
  5256. } else {
  5257. return;
  5258. }
  5259. for (var i = 0; i < attributes.length; i++) {
  5260. var name = attributes[i];
  5261. var value = this.data[name];
  5262. if (value != null) {
  5263. element.setAttribute('data-' + name, value);
  5264. } else {
  5265. element.removeAttribute('data-' + name);
  5266. }
  5267. }
  5268. }
  5269. };
  5270. /**
  5271. * Update custom styles of the element
  5272. * @param {Element} element
  5273. * @private
  5274. */
  5275. Item.prototype._updateStyle = function (element) {
  5276. // remove old styles
  5277. if (this.style) {
  5278. util.removeCssText(element, this.style);
  5279. this.style = null;
  5280. }
  5281. // append new styles
  5282. if (this.data.style) {
  5283. util.addCssText(element, this.data.style);
  5284. this.style = this.data.style;
  5285. }
  5286. };
  5287. /**
  5288. * Stringify the items contents
  5289. * @param {string | Element | undefined} content
  5290. * @returns {string | undefined}
  5291. * @private
  5292. */
  5293. Item.prototype._contentToString = function (content) {
  5294. if (typeof content === 'string') return content;
  5295. if (content && 'outerHTML' in content) return content.outerHTML;
  5296. return content;
  5297. };
  5298. /**
  5299. * Update the editability of this item.
  5300. */
  5301. Item.prototype._updateEditStatus = function () {
  5302. if (this.options) {
  5303. if (typeof this.options.editable === 'boolean') {
  5304. this.editable = {
  5305. updateTime: this.options.editable,
  5306. updateGroup: this.options.editable,
  5307. remove: this.options.editable
  5308. };
  5309. } else if ((0, _typeof3['default'])(this.options.editable) === 'object') {
  5310. this.editable = {};
  5311. util.selectiveExtend(['updateTime', 'updateGroup', 'remove'], this.editable, this.options.editable);
  5312. }
  5313. }
  5314. // Item data overrides, except if options.editable.overrideItems is set.
  5315. if (!this.options || !this.options.editable || this.options.editable.overrideItems !== true) {
  5316. if (this.data) {
  5317. if (typeof this.data.editable === 'boolean') {
  5318. this.editable = {
  5319. updateTime: this.data.editable,
  5320. updateGroup: this.data.editable,
  5321. remove: this.data.editable
  5322. };
  5323. } else if ((0, _typeof3['default'])(this.data.editable) === 'object') {
  5324. // TODO: in vis.js 5.0, we should change this to not reset options from the timeline configuration.
  5325. // Basically just remove the next line...
  5326. this.editable = {};
  5327. util.selectiveExtend(['updateTime', 'updateGroup', 'remove'], this.editable, this.data.editable);
  5328. }
  5329. }
  5330. }
  5331. };
  5332. /**
  5333. * Return the width of the item left from its start date
  5334. * @return {number}
  5335. */
  5336. Item.prototype.getWidthLeft = function () {
  5337. return 0;
  5338. };
  5339. /**
  5340. * Return the width of the item right from the max of its start and end date
  5341. * @return {number}
  5342. */
  5343. Item.prototype.getWidthRight = function () {
  5344. return 0;
  5345. };
  5346. /**
  5347. * Return the title of the item
  5348. * @return {string | undefined}
  5349. */
  5350. Item.prototype.getTitle = function () {
  5351. return this.data.title;
  5352. };
  5353. module.exports = Item;
  5354. /***/ }),
  5355. /* 39 */
  5356. /***/ (function(module, exports) {
  5357. module.exports = function (bitmap, value) {
  5358. return {
  5359. enumerable: !(bitmap & 1),
  5360. configurable: !(bitmap & 2),
  5361. writable: !(bitmap & 4),
  5362. value: value
  5363. };
  5364. };
  5365. /***/ }),
  5366. /* 40 */
  5367. /***/ (function(module, exports) {
  5368. var id = 0;
  5369. var px = Math.random();
  5370. module.exports = function (key) {
  5371. return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
  5372. };
  5373. /***/ }),
  5374. /* 41 */
  5375. /***/ (function(module, exports, __webpack_require__) {
  5376. // 7.1.13 ToObject(argument)
  5377. var defined = __webpack_require__(51);
  5378. module.exports = function (it) {
  5379. return Object(defined(it));
  5380. };
  5381. /***/ }),
  5382. /* 42 */
  5383. /***/ (function(module, exports) {
  5384. exports.f = {}.propertyIsEnumerable;
  5385. /***/ }),
  5386. /* 43 */
  5387. /***/ (function(module, exports, __webpack_require__) {
  5388. "use strict";
  5389. /**
  5390. * A queue
  5391. * @param {Object} options
  5392. * Available options:
  5393. * - delay: number When provided, the queue will be flushed
  5394. * automatically after an inactivity of this delay
  5395. * in milliseconds.
  5396. * Default value is null.
  5397. * - max: number When the queue exceeds the given maximum number
  5398. * of entries, the queue is flushed automatically.
  5399. * Default value of max is Infinity.
  5400. * @constructor Queue
  5401. */
  5402. function Queue(options) {
  5403. // options
  5404. this.delay = null;
  5405. this.max = Infinity;
  5406. // properties
  5407. this._queue = [];
  5408. this._timeout = null;
  5409. this._extended = null;
  5410. this.setOptions(options);
  5411. }
  5412. /**
  5413. * Update the configuration of the queue
  5414. * @param {Object} options
  5415. * Available options:
  5416. * - delay: number When provided, the queue will be flushed
  5417. * automatically after an inactivity of this delay
  5418. * in milliseconds.
  5419. * Default value is null.
  5420. * - max: number When the queue exceeds the given maximum number
  5421. * of entries, the queue is flushed automatically.
  5422. * Default value of max is Infinity.
  5423. */
  5424. Queue.prototype.setOptions = function (options) {
  5425. if (options && typeof options.delay !== 'undefined') {
  5426. this.delay = options.delay;
  5427. }
  5428. if (options && typeof options.max !== 'undefined') {
  5429. this.max = options.max;
  5430. }
  5431. this._flushIfNeeded();
  5432. };
  5433. /**
  5434. * Extend an object with queuing functionality.
  5435. * The object will be extended with a function flush, and the methods provided
  5436. * in options.replace will be replaced with queued ones.
  5437. * @param {Object} object
  5438. * @param {Object} options
  5439. * Available options:
  5440. * - replace: Array.<string>
  5441. * A list with method names of the methods
  5442. * on the object to be replaced with queued ones.
  5443. * - delay: number When provided, the queue will be flushed
  5444. * automatically after an inactivity of this delay
  5445. * in milliseconds.
  5446. * Default value is null.
  5447. * - max: number When the queue exceeds the given maximum number
  5448. * of entries, the queue is flushed automatically.
  5449. * Default value of max is Infinity.
  5450. * @return {Queue} Returns the created queue
  5451. */
  5452. Queue.extend = function (object, options) {
  5453. var queue = new Queue(options);
  5454. if (object.flush !== undefined) {
  5455. throw new Error('Target object already has a property flush');
  5456. }
  5457. object.flush = function () {
  5458. queue.flush();
  5459. };
  5460. var methods = [{
  5461. name: 'flush',
  5462. original: undefined
  5463. }];
  5464. if (options && options.replace) {
  5465. for (var i = 0; i < options.replace.length; i++) {
  5466. var name = options.replace[i];
  5467. methods.push({
  5468. name: name,
  5469. original: object[name]
  5470. });
  5471. queue.replace(object, name);
  5472. }
  5473. }
  5474. queue._extended = {
  5475. object: object,
  5476. methods: methods
  5477. };
  5478. return queue;
  5479. };
  5480. /**
  5481. * Destroy the queue. The queue will first flush all queued actions, and in
  5482. * case it has extended an object, will restore the original object.
  5483. */
  5484. Queue.prototype.destroy = function () {
  5485. this.flush();
  5486. if (this._extended) {
  5487. var object = this._extended.object;
  5488. var methods = this._extended.methods;
  5489. for (var i = 0; i < methods.length; i++) {
  5490. var method = methods[i];
  5491. if (method.original) {
  5492. object[method.name] = method.original;
  5493. } else {
  5494. delete object[method.name];
  5495. }
  5496. }
  5497. this._extended = null;
  5498. }
  5499. };
  5500. /**
  5501. * Replace a method on an object with a queued version
  5502. * @param {Object} object Object having the method
  5503. * @param {string} method The method name
  5504. */
  5505. Queue.prototype.replace = function (object, method) {
  5506. var me = this;
  5507. var original = object[method];
  5508. if (!original) {
  5509. throw new Error('Method ' + method + ' undefined');
  5510. }
  5511. object[method] = function () {
  5512. // create an Array with the arguments
  5513. var args = [];
  5514. for (var i = 0; i < arguments.length; i++) {
  5515. args[i] = arguments[i];
  5516. }
  5517. // add this call to the queue
  5518. me.queue({
  5519. args: args,
  5520. fn: original,
  5521. context: this
  5522. });
  5523. };
  5524. };
  5525. /**
  5526. * Queue a call
  5527. * @param {function | {fn: function, args: Array} | {fn: function, args: Array, context: Object}} entry
  5528. */
  5529. Queue.prototype.queue = function (entry) {
  5530. if (typeof entry === 'function') {
  5531. this._queue.push({ fn: entry });
  5532. } else {
  5533. this._queue.push(entry);
  5534. }
  5535. this._flushIfNeeded();
  5536. };
  5537. /**
  5538. * Check whether the queue needs to be flushed
  5539. * @private
  5540. */
  5541. Queue.prototype._flushIfNeeded = function () {
  5542. // flush when the maximum is exceeded.
  5543. if (this._queue.length > this.max) {
  5544. this.flush();
  5545. }
  5546. // flush after a period of inactivity when a delay is configured
  5547. clearTimeout(this._timeout);
  5548. if (this.queue.length > 0 && typeof this.delay === 'number') {
  5549. var me = this;
  5550. this._timeout = setTimeout(function () {
  5551. me.flush();
  5552. }, this.delay);
  5553. }
  5554. };
  5555. /**
  5556. * Flush all queued calls
  5557. */
  5558. Queue.prototype.flush = function () {
  5559. while (this._queue.length > 0) {
  5560. var entry = this._queue.shift();
  5561. entry.fn.apply(entry.context || entry.fn, entry.args || []);
  5562. }
  5563. };
  5564. module.exports = Queue;
  5565. /***/ }),
  5566. /* 44 */
  5567. /***/ (function(module, exports) {
  5568. /**
  5569. * Expose `Emitter`.
  5570. */
  5571. module.exports = Emitter;
  5572. /**
  5573. * Initialize a new `Emitter`.
  5574. *
  5575. * @api public
  5576. */
  5577. function Emitter(obj) {
  5578. if (obj) return mixin(obj);
  5579. };
  5580. /**
  5581. * Mixin the emitter properties.
  5582. *
  5583. * @param {Object} obj
  5584. * @return {Object}
  5585. * @api private
  5586. */
  5587. function mixin(obj) {
  5588. for (var key in Emitter.prototype) {
  5589. obj[key] = Emitter.prototype[key];
  5590. }
  5591. return obj;
  5592. }
  5593. /**
  5594. * Listen on the given `event` with `fn`.
  5595. *
  5596. * @param {String} event
  5597. * @param {Function} fn
  5598. * @return {Emitter}
  5599. * @api public
  5600. */
  5601. Emitter.prototype.on =
  5602. Emitter.prototype.addEventListener = function(event, fn){
  5603. this._callbacks = this._callbacks || {};
  5604. (this._callbacks[event] = this._callbacks[event] || [])
  5605. .push(fn);
  5606. return this;
  5607. };
  5608. /**
  5609. * Adds an `event` listener that will be invoked a single
  5610. * time then automatically removed.
  5611. *
  5612. * @param {String} event
  5613. * @param {Function} fn
  5614. * @return {Emitter}
  5615. * @api public
  5616. */
  5617. Emitter.prototype.once = function(event, fn){
  5618. var self = this;
  5619. this._callbacks = this._callbacks || {};
  5620. function on() {
  5621. self.off(event, on);
  5622. fn.apply(this, arguments);
  5623. }
  5624. on.fn = fn;
  5625. this.on(event, on);
  5626. return this;
  5627. };
  5628. /**
  5629. * Remove the given callback for `event` or all
  5630. * registered callbacks.
  5631. *
  5632. * @param {String} event
  5633. * @param {Function} fn
  5634. * @return {Emitter}
  5635. * @api public
  5636. */
  5637. Emitter.prototype.off =
  5638. Emitter.prototype.removeListener =
  5639. Emitter.prototype.removeAllListeners =
  5640. Emitter.prototype.removeEventListener = function(event, fn){
  5641. this._callbacks = this._callbacks || {};
  5642. // all
  5643. if (0 == arguments.length) {
  5644. this._callbacks = {};
  5645. return this;
  5646. }
  5647. // specific event
  5648. var callbacks = this._callbacks[event];
  5649. if (!callbacks) return this;
  5650. // remove all handlers
  5651. if (1 == arguments.length) {
  5652. delete this._callbacks[event];
  5653. return this;
  5654. }
  5655. // remove specific handler
  5656. var cb;
  5657. for (var i = 0; i < callbacks.length; i++) {
  5658. cb = callbacks[i];
  5659. if (cb === fn || cb.fn === fn) {
  5660. callbacks.splice(i, 1);
  5661. break;
  5662. }
  5663. }
  5664. return this;
  5665. };
  5666. /**
  5667. * Emit `event` with the given args.
  5668. *
  5669. * @param {String} event
  5670. * @param {Mixed} ...
  5671. * @return {Emitter}
  5672. */
  5673. Emitter.prototype.emit = function(event){
  5674. this._callbacks = this._callbacks || {};
  5675. var args = [].slice.call(arguments, 1)
  5676. , callbacks = this._callbacks[event];
  5677. if (callbacks) {
  5678. callbacks = callbacks.slice(0);
  5679. for (var i = 0, len = callbacks.length; i < len; ++i) {
  5680. callbacks[i].apply(this, args);
  5681. }
  5682. }
  5683. return this;
  5684. };
  5685. /**
  5686. * Return array of callbacks for `event`.
  5687. *
  5688. * @param {String} event
  5689. * @return {Array}
  5690. * @api public
  5691. */
  5692. Emitter.prototype.listeners = function(event){
  5693. this._callbacks = this._callbacks || {};
  5694. return this._callbacks[event] || [];
  5695. };
  5696. /**
  5697. * Check if this emitter has `event` handlers.
  5698. *
  5699. * @param {String} event
  5700. * @return {Boolean}
  5701. * @api public
  5702. */
  5703. Emitter.prototype.hasListeners = function(event){
  5704. return !! this.listeners(event).length;
  5705. };
  5706. /***/ }),
  5707. /* 45 */
  5708. /***/ (function(module, exports, __webpack_require__) {
  5709. "use strict";
  5710. var _typeof2 = __webpack_require__(6);
  5711. var _typeof3 = _interopRequireDefault(_typeof2);
  5712. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  5713. var util = __webpack_require__(2);
  5714. var Component = __webpack_require__(16);
  5715. var TimeStep = __webpack_require__(66);
  5716. var DateUtil = __webpack_require__(36);
  5717. var moment = __webpack_require__(9);
  5718. /**
  5719. * A horizontal time axis
  5720. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  5721. * @param {Object} [options] See TimeAxis.setOptions for the available
  5722. * options.
  5723. * @constructor TimeAxis
  5724. * @extends Component
  5725. */
  5726. function TimeAxis(body, options) {
  5727. this.dom = {
  5728. foreground: null,
  5729. lines: [],
  5730. majorTexts: [],
  5731. minorTexts: [],
  5732. redundant: {
  5733. lines: [],
  5734. majorTexts: [],
  5735. minorTexts: []
  5736. }
  5737. };
  5738. this.props = {
  5739. range: {
  5740. start: 0,
  5741. end: 0,
  5742. minimumStep: 0
  5743. },
  5744. lineTop: 0
  5745. };
  5746. this.defaultOptions = {
  5747. orientation: {
  5748. axis: 'bottom'
  5749. }, // axis orientation: 'top' or 'bottom'
  5750. showMinorLabels: true,
  5751. showMajorLabels: true,
  5752. maxMinorChars: 7,
  5753. format: TimeStep.FORMAT,
  5754. moment: moment,
  5755. timeAxis: null
  5756. };
  5757. this.options = util.extend({}, this.defaultOptions);
  5758. this.body = body;
  5759. // create the HTML DOM
  5760. this._create();
  5761. this.setOptions(options);
  5762. }
  5763. TimeAxis.prototype = new Component();
  5764. /**
  5765. * Set options for the TimeAxis.
  5766. * Parameters will be merged in current options.
  5767. * @param {Object} options Available options:
  5768. * {string} [orientation.axis]
  5769. * {boolean} [showMinorLabels]
  5770. * {boolean} [showMajorLabels]
  5771. */
  5772. TimeAxis.prototype.setOptions = function (options) {
  5773. if (options) {
  5774. // copy all options that we know
  5775. util.selectiveExtend(['showMinorLabels', 'showMajorLabels', 'maxMinorChars', 'hiddenDates', 'timeAxis', 'moment', 'rtl'], this.options, options);
  5776. // deep copy the format options
  5777. util.selectiveDeepExtend(['format'], this.options, options);
  5778. if ('orientation' in options) {
  5779. if (typeof options.orientation === 'string') {
  5780. this.options.orientation.axis = options.orientation;
  5781. } else if ((0, _typeof3['default'])(options.orientation) === 'object' && 'axis' in options.orientation) {
  5782. this.options.orientation.axis = options.orientation.axis;
  5783. }
  5784. }
  5785. // apply locale to moment.js
  5786. // TODO: not so nice, this is applied globally to moment.js
  5787. if ('locale' in options) {
  5788. if (typeof moment.locale === 'function') {
  5789. // moment.js 2.8.1+
  5790. moment.locale(options.locale);
  5791. } else {
  5792. moment.lang(options.locale);
  5793. }
  5794. }
  5795. }
  5796. };
  5797. /**
  5798. * Create the HTML DOM for the TimeAxis
  5799. */
  5800. TimeAxis.prototype._create = function () {
  5801. this.dom.foreground = document.createElement('div');
  5802. this.dom.background = document.createElement('div');
  5803. this.dom.foreground.className = 'vis-time-axis vis-foreground';
  5804. this.dom.background.className = 'vis-time-axis vis-background';
  5805. };
  5806. /**
  5807. * Destroy the TimeAxis
  5808. */
  5809. TimeAxis.prototype.destroy = function () {
  5810. // remove from DOM
  5811. if (this.dom.foreground.parentNode) {
  5812. this.dom.foreground.parentNode.removeChild(this.dom.foreground);
  5813. }
  5814. if (this.dom.background.parentNode) {
  5815. this.dom.background.parentNode.removeChild(this.dom.background);
  5816. }
  5817. this.body = null;
  5818. };
  5819. /**
  5820. * Repaint the component
  5821. * @return {boolean} Returns true if the component is resized
  5822. */
  5823. TimeAxis.prototype.redraw = function () {
  5824. var props = this.props;
  5825. var foreground = this.dom.foreground;
  5826. var background = this.dom.background;
  5827. // determine the correct parent DOM element (depending on option orientation)
  5828. var parent = this.options.orientation.axis == 'top' ? this.body.dom.top : this.body.dom.bottom;
  5829. var parentChanged = foreground.parentNode !== parent;
  5830. // calculate character width and height
  5831. this._calculateCharSize();
  5832. // TODO: recalculate sizes only needed when parent is resized or options is changed
  5833. var showMinorLabels = this.options.showMinorLabels && this.options.orientation.axis !== 'none';
  5834. var showMajorLabels = this.options.showMajorLabels && this.options.orientation.axis !== 'none';
  5835. // determine the width and height of the elemens for the axis
  5836. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  5837. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  5838. props.height = props.minorLabelHeight + props.majorLabelHeight;
  5839. props.width = foreground.offsetWidth;
  5840. props.minorLineHeight = this.body.domProps.root.height - props.majorLabelHeight - (this.options.orientation.axis == 'top' ? this.body.domProps.bottom.height : this.body.domProps.top.height);
  5841. props.minorLineWidth = 1; // TODO: really calculate width
  5842. props.majorLineHeight = props.minorLineHeight + props.majorLabelHeight;
  5843. props.majorLineWidth = 1; // TODO: really calculate width
  5844. // take foreground and background offline while updating (is almost twice as fast)
  5845. var foregroundNextSibling = foreground.nextSibling;
  5846. var backgroundNextSibling = background.nextSibling;
  5847. foreground.parentNode && foreground.parentNode.removeChild(foreground);
  5848. background.parentNode && background.parentNode.removeChild(background);
  5849. foreground.style.height = this.props.height + 'px';
  5850. this._repaintLabels();
  5851. // put DOM online again (at the same place)
  5852. if (foregroundNextSibling) {
  5853. parent.insertBefore(foreground, foregroundNextSibling);
  5854. } else {
  5855. parent.appendChild(foreground);
  5856. }
  5857. if (backgroundNextSibling) {
  5858. this.body.dom.backgroundVertical.insertBefore(background, backgroundNextSibling);
  5859. } else {
  5860. this.body.dom.backgroundVertical.appendChild(background);
  5861. }
  5862. return this._isResized() || parentChanged;
  5863. };
  5864. /**
  5865. * Repaint major and minor text labels and vertical grid lines
  5866. * @private
  5867. */
  5868. TimeAxis.prototype._repaintLabels = function () {
  5869. var orientation = this.options.orientation.axis;
  5870. // calculate range and step (step such that we have space for 7 characters per label)
  5871. var start = util.convert(this.body.range.start, 'Number');
  5872. var end = util.convert(this.body.range.end, 'Number');
  5873. var timeLabelsize = this.body.util.toTime((this.props.minorCharWidth || 10) * this.options.maxMinorChars).valueOf();
  5874. var minimumStep = timeLabelsize - DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this.body.range, timeLabelsize);
  5875. minimumStep -= this.body.util.toTime(0).valueOf();
  5876. var step = new TimeStep(new Date(start), new Date(end), minimumStep, this.body.hiddenDates, this.options);
  5877. step.setMoment(this.options.moment);
  5878. if (this.options.format) {
  5879. step.setFormat(this.options.format);
  5880. }
  5881. if (this.options.timeAxis) {
  5882. step.setScale(this.options.timeAxis);
  5883. }
  5884. this.step = step;
  5885. // Move all DOM elements to a "redundant" list, where they
  5886. // can be picked for re-use, and clear the lists with lines and texts.
  5887. // At the end of the function _repaintLabels, left over elements will be cleaned up
  5888. var dom = this.dom;
  5889. dom.redundant.lines = dom.lines;
  5890. dom.redundant.majorTexts = dom.majorTexts;
  5891. dom.redundant.minorTexts = dom.minorTexts;
  5892. dom.lines = [];
  5893. dom.majorTexts = [];
  5894. dom.minorTexts = [];
  5895. var current; // eslint-disable-line no-unused-vars
  5896. var next;
  5897. var x;
  5898. var xNext;
  5899. var isMajor;
  5900. var nextIsMajor; // eslint-disable-line no-unused-vars
  5901. var showMinorGrid;
  5902. var width = 0,
  5903. prevWidth;
  5904. var line;
  5905. var labelMinor;
  5906. var xFirstMajorLabel = undefined;
  5907. var count = 0;
  5908. var MAX = 1000;
  5909. var className;
  5910. step.start();
  5911. next = step.getCurrent();
  5912. xNext = this.body.util.toScreen(next);
  5913. while (step.hasNext() && count < MAX) {
  5914. count++;
  5915. isMajor = step.isMajor();
  5916. className = step.getClassName();
  5917. labelMinor = step.getLabelMinor();
  5918. current = next;
  5919. x = xNext;
  5920. step.next();
  5921. next = step.getCurrent();
  5922. nextIsMajor = step.isMajor();
  5923. xNext = this.body.util.toScreen(next);
  5924. prevWidth = width;
  5925. width = xNext - x;
  5926. switch (step.scale) {
  5927. case 'week':
  5928. showMinorGrid = true;break;
  5929. default:
  5930. showMinorGrid = width >= prevWidth * 0.4;break; // prevent displaying of the 31th of the month on a scale of 5 days
  5931. }
  5932. if (this.options.showMinorLabels && showMinorGrid) {
  5933. var label = this._repaintMinorText(x, labelMinor, orientation, className);
  5934. label.style.width = width + 'px'; // set width to prevent overflow
  5935. }
  5936. if (isMajor && this.options.showMajorLabels) {
  5937. if (x > 0) {
  5938. if (xFirstMajorLabel == undefined) {
  5939. xFirstMajorLabel = x;
  5940. }
  5941. label = this._repaintMajorText(x, step.getLabelMajor(), orientation, className);
  5942. }
  5943. line = this._repaintMajorLine(x, width, orientation, className);
  5944. } else {
  5945. // minor line
  5946. if (showMinorGrid) {
  5947. line = this._repaintMinorLine(x, width, orientation, className);
  5948. } else {
  5949. if (line) {
  5950. // adjust the width of the previous grid
  5951. line.style.width = parseInt(line.style.width) + width + 'px';
  5952. }
  5953. }
  5954. }
  5955. }
  5956. if (count === MAX && !warnedForOverflow) {
  5957. console.warn('Something is wrong with the Timeline scale. Limited drawing of grid lines to ' + MAX + ' lines.');
  5958. warnedForOverflow = true;
  5959. }
  5960. // create a major label on the left when needed
  5961. if (this.options.showMajorLabels) {
  5962. var leftTime = this.body.util.toTime(0),
  5963. leftText = step.getLabelMajor(leftTime),
  5964. widthText = leftText.length * (this.props.majorCharWidth || 10) + 10; // upper bound estimation
  5965. if (xFirstMajorLabel == undefined || widthText < xFirstMajorLabel) {
  5966. this._repaintMajorText(0, leftText, orientation, className);
  5967. }
  5968. }
  5969. // Cleanup leftover DOM elements from the redundant list
  5970. util.forEach(this.dom.redundant, function (arr) {
  5971. while (arr.length) {
  5972. var elem = arr.pop();
  5973. if (elem && elem.parentNode) {
  5974. elem.parentNode.removeChild(elem);
  5975. }
  5976. }
  5977. });
  5978. };
  5979. /**
  5980. * Create a minor label for the axis at position x
  5981. * @param {number} x
  5982. * @param {string} text
  5983. * @param {string} orientation "top" or "bottom" (default)
  5984. * @param {string} className
  5985. * @return {Element} Returns the HTML element of the created label
  5986. * @private
  5987. */
  5988. TimeAxis.prototype._repaintMinorText = function (x, text, orientation, className) {
  5989. // reuse redundant label
  5990. var label = this.dom.redundant.minorTexts.shift();
  5991. if (!label) {
  5992. // create new label
  5993. var content = document.createTextNode('');
  5994. label = document.createElement('div');
  5995. label.appendChild(content);
  5996. this.dom.foreground.appendChild(label);
  5997. }
  5998. this.dom.minorTexts.push(label);
  5999. label.innerHTML = text;
  6000. label.style.top = orientation == 'top' ? this.props.majorLabelHeight + 'px' : '0';
  6001. if (this.options.rtl) {
  6002. label.style.left = "";
  6003. label.style.right = x + 'px';
  6004. } else {
  6005. label.style.left = x + 'px';
  6006. }
  6007. label.className = 'vis-text vis-minor ' + className;
  6008. //label.title = title; // TODO: this is a heavy operation
  6009. return label;
  6010. };
  6011. /**
  6012. * Create a Major label for the axis at position x
  6013. * @param {number} x
  6014. * @param {string} text
  6015. * @param {string} orientation "top" or "bottom" (default)
  6016. * @param {string} className
  6017. * @return {Element} Returns the HTML element of the created label
  6018. * @private
  6019. */
  6020. TimeAxis.prototype._repaintMajorText = function (x, text, orientation, className) {
  6021. // reuse redundant label
  6022. var label = this.dom.redundant.majorTexts.shift();
  6023. if (!label) {
  6024. // create label
  6025. var content = document.createElement('div');
  6026. label = document.createElement('div');
  6027. label.appendChild(content);
  6028. this.dom.foreground.appendChild(label);
  6029. }
  6030. label.childNodes[0].innerHTML = text;
  6031. label.className = 'vis-text vis-major ' + className;
  6032. //label.title = title; // TODO: this is a heavy operation
  6033. label.style.top = orientation == 'top' ? '0' : this.props.minorLabelHeight + 'px';
  6034. if (this.options.rtl) {
  6035. label.style.left = "";
  6036. label.style.right = x + 'px';
  6037. } else {
  6038. label.style.left = x + 'px';
  6039. }
  6040. this.dom.majorTexts.push(label);
  6041. return label;
  6042. };
  6043. /**
  6044. * Create a minor line for the axis at position x
  6045. * @param {number} x
  6046. * @param {number} width
  6047. * @param {string} orientation "top" or "bottom" (default)
  6048. * @param {string} className
  6049. * @return {Element} Returns the created line
  6050. * @private
  6051. */
  6052. TimeAxis.prototype._repaintMinorLine = function (x, width, orientation, className) {
  6053. // reuse redundant line
  6054. var line = this.dom.redundant.lines.shift();
  6055. if (!line) {
  6056. // create vertical line
  6057. line = document.createElement('div');
  6058. this.dom.background.appendChild(line);
  6059. }
  6060. this.dom.lines.push(line);
  6061. var props = this.props;
  6062. if (orientation == 'top') {
  6063. line.style.top = props.majorLabelHeight + 'px';
  6064. } else {
  6065. line.style.top = this.body.domProps.top.height + 'px';
  6066. }
  6067. line.style.height = props.minorLineHeight + 'px';
  6068. if (this.options.rtl) {
  6069. line.style.left = "";
  6070. line.style.right = x - props.minorLineWidth / 2 + 'px';
  6071. line.className = 'vis-grid vis-vertical-rtl vis-minor ' + className;
  6072. } else {
  6073. line.style.left = x - props.minorLineWidth / 2 + 'px';
  6074. line.className = 'vis-grid vis-vertical vis-minor ' + className;
  6075. }
  6076. line.style.width = width + 'px';
  6077. return line;
  6078. };
  6079. /**
  6080. * Create a Major line for the axis at position x
  6081. * @param {number} x
  6082. * @param {number} width
  6083. * @param {string} orientation "top" or "bottom" (default)
  6084. * @param {string} className
  6085. * @return {Element} Returns the created line
  6086. * @private
  6087. */
  6088. TimeAxis.prototype._repaintMajorLine = function (x, width, orientation, className) {
  6089. // reuse redundant line
  6090. var line = this.dom.redundant.lines.shift();
  6091. if (!line) {
  6092. // create vertical line
  6093. line = document.createElement('div');
  6094. this.dom.background.appendChild(line);
  6095. }
  6096. this.dom.lines.push(line);
  6097. var props = this.props;
  6098. if (orientation == 'top') {
  6099. line.style.top = '0';
  6100. } else {
  6101. line.style.top = this.body.domProps.top.height + 'px';
  6102. }
  6103. if (this.options.rtl) {
  6104. line.style.left = "";
  6105. line.style.right = x - props.majorLineWidth / 2 + 'px';
  6106. line.className = 'vis-grid vis-vertical-rtl vis-major ' + className;
  6107. } else {
  6108. line.style.left = x - props.majorLineWidth / 2 + 'px';
  6109. line.className = 'vis-grid vis-vertical vis-major ' + className;
  6110. }
  6111. line.style.height = props.majorLineHeight + 'px';
  6112. line.style.width = width + 'px';
  6113. return line;
  6114. };
  6115. /**
  6116. * Determine the size of text on the axis (both major and minor axis).
  6117. * The size is calculated only once and then cached in this.props.
  6118. * @private
  6119. */
  6120. TimeAxis.prototype._calculateCharSize = function () {
  6121. // Note: We calculate char size with every redraw. Size may change, for
  6122. // example when any of the timelines parents had display:none for example.
  6123. // determine the char width and height on the minor axis
  6124. if (!this.dom.measureCharMinor) {
  6125. this.dom.measureCharMinor = document.createElement('DIV');
  6126. this.dom.measureCharMinor.className = 'vis-text vis-minor vis-measure';
  6127. this.dom.measureCharMinor.style.position = 'absolute';
  6128. this.dom.measureCharMinor.appendChild(document.createTextNode('0'));
  6129. this.dom.foreground.appendChild(this.dom.measureCharMinor);
  6130. }
  6131. this.props.minorCharHeight = this.dom.measureCharMinor.clientHeight;
  6132. this.props.minorCharWidth = this.dom.measureCharMinor.clientWidth;
  6133. // determine the char width and height on the major axis
  6134. if (!this.dom.measureCharMajor) {
  6135. this.dom.measureCharMajor = document.createElement('DIV');
  6136. this.dom.measureCharMajor.className = 'vis-text vis-major vis-measure';
  6137. this.dom.measureCharMajor.style.position = 'absolute';
  6138. this.dom.measureCharMajor.appendChild(document.createTextNode('0'));
  6139. this.dom.foreground.appendChild(this.dom.measureCharMajor);
  6140. }
  6141. this.props.majorCharHeight = this.dom.measureCharMajor.clientHeight;
  6142. this.props.majorCharWidth = this.dom.measureCharMajor.clientWidth;
  6143. };
  6144. var warnedForOverflow = false;
  6145. module.exports = TimeAxis;
  6146. /***/ }),
  6147. /* 46 */
  6148. /***/ (function(module, exports, __webpack_require__) {
  6149. "use strict";
  6150. var Hammer = __webpack_require__(10);
  6151. var util = __webpack_require__(2);
  6152. var Component = __webpack_require__(16);
  6153. var moment = __webpack_require__(9);
  6154. var locales = __webpack_require__(98);
  6155. /**
  6156. * A custom time bar
  6157. * @param {{range: Range, dom: Object}} body
  6158. * @param {Object} [options] Available parameters:
  6159. * {number | string} id
  6160. * {string} locales
  6161. * {string} locale
  6162. * @constructor CustomTime
  6163. * @extends Component
  6164. */
  6165. function CustomTime(body, options) {
  6166. this.body = body;
  6167. // default options
  6168. this.defaultOptions = {
  6169. moment: moment,
  6170. locales: locales,
  6171. locale: 'en',
  6172. id: undefined,
  6173. title: undefined
  6174. };
  6175. this.options = util.extend({}, this.defaultOptions);
  6176. if (options && options.time) {
  6177. this.customTime = options.time;
  6178. } else {
  6179. this.customTime = new Date();
  6180. }
  6181. this.eventParams = {}; // stores state parameters while dragging the bar
  6182. this.setOptions(options);
  6183. // create the DOM
  6184. this._create();
  6185. }
  6186. CustomTime.prototype = new Component();
  6187. /**
  6188. * Set options for the component. Options will be merged in current options.
  6189. * @param {Object} options Available parameters:
  6190. * {number | string} id
  6191. * {string} locales
  6192. * {string} locale
  6193. */
  6194. CustomTime.prototype.setOptions = function (options) {
  6195. if (options) {
  6196. // copy all options that we know
  6197. util.selectiveExtend(['moment', 'locale', 'locales', 'id'], this.options, options);
  6198. }
  6199. };
  6200. /**
  6201. * Create the DOM for the custom time
  6202. * @private
  6203. */
  6204. CustomTime.prototype._create = function () {
  6205. var bar = document.createElement('div');
  6206. bar['custom-time'] = this;
  6207. bar.className = 'vis-custom-time ' + (this.options.id || '');
  6208. bar.style.position = 'absolute';
  6209. bar.style.top = '0px';
  6210. bar.style.height = '100%';
  6211. this.bar = bar;
  6212. var drag = document.createElement('div');
  6213. drag.style.position = 'relative';
  6214. drag.style.top = '0px';
  6215. drag.style.left = '-10px';
  6216. drag.style.height = '100%';
  6217. drag.style.width = '20px';
  6218. /**
  6219. *
  6220. * @param {WheelEvent} e
  6221. */
  6222. function onMouseWheel(e) {
  6223. this.body.range._onMouseWheel(e);
  6224. }
  6225. if (drag.addEventListener) {
  6226. // IE9, Chrome, Safari, Opera
  6227. drag.addEventListener("mousewheel", onMouseWheel.bind(this), false);
  6228. // Firefox
  6229. drag.addEventListener("DOMMouseScroll", onMouseWheel.bind(this), false);
  6230. } else {
  6231. // IE 6/7/8
  6232. drag.attachEvent("onmousewheel", onMouseWheel.bind(this));
  6233. }
  6234. bar.appendChild(drag);
  6235. // attach event listeners
  6236. this.hammer = new Hammer(drag);
  6237. this.hammer.on('panstart', this._onDragStart.bind(this));
  6238. this.hammer.on('panmove', this._onDrag.bind(this));
  6239. this.hammer.on('panend', this._onDragEnd.bind(this));
  6240. this.hammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_HORIZONTAL });
  6241. };
  6242. /**
  6243. * Destroy the CustomTime bar
  6244. */
  6245. CustomTime.prototype.destroy = function () {
  6246. this.hide();
  6247. this.hammer.destroy();
  6248. this.hammer = null;
  6249. this.body = null;
  6250. };
  6251. /**
  6252. * Repaint the component
  6253. * @return {boolean} Returns true if the component is resized
  6254. */
  6255. CustomTime.prototype.redraw = function () {
  6256. var parent = this.body.dom.backgroundVertical;
  6257. if (this.bar.parentNode != parent) {
  6258. // attach to the dom
  6259. if (this.bar.parentNode) {
  6260. this.bar.parentNode.removeChild(this.bar);
  6261. }
  6262. parent.appendChild(this.bar);
  6263. }
  6264. var x = this.body.util.toScreen(this.customTime);
  6265. var locale = this.options.locales[this.options.locale];
  6266. if (!locale) {
  6267. if (!this.warned) {
  6268. console.log('WARNING: options.locales[\'' + this.options.locale + '\'] not found. See http://visjs.org/docs/timeline/#Localization');
  6269. this.warned = true;
  6270. }
  6271. locale = this.options.locales['en']; // fall back on english when not available
  6272. }
  6273. var title = this.options.title;
  6274. // To hide the title completely use empty string ''.
  6275. if (title === undefined) {
  6276. title = locale.time + ': ' + this.options.moment(this.customTime).format('dddd, MMMM Do YYYY, H:mm:ss');
  6277. title = title.charAt(0).toUpperCase() + title.substring(1);
  6278. } else if (typeof title === "function") {
  6279. title = title.call(this.customTime);
  6280. }
  6281. this.bar.style.left = x + 'px';
  6282. this.bar.title = title;
  6283. return false;
  6284. };
  6285. /**
  6286. * Remove the CustomTime from the DOM
  6287. */
  6288. CustomTime.prototype.hide = function () {
  6289. // remove the line from the DOM
  6290. if (this.bar.parentNode) {
  6291. this.bar.parentNode.removeChild(this.bar);
  6292. }
  6293. };
  6294. /**
  6295. * Set custom time.
  6296. * @param {Date | number | string} time
  6297. */
  6298. CustomTime.prototype.setCustomTime = function (time) {
  6299. this.customTime = util.convert(time, 'Date');
  6300. this.redraw();
  6301. };
  6302. /**
  6303. * Retrieve the current custom time.
  6304. * @return {Date} customTime
  6305. */
  6306. CustomTime.prototype.getCustomTime = function () {
  6307. return new Date(this.customTime.valueOf());
  6308. };
  6309. /**
  6310. * Set custom title.
  6311. * @param {Date | number | string} title
  6312. */
  6313. CustomTime.prototype.setCustomTitle = function (title) {
  6314. this.options.title = title;
  6315. };
  6316. /**
  6317. * Start moving horizontally
  6318. * @param {Event} event
  6319. * @private
  6320. */
  6321. CustomTime.prototype._onDragStart = function (event) {
  6322. this.eventParams.dragging = true;
  6323. this.eventParams.customTime = this.customTime;
  6324. event.stopPropagation();
  6325. };
  6326. /**
  6327. * Perform moving operating.
  6328. * @param {Event} event
  6329. * @private
  6330. */
  6331. CustomTime.prototype._onDrag = function (event) {
  6332. if (!this.eventParams.dragging) return;
  6333. var x = this.body.util.toScreen(this.eventParams.customTime) + event.deltaX;
  6334. var time = this.body.util.toTime(x);
  6335. this.setCustomTime(time);
  6336. // fire a timechange event
  6337. this.body.emitter.emit('timechange', {
  6338. id: this.options.id,
  6339. time: new Date(this.customTime.valueOf()),
  6340. event: event
  6341. });
  6342. event.stopPropagation();
  6343. };
  6344. /**
  6345. * Stop moving operating.
  6346. * @param {Event} event
  6347. * @private
  6348. */
  6349. CustomTime.prototype._onDragEnd = function (event) {
  6350. if (!this.eventParams.dragging) return;
  6351. // fire a timechanged event
  6352. this.body.emitter.emit('timechanged', {
  6353. id: this.options.id,
  6354. time: new Date(this.customTime.valueOf()),
  6355. event: event
  6356. });
  6357. event.stopPropagation();
  6358. };
  6359. /**
  6360. * Find a custom time from an event target:
  6361. * searches for the attribute 'custom-time' in the event target's element tree
  6362. * @param {Event} event
  6363. * @return {CustomTime | null} customTime
  6364. */
  6365. CustomTime.customTimeFromTarget = function (event) {
  6366. var target = event.target;
  6367. while (target) {
  6368. if (target.hasOwnProperty('custom-time')) {
  6369. return target['custom-time'];
  6370. }
  6371. target = target.parentNode;
  6372. }
  6373. return null;
  6374. };
  6375. module.exports = CustomTime;
  6376. /***/ }),
  6377. /* 47 */
  6378. /***/ (function(module, exports, __webpack_require__) {
  6379. "use strict";
  6380. Object.defineProperty(exports, "__esModule", {
  6381. value: true
  6382. });
  6383. var _classCallCheck2 = __webpack_require__(0);
  6384. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  6385. var _createClass2 = __webpack_require__(1);
  6386. var _createClass3 = _interopRequireDefault(_createClass2);
  6387. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  6388. var util = __webpack_require__(2);
  6389. var Label = __webpack_require__(117)['default'];
  6390. var ComponentUtil = __webpack_require__(48)['default'];
  6391. var Box = __webpack_require__(193)['default'];
  6392. var Circle = __webpack_require__(200)['default'];
  6393. var CircularImage = __webpack_require__(201)['default'];
  6394. var Database = __webpack_require__(202)['default'];
  6395. var Diamond = __webpack_require__(203)['default'];
  6396. var Dot = __webpack_require__(204)['default'];
  6397. var Ellipse = __webpack_require__(205)['default'];
  6398. var Icon = __webpack_require__(206)['default'];
  6399. var Image = __webpack_require__(207)['default'];
  6400. var Square = __webpack_require__(208)['default'];
  6401. var Hexagon = __webpack_require__(209)['default'];
  6402. var Star = __webpack_require__(210)['default'];
  6403. var Text = __webpack_require__(211)['default'];
  6404. var Triangle = __webpack_require__(212)['default'];
  6405. var TriangleDown = __webpack_require__(213)['default'];
  6406. var _require = __webpack_require__(15),
  6407. printStyle = _require.printStyle;
  6408. /**
  6409. * A node. A node can be connected to other nodes via one or multiple edges.
  6410. */
  6411. var Node = function () {
  6412. /**
  6413. *
  6414. * @param {object} options An object containing options for the node. All
  6415. * options are optional, except for the id.
  6416. * {number} id Id of the node. Required
  6417. * {string} label Text label for the node
  6418. * {number} x Horizontal position of the node
  6419. * {number} y Vertical position of the node
  6420. * {string} shape Node shape
  6421. * {string} image An image url
  6422. * {string} title A title text, can be HTML
  6423. * {anytype} group A group name or number
  6424. *
  6425. * @param {Object} body Shared state of current network instance
  6426. * @param {Network.Images} imagelist A list with images. Only needed when the node has an image
  6427. * @param {Groups} grouplist A list with groups. Needed for retrieving group options
  6428. * @param {Object} globalOptions Current global node options; these serve as defaults for the node instance
  6429. * @param {Object} defaultOptions Global default options for nodes; note that this is also the prototype
  6430. * for parameter `globalOptions`.
  6431. */
  6432. function Node(options, body, imagelist, grouplist, globalOptions, defaultOptions) {
  6433. (0, _classCallCheck3['default'])(this, Node);
  6434. this.options = util.bridgeObject(globalOptions);
  6435. this.globalOptions = globalOptions;
  6436. this.defaultOptions = defaultOptions;
  6437. this.body = body;
  6438. this.edges = []; // all edges connected to this node
  6439. // set defaults for the options
  6440. this.id = undefined;
  6441. this.imagelist = imagelist;
  6442. this.grouplist = grouplist;
  6443. // state options
  6444. this.x = undefined;
  6445. this.y = undefined;
  6446. this.baseSize = this.options.size;
  6447. this.baseFontSize = this.options.font.size;
  6448. this.predefinedPosition = false; // used to check if initial fit should just take the range or approximate
  6449. this.selected = false;
  6450. this.hover = false;
  6451. this.labelModule = new Label(this.body, this.options, false /* Not edge label */);
  6452. this.setOptions(options);
  6453. }
  6454. /**
  6455. * Attach a edge to the node
  6456. * @param {Edge} edge
  6457. */
  6458. (0, _createClass3['default'])(Node, [{
  6459. key: 'attachEdge',
  6460. value: function attachEdge(edge) {
  6461. if (this.edges.indexOf(edge) === -1) {
  6462. this.edges.push(edge);
  6463. }
  6464. }
  6465. /**
  6466. * Detach a edge from the node
  6467. *
  6468. * @param {Edge} edge
  6469. */
  6470. }, {
  6471. key: 'detachEdge',
  6472. value: function detachEdge(edge) {
  6473. var index = this.edges.indexOf(edge);
  6474. if (index != -1) {
  6475. this.edges.splice(index, 1);
  6476. }
  6477. }
  6478. /**
  6479. * Set or overwrite options for the node
  6480. *
  6481. * @param {Object} options an object with options
  6482. * @returns {null|boolean}
  6483. */
  6484. }, {
  6485. key: 'setOptions',
  6486. value: function setOptions(options) {
  6487. var currentShape = this.options.shape;
  6488. if (!options) {
  6489. return; // Note that the return value will be 'undefined'! This is OK.
  6490. }
  6491. // basic options
  6492. if (options.id !== undefined) {
  6493. this.id = options.id;
  6494. }
  6495. if (this.id === undefined) {
  6496. throw new Error("Node must have an id");
  6497. }
  6498. Node.checkMass(options, this.id);
  6499. // set these options locally
  6500. // clear x and y positions
  6501. if (options.x !== undefined) {
  6502. if (options.x === null) {
  6503. this.x = undefined;this.predefinedPosition = false;
  6504. } else {
  6505. this.x = parseInt(options.x);this.predefinedPosition = true;
  6506. }
  6507. }
  6508. if (options.y !== undefined) {
  6509. if (options.y === null) {
  6510. this.y = undefined;this.predefinedPosition = false;
  6511. } else {
  6512. this.y = parseInt(options.y);this.predefinedPosition = true;
  6513. }
  6514. }
  6515. if (options.size !== undefined) {
  6516. this.baseSize = options.size;
  6517. }
  6518. if (options.value !== undefined) {
  6519. options.value = parseFloat(options.value);
  6520. }
  6521. // this transforms all shorthands into fully defined options
  6522. Node.parseOptions(this.options, options, true, this.globalOptions, this.grouplist);
  6523. var pile = [options, this.options, this.defaultOptions];
  6524. this.chooser = ComponentUtil.choosify('node', pile);
  6525. this._load_images();
  6526. this.updateLabelModule(options);
  6527. this.updateShape(currentShape);
  6528. return options.hidden !== undefined || options.physics !== undefined;
  6529. }
  6530. /**
  6531. * Load the images from the options, for the nodes that need them.
  6532. *
  6533. * TODO: The imageObj members should be moved to CircularImageBase.
  6534. * It's the only place where they are required.
  6535. *
  6536. * @private
  6537. */
  6538. }, {
  6539. key: '_load_images',
  6540. value: function _load_images() {
  6541. // Don't bother loading for nodes without images
  6542. if (this.options.shape !== 'circularImage' && this.options.shape !== 'image') {
  6543. return;
  6544. }
  6545. if (this.options.image === undefined) {
  6546. throw new Error("Option image must be defined for node type '" + this.options.shape + "'");
  6547. }
  6548. if (this.imagelist === undefined) {
  6549. throw new Error("Internal Error: No images provided");
  6550. }
  6551. if (typeof this.options.image === 'string') {
  6552. this.imageObj = this.imagelist.load(this.options.image, this.options.brokenImage, this.id);
  6553. } else {
  6554. if (this.options.image.unselected === undefined) {
  6555. throw new Error("No unselected image provided");
  6556. }
  6557. this.imageObj = this.imagelist.load(this.options.image.unselected, this.options.brokenImage, this.id);
  6558. if (this.options.image.selected !== undefined) {
  6559. this.imageObjAlt = this.imagelist.load(this.options.image.selected, this.options.brokenImage, this.id);
  6560. } else {
  6561. this.imageObjAlt = undefined;
  6562. }
  6563. }
  6564. }
  6565. /**
  6566. * Copy group option values into the node options.
  6567. *
  6568. * The group options override the global node options, so the copy of group options
  6569. * must happen *after* the global node options have been set.
  6570. *
  6571. * This method must also be called also if the global node options have changed and the group options did not.
  6572. *
  6573. * @param {Object} parentOptions
  6574. * @param {Object} newOptions new values for the options, currently only passed in for check
  6575. * @param {Object} groupList
  6576. */
  6577. }, {
  6578. key: 'getFormattingValues',
  6579. /**
  6580. *
  6581. * @returns {{color: *, borderWidth: *, borderColor: *, size: *, borderDashes: (boolean|Array|allOptions.nodes.shapeProperties.borderDashes|{boolean, array}), borderRadius: (number|allOptions.nodes.shapeProperties.borderRadius|{number}|Array), shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *}}
  6582. */
  6583. value: function getFormattingValues() {
  6584. var values = {
  6585. color: this.options.color.background,
  6586. borderWidth: this.options.borderWidth,
  6587. borderColor: this.options.color.border,
  6588. size: this.options.size,
  6589. borderDashes: this.options.shapeProperties.borderDashes,
  6590. borderRadius: this.options.shapeProperties.borderRadius,
  6591. shadow: this.options.shadow.enabled,
  6592. shadowColor: this.options.shadow.color,
  6593. shadowSize: this.options.shadow.size,
  6594. shadowX: this.options.shadow.x,
  6595. shadowY: this.options.shadow.y
  6596. };
  6597. if (this.selected || this.hover) {
  6598. if (this.chooser === true) {
  6599. if (this.selected) {
  6600. values.borderWidth *= 2;
  6601. values.color = this.options.color.highlight.background;
  6602. values.borderColor = this.options.color.highlight.border;
  6603. values.shadow = this.options.shadow.enabled;
  6604. } else if (this.hover) {
  6605. values.color = this.options.color.hover.background;
  6606. values.borderColor = this.options.color.hover.border;
  6607. values.shadow = this.options.shadow.enabled;
  6608. }
  6609. } else if (typeof this.chooser === 'function') {
  6610. this.chooser(values, this.options.id, this.selected, this.hover);
  6611. if (values.shadow === false) {
  6612. if (values.shadowColor !== this.options.shadow.color || values.shadowSize !== this.options.shadow.size || values.shadowX !== this.options.shadow.x || values.shadowY !== this.options.shadow.y) {
  6613. values.shadow = true;
  6614. }
  6615. }
  6616. }
  6617. } else {
  6618. values.shadow = this.options.shadow.enabled;
  6619. }
  6620. return values;
  6621. }
  6622. /**
  6623. *
  6624. * @param {Object} options
  6625. */
  6626. }, {
  6627. key: 'updateLabelModule',
  6628. value: function updateLabelModule(options) {
  6629. if (this.options.label === undefined || this.options.label === null) {
  6630. this.options.label = '';
  6631. }
  6632. Node.updateGroupOptions(this.options, options, this.grouplist);
  6633. //
  6634. // Note:The prototype chain for this.options is:
  6635. //
  6636. // this.options -> NodesHandler.options -> NodesHandler.defaultOptions
  6637. // (also: this.globalOptions)
  6638. //
  6639. // Note that the prototypes are mentioned explicitly in the pile list below;
  6640. // WE DON'T WANT THE ORDER OF THE PROTOTYPES!!!! At least, not for font handling of labels.
  6641. // This is a good indication that the prototype usage of options is deficient.
  6642. //
  6643. var currentGroup = this.grouplist.get(this.options.group, false);
  6644. var pile = [options, // new options
  6645. this.options, // current node options, see comment above for prototype
  6646. currentGroup, // group options, if any
  6647. this.globalOptions, // Currently set global node options
  6648. this.defaultOptions // Default global node options
  6649. ];
  6650. this.labelModule.update(this.options, pile);
  6651. if (this.labelModule.baseSize !== undefined) {
  6652. this.baseFontSize = this.labelModule.baseSize;
  6653. }
  6654. }
  6655. /**
  6656. *
  6657. * @param {string} currentShape
  6658. */
  6659. }, {
  6660. key: 'updateShape',
  6661. value: function updateShape(currentShape) {
  6662. if (currentShape === this.options.shape && this.shape) {
  6663. this.shape.setOptions(this.options, this.imageObj, this.imageObjAlt);
  6664. } else {
  6665. // choose draw method depending on the shape
  6666. switch (this.options.shape) {
  6667. case 'box':
  6668. this.shape = new Box(this.options, this.body, this.labelModule);
  6669. break;
  6670. case 'circle':
  6671. this.shape = new Circle(this.options, this.body, this.labelModule);
  6672. break;
  6673. case 'circularImage':
  6674. this.shape = new CircularImage(this.options, this.body, this.labelModule, this.imageObj, this.imageObjAlt);
  6675. break;
  6676. case 'database':
  6677. this.shape = new Database(this.options, this.body, this.labelModule);
  6678. break;
  6679. case 'diamond':
  6680. this.shape = new Diamond(this.options, this.body, this.labelModule);
  6681. break;
  6682. case 'dot':
  6683. this.shape = new Dot(this.options, this.body, this.labelModule);
  6684. break;
  6685. case 'ellipse':
  6686. this.shape = new Ellipse(this.options, this.body, this.labelModule);
  6687. break;
  6688. case 'icon':
  6689. this.shape = new Icon(this.options, this.body, this.labelModule);
  6690. break;
  6691. case 'image':
  6692. this.shape = new Image(this.options, this.body, this.labelModule, this.imageObj, this.imageObjAlt);
  6693. break;
  6694. case 'square':
  6695. this.shape = new Square(this.options, this.body, this.labelModule);
  6696. break;
  6697. case 'hexagon':
  6698. this.shape = new Hexagon(this.options, this.body, this.labelModule);
  6699. break;
  6700. case 'star':
  6701. this.shape = new Star(this.options, this.body, this.labelModule);
  6702. break;
  6703. case 'text':
  6704. this.shape = new Text(this.options, this.body, this.labelModule);
  6705. break;
  6706. case 'triangle':
  6707. this.shape = new Triangle(this.options, this.body, this.labelModule);
  6708. break;
  6709. case 'triangleDown':
  6710. this.shape = new TriangleDown(this.options, this.body, this.labelModule);
  6711. break;
  6712. default:
  6713. this.shape = new Ellipse(this.options, this.body, this.labelModule);
  6714. break;
  6715. }
  6716. }
  6717. this.needsRefresh();
  6718. }
  6719. /**
  6720. * select this node
  6721. */
  6722. }, {
  6723. key: 'select',
  6724. value: function select() {
  6725. this.selected = true;
  6726. this.needsRefresh();
  6727. }
  6728. /**
  6729. * unselect this node
  6730. */
  6731. }, {
  6732. key: 'unselect',
  6733. value: function unselect() {
  6734. this.selected = false;
  6735. this.needsRefresh();
  6736. }
  6737. /**
  6738. * Reset the calculated size of the node, forces it to recalculate its size
  6739. */
  6740. }, {
  6741. key: 'needsRefresh',
  6742. value: function needsRefresh() {
  6743. this.shape.refreshNeeded = true;
  6744. }
  6745. /**
  6746. * get the title of this node.
  6747. * @return {string} title The title of the node, or undefined when no title
  6748. * has been set.
  6749. */
  6750. }, {
  6751. key: 'getTitle',
  6752. value: function getTitle() {
  6753. return this.options.title;
  6754. }
  6755. /**
  6756. * Calculate the distance to the border of the Node
  6757. * @param {CanvasRenderingContext2D} ctx
  6758. * @param {number} angle Angle in radians
  6759. * @returns {number} distance Distance to the border in pixels
  6760. */
  6761. }, {
  6762. key: 'distanceToBorder',
  6763. value: function distanceToBorder(ctx, angle) {
  6764. return this.shape.distanceToBorder(ctx, angle);
  6765. }
  6766. /**
  6767. * Check if this node has a fixed x and y position
  6768. * @return {boolean} true if fixed, false if not
  6769. */
  6770. }, {
  6771. key: 'isFixed',
  6772. value: function isFixed() {
  6773. return this.options.fixed.x && this.options.fixed.y;
  6774. }
  6775. /**
  6776. * check if this node is selecte
  6777. * @return {boolean} selected True if node is selected, else false
  6778. */
  6779. }, {
  6780. key: 'isSelected',
  6781. value: function isSelected() {
  6782. return this.selected;
  6783. }
  6784. /**
  6785. * Retrieve the value of the node. Can be undefined
  6786. * @return {number} value
  6787. */
  6788. }, {
  6789. key: 'getValue',
  6790. value: function getValue() {
  6791. return this.options.value;
  6792. }
  6793. /**
  6794. * Get the current dimensions of the label
  6795. *
  6796. * @return {rect}
  6797. */
  6798. }, {
  6799. key: 'getLabelSize',
  6800. value: function getLabelSize() {
  6801. return this.labelModule.size();
  6802. }
  6803. /**
  6804. * Adjust the value range of the node. The node will adjust it's size
  6805. * based on its value.
  6806. * @param {number} min
  6807. * @param {number} max
  6808. * @param {number} total
  6809. */
  6810. }, {
  6811. key: 'setValueRange',
  6812. value: function setValueRange(min, max, total) {
  6813. if (this.options.value !== undefined) {
  6814. var scale = this.options.scaling.customScalingFunction(min, max, total, this.options.value);
  6815. var sizeDiff = this.options.scaling.max - this.options.scaling.min;
  6816. if (this.options.scaling.label.enabled === true) {
  6817. var fontDiff = this.options.scaling.label.max - this.options.scaling.label.min;
  6818. this.options.font.size = this.options.scaling.label.min + scale * fontDiff;
  6819. }
  6820. this.options.size = this.options.scaling.min + scale * sizeDiff;
  6821. } else {
  6822. this.options.size = this.baseSize;
  6823. this.options.font.size = this.baseFontSize;
  6824. }
  6825. this.updateLabelModule();
  6826. }
  6827. /**
  6828. * Draw this node in the given canvas
  6829. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  6830. * @param {CanvasRenderingContext2D} ctx
  6831. */
  6832. }, {
  6833. key: 'draw',
  6834. value: function draw(ctx) {
  6835. var values = this.getFormattingValues();
  6836. this.shape.draw(ctx, this.x, this.y, this.selected, this.hover, values);
  6837. }
  6838. /**
  6839. * Update the bounding box of the shape
  6840. * @param {CanvasRenderingContext2D} ctx
  6841. */
  6842. }, {
  6843. key: 'updateBoundingBox',
  6844. value: function updateBoundingBox(ctx) {
  6845. this.shape.updateBoundingBox(this.x, this.y, ctx);
  6846. }
  6847. /**
  6848. * Recalculate the size of this node in the given canvas
  6849. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  6850. * @param {CanvasRenderingContext2D} ctx
  6851. */
  6852. }, {
  6853. key: 'resize',
  6854. value: function resize(ctx) {
  6855. var values = this.getFormattingValues();
  6856. this.shape.resize(ctx, this.selected, this.hover, values);
  6857. }
  6858. /**
  6859. * Determine all visual elements of this node instance, in which the given
  6860. * point falls within the bounding shape.
  6861. *
  6862. * @param {point} point
  6863. * @returns {Array.<nodeClickItem|nodeLabelClickItem>} list with the items which are on the point
  6864. */
  6865. }, {
  6866. key: 'getItemsOnPoint',
  6867. value: function getItemsOnPoint(point) {
  6868. var ret = [];
  6869. if (this.labelModule.visible()) {
  6870. if (ComponentUtil.pointInRect(this.labelModule.getSize(), point)) {
  6871. ret.push({ nodeId: this.id, labelId: 0 });
  6872. }
  6873. }
  6874. if (ComponentUtil.pointInRect(this.shape.boundingBox, point)) {
  6875. ret.push({ nodeId: this.id });
  6876. }
  6877. return ret;
  6878. }
  6879. /**
  6880. * Check if this object is overlapping with the provided object
  6881. * @param {Object} obj an object with parameters left, top, right, bottom
  6882. * @return {boolean} True if location is located on node
  6883. */
  6884. }, {
  6885. key: 'isOverlappingWith',
  6886. value: function isOverlappingWith(obj) {
  6887. 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;
  6888. }
  6889. /**
  6890. * Check if this object is overlapping with the provided object
  6891. * @param {Object} obj an object with parameters left, top, right, bottom
  6892. * @return {boolean} True if location is located on node
  6893. */
  6894. }, {
  6895. key: 'isBoundingBoxOverlappingWith',
  6896. value: function isBoundingBoxOverlappingWith(obj) {
  6897. 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;
  6898. }
  6899. /**
  6900. * Check valid values for mass
  6901. *
  6902. * The mass may not be negative or zero. If it is, reset to 1
  6903. *
  6904. * @param {object} options
  6905. * @param {Node.id} id
  6906. * @static
  6907. */
  6908. }], [{
  6909. key: 'updateGroupOptions',
  6910. value: function updateGroupOptions(parentOptions, newOptions, groupList) {
  6911. if (groupList === undefined) return; // No groups, nothing to do
  6912. var group = parentOptions.group;
  6913. // paranoia: the selected group is already merged into node options, check.
  6914. if (newOptions !== undefined && newOptions.group !== undefined && group !== newOptions.group) {
  6915. throw new Error("updateGroupOptions: group values in options don't match.");
  6916. }
  6917. var hasGroup = typeof group === 'number' || typeof group === 'string' && group != '';
  6918. if (!hasGroup) return; // current node has no group, no need to merge
  6919. var groupObj = groupList.get(group);
  6920. // Skip merging of group font options into parent; these are required to be distinct for labels
  6921. // TODO: It might not be a good idea either to merge the rest of the options, investigate this.
  6922. util.selectiveNotDeepExtend(['font'], parentOptions, groupObj);
  6923. // the color object needs to be completely defined.
  6924. // Since groups can partially overwrite the colors, we parse it again, just in case.
  6925. parentOptions.color = util.parseColor(parentOptions.color);
  6926. }
  6927. /**
  6928. * This process all possible shorthands in the new options and makes sure that the parentOptions are fully defined.
  6929. * Static so it can also be used by the handler.
  6930. *
  6931. * @param {Object} parentOptions
  6932. * @param {Object} newOptions
  6933. * @param {boolean} [allowDeletion=false]
  6934. * @param {Object} [globalOptions={}]
  6935. * @param {Object} [groupList]
  6936. * @static
  6937. */
  6938. }, {
  6939. key: 'parseOptions',
  6940. value: function parseOptions(parentOptions, newOptions) {
  6941. var allowDeletion = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  6942. var globalOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  6943. var groupList = arguments[4];
  6944. var fields = ['color', 'fixed', 'shadow'];
  6945. util.selectiveNotDeepExtend(fields, parentOptions, newOptions, allowDeletion);
  6946. Node.checkMass(newOptions);
  6947. // merge the shadow options into the parent.
  6948. util.mergeOptions(parentOptions, newOptions, 'shadow', globalOptions);
  6949. // individual shape newOptions
  6950. if (newOptions.color !== undefined && newOptions.color !== null) {
  6951. var parsedColor = util.parseColor(newOptions.color);
  6952. util.fillIfDefined(parentOptions.color, parsedColor);
  6953. } else if (allowDeletion === true && newOptions.color === null) {
  6954. parentOptions.color = util.bridgeObject(globalOptions.color); // set the object back to the global options
  6955. }
  6956. // handle the fixed options
  6957. if (newOptions.fixed !== undefined && newOptions.fixed !== null) {
  6958. if (typeof newOptions.fixed === 'boolean') {
  6959. parentOptions.fixed.x = newOptions.fixed;
  6960. parentOptions.fixed.y = newOptions.fixed;
  6961. } else {
  6962. if (newOptions.fixed.x !== undefined && typeof newOptions.fixed.x === 'boolean') {
  6963. parentOptions.fixed.x = newOptions.fixed.x;
  6964. }
  6965. if (newOptions.fixed.y !== undefined && typeof newOptions.fixed.y === 'boolean') {
  6966. parentOptions.fixed.y = newOptions.fixed.y;
  6967. }
  6968. }
  6969. }
  6970. if (allowDeletion === true && newOptions.font === null) {
  6971. parentOptions.font = util.bridgeObject(globalOptions.font); // set the object back to the global options
  6972. }
  6973. Node.updateGroupOptions(parentOptions, newOptions, groupList);
  6974. // handle the scaling options, specifically the label part
  6975. if (newOptions.scaling !== undefined) {
  6976. util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label', globalOptions.scaling);
  6977. }
  6978. }
  6979. }, {
  6980. key: 'checkMass',
  6981. value: function checkMass(options, id) {
  6982. if (options.mass !== undefined && options.mass <= 0) {
  6983. var strId = '';
  6984. if (id !== undefined) {
  6985. strId = ' in node id: ' + id;
  6986. }
  6987. console.log('%cNegative or zero mass disallowed' + strId + ', setting mass to 1.', printStyle);
  6988. options.mass = 1;
  6989. }
  6990. }
  6991. }]);
  6992. return Node;
  6993. }();
  6994. exports['default'] = Node;
  6995. /***/ }),
  6996. /* 48 */
  6997. /***/ (function(module, exports, __webpack_require__) {
  6998. "use strict";
  6999. Object.defineProperty(exports, "__esModule", {
  7000. value: true
  7001. });
  7002. var _typeof2 = __webpack_require__(6);
  7003. var _typeof3 = _interopRequireDefault(_typeof2);
  7004. var _classCallCheck2 = __webpack_require__(0);
  7005. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  7006. var _createClass2 = __webpack_require__(1);
  7007. var _createClass3 = _interopRequireDefault(_createClass2);
  7008. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  7009. /**
  7010. * Definitions for param's in jsdoc.
  7011. * These are more or less global within Network. Putting them here until I can figure out
  7012. * where to really put them
  7013. *
  7014. * @typedef {string|number} Id
  7015. * @typedef {Id} NodeId
  7016. * @typedef {Id} EdgeId
  7017. * @typedef {Id} LabelId
  7018. *
  7019. * @typedef {{x: number, y: number}} point
  7020. * @typedef {{left: number, top: number, width: number, height: number}} rect
  7021. * @typedef {{x: number, y:number, angle: number}} rotationPoint
  7022. * - point to rotate around and the angle in radians to rotate. angle == 0 means no rotation
  7023. * @typedef {{nodeId:NodeId}} nodeClickItem
  7024. * @typedef {{nodeId:NodeId, labelId:LabelId}} nodeLabelClickItem
  7025. * @typedef {{edgeId:EdgeId}} edgeClickItem
  7026. * @typedef {{edgeId:EdgeId, labelId:LabelId}} edgeLabelClickItem
  7027. */
  7028. var util = __webpack_require__(2);
  7029. /**
  7030. * Helper functions for components
  7031. * @class
  7032. */
  7033. var ComponentUtil = function () {
  7034. function ComponentUtil() {
  7035. (0, _classCallCheck3['default'])(this, ComponentUtil);
  7036. }
  7037. (0, _createClass3['default'])(ComponentUtil, null, [{
  7038. key: 'choosify',
  7039. /**
  7040. * Determine values to use for (sub)options of 'chosen'.
  7041. *
  7042. * This option is either a boolean or an object whose values should be examined further.
  7043. * The relevant structures are:
  7044. *
  7045. * - chosen: <boolean value>
  7046. * - chosen: { subOption: <boolean or function> }
  7047. *
  7048. * Where subOption is 'node', 'edge' or 'label'.
  7049. *
  7050. * The intention of this method appears to be to set a specific priority to the options;
  7051. * Since most properties are either bridged or merged into the local options objects, there
  7052. * is not much point in handling them separately.
  7053. * TODO: examine if 'most' in previous sentence can be replaced with 'all'. In that case, we
  7054. * should be able to get rid of this method.
  7055. *
  7056. * @param {string} subOption option within object 'chosen' to consider; either 'node', 'edge' or 'label'
  7057. * @param {Object} pile array of options objects to consider
  7058. *
  7059. * @return {boolean|function} value for passed subOption of 'chosen' to use
  7060. */
  7061. value: function choosify(subOption, pile) {
  7062. // allowed values for subOption
  7063. var allowed = ['node', 'edge', 'label'];
  7064. var value = true;
  7065. var chosen = util.topMost(pile, 'chosen');
  7066. if (typeof chosen === 'boolean') {
  7067. value = chosen;
  7068. } else if ((typeof chosen === 'undefined' ? 'undefined' : (0, _typeof3['default'])(chosen)) === 'object') {
  7069. if (allowed.indexOf(subOption) === -1) {
  7070. throw new Error('choosify: subOption \'' + subOption + '\' should be one of ' + "'" + allowed.join("', '") + "'");
  7071. }
  7072. var chosenEdge = util.topMost(pile, ['chosen', subOption]);
  7073. if (typeof chosenEdge === 'boolean' || typeof chosenEdge === 'function') {
  7074. value = chosenEdge;
  7075. }
  7076. }
  7077. return value;
  7078. }
  7079. /**
  7080. * Check if the point falls within the given rectangle.
  7081. *
  7082. * @param {rect} rect
  7083. * @param {point} point
  7084. * @param {rotationPoint} [rotationPoint] if specified, the rotation that applies to the rectangle.
  7085. * @returns {boolean} true if point within rectangle, false otherwise
  7086. * @static
  7087. */
  7088. }, {
  7089. key: 'pointInRect',
  7090. value: function pointInRect(rect, point, rotationPoint) {
  7091. if (rect.width <= 0 || rect.height <= 0) {
  7092. return false; // early out
  7093. }
  7094. if (rotationPoint !== undefined) {
  7095. // Rotate the point the same amount as the rectangle
  7096. var tmp = {
  7097. x: point.x - rotationPoint.x,
  7098. y: point.y - rotationPoint.y
  7099. };
  7100. if (rotationPoint.angle !== 0) {
  7101. // In order to get the coordinates the same, you need to
  7102. // rotate in the reverse direction
  7103. var angle = -rotationPoint.angle;
  7104. var tmp2 = {
  7105. x: Math.cos(angle) * tmp.x - Math.sin(angle) * tmp.y,
  7106. y: Math.sin(angle) * tmp.x + Math.cos(angle) * tmp.y
  7107. };
  7108. point = tmp2;
  7109. } else {
  7110. point = tmp;
  7111. }
  7112. // Note that if a rotation is specified, the rectangle coordinates
  7113. // are **not* the full canvas coordinates. They are relative to the
  7114. // rotationPoint. Hence, the point coordinates need not be translated
  7115. // back in this case.
  7116. }
  7117. var right = rect.x + rect.width;
  7118. var bottom = rect.y + rect.width;
  7119. return rect.left < point.x && right > point.x && rect.top < point.y && bottom > point.y;
  7120. }
  7121. /**
  7122. * Check if given value is acceptable as a label text.
  7123. *
  7124. * @param {*} text value to check; can be anything at this point
  7125. * @returns {boolean} true if valid label value, false otherwise
  7126. */
  7127. }, {
  7128. key: 'isValidLabel',
  7129. value: function isValidLabel(text) {
  7130. // Note that this is quite strict: types that *might* be converted to string are disallowed
  7131. return typeof text === 'string' && text !== '';
  7132. }
  7133. }]);
  7134. return ComponentUtil;
  7135. }();
  7136. exports['default'] = ComponentUtil;
  7137. /***/ }),
  7138. /* 49 */
  7139. /***/ (function(module, exports, __webpack_require__) {
  7140. __webpack_require__(125);
  7141. var global = __webpack_require__(18);
  7142. var hide = __webpack_require__(26);
  7143. var Iterators = __webpack_require__(31);
  7144. var TO_STRING_TAG = __webpack_require__(13)('toStringTag');
  7145. var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +
  7146. 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +
  7147. 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +
  7148. 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +
  7149. 'TextTrackList,TouchList').split(',');
  7150. for (var i = 0; i < DOMIterables.length; i++) {
  7151. var NAME = DOMIterables[i];
  7152. var Collection = global[NAME];
  7153. var proto = Collection && Collection.prototype;
  7154. if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
  7155. Iterators[NAME] = Iterators.Array;
  7156. }
  7157. /***/ }),
  7158. /* 50 */
  7159. /***/ (function(module, exports) {
  7160. var toString = {}.toString;
  7161. module.exports = function (it) {
  7162. return toString.call(it).slice(8, -1);
  7163. };
  7164. /***/ }),
  7165. /* 51 */
  7166. /***/ (function(module, exports) {
  7167. // 7.2.1 RequireObjectCoercible(argument)
  7168. module.exports = function (it) {
  7169. if (it == undefined) throw TypeError("Can't call method on " + it);
  7170. return it;
  7171. };
  7172. /***/ }),
  7173. /* 52 */
  7174. /***/ (function(module, exports) {
  7175. module.exports = true;
  7176. /***/ }),
  7177. /* 53 */
  7178. /***/ (function(module, exports, __webpack_require__) {
  7179. // 7.1.1 ToPrimitive(input [, PreferredType])
  7180. var isObject = __webpack_require__(32);
  7181. // instead of the ES6 spec version, we didn't implement @@toPrimitive case
  7182. // and the second argument - flag - preferred type is a string
  7183. module.exports = function (it, S) {
  7184. if (!isObject(it)) return it;
  7185. var fn, val;
  7186. if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
  7187. if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
  7188. if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
  7189. throw TypeError("Can't convert object to primitive value");
  7190. };
  7191. /***/ }),
  7192. /* 54 */
  7193. /***/ (function(module, exports, __webpack_require__) {
  7194. // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
  7195. var anObject = __webpack_require__(27);
  7196. var dPs = __webpack_require__(130);
  7197. var enumBugKeys = __webpack_require__(58);
  7198. var IE_PROTO = __webpack_require__(56)('IE_PROTO');
  7199. var Empty = function () { /* empty */ };
  7200. var PROTOTYPE = 'prototype';
  7201. // Create object with fake `null` prototype: use iframe Object with cleared prototype
  7202. var createDict = function () {
  7203. // Thrash, waste and sodomy: IE GC bug
  7204. var iframe = __webpack_require__(82)('iframe');
  7205. var i = enumBugKeys.length;
  7206. var lt = '<';
  7207. var gt = '>';
  7208. var iframeDocument;
  7209. iframe.style.display = 'none';
  7210. __webpack_require__(134).appendChild(iframe);
  7211. iframe.src = 'javascript:'; // eslint-disable-line no-script-url
  7212. // createDict = iframe.contentWindow.Object;
  7213. // html.removeChild(iframe);
  7214. iframeDocument = iframe.contentWindow.document;
  7215. iframeDocument.open();
  7216. iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
  7217. iframeDocument.close();
  7218. createDict = iframeDocument.F;
  7219. while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]];
  7220. return createDict();
  7221. };
  7222. module.exports = Object.create || function create(O, Properties) {
  7223. var result;
  7224. if (O !== null) {
  7225. Empty[PROTOTYPE] = anObject(O);
  7226. result = new Empty();
  7227. Empty[PROTOTYPE] = null;
  7228. // add "__proto__" for Object.getPrototypeOf polyfill
  7229. result[IE_PROTO] = O;
  7230. } else result = createDict();
  7231. return Properties === undefined ? result : dPs(result, Properties);
  7232. };
  7233. /***/ }),
  7234. /* 55 */
  7235. /***/ (function(module, exports) {
  7236. // 7.1.4 ToInteger
  7237. var ceil = Math.ceil;
  7238. var floor = Math.floor;
  7239. module.exports = function (it) {
  7240. return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
  7241. };
  7242. /***/ }),
  7243. /* 56 */
  7244. /***/ (function(module, exports, __webpack_require__) {
  7245. var shared = __webpack_require__(57)('keys');
  7246. var uid = __webpack_require__(40);
  7247. module.exports = function (key) {
  7248. return shared[key] || (shared[key] = uid(key));
  7249. };
  7250. /***/ }),
  7251. /* 57 */
  7252. /***/ (function(module, exports, __webpack_require__) {
  7253. var global = __webpack_require__(18);
  7254. var SHARED = '__core-js_shared__';
  7255. var store = global[SHARED] || (global[SHARED] = {});
  7256. module.exports = function (key) {
  7257. return store[key] || (store[key] = {});
  7258. };
  7259. /***/ }),
  7260. /* 58 */
  7261. /***/ (function(module, exports) {
  7262. // IE 8- don't enum bug keys
  7263. module.exports = (
  7264. 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
  7265. ).split(',');
  7266. /***/ }),
  7267. /* 59 */
  7268. /***/ (function(module, exports, __webpack_require__) {
  7269. var def = __webpack_require__(20).f;
  7270. var has = __webpack_require__(22);
  7271. var TAG = __webpack_require__(13)('toStringTag');
  7272. module.exports = function (it, tag, stat) {
  7273. if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
  7274. };
  7275. /***/ }),
  7276. /* 60 */
  7277. /***/ (function(module, exports, __webpack_require__) {
  7278. "use strict";
  7279. var $at = __webpack_require__(135)(true);
  7280. // 21.1.3.27 String.prototype[@@iterator]()
  7281. __webpack_require__(79)(String, 'String', function (iterated) {
  7282. this._t = String(iterated); // target
  7283. this._i = 0; // next index
  7284. // 21.1.5.2.1 %StringIteratorPrototype%.next()
  7285. }, function () {
  7286. var O = this._t;
  7287. var index = this._i;
  7288. var point;
  7289. if (index >= O.length) return { value: undefined, done: true };
  7290. point = $at(O, index);
  7291. this._i += point.length;
  7292. return { value: point, done: false };
  7293. });
  7294. /***/ }),
  7295. /* 61 */
  7296. /***/ (function(module, exports, __webpack_require__) {
  7297. exports.f = __webpack_require__(13);
  7298. /***/ }),
  7299. /* 62 */
  7300. /***/ (function(module, exports, __webpack_require__) {
  7301. var global = __webpack_require__(18);
  7302. var core = __webpack_require__(7);
  7303. var LIBRARY = __webpack_require__(52);
  7304. var wksExt = __webpack_require__(61);
  7305. var defineProperty = __webpack_require__(20).f;
  7306. module.exports = function (name) {
  7307. var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
  7308. if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
  7309. };
  7310. /***/ }),
  7311. /* 63 */
  7312. /***/ (function(module, exports) {
  7313. exports.f = Object.getOwnPropertySymbols;
  7314. /***/ }),
  7315. /* 64 */
  7316. /***/ (function(module, exports, __webpack_require__) {
  7317. "use strict";
  7318. var _keys = __webpack_require__(8);
  7319. var _keys2 = _interopRequireDefault(_keys);
  7320. var _stringify = __webpack_require__(19);
  7321. var _stringify2 = _interopRequireDefault(_stringify);
  7322. var _typeof2 = __webpack_require__(6);
  7323. var _typeof3 = _interopRequireDefault(_typeof2);
  7324. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  7325. var util = __webpack_require__(2);
  7326. var moment = __webpack_require__(9);
  7327. var Component = __webpack_require__(16);
  7328. var DateUtil = __webpack_require__(36);
  7329. /**
  7330. * A Range controls a numeric range with a start and end value.
  7331. * The Range adjusts the range based on mouse events or programmatic changes,
  7332. * and triggers events when the range is changing or has been changed.
  7333. * @param {{dom: Object, domProps: Object, emitter: Emitter}} body
  7334. * @param {Object} [options] See description at Range.setOptions
  7335. * @constructor Range
  7336. * @extends Component
  7337. */
  7338. function Range(body, options) {
  7339. var now = moment().hours(0).minutes(0).seconds(0).milliseconds(0);
  7340. var start = now.clone().add(-3, 'days').valueOf();
  7341. var end = now.clone().add(3, 'days').valueOf();
  7342. this.millisecondsPerPixelCache = undefined;
  7343. if (options === undefined) {
  7344. this.start = start;
  7345. this.end = end;
  7346. } else {
  7347. this.start = options.start || start;
  7348. this.end = options.end || end;
  7349. }
  7350. this.rolling = false;
  7351. this.body = body;
  7352. this.deltaDifference = 0;
  7353. this.scaleOffset = 0;
  7354. this.startToFront = false;
  7355. this.endToFront = true;
  7356. // default options
  7357. this.defaultOptions = {
  7358. rtl: false,
  7359. start: null,
  7360. end: null,
  7361. moment: moment,
  7362. direction: 'horizontal', // 'horizontal' or 'vertical'
  7363. moveable: true,
  7364. zoomable: true,
  7365. min: null,
  7366. max: null,
  7367. zoomMin: 10, // milliseconds
  7368. zoomMax: 1000 * 60 * 60 * 24 * 365 * 10000, // milliseconds
  7369. rollingMode: {
  7370. follow: false,
  7371. offset: 0.5
  7372. }
  7373. };
  7374. this.options = util.extend({}, this.defaultOptions);
  7375. this.props = {
  7376. touch: {}
  7377. };
  7378. this.animationTimer = null;
  7379. // drag listeners for dragging
  7380. this.body.emitter.on('panstart', this._onDragStart.bind(this));
  7381. this.body.emitter.on('panmove', this._onDrag.bind(this));
  7382. this.body.emitter.on('panend', this._onDragEnd.bind(this));
  7383. // mouse wheel for zooming
  7384. this.body.emitter.on('mousewheel', this._onMouseWheel.bind(this));
  7385. // pinch to zoom
  7386. this.body.emitter.on('touch', this._onTouch.bind(this));
  7387. this.body.emitter.on('pinch', this._onPinch.bind(this));
  7388. // on click of rolling mode button
  7389. this.body.dom.rollingModeBtn.addEventListener('click', this.startRolling.bind(this));
  7390. this.setOptions(options);
  7391. }
  7392. Range.prototype = new Component();
  7393. /**
  7394. * Set options for the range controller
  7395. * @param {Object} options Available options:
  7396. * {number | Date | String} start Start date for the range
  7397. * {number | Date | String} end End date for the range
  7398. * {number} min Minimum value for start
  7399. * {number} max Maximum value for end
  7400. * {number} zoomMin Set a minimum value for
  7401. * (end - start).
  7402. * {number} zoomMax Set a maximum value for
  7403. * (end - start).
  7404. * {boolean} moveable Enable moving of the range
  7405. * by dragging. True by default
  7406. * {boolean} zoomable Enable zooming of the range
  7407. * by pinching/scrolling. True by default
  7408. */
  7409. Range.prototype.setOptions = function (options) {
  7410. if (options) {
  7411. // copy the options that we know
  7412. var fields = ['animation', 'direction', 'min', 'max', 'zoomMin', 'zoomMax', 'moveable', 'zoomable', 'moment', 'activate', 'hiddenDates', 'zoomKey', 'rtl', 'showCurrentTime', 'rollingMode', 'horizontalScroll'];
  7413. util.selectiveExtend(fields, this.options, options);
  7414. if (options.rollingMode && options.rollingMode.follow) {
  7415. this.startRolling();
  7416. }
  7417. if ('start' in options || 'end' in options) {
  7418. // apply a new range. both start and end are optional
  7419. this.setRange(options.start, options.end);
  7420. }
  7421. }
  7422. };
  7423. /**
  7424. * Test whether direction has a valid value
  7425. * @param {string} direction 'horizontal' or 'vertical'
  7426. */
  7427. function validateDirection(direction) {
  7428. if (direction != 'horizontal' && direction != 'vertical') {
  7429. throw new TypeError('Unknown direction "' + direction + '". ' + 'Choose "horizontal" or "vertical".');
  7430. }
  7431. }
  7432. /**
  7433. * Start auto refreshing the current time bar
  7434. */
  7435. Range.prototype.startRolling = function () {
  7436. var me = this;
  7437. /**
  7438. * Updates the current time.
  7439. */
  7440. function update() {
  7441. me.stopRolling();
  7442. me.rolling = true;
  7443. var interval = me.end - me.start;
  7444. var t = util.convert(new Date(), 'Date').valueOf();
  7445. var start = t - interval * me.options.rollingMode.offset;
  7446. var end = t + interval * (1 - me.options.rollingMode.offset);
  7447. var options = {
  7448. animation: false
  7449. };
  7450. me.setRange(start, end, options);
  7451. // determine interval to refresh
  7452. var scale = me.conversion(me.body.domProps.center.width).scale;
  7453. interval = 1 / scale / 10;
  7454. if (interval < 30) interval = 30;
  7455. if (interval > 1000) interval = 1000;
  7456. me.body.dom.rollingModeBtn.style.visibility = "hidden";
  7457. // start a renderTimer to adjust for the new time
  7458. me.currentTimeTimer = setTimeout(update, interval);
  7459. }
  7460. update();
  7461. };
  7462. /**
  7463. * Stop auto refreshing the current time bar
  7464. */
  7465. Range.prototype.stopRolling = function () {
  7466. if (this.currentTimeTimer !== undefined) {
  7467. clearTimeout(this.currentTimeTimer);
  7468. this.rolling = false;
  7469. this.body.dom.rollingModeBtn.style.visibility = "visible";
  7470. }
  7471. };
  7472. /**
  7473. * Set a new start and end range
  7474. * @param {Date | number | string} [start]
  7475. * @param {Date | number | string} [end]
  7476. * @param {Object} options Available options:
  7477. * {boolean | {duration: number, easingFunction: string}} [animation=false]
  7478. * If true, the range is animated
  7479. * smoothly to the new window. An object can be
  7480. * provided to specify duration and easing function.
  7481. * Default duration is 500 ms, and default easing
  7482. * function is 'easeInOutQuad'.
  7483. * {boolean} [byUser=false]
  7484. * {Event} event Mouse event
  7485. * @param {Function} callback a callback function to be executed at the end of this function
  7486. * @param {Function} frameCallback a callback function executed each frame of the range animation.
  7487. * The callback will be passed three parameters:
  7488. * {number} easeCoefficient an easing coefficent
  7489. * {boolean} willDraw If true the caller will redraw after the callback completes
  7490. * {boolean} done If true then animation is ending after the current frame
  7491. */
  7492. Range.prototype.setRange = function (start, end, options, callback, frameCallback) {
  7493. if (!options) {
  7494. options = {};
  7495. }
  7496. if (options.byUser !== true) {
  7497. options.byUser = false;
  7498. }
  7499. var me = this;
  7500. var finalStart = start != undefined ? util.convert(start, 'Date').valueOf() : null;
  7501. var finalEnd = end != undefined ? util.convert(end, 'Date').valueOf() : null;
  7502. this._cancelAnimation();
  7503. this.millisecondsPerPixelCache = undefined;
  7504. if (options.animation) {
  7505. // true or an Object
  7506. var initStart = this.start;
  7507. var initEnd = this.end;
  7508. var duration = (0, _typeof3['default'])(options.animation) === 'object' && 'duration' in options.animation ? options.animation.duration : 500;
  7509. var easingName = (0, _typeof3['default'])(options.animation) === 'object' && 'easingFunction' in options.animation ? options.animation.easingFunction : 'easeInOutQuad';
  7510. var easingFunction = util.easingFunctions[easingName];
  7511. if (!easingFunction) {
  7512. throw new Error('Unknown easing function ' + (0, _stringify2['default'])(easingName) + '. ' + 'Choose from: ' + (0, _keys2['default'])(util.easingFunctions).join(', '));
  7513. }
  7514. var initTime = new Date().valueOf();
  7515. var anyChanged = false;
  7516. var next = function next() {
  7517. if (!me.props.touch.dragging) {
  7518. var now = new Date().valueOf();
  7519. var time = now - initTime;
  7520. var ease = easingFunction(time / duration);
  7521. var done = time > duration;
  7522. var s = done || finalStart === null ? finalStart : initStart + (finalStart - initStart) * ease;
  7523. var e = done || finalEnd === null ? finalEnd : initEnd + (finalEnd - initEnd) * ease;
  7524. changed = me._applyRange(s, e);
  7525. DateUtil.updateHiddenDates(me.options.moment, me.body, me.options.hiddenDates);
  7526. anyChanged = anyChanged || changed;
  7527. var params = {
  7528. start: new Date(me.start),
  7529. end: new Date(me.end),
  7530. byUser: options.byUser,
  7531. event: options.event
  7532. };
  7533. if (frameCallback) {
  7534. frameCallback(ease, changed, done);
  7535. }
  7536. if (changed) {
  7537. me.body.emitter.emit('rangechange', params);
  7538. }
  7539. if (done) {
  7540. if (anyChanged) {
  7541. me.body.emitter.emit('rangechanged', params);
  7542. if (callback) {
  7543. return callback();
  7544. }
  7545. }
  7546. } else {
  7547. // animate with as high as possible frame rate, leave 20 ms in between
  7548. // each to prevent the browser from blocking
  7549. me.animationTimer = setTimeout(next, 20);
  7550. }
  7551. }
  7552. };
  7553. return next();
  7554. } else {
  7555. var changed = this._applyRange(finalStart, finalEnd);
  7556. DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
  7557. if (changed) {
  7558. var params = {
  7559. start: new Date(this.start),
  7560. end: new Date(this.end),
  7561. byUser: options.byUser,
  7562. event: options.event
  7563. };
  7564. this.body.emitter.emit('rangechange', params);
  7565. clearTimeout(me.timeoutID);
  7566. me.timeoutID = setTimeout(function () {
  7567. me.body.emitter.emit('rangechanged', params);
  7568. }, 200);
  7569. if (callback) {
  7570. return callback();
  7571. }
  7572. }
  7573. }
  7574. };
  7575. /**
  7576. * Get the number of milliseconds per pixel.
  7577. *
  7578. * @returns {undefined|number}
  7579. */
  7580. Range.prototype.getMillisecondsPerPixel = function () {
  7581. if (this.millisecondsPerPixelCache === undefined) {
  7582. this.millisecondsPerPixelCache = (this.end - this.start) / this.body.dom.center.clientWidth;
  7583. }
  7584. return this.millisecondsPerPixelCache;
  7585. };
  7586. /**
  7587. * Stop an animation
  7588. * @private
  7589. */
  7590. Range.prototype._cancelAnimation = function () {
  7591. if (this.animationTimer) {
  7592. clearTimeout(this.animationTimer);
  7593. this.animationTimer = null;
  7594. }
  7595. };
  7596. /**
  7597. * Set a new start and end range. This method is the same as setRange, but
  7598. * does not trigger a range change and range changed event, and it returns
  7599. * true when the range is changed
  7600. * @param {number} [start]
  7601. * @param {number} [end]
  7602. * @return {boolean} changed
  7603. * @private
  7604. */
  7605. Range.prototype._applyRange = function (start, end) {
  7606. var newStart = start != null ? util.convert(start, 'Date').valueOf() : this.start,
  7607. newEnd = end != null ? util.convert(end, 'Date').valueOf() : this.end,
  7608. max = this.options.max != null ? util.convert(this.options.max, 'Date').valueOf() : null,
  7609. min = this.options.min != null ? util.convert(this.options.min, 'Date').valueOf() : null,
  7610. diff;
  7611. // check for valid number
  7612. if (isNaN(newStart) || newStart === null) {
  7613. throw new Error('Invalid start "' + start + '"');
  7614. }
  7615. if (isNaN(newEnd) || newEnd === null) {
  7616. throw new Error('Invalid end "' + end + '"');
  7617. }
  7618. // prevent end < start
  7619. if (newEnd < newStart) {
  7620. newEnd = newStart;
  7621. }
  7622. // prevent start < min
  7623. if (min !== null) {
  7624. if (newStart < min) {
  7625. diff = min - newStart;
  7626. newStart += diff;
  7627. newEnd += diff;
  7628. // prevent end > max
  7629. if (max != null) {
  7630. if (newEnd > max) {
  7631. newEnd = max;
  7632. }
  7633. }
  7634. }
  7635. }
  7636. // prevent end > max
  7637. if (max !== null) {
  7638. if (newEnd > max) {
  7639. diff = newEnd - max;
  7640. newStart -= diff;
  7641. newEnd -= diff;
  7642. // prevent start < min
  7643. if (min != null) {
  7644. if (newStart < min) {
  7645. newStart = min;
  7646. }
  7647. }
  7648. }
  7649. }
  7650. // prevent (end-start) < zoomMin
  7651. if (this.options.zoomMin !== null) {
  7652. var zoomMin = parseFloat(this.options.zoomMin);
  7653. if (zoomMin < 0) {
  7654. zoomMin = 0;
  7655. }
  7656. if (newEnd - newStart < zoomMin) {
  7657. // compensate for a scale of 0.5 ms
  7658. var compensation = 0.5;
  7659. if (this.end - this.start === zoomMin && newStart >= this.start - compensation && newEnd <= this.end) {
  7660. // ignore this action, we are already zoomed to the minimum
  7661. newStart = this.start;
  7662. newEnd = this.end;
  7663. } else {
  7664. // zoom to the minimum
  7665. diff = zoomMin - (newEnd - newStart);
  7666. newStart -= diff / 2;
  7667. newEnd += diff / 2;
  7668. }
  7669. }
  7670. }
  7671. // prevent (end-start) > zoomMax
  7672. if (this.options.zoomMax !== null) {
  7673. var zoomMax = parseFloat(this.options.zoomMax);
  7674. if (zoomMax < 0) {
  7675. zoomMax = 0;
  7676. }
  7677. if (newEnd - newStart > zoomMax) {
  7678. if (this.end - this.start === zoomMax && newStart < this.start && newEnd > this.end) {
  7679. // ignore this action, we are already zoomed to the maximum
  7680. newStart = this.start;
  7681. newEnd = this.end;
  7682. } else {
  7683. // zoom to the maximum
  7684. diff = newEnd - newStart - zoomMax;
  7685. newStart += diff / 2;
  7686. newEnd -= diff / 2;
  7687. }
  7688. }
  7689. }
  7690. var changed = this.start != newStart || this.end != newEnd;
  7691. // 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)
  7692. 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)) {
  7693. this.body.emitter.emit('checkRangedItems');
  7694. }
  7695. this.start = newStart;
  7696. this.end = newEnd;
  7697. return changed;
  7698. };
  7699. /**
  7700. * Retrieve the current range.
  7701. * @return {Object} An object with start and end properties
  7702. */
  7703. Range.prototype.getRange = function () {
  7704. return {
  7705. start: this.start,
  7706. end: this.end
  7707. };
  7708. };
  7709. /**
  7710. * Calculate the conversion offset and scale for current range, based on
  7711. * the provided width
  7712. * @param {number} width
  7713. * @param {number} [totalHidden=0]
  7714. * @returns {{offset: number, scale: number}} conversion
  7715. */
  7716. Range.prototype.conversion = function (width, totalHidden) {
  7717. return Range.conversion(this.start, this.end, width, totalHidden);
  7718. };
  7719. /**
  7720. * Static method to calculate the conversion offset and scale for a range,
  7721. * based on the provided start, end, and width
  7722. * @param {number} start
  7723. * @param {number} end
  7724. * @param {number} width
  7725. * @param {number} [totalHidden=0]
  7726. * @returns {{offset: number, scale: number}} conversion
  7727. */
  7728. Range.conversion = function (start, end, width, totalHidden) {
  7729. if (totalHidden === undefined) {
  7730. totalHidden = 0;
  7731. }
  7732. if (width != 0 && end - start != 0) {
  7733. return {
  7734. offset: start,
  7735. scale: width / (end - start - totalHidden)
  7736. };
  7737. } else {
  7738. return {
  7739. offset: 0,
  7740. scale: 1
  7741. };
  7742. }
  7743. };
  7744. /**
  7745. * Start dragging horizontally or vertically
  7746. * @param {Event} event
  7747. * @private
  7748. */
  7749. Range.prototype._onDragStart = function (event) {
  7750. this.deltaDifference = 0;
  7751. this.previousDelta = 0;
  7752. // only allow dragging when configured as movable
  7753. if (!this.options.moveable) return;
  7754. // only start dragging when the mouse is inside the current range
  7755. if (!this._isInsideRange(event)) return;
  7756. // refuse to drag when we where pinching to prevent the timeline make a jump
  7757. // when releasing the fingers in opposite order from the touch screen
  7758. if (!this.props.touch.allowDragging) return;
  7759. this.stopRolling();
  7760. this.props.touch.start = this.start;
  7761. this.props.touch.end = this.end;
  7762. this.props.touch.dragging = true;
  7763. if (this.body.dom.root) {
  7764. this.body.dom.root.style.cursor = 'move';
  7765. }
  7766. };
  7767. /**
  7768. * Perform dragging operation
  7769. * @param {Event} event
  7770. * @private
  7771. */
  7772. Range.prototype._onDrag = function (event) {
  7773. if (!event) return;
  7774. if (!this.props.touch.dragging) return;
  7775. // only allow dragging when configured as movable
  7776. if (!this.options.moveable) return;
  7777. // TODO: this may be redundant in hammerjs2
  7778. // refuse to drag when we where pinching to prevent the timeline make a jump
  7779. // when releasing the fingers in opposite order from the touch screen
  7780. if (!this.props.touch.allowDragging) return;
  7781. var direction = this.options.direction;
  7782. validateDirection(direction);
  7783. var delta = direction == 'horizontal' ? event.deltaX : event.deltaY;
  7784. delta -= this.deltaDifference;
  7785. var interval = this.props.touch.end - this.props.touch.start;
  7786. // normalize dragging speed if cutout is in between.
  7787. var duration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  7788. interval -= duration;
  7789. var width = direction == 'horizontal' ? this.body.domProps.center.width : this.body.domProps.center.height;
  7790. var diffRange;
  7791. if (this.options.rtl) {
  7792. diffRange = delta / width * interval;
  7793. } else {
  7794. diffRange = -delta / width * interval;
  7795. }
  7796. var newStart = this.props.touch.start + diffRange;
  7797. var newEnd = this.props.touch.end + diffRange;
  7798. // snapping times away from hidden zones
  7799. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, this.previousDelta - delta, true);
  7800. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, this.previousDelta - delta, true);
  7801. if (safeStart != newStart || safeEnd != newEnd) {
  7802. this.deltaDifference += delta;
  7803. this.props.touch.start = safeStart;
  7804. this.props.touch.end = safeEnd;
  7805. this._onDrag(event);
  7806. return;
  7807. }
  7808. this.previousDelta = delta;
  7809. this._applyRange(newStart, newEnd);
  7810. var startDate = new Date(this.start);
  7811. var endDate = new Date(this.end);
  7812. // fire a rangechange event
  7813. this.body.emitter.emit('rangechange', {
  7814. start: startDate,
  7815. end: endDate,
  7816. byUser: true,
  7817. event: event
  7818. });
  7819. // fire a panmove event
  7820. this.body.emitter.emit('panmove');
  7821. };
  7822. /**
  7823. * Stop dragging operation
  7824. * @param {event} event
  7825. * @private
  7826. */
  7827. Range.prototype._onDragEnd = function (event) {
  7828. if (!this.props.touch.dragging) return;
  7829. // only allow dragging when configured as movable
  7830. if (!this.options.moveable) return;
  7831. // TODO: this may be redundant in hammerjs2
  7832. // refuse to drag when we where pinching to prevent the timeline make a jump
  7833. // when releasing the fingers in opposite order from the touch screen
  7834. if (!this.props.touch.allowDragging) return;
  7835. this.props.touch.dragging = false;
  7836. if (this.body.dom.root) {
  7837. this.body.dom.root.style.cursor = 'auto';
  7838. }
  7839. // fire a rangechanged event
  7840. this.body.emitter.emit('rangechanged', {
  7841. start: new Date(this.start),
  7842. end: new Date(this.end),
  7843. byUser: true,
  7844. event: event
  7845. });
  7846. };
  7847. /**
  7848. * Event handler for mouse wheel event, used to zoom
  7849. * Code from http://adomas.org/javascript-mouse-wheel/
  7850. * @param {Event} event
  7851. * @private
  7852. */
  7853. Range.prototype._onMouseWheel = function (event) {
  7854. // retrieve delta
  7855. var delta = 0;
  7856. if (event.wheelDelta) {
  7857. /* IE/Opera. */
  7858. delta = event.wheelDelta / 120;
  7859. } else if (event.detail) {
  7860. /* Mozilla case. */
  7861. // In Mozilla, sign of delta is different than in IE.
  7862. // Also, delta is multiple of 3.
  7863. delta = -event.detail / 3;
  7864. }
  7865. // don't allow zoom when the according key is pressed and the zoomKey option or not zoomable but movable
  7866. if (this.options.zoomKey && !event[this.options.zoomKey] && this.options.zoomable || !this.options.zoomable && this.options.moveable) {
  7867. return;
  7868. }
  7869. // only allow zooming when configured as zoomable and moveable
  7870. if (!(this.options.zoomable && this.options.moveable)) return;
  7871. // only zoom when the mouse is inside the current range
  7872. if (!this._isInsideRange(event)) return;
  7873. // If delta is nonzero, handle it.
  7874. // Basically, delta is now positive if wheel was scrolled up,
  7875. // and negative, if wheel was scrolled down.
  7876. if (delta) {
  7877. // perform the zoom action. Delta is normally 1 or -1
  7878. // adjust a negative delta such that zooming in with delta 0.1
  7879. // equals zooming out with a delta -0.1
  7880. var scale;
  7881. if (delta < 0) {
  7882. scale = 1 - delta / 5;
  7883. } else {
  7884. scale = 1 / (1 + delta / 5);
  7885. }
  7886. // calculate center, the date to zoom around
  7887. var pointerDate;
  7888. if (this.rolling) {
  7889. pointerDate = this.start + (this.end - this.start) * this.options.rollingMode.offset;
  7890. } else {
  7891. var pointer = this.getPointer({ x: event.clientX, y: event.clientY }, this.body.dom.center);
  7892. pointerDate = this._pointerToDate(pointer);
  7893. }
  7894. this.zoom(scale, pointerDate, delta, event);
  7895. // Prevent default actions caused by mouse wheel
  7896. // (else the page and timeline both scroll)
  7897. event.preventDefault();
  7898. }
  7899. };
  7900. /**
  7901. * Start of a touch gesture
  7902. * @param {Event} event
  7903. * @private
  7904. */
  7905. Range.prototype._onTouch = function (event) {
  7906. // eslint-disable-line no-unused-vars
  7907. this.props.touch.start = this.start;
  7908. this.props.touch.end = this.end;
  7909. this.props.touch.allowDragging = true;
  7910. this.props.touch.center = null;
  7911. this.scaleOffset = 0;
  7912. this.deltaDifference = 0;
  7913. // Disable the browser default handling of this event.
  7914. util.preventDefault(event);
  7915. };
  7916. /**
  7917. * Handle pinch event
  7918. * @param {Event} event
  7919. * @private
  7920. */
  7921. Range.prototype._onPinch = function (event) {
  7922. // only allow zooming when configured as zoomable and moveable
  7923. if (!(this.options.zoomable && this.options.moveable)) return;
  7924. // Disable the browser default handling of this event.
  7925. util.preventDefault(event);
  7926. this.props.touch.allowDragging = false;
  7927. if (!this.props.touch.center) {
  7928. this.props.touch.center = this.getPointer(event.center, this.body.dom.center);
  7929. }
  7930. this.stopRolling();
  7931. var scale = 1 / (event.scale + this.scaleOffset);
  7932. var centerDate = this._pointerToDate(this.props.touch.center);
  7933. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  7934. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this, centerDate);
  7935. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  7936. // calculate new start and end
  7937. var newStart = centerDate - hiddenDurationBefore + (this.props.touch.start - (centerDate - hiddenDurationBefore)) * scale;
  7938. var newEnd = centerDate + hiddenDurationAfter + (this.props.touch.end - (centerDate + hiddenDurationAfter)) * scale;
  7939. // snapping times away from hidden zones
  7940. this.startToFront = 1 - scale <= 0; // used to do the right auto correction with periodic hidden times
  7941. this.endToFront = scale - 1 <= 0; // used to do the right auto correction with periodic hidden times
  7942. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, 1 - scale, true);
  7943. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, scale - 1, true);
  7944. if (safeStart != newStart || safeEnd != newEnd) {
  7945. this.props.touch.start = safeStart;
  7946. this.props.touch.end = safeEnd;
  7947. this.scaleOffset = 1 - event.scale;
  7948. newStart = safeStart;
  7949. newEnd = safeEnd;
  7950. }
  7951. var options = {
  7952. animation: false,
  7953. byUser: true,
  7954. event: event
  7955. };
  7956. this.setRange(newStart, newEnd, options);
  7957. this.startToFront = false; // revert to default
  7958. this.endToFront = true; // revert to default
  7959. };
  7960. /**
  7961. * Test whether the mouse from a mouse event is inside the visible window,
  7962. * between the current start and end date
  7963. * @param {Object} event
  7964. * @return {boolean} Returns true when inside the visible window
  7965. * @private
  7966. */
  7967. Range.prototype._isInsideRange = function (event) {
  7968. // calculate the time where the mouse is, check whether inside
  7969. // and no scroll action should happen.
  7970. var clientX = event.center ? event.center.x : event.clientX;
  7971. var x;
  7972. if (this.options.rtl) {
  7973. x = clientX - util.getAbsoluteLeft(this.body.dom.centerContainer);
  7974. } else {
  7975. x = util.getAbsoluteRight(this.body.dom.centerContainer) - clientX;
  7976. }
  7977. var time = this.body.util.toTime(x);
  7978. return time >= this.start && time <= this.end;
  7979. };
  7980. /**
  7981. * Helper function to calculate the center date for zooming
  7982. * @param {{x: number, y: number}} pointer
  7983. * @return {number} date
  7984. * @private
  7985. */
  7986. Range.prototype._pointerToDate = function (pointer) {
  7987. var conversion;
  7988. var direction = this.options.direction;
  7989. validateDirection(direction);
  7990. if (direction == 'horizontal') {
  7991. return this.body.util.toTime(pointer.x).valueOf();
  7992. } else {
  7993. var height = this.body.domProps.center.height;
  7994. conversion = this.conversion(height);
  7995. return pointer.y / conversion.scale + conversion.offset;
  7996. }
  7997. };
  7998. /**
  7999. * Get the pointer location relative to the location of the dom element
  8000. * @param {{x: number, y: number}} touch
  8001. * @param {Element} element HTML DOM element
  8002. * @return {{x: number, y: number}} pointer
  8003. * @private
  8004. */
  8005. Range.prototype.getPointer = function (touch, element) {
  8006. if (this.options.rtl) {
  8007. return {
  8008. x: util.getAbsoluteRight(element) - touch.x,
  8009. y: touch.y - util.getAbsoluteTop(element)
  8010. };
  8011. } else {
  8012. return {
  8013. x: touch.x - util.getAbsoluteLeft(element),
  8014. y: touch.y - util.getAbsoluteTop(element)
  8015. };
  8016. }
  8017. };
  8018. /**
  8019. * Zoom the range the given scale in or out. Start and end date will
  8020. * be adjusted, and the timeline will be redrawn. You can optionally give a
  8021. * date around which to zoom.
  8022. * For example, try scale = 0.9 or 1.1
  8023. * @param {number} scale Scaling factor. Values above 1 will zoom out,
  8024. * values below 1 will zoom in.
  8025. * @param {number} [center] Value representing a date around which will
  8026. * be zoomed.
  8027. * @param {number} delta
  8028. * @param {Event} event
  8029. */
  8030. Range.prototype.zoom = function (scale, center, delta, event) {
  8031. // if centerDate is not provided, take it half between start Date and end Date
  8032. if (center == null) {
  8033. center = (this.start + this.end) / 2;
  8034. }
  8035. var hiddenDuration = DateUtil.getHiddenDurationBetween(this.body.hiddenDates, this.start, this.end);
  8036. var hiddenDurationBefore = DateUtil.getHiddenDurationBefore(this.options.moment, this.body.hiddenDates, this, center);
  8037. var hiddenDurationAfter = hiddenDuration - hiddenDurationBefore;
  8038. // calculate new start and end
  8039. var newStart = center - hiddenDurationBefore + (this.start - (center - hiddenDurationBefore)) * scale;
  8040. var newEnd = center + hiddenDurationAfter + (this.end - (center + hiddenDurationAfter)) * scale;
  8041. // snapping times away from hidden zones
  8042. this.startToFront = delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  8043. this.endToFront = -delta > 0 ? false : true; // used to do the right autocorrection with periodic hidden times
  8044. var safeStart = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newStart, delta, true);
  8045. var safeEnd = DateUtil.snapAwayFromHidden(this.body.hiddenDates, newEnd, -delta, true);
  8046. if (safeStart != newStart || safeEnd != newEnd) {
  8047. newStart = safeStart;
  8048. newEnd = safeEnd;
  8049. }
  8050. var options = {
  8051. animation: false,
  8052. byUser: true,
  8053. event: event
  8054. };
  8055. this.setRange(newStart, newEnd, options);
  8056. this.startToFront = false; // revert to default
  8057. this.endToFront = true; // revert to default
  8058. };
  8059. /**
  8060. * Move the range with a given delta to the left or right. Start and end
  8061. * value will be adjusted. For example, try delta = 0.1 or -0.1
  8062. * @param {number} delta Moving amount. Positive value will move right,
  8063. * negative value will move left
  8064. */
  8065. Range.prototype.move = function (delta) {
  8066. // zoom start Date and end Date relative to the centerDate
  8067. var diff = this.end - this.start;
  8068. // apply new values
  8069. var newStart = this.start + diff * delta;
  8070. var newEnd = this.end + diff * delta;
  8071. // TODO: reckon with min and max range
  8072. this.start = newStart;
  8073. this.end = newEnd;
  8074. };
  8075. /**
  8076. * Move the range to a new center point
  8077. * @param {number} moveTo New center point of the range
  8078. */
  8079. Range.prototype.moveTo = function (moveTo) {
  8080. var center = (this.start + this.end) / 2;
  8081. var diff = center - moveTo;
  8082. // calculate new start and end
  8083. var newStart = this.start - diff;
  8084. var newEnd = this.end - diff;
  8085. var options = {
  8086. animation: false,
  8087. byUser: true,
  8088. event: null
  8089. };
  8090. this.setRange(newStart, newEnd, options);
  8091. };
  8092. module.exports = Range;
  8093. /***/ }),
  8094. /* 65 */
  8095. /***/ (function(module, exports, __webpack_require__) {
  8096. "use strict";
  8097. var _stringify = __webpack_require__(19);
  8098. var _stringify2 = _interopRequireDefault(_stringify);
  8099. var _typeof2 = __webpack_require__(6);
  8100. var _typeof3 = _interopRequireDefault(_typeof2);
  8101. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  8102. var Emitter = __webpack_require__(44);
  8103. var Hammer = __webpack_require__(10);
  8104. var hammerUtil = __webpack_require__(37);
  8105. var util = __webpack_require__(2);
  8106. var TimeAxis = __webpack_require__(45);
  8107. var Activator = __webpack_require__(97);
  8108. var DateUtil = __webpack_require__(36);
  8109. var CustomTime = __webpack_require__(46);
  8110. /**
  8111. * Create a timeline visualization
  8112. * @constructor Core
  8113. */
  8114. function Core() {}
  8115. // turn Core into an event emitter
  8116. Emitter(Core.prototype);
  8117. /**
  8118. * Create the main DOM for the Core: a root panel containing left, right,
  8119. * top, bottom, content, and background panel.
  8120. * @param {Element} container The container element where the Core will
  8121. * be attached.
  8122. * @protected
  8123. */
  8124. Core.prototype._create = function (container) {
  8125. this.dom = {};
  8126. this.dom.container = container;
  8127. this.dom.root = document.createElement('div');
  8128. this.dom.background = document.createElement('div');
  8129. this.dom.backgroundVertical = document.createElement('div');
  8130. this.dom.backgroundHorizontal = document.createElement('div');
  8131. this.dom.centerContainer = document.createElement('div');
  8132. this.dom.leftContainer = document.createElement('div');
  8133. this.dom.rightContainer = document.createElement('div');
  8134. this.dom.center = document.createElement('div');
  8135. this.dom.left = document.createElement('div');
  8136. this.dom.right = document.createElement('div');
  8137. this.dom.top = document.createElement('div');
  8138. this.dom.bottom = document.createElement('div');
  8139. this.dom.shadowTop = document.createElement('div');
  8140. this.dom.shadowBottom = document.createElement('div');
  8141. this.dom.shadowTopLeft = document.createElement('div');
  8142. this.dom.shadowBottomLeft = document.createElement('div');
  8143. this.dom.shadowTopRight = document.createElement('div');
  8144. this.dom.shadowBottomRight = document.createElement('div');
  8145. this.dom.rollingModeBtn = document.createElement('div');
  8146. this.dom.root.className = 'vis-timeline';
  8147. this.dom.background.className = 'vis-panel vis-background';
  8148. this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical';
  8149. this.dom.backgroundHorizontal.className = 'vis-panel vis-background vis-horizontal';
  8150. this.dom.centerContainer.className = 'vis-panel vis-center';
  8151. this.dom.leftContainer.className = 'vis-panel vis-left';
  8152. this.dom.rightContainer.className = 'vis-panel vis-right';
  8153. this.dom.top.className = 'vis-panel vis-top';
  8154. this.dom.bottom.className = 'vis-panel vis-bottom';
  8155. this.dom.left.className = 'vis-content';
  8156. this.dom.center.className = 'vis-content';
  8157. this.dom.right.className = 'vis-content';
  8158. this.dom.shadowTop.className = 'vis-shadow vis-top';
  8159. this.dom.shadowBottom.className = 'vis-shadow vis-bottom';
  8160. this.dom.shadowTopLeft.className = 'vis-shadow vis-top';
  8161. this.dom.shadowBottomLeft.className = 'vis-shadow vis-bottom';
  8162. this.dom.shadowTopRight.className = 'vis-shadow vis-top';
  8163. this.dom.shadowBottomRight.className = 'vis-shadow vis-bottom';
  8164. this.dom.rollingModeBtn.className = 'vis-rolling-mode-btn';
  8165. this.dom.root.appendChild(this.dom.background);
  8166. this.dom.root.appendChild(this.dom.backgroundVertical);
  8167. this.dom.root.appendChild(this.dom.backgroundHorizontal);
  8168. this.dom.root.appendChild(this.dom.centerContainer);
  8169. this.dom.root.appendChild(this.dom.leftContainer);
  8170. this.dom.root.appendChild(this.dom.rightContainer);
  8171. this.dom.root.appendChild(this.dom.top);
  8172. this.dom.root.appendChild(this.dom.bottom);
  8173. this.dom.root.appendChild(this.dom.bottom);
  8174. this.dom.root.appendChild(this.dom.rollingModeBtn);
  8175. this.dom.centerContainer.appendChild(this.dom.center);
  8176. this.dom.leftContainer.appendChild(this.dom.left);
  8177. this.dom.rightContainer.appendChild(this.dom.right);
  8178. this.dom.centerContainer.appendChild(this.dom.shadowTop);
  8179. this.dom.centerContainer.appendChild(this.dom.shadowBottom);
  8180. this.dom.leftContainer.appendChild(this.dom.shadowTopLeft);
  8181. this.dom.leftContainer.appendChild(this.dom.shadowBottomLeft);
  8182. this.dom.rightContainer.appendChild(this.dom.shadowTopRight);
  8183. this.dom.rightContainer.appendChild(this.dom.shadowBottomRight);
  8184. // size properties of each of the panels
  8185. this.props = {
  8186. root: {},
  8187. background: {},
  8188. centerContainer: {},
  8189. leftContainer: {},
  8190. rightContainer: {},
  8191. center: {},
  8192. left: {},
  8193. right: {},
  8194. top: {},
  8195. bottom: {},
  8196. border: {},
  8197. scrollTop: 0,
  8198. scrollTopMin: 0
  8199. };
  8200. this.on('rangechange', function () {
  8201. if (this.initialDrawDone === true) {
  8202. this._redraw();
  8203. }
  8204. }.bind(this));
  8205. this.on('rangechanged', function () {
  8206. if (!this.initialRangeChangeDone) {
  8207. this.initialRangeChangeDone = true;
  8208. }
  8209. }.bind(this));
  8210. this.on('touch', this._onTouch.bind(this));
  8211. this.on('panmove', this._onDrag.bind(this));
  8212. var me = this;
  8213. this._origRedraw = this._redraw.bind(this);
  8214. this._redraw = util.throttle(this._origRedraw);
  8215. this.on('_change', function (properties) {
  8216. if (me.itemSet && me.itemSet.initialItemSetDrawn && properties && properties.queue == true) {
  8217. me._redraw();
  8218. } else {
  8219. me._origRedraw();
  8220. }
  8221. });
  8222. // create event listeners for all interesting events, these events will be
  8223. // emitted via emitter
  8224. this.hammer = new Hammer(this.dom.root);
  8225. var pinchRecognizer = this.hammer.get('pinch').set({ enable: true });
  8226. hammerUtil.disablePreventDefaultVertically(pinchRecognizer);
  8227. this.hammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_HORIZONTAL });
  8228. this.listeners = {};
  8229. var events = ['tap', 'doubletap', 'press', 'pinch', 'pan', 'panstart', 'panmove', 'panend'
  8230. // TODO: cleanup
  8231. //'touch', 'pinch',
  8232. //'tap', 'doubletap', 'hold',
  8233. //'dragstart', 'drag', 'dragend',
  8234. //'mousewheel', 'DOMMouseScroll' // DOMMouseScroll is needed for Firefox
  8235. ];
  8236. events.forEach(function (type) {
  8237. var listener = function listener(event) {
  8238. if (me.isActive()) {
  8239. me.emit(type, event);
  8240. }
  8241. };
  8242. me.hammer.on(type, listener);
  8243. me.listeners[type] = listener;
  8244. });
  8245. // emulate a touch event (emitted before the start of a pan, pinch, tap, or press)
  8246. hammerUtil.onTouch(this.hammer, function (event) {
  8247. me.emit('touch', event);
  8248. }.bind(this));
  8249. // emulate a release event (emitted after a pan, pinch, tap, or press)
  8250. hammerUtil.onRelease(this.hammer, function (event) {
  8251. me.emit('release', event);
  8252. }.bind(this));
  8253. /**
  8254. *
  8255. * @param {WheelEvent} event
  8256. */
  8257. function onMouseWheel(event) {
  8258. if (this.isActive()) {
  8259. this.emit('mousewheel', event);
  8260. }
  8261. // deltaX and deltaY normalization from jquery.mousewheel.js
  8262. var deltaX = 0;
  8263. var deltaY = 0;
  8264. // Old school scrollwheel delta
  8265. if ('detail' in event) {
  8266. deltaY = event.detail * -1;
  8267. }
  8268. if ('wheelDelta' in event) {
  8269. deltaY = event.wheelDelta;
  8270. }
  8271. if ('wheelDeltaY' in event) {
  8272. deltaY = event.wheelDeltaY;
  8273. }
  8274. if ('wheelDeltaX' in event) {
  8275. deltaX = event.wheelDeltaX * -1;
  8276. }
  8277. // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
  8278. if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) {
  8279. deltaX = deltaY * -1;
  8280. deltaY = 0;
  8281. }
  8282. // New school wheel delta (wheel event)
  8283. if ('deltaY' in event) {
  8284. deltaY = event.deltaY * -1;
  8285. }
  8286. if ('deltaX' in event) {
  8287. deltaX = event.deltaX;
  8288. }
  8289. // prevent scrolling when zoomKey defined or activated
  8290. if (!this.options.zoomKey || event[this.options.zoomKey]) return;
  8291. // Prevent default actions caused by mouse wheel
  8292. // (else the page and timeline both scroll)
  8293. event.preventDefault();
  8294. if (this.options.verticalScroll && Math.abs(deltaY) >= Math.abs(deltaX)) {
  8295. var current = this.props.scrollTop;
  8296. var adjusted = current + deltaY;
  8297. if (this.isActive()) {
  8298. this._setScrollTop(adjusted);
  8299. this._redraw();
  8300. this.emit('scroll', event);
  8301. }
  8302. } else if (this.options.horizontalScroll) {
  8303. var delta = Math.abs(deltaX) >= Math.abs(deltaY) ? deltaX : deltaY;
  8304. // calculate a single scroll jump relative to the range scale
  8305. var diff = delta / 120 * (this.range.end - this.range.start) / 20;
  8306. // calculate new start and end
  8307. var newStart = this.range.start + diff;
  8308. var newEnd = this.range.end + diff;
  8309. var options = {
  8310. animation: false,
  8311. byUser: true,
  8312. event: event
  8313. };
  8314. this.range.setRange(newStart, newEnd, options);
  8315. }
  8316. }
  8317. if (this.dom.centerContainer.addEventListener) {
  8318. // IE9, Chrome, Safari, Opera
  8319. this.dom.centerContainer.addEventListener("mousewheel", onMouseWheel.bind(this), false);
  8320. // Firefox
  8321. this.dom.centerContainer.addEventListener("DOMMouseScroll", onMouseWheel.bind(this), false);
  8322. } else {
  8323. // IE 6/7/8
  8324. this.dom.centerContainer.attachEvent("onmousewheel", onMouseWheel.bind(this));
  8325. }
  8326. /**
  8327. *
  8328. * @param {scroll} event
  8329. */
  8330. function onMouseScrollSide(event) {
  8331. if (!me.options.verticalScroll) return;
  8332. event.preventDefault();
  8333. if (me.isActive()) {
  8334. var adjusted = -event.target.scrollTop;
  8335. me._setScrollTop(adjusted);
  8336. me._redraw();
  8337. me.emit('scrollSide', event);
  8338. }
  8339. }
  8340. this.dom.left.parentNode.addEventListener('scroll', onMouseScrollSide.bind(this));
  8341. this.dom.right.parentNode.addEventListener('scroll', onMouseScrollSide.bind(this));
  8342. var itemAddedToTimeline = false;
  8343. /**
  8344. *
  8345. * @param {dragover} event
  8346. * @returns {boolean}
  8347. */
  8348. function handleDragOver(event) {
  8349. if (event.preventDefault) {
  8350. event.preventDefault(); // Necessary. Allows us to drop.
  8351. }
  8352. // make sure your target is a vis element
  8353. if (!event.target.className.indexOf("vis") > -1) return;
  8354. // make sure only one item is added every time you're over the timeline
  8355. if (itemAddedToTimeline) return;
  8356. event.dataTransfer.dropEffect = 'move';
  8357. itemAddedToTimeline = true;
  8358. return false;
  8359. }
  8360. /**
  8361. *
  8362. * @param {drop} event
  8363. * @returns {boolean}
  8364. */
  8365. function handleDrop(event) {
  8366. // prevent redirect to blank page - Firefox
  8367. if (event.preventDefault) {
  8368. event.preventDefault();
  8369. }
  8370. if (event.stopPropagation) {
  8371. event.stopPropagation();
  8372. }
  8373. // return when dropping non-vis items
  8374. try {
  8375. var itemData = JSON.parse(event.dataTransfer.getData("text"));
  8376. if (!itemData || !itemData.content) return;
  8377. } catch (err) {
  8378. return false;
  8379. }
  8380. itemAddedToTimeline = false;
  8381. event.center = {
  8382. x: event.clientX,
  8383. y: event.clientY
  8384. };
  8385. if (itemData.target !== 'item') {
  8386. me.itemSet._onAddItem(event);
  8387. } else {
  8388. me.itemSet._onDropObjectOnItem(event);
  8389. }
  8390. me.emit('drop', me.getEventProperties(event));
  8391. return false;
  8392. }
  8393. this.dom.center.addEventListener('dragover', handleDragOver.bind(this), false);
  8394. this.dom.center.addEventListener('drop', handleDrop.bind(this), false);
  8395. this.customTimes = [];
  8396. // store state information needed for touch events
  8397. this.touch = {};
  8398. this.redrawCount = 0;
  8399. this.initialDrawDone = false;
  8400. this.initialRangeChangeDone = false;
  8401. // attach the root panel to the provided container
  8402. if (!container) throw new Error('No container provided');
  8403. container.appendChild(this.dom.root);
  8404. };
  8405. /**
  8406. * Set options. Options will be passed to all components loaded in the Timeline.
  8407. * @param {Object} [options]
  8408. * {String} orientation
  8409. * Vertical orientation for the Timeline,
  8410. * can be 'bottom' (default) or 'top'.
  8411. * {string | number} width
  8412. * Width for the timeline, a number in pixels or
  8413. * a css string like '1000px' or '75%'. '100%' by default.
  8414. * {string | number} height
  8415. * Fixed height for the Timeline, a number in pixels or
  8416. * a css string like '400px' or '75%'. If undefined,
  8417. * The Timeline will automatically size such that
  8418. * its contents fit.
  8419. * {string | number} minHeight
  8420. * Minimum height for the Timeline, a number in pixels or
  8421. * a css string like '400px' or '75%'.
  8422. * {string | number} maxHeight
  8423. * Maximum height for the Timeline, a number in pixels or
  8424. * a css string like '400px' or '75%'.
  8425. * {number | Date | string} start
  8426. * Start date for the visible window
  8427. * {number | Date | string} end
  8428. * End date for the visible window
  8429. */
  8430. Core.prototype.setOptions = function (options) {
  8431. if (options) {
  8432. // copy the known options
  8433. var fields = ['width', 'height', 'minHeight', 'maxHeight', 'autoResize', 'start', 'end', 'clickToUse', 'dataAttributes', 'hiddenDates', 'locale', 'locales', 'moment', 'rtl', 'zoomKey', 'horizontalScroll', 'verticalScroll'];
  8434. util.selectiveExtend(fields, this.options, options);
  8435. this.dom.rollingModeBtn.style.visibility = 'hidden';
  8436. if (this.options.rtl) {
  8437. this.dom.container.style.direction = "rtl";
  8438. this.dom.backgroundVertical.className = 'vis-panel vis-background vis-vertical-rtl';
  8439. }
  8440. if (this.options.verticalScroll) {
  8441. if (this.options.rtl) {
  8442. this.dom.rightContainer.className = 'vis-panel vis-right vis-vertical-scroll';
  8443. } else {
  8444. this.dom.leftContainer.className = 'vis-panel vis-left vis-vertical-scroll';
  8445. }
  8446. }
  8447. if ((0, _typeof3['default'])(this.options.orientation) !== 'object') {
  8448. this.options.orientation = { item: undefined, axis: undefined };
  8449. }
  8450. if ('orientation' in options) {
  8451. if (typeof options.orientation === 'string') {
  8452. this.options.orientation = {
  8453. item: options.orientation,
  8454. axis: options.orientation
  8455. };
  8456. } else if ((0, _typeof3['default'])(options.orientation) === 'object') {
  8457. if ('item' in options.orientation) {
  8458. this.options.orientation.item = options.orientation.item;
  8459. }
  8460. if ('axis' in options.orientation) {
  8461. this.options.orientation.axis = options.orientation.axis;
  8462. }
  8463. }
  8464. }
  8465. if (this.options.orientation.axis === 'both') {
  8466. if (!this.timeAxis2) {
  8467. var timeAxis2 = this.timeAxis2 = new TimeAxis(this.body);
  8468. timeAxis2.setOptions = function (options) {
  8469. var _options = options ? util.extend({}, options) : {};
  8470. _options.orientation = 'top'; // override the orientation option, always top
  8471. TimeAxis.prototype.setOptions.call(timeAxis2, _options);
  8472. };
  8473. this.components.push(timeAxis2);
  8474. }
  8475. } else {
  8476. if (this.timeAxis2) {
  8477. var index = this.components.indexOf(this.timeAxis2);
  8478. if (index !== -1) {
  8479. this.components.splice(index, 1);
  8480. }
  8481. this.timeAxis2.destroy();
  8482. this.timeAxis2 = null;
  8483. }
  8484. }
  8485. // if the graph2d's drawPoints is a function delegate the callback to the onRender property
  8486. if (typeof options.drawPoints == 'function') {
  8487. options.drawPoints = {
  8488. onRender: options.drawPoints
  8489. };
  8490. }
  8491. if ('hiddenDates' in this.options) {
  8492. DateUtil.convertHiddenOptions(this.options.moment, this.body, this.options.hiddenDates);
  8493. }
  8494. if ('clickToUse' in options) {
  8495. if (options.clickToUse) {
  8496. if (!this.activator) {
  8497. this.activator = new Activator(this.dom.root);
  8498. }
  8499. } else {
  8500. if (this.activator) {
  8501. this.activator.destroy();
  8502. delete this.activator;
  8503. }
  8504. }
  8505. }
  8506. if ('showCustomTime' in options) {
  8507. throw new Error('Option `showCustomTime` is deprecated. Create a custom time bar via timeline.addCustomTime(time [, id])');
  8508. }
  8509. // enable/disable autoResize
  8510. this._initAutoResize();
  8511. }
  8512. // propagate options to all components
  8513. this.components.forEach(function (component) {
  8514. return component.setOptions(options);
  8515. });
  8516. // enable/disable configure
  8517. if ('configure' in options) {
  8518. if (!this.configurator) {
  8519. this.configurator = this._createConfigurator();
  8520. }
  8521. this.configurator.setOptions(options.configure);
  8522. // collect the settings of all components, and pass them to the configuration system
  8523. var appliedOptions = util.deepExtend({}, this.options);
  8524. this.components.forEach(function (component) {
  8525. util.deepExtend(appliedOptions, component.options);
  8526. });
  8527. this.configurator.setModuleOptions({ global: appliedOptions });
  8528. }
  8529. this._redraw();
  8530. };
  8531. /**
  8532. * Returns true when the Timeline is active.
  8533. * @returns {boolean}
  8534. */
  8535. Core.prototype.isActive = function () {
  8536. return !this.activator || this.activator.active;
  8537. };
  8538. /**
  8539. * Destroy the Core, clean up all DOM elements and event listeners.
  8540. */
  8541. Core.prototype.destroy = function () {
  8542. // unbind datasets
  8543. this.setItems(null);
  8544. this.setGroups(null);
  8545. // remove all event listeners
  8546. this.off();
  8547. // stop checking for changed size
  8548. this._stopAutoResize();
  8549. // remove from DOM
  8550. if (this.dom.root.parentNode) {
  8551. this.dom.root.parentNode.removeChild(this.dom.root);
  8552. }
  8553. this.dom = null;
  8554. // remove Activator
  8555. if (this.activator) {
  8556. this.activator.destroy();
  8557. delete this.activator;
  8558. }
  8559. // cleanup hammer touch events
  8560. for (var event in this.listeners) {
  8561. if (this.listeners.hasOwnProperty(event)) {
  8562. delete this.listeners[event];
  8563. }
  8564. }
  8565. this.listeners = null;
  8566. this.hammer = null;
  8567. // give all components the opportunity to cleanup
  8568. this.components.forEach(function (component) {
  8569. return component.destroy();
  8570. });
  8571. this.body = null;
  8572. };
  8573. /**
  8574. * Set a custom time bar
  8575. * @param {Date} time
  8576. * @param {number} [id=undefined] Optional id of the custom time bar to be adjusted.
  8577. */
  8578. Core.prototype.setCustomTime = function (time, id) {
  8579. var customTimes = this.customTimes.filter(function (component) {
  8580. return id === component.options.id;
  8581. });
  8582. if (customTimes.length === 0) {
  8583. throw new Error('No custom time bar found with id ' + (0, _stringify2['default'])(id));
  8584. }
  8585. if (customTimes.length > 0) {
  8586. customTimes[0].setCustomTime(time);
  8587. }
  8588. };
  8589. /**
  8590. * Retrieve the current custom time.
  8591. * @param {number} [id=undefined] Id of the custom time bar.
  8592. * @return {Date | undefined} customTime
  8593. */
  8594. Core.prototype.getCustomTime = function (id) {
  8595. var customTimes = this.customTimes.filter(function (component) {
  8596. return component.options.id === id;
  8597. });
  8598. if (customTimes.length === 0) {
  8599. throw new Error('No custom time bar found with id ' + (0, _stringify2['default'])(id));
  8600. }
  8601. return customTimes[0].getCustomTime();
  8602. };
  8603. /**
  8604. * Set a custom title for the custom time bar.
  8605. * @param {string} [title] Custom title
  8606. * @param {number} [id=undefined] Id of the custom time bar.
  8607. * @returns {*}
  8608. */
  8609. Core.prototype.setCustomTimeTitle = function (title, id) {
  8610. var customTimes = this.customTimes.filter(function (component) {
  8611. return component.options.id === id;
  8612. });
  8613. if (customTimes.length === 0) {
  8614. throw new Error('No custom time bar found with id ' + (0, _stringify2['default'])(id));
  8615. }
  8616. if (customTimes.length > 0) {
  8617. return customTimes[0].setCustomTitle(title);
  8618. }
  8619. };
  8620. /**
  8621. * Retrieve meta information from an event.
  8622. * Should be overridden by classes extending Core
  8623. * @param {Event} event
  8624. * @return {Object} An object with related information.
  8625. */
  8626. Core.prototype.getEventProperties = function (event) {
  8627. return { event: event };
  8628. };
  8629. /**
  8630. * Add custom vertical bar
  8631. * @param {Date | string | number} [time] A Date, unix timestamp, or
  8632. * ISO date string. Time point where
  8633. * the new bar should be placed.
  8634. * If not provided, `new Date()` will
  8635. * be used.
  8636. * @param {number | string} [id=undefined] Id of the new bar. Optional
  8637. * @return {number | string} Returns the id of the new bar
  8638. */
  8639. Core.prototype.addCustomTime = function (time, id) {
  8640. var timestamp = time !== undefined ? util.convert(time, 'Date').valueOf() : new Date();
  8641. var exists = this.customTimes.some(function (customTime) {
  8642. return customTime.options.id === id;
  8643. });
  8644. if (exists) {
  8645. throw new Error('A custom time with id ' + (0, _stringify2['default'])(id) + ' already exists');
  8646. }
  8647. var customTime = new CustomTime(this.body, util.extend({}, this.options, {
  8648. time: timestamp,
  8649. id: id
  8650. }));
  8651. this.customTimes.push(customTime);
  8652. this.components.push(customTime);
  8653. this._redraw();
  8654. return id;
  8655. };
  8656. /**
  8657. * Remove previously added custom bar
  8658. * @param {int} id ID of the custom bar to be removed
  8659. * [at]returns {boolean} True if the bar exists and is removed, false otherwise
  8660. */
  8661. Core.prototype.removeCustomTime = function (id) {
  8662. var customTimes = this.customTimes.filter(function (bar) {
  8663. return bar.options.id === id;
  8664. });
  8665. if (customTimes.length === 0) {
  8666. throw new Error('No custom time bar found with id ' + (0, _stringify2['default'])(id));
  8667. }
  8668. customTimes.forEach(function (customTime) {
  8669. this.customTimes.splice(this.customTimes.indexOf(customTime), 1);
  8670. this.components.splice(this.components.indexOf(customTime), 1);
  8671. customTime.destroy();
  8672. }.bind(this));
  8673. };
  8674. /**
  8675. * Get the id's of the currently visible items.
  8676. * @returns {Array} The ids of the visible items
  8677. */
  8678. Core.prototype.getVisibleItems = function () {
  8679. return this.itemSet && this.itemSet.getVisibleItems() || [];
  8680. };
  8681. /**
  8682. * Set Core window such that it fits all items
  8683. * @param {Object} [options] Available options:
  8684. * `animation: boolean | {duration: number, easingFunction: string}`
  8685. * If true (default), the range is animated
  8686. * smoothly to the new window. An object can be
  8687. * provided to specify duration and easing function.
  8688. * Default duration is 500 ms, and default easing
  8689. * function is 'easeInOutQuad'.
  8690. * @param {function} [callback] a callback funtion to be executed at the end of this function
  8691. */
  8692. Core.prototype.fit = function (options, callback) {
  8693. var range = this.getDataRange();
  8694. // skip range set if there is no min and max date
  8695. if (range.min === null && range.max === null) {
  8696. return;
  8697. }
  8698. // apply a margin of 1% left and right of the data
  8699. var interval = range.max - range.min;
  8700. var min = new Date(range.min.valueOf() - interval * 0.01);
  8701. var max = new Date(range.max.valueOf() + interval * 0.01);
  8702. var animation = options && options.animation !== undefined ? options.animation : true;
  8703. this.range.setRange(min, max, { animation: animation }, callback);
  8704. };
  8705. /**
  8706. * Calculate the data range of the items start and end dates
  8707. * [at]returns {{min: [Date], max: [Date]}}
  8708. * @protected
  8709. */
  8710. Core.prototype.getDataRange = function () {
  8711. // must be implemented by Timeline and Graph2d
  8712. throw new Error('Cannot invoke abstract method getDataRange');
  8713. };
  8714. /**
  8715. * Set the visible window. Both parameters are optional, you can change only
  8716. * start or only end. Syntax:
  8717. *
  8718. * TimeLine.setWindow(start, end)
  8719. * TimeLine.setWindow(start, end, options)
  8720. * TimeLine.setWindow(range)
  8721. *
  8722. * Where start and end can be a Date, number, or string, and range is an
  8723. * object with properties start and end.
  8724. *
  8725. * @param {Date | number | string | Object} [start] Start date of visible window
  8726. * @param {Date | number | string} [end] End date of visible window
  8727. * @param {Object} [options] Available options:
  8728. * `animation: boolean | {duration: number, easingFunction: string}`
  8729. * If true (default), the range is animated
  8730. * smoothly to the new window. An object can be
  8731. * provided to specify duration and easing function.
  8732. * Default duration is 500 ms, and default easing
  8733. * function is 'easeInOutQuad'.
  8734. * @param {function} [callback] a callback funtion to be executed at the end of this function
  8735. */
  8736. Core.prototype.setWindow = function (start, end, options, callback) {
  8737. if (typeof arguments[2] == "function") {
  8738. callback = arguments[2];
  8739. options = {};
  8740. }
  8741. var animation;
  8742. var range;
  8743. if (arguments.length == 1) {
  8744. range = arguments[0];
  8745. animation = range.animation !== undefined ? range.animation : true;
  8746. this.range.setRange(range.start, range.end, { animation: animation });
  8747. } else if (arguments.length == 2 && typeof arguments[1] == "function") {
  8748. range = arguments[0];
  8749. callback = arguments[1];
  8750. animation = range.animation !== undefined ? range.animation : true;
  8751. this.range.setRange(range.start, range.end, { animation: animation }, callback);
  8752. } else {
  8753. animation = options && options.animation !== undefined ? options.animation : true;
  8754. this.range.setRange(start, end, { animation: animation }, callback);
  8755. }
  8756. };
  8757. /**
  8758. * Move the window such that given time is centered on screen.
  8759. * @param {Date | number | string} time
  8760. * @param {Object} [options] Available options:
  8761. * `animation: boolean | {duration: number, easingFunction: string}`
  8762. * If true (default), the range is animated
  8763. * smoothly to the new window. An object can be
  8764. * provided to specify duration and easing function.
  8765. * Default duration is 500 ms, and default easing
  8766. * function is 'easeInOutQuad'.
  8767. * @param {function} [callback] a callback funtion to be executed at the end of this function
  8768. */
  8769. Core.prototype.moveTo = function (time, options, callback) {
  8770. if (typeof arguments[1] == "function") {
  8771. callback = arguments[1];
  8772. options = {};
  8773. }
  8774. var interval = this.range.end - this.range.start;
  8775. var t = util.convert(time, 'Date').valueOf();
  8776. var start = t - interval / 2;
  8777. var end = t + interval / 2;
  8778. var animation = options && options.animation !== undefined ? options.animation : true;
  8779. this.range.setRange(start, end, { animation: animation }, callback);
  8780. };
  8781. /**
  8782. * Get the visible window
  8783. * @return {{start: Date, end: Date}} Visible range
  8784. */
  8785. Core.prototype.getWindow = function () {
  8786. var range = this.range.getRange();
  8787. return {
  8788. start: new Date(range.start),
  8789. end: new Date(range.end)
  8790. };
  8791. };
  8792. /**
  8793. * Zoom in the window such that given time is centered on screen.
  8794. * @param {number} percentage - must be between [0..1]
  8795. * @param {Object} [options] Available options:
  8796. * `animation: boolean | {duration: number, easingFunction: string}`
  8797. * If true (default), the range is animated
  8798. * smoothly to the new window. An object can be
  8799. * provided to specify duration and easing function.
  8800. * Default duration is 500 ms, and default easing
  8801. * function is 'easeInOutQuad'.
  8802. * @param {function} [callback] a callback funtion to be executed at the end of this function
  8803. */
  8804. Core.prototype.zoomIn = function (percentage, options, callback) {
  8805. if (!percentage || percentage < 0 || percentage > 1) return;
  8806. if (typeof arguments[1] == "function") {
  8807. callback = arguments[1];
  8808. options = {};
  8809. }
  8810. var range = this.getWindow();
  8811. var start = range.start.valueOf();
  8812. var end = range.end.valueOf();
  8813. var interval = end - start;
  8814. var newInterval = interval / (1 + percentage);
  8815. var distance = (interval - newInterval) / 2;
  8816. var newStart = start + distance;
  8817. var newEnd = end - distance;
  8818. this.setWindow(newStart, newEnd, options, callback);
  8819. };
  8820. /**
  8821. * Zoom out the window such that given time is centered on screen.
  8822. * @param {number} percentage - must be between [0..1]
  8823. * @param {Object} [options] Available options:
  8824. * `animation: boolean | {duration: number, easingFunction: string}`
  8825. * If true (default), the range is animated
  8826. * smoothly to the new window. An object can be
  8827. * provided to specify duration and easing function.
  8828. * Default duration is 500 ms, and default easing
  8829. * function is 'easeInOutQuad'.
  8830. * @param {function} [callback] a callback funtion to be executed at the end of this function
  8831. */
  8832. Core.prototype.zoomOut = function (percentage, options, callback) {
  8833. if (!percentage || percentage < 0 || percentage > 1) return;
  8834. if (typeof arguments[1] == "function") {
  8835. callback = arguments[1];
  8836. options = {};
  8837. }
  8838. var range = this.getWindow();
  8839. var start = range.start.valueOf();
  8840. var end = range.end.valueOf();
  8841. var interval = end - start;
  8842. var newStart = start - interval * percentage / 2;
  8843. var newEnd = end + interval * percentage / 2;
  8844. this.setWindow(newStart, newEnd, options, callback);
  8845. };
  8846. /**
  8847. * Force a redraw. Can be overridden by implementations of Core
  8848. *
  8849. * Note: this function will be overridden on construction with a trottled version
  8850. */
  8851. Core.prototype.redraw = function () {
  8852. this._redraw();
  8853. };
  8854. /**
  8855. * Redraw for internal use. Redraws all components. See also the public
  8856. * method redraw.
  8857. * @protected
  8858. */
  8859. Core.prototype._redraw = function () {
  8860. this.redrawCount++;
  8861. var resized = false;
  8862. var options = this.options;
  8863. var props = this.props;
  8864. var dom = this.dom;
  8865. if (!dom || !dom.container || dom.root.offsetWidth == 0) return; // when destroyed, or invisible
  8866. DateUtil.updateHiddenDates(this.options.moment, this.body, this.options.hiddenDates);
  8867. // update class names
  8868. if (options.orientation == 'top') {
  8869. util.addClassName(dom.root, 'vis-top');
  8870. util.removeClassName(dom.root, 'vis-bottom');
  8871. } else {
  8872. util.removeClassName(dom.root, 'vis-top');
  8873. util.addClassName(dom.root, 'vis-bottom');
  8874. }
  8875. // update root width and height options
  8876. dom.root.style.maxHeight = util.option.asSize(options.maxHeight, '');
  8877. dom.root.style.minHeight = util.option.asSize(options.minHeight, '');
  8878. dom.root.style.width = util.option.asSize(options.width, '');
  8879. // calculate border widths
  8880. props.border.left = (dom.centerContainer.offsetWidth - dom.centerContainer.clientWidth) / 2;
  8881. props.border.right = props.border.left;
  8882. props.border.top = (dom.centerContainer.offsetHeight - dom.centerContainer.clientHeight) / 2;
  8883. props.border.bottom = props.border.top;
  8884. props.borderRootHeight = dom.root.offsetHeight - dom.root.clientHeight;
  8885. props.borderRootWidth = dom.root.offsetWidth - dom.root.clientWidth;
  8886. // workaround for a bug in IE: the clientWidth of an element with
  8887. // a height:0px and overflow:hidden is not calculated and always has value 0
  8888. if (dom.centerContainer.clientHeight === 0) {
  8889. props.border.left = props.border.top;
  8890. props.border.right = props.border.left;
  8891. }
  8892. if (dom.root.clientHeight === 0) {
  8893. props.borderRootWidth = props.borderRootHeight;
  8894. }
  8895. // calculate the heights. If any of the side panels is empty, we set the height to
  8896. // minus the border width, such that the border will be invisible
  8897. props.center.height = dom.center.offsetHeight;
  8898. props.left.height = dom.left.offsetHeight;
  8899. props.right.height = dom.right.offsetHeight;
  8900. props.top.height = dom.top.clientHeight || -props.border.top;
  8901. props.bottom.height = dom.bottom.clientHeight || -props.border.bottom;
  8902. // TODO: compensate borders when any of the panels is empty.
  8903. // apply auto height
  8904. // TODO: only calculate autoHeight when needed (else we cause an extra reflow/repaint of the DOM)
  8905. var contentHeight = Math.max(props.left.height, props.center.height, props.right.height);
  8906. var autoHeight = props.top.height + contentHeight + props.bottom.height + props.borderRootHeight + props.border.top + props.border.bottom;
  8907. dom.root.style.height = util.option.asSize(options.height, autoHeight + 'px');
  8908. // calculate heights of the content panels
  8909. props.root.height = dom.root.offsetHeight;
  8910. props.background.height = props.root.height - props.borderRootHeight;
  8911. var containerHeight = props.root.height - props.top.height - props.bottom.height - props.borderRootHeight;
  8912. props.centerContainer.height = containerHeight;
  8913. props.leftContainer.height = containerHeight;
  8914. props.rightContainer.height = props.leftContainer.height;
  8915. // calculate the widths of the panels
  8916. props.root.width = dom.root.offsetWidth;
  8917. props.background.width = props.root.width - props.borderRootWidth;
  8918. if (!this.initialDrawDone) {
  8919. props.scrollbarWidth = util.getScrollBarWidth();
  8920. }
  8921. if (options.verticalScroll) {
  8922. if (options.rtl) {
  8923. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  8924. props.right.width = dom.rightContainer.clientWidth + props.scrollbarWidth || -props.border.right;
  8925. } else {
  8926. props.left.width = dom.leftContainer.clientWidth + props.scrollbarWidth || -props.border.left;
  8927. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  8928. }
  8929. } else {
  8930. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  8931. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  8932. }
  8933. this._setDOM();
  8934. // update the scrollTop, feasible range for the offset can be changed
  8935. // when the height of the Core or of the contents of the center changed
  8936. var offset = this._updateScrollTop();
  8937. // reposition the scrollable contents
  8938. if (options.orientation.item != 'top') {
  8939. offset += Math.max(props.centerContainer.height - props.center.height - props.border.top - props.border.bottom, 0);
  8940. }
  8941. dom.center.style.top = offset + 'px';
  8942. // show shadows when vertical scrolling is available
  8943. var visibilityTop = props.scrollTop == 0 ? 'hidden' : '';
  8944. var visibilityBottom = props.scrollTop == props.scrollTopMin ? 'hidden' : '';
  8945. dom.shadowTop.style.visibility = visibilityTop;
  8946. dom.shadowBottom.style.visibility = visibilityBottom;
  8947. dom.shadowTopLeft.style.visibility = visibilityTop;
  8948. dom.shadowBottomLeft.style.visibility = visibilityBottom;
  8949. dom.shadowTopRight.style.visibility = visibilityTop;
  8950. dom.shadowBottomRight.style.visibility = visibilityBottom;
  8951. if (options.verticalScroll) {
  8952. dom.rightContainer.className = 'vis-panel vis-right vis-vertical-scroll';
  8953. dom.leftContainer.className = 'vis-panel vis-left vis-vertical-scroll';
  8954. dom.shadowTopRight.style.visibility = "hidden";
  8955. dom.shadowBottomRight.style.visibility = "hidden";
  8956. dom.shadowTopLeft.style.visibility = "hidden";
  8957. dom.shadowBottomLeft.style.visibility = "hidden";
  8958. dom.left.style.top = '0px';
  8959. dom.right.style.top = '0px';
  8960. }
  8961. if (!options.verticalScroll || props.center.height < props.centerContainer.height) {
  8962. dom.left.style.top = offset + 'px';
  8963. dom.right.style.top = offset + 'px';
  8964. dom.rightContainer.className = dom.rightContainer.className.replace(new RegExp('(?:^|\\s)' + 'vis-vertical-scroll' + '(?:\\s|$)'), ' ');
  8965. dom.leftContainer.className = dom.leftContainer.className.replace(new RegExp('(?:^|\\s)' + 'vis-vertical-scroll' + '(?:\\s|$)'), ' ');
  8966. props.left.width = dom.leftContainer.clientWidth || -props.border.left;
  8967. props.right.width = dom.rightContainer.clientWidth || -props.border.right;
  8968. this._setDOM();
  8969. }
  8970. // enable/disable vertical panning
  8971. var contentsOverflow = props.center.height > props.centerContainer.height;
  8972. this.hammer.get('pan').set({
  8973. direction: contentsOverflow ? Hammer.DIRECTION_ALL : Hammer.DIRECTION_HORIZONTAL
  8974. });
  8975. // redraw all components
  8976. this.components.forEach(function (component) {
  8977. resized = component.redraw() || resized;
  8978. });
  8979. var MAX_REDRAW = 5;
  8980. if (resized) {
  8981. if (this.redrawCount < MAX_REDRAW) {
  8982. this.body.emitter.emit('_change');
  8983. return;
  8984. } else {
  8985. console.log('WARNING: infinite loop in redraw?');
  8986. }
  8987. } else {
  8988. this.redrawCount = 0;
  8989. }
  8990. //Emit public 'changed' event for UI updates, see issue #1592
  8991. this.body.emitter.emit("changed");
  8992. };
  8993. Core.prototype._setDOM = function () {
  8994. var props = this.props;
  8995. var dom = this.dom;
  8996. props.leftContainer.width = props.left.width;
  8997. props.rightContainer.width = props.right.width;
  8998. var centerWidth = props.root.width - props.left.width - props.right.width - props.borderRootWidth;
  8999. props.center.width = centerWidth;
  9000. props.centerContainer.width = centerWidth;
  9001. props.top.width = centerWidth;
  9002. props.bottom.width = centerWidth;
  9003. // resize the panels
  9004. dom.background.style.height = props.background.height + 'px';
  9005. dom.backgroundVertical.style.height = props.background.height + 'px';
  9006. dom.backgroundHorizontal.style.height = props.centerContainer.height + 'px';
  9007. dom.centerContainer.style.height = props.centerContainer.height + 'px';
  9008. dom.leftContainer.style.height = props.leftContainer.height + 'px';
  9009. dom.rightContainer.style.height = props.rightContainer.height + 'px';
  9010. dom.background.style.width = props.background.width + 'px';
  9011. dom.backgroundVertical.style.width = props.centerContainer.width + 'px';
  9012. dom.backgroundHorizontal.style.width = props.background.width + 'px';
  9013. dom.centerContainer.style.width = props.center.width + 'px';
  9014. dom.top.style.width = props.top.width + 'px';
  9015. dom.bottom.style.width = props.bottom.width + 'px';
  9016. // reposition the panels
  9017. dom.background.style.left = '0';
  9018. dom.background.style.top = '0';
  9019. dom.backgroundVertical.style.left = props.left.width + props.border.left + 'px';
  9020. dom.backgroundVertical.style.top = '0';
  9021. dom.backgroundHorizontal.style.left = '0';
  9022. dom.backgroundHorizontal.style.top = props.top.height + 'px';
  9023. dom.centerContainer.style.left = props.left.width + 'px';
  9024. dom.centerContainer.style.top = props.top.height + 'px';
  9025. dom.leftContainer.style.left = '0';
  9026. dom.leftContainer.style.top = props.top.height + 'px';
  9027. dom.rightContainer.style.left = props.left.width + props.center.width + 'px';
  9028. dom.rightContainer.style.top = props.top.height + 'px';
  9029. dom.top.style.left = props.left.width + 'px';
  9030. dom.top.style.top = '0';
  9031. dom.bottom.style.left = props.left.width + 'px';
  9032. dom.bottom.style.top = props.top.height + props.centerContainer.height + 'px';
  9033. dom.center.style.left = '0';
  9034. dom.left.style.left = '0';
  9035. dom.right.style.left = '0';
  9036. };
  9037. // TODO: deprecated since version 1.1.0, remove some day
  9038. Core.prototype.repaint = function () {
  9039. throw new Error('Function repaint is deprecated. Use redraw instead.');
  9040. };
  9041. /**
  9042. * Set a current time. This can be used for example to ensure that a client's
  9043. * time is synchronized with a shared server time.
  9044. * Only applicable when option `showCurrentTime` is true.
  9045. * @param {Date | string | number} time A Date, unix timestamp, or
  9046. * ISO date string.
  9047. */
  9048. Core.prototype.setCurrentTime = function (time) {
  9049. if (!this.currentTime) {
  9050. throw new Error('Option showCurrentTime must be true');
  9051. }
  9052. this.currentTime.setCurrentTime(time);
  9053. };
  9054. /**
  9055. * Get the current time.
  9056. * Only applicable when option `showCurrentTime` is true.
  9057. * @return {Date} Returns the current time.
  9058. */
  9059. Core.prototype.getCurrentTime = function () {
  9060. if (!this.currentTime) {
  9061. throw new Error('Option showCurrentTime must be true');
  9062. }
  9063. return this.currentTime.getCurrentTime();
  9064. };
  9065. /**
  9066. * Convert a position on screen (pixels) to a datetime
  9067. * @param {int} x Position on the screen in pixels
  9068. * @return {Date} time The datetime the corresponds with given position x
  9069. * @protected
  9070. */
  9071. // TODO: move this function to Range
  9072. Core.prototype._toTime = function (x) {
  9073. return DateUtil.toTime(this, x, this.props.center.width);
  9074. };
  9075. /**
  9076. * Convert a position on the global screen (pixels) to a datetime
  9077. * @param {int} x Position on the screen in pixels
  9078. * @return {Date} time The datetime the corresponds with given position x
  9079. * @protected
  9080. */
  9081. // TODO: move this function to Range
  9082. Core.prototype._toGlobalTime = function (x) {
  9083. return DateUtil.toTime(this, x, this.props.root.width);
  9084. //var conversion = this.range.conversion(this.props.root.width);
  9085. //return new Date(x / conversion.scale + conversion.offset);
  9086. };
  9087. /**
  9088. * Convert a datetime (Date object) into a position on the screen
  9089. * @param {Date} time A date
  9090. * @return {int} x The position on the screen in pixels which corresponds
  9091. * with the given date.
  9092. * @protected
  9093. */
  9094. // TODO: move this function to Range
  9095. Core.prototype._toScreen = function (time) {
  9096. return DateUtil.toScreen(this, time, this.props.center.width);
  9097. };
  9098. /**
  9099. * Convert a datetime (Date object) into a position on the root
  9100. * This is used to get the pixel density estimate for the screen, not the center panel
  9101. * @param {Date} time A date
  9102. * @return {int} x The position on root in pixels which corresponds
  9103. * with the given date.
  9104. * @protected
  9105. */
  9106. // TODO: move this function to Range
  9107. Core.prototype._toGlobalScreen = function (time) {
  9108. return DateUtil.toScreen(this, time, this.props.root.width);
  9109. //var conversion = this.range.conversion(this.props.root.width);
  9110. //return (time.valueOf() - conversion.offset) * conversion.scale;
  9111. };
  9112. /**
  9113. * Initialize watching when option autoResize is true
  9114. * @private
  9115. */
  9116. Core.prototype._initAutoResize = function () {
  9117. if (this.options.autoResize == true) {
  9118. this._startAutoResize();
  9119. } else {
  9120. this._stopAutoResize();
  9121. }
  9122. };
  9123. /**
  9124. * Watch for changes in the size of the container. On resize, the Panel will
  9125. * automatically redraw itself.
  9126. * @private
  9127. */
  9128. Core.prototype._startAutoResize = function () {
  9129. var me = this;
  9130. this._stopAutoResize();
  9131. this._onResize = function () {
  9132. if (me.options.autoResize != true) {
  9133. // stop watching when the option autoResize is changed to false
  9134. me._stopAutoResize();
  9135. return;
  9136. }
  9137. if (me.dom.root) {
  9138. // check whether the frame is resized
  9139. // Note: we compare offsetWidth here, not clientWidth. For some reason,
  9140. // IE does not restore the clientWidth from 0 to the actual width after
  9141. // changing the timeline's container display style from none to visible
  9142. if (me.dom.root.offsetWidth != me.props.lastWidth || me.dom.root.offsetHeight != me.props.lastHeight) {
  9143. me.props.lastWidth = me.dom.root.offsetWidth;
  9144. me.props.lastHeight = me.dom.root.offsetHeight;
  9145. me.props.scrollbarWidth = util.getScrollBarWidth();
  9146. me.body.emitter.emit('_change');
  9147. }
  9148. }
  9149. };
  9150. // add event listener to window resize
  9151. util.addEventListener(window, 'resize', this._onResize);
  9152. //Prevent initial unnecessary redraw
  9153. if (me.dom.root) {
  9154. me.props.lastWidth = me.dom.root.offsetWidth;
  9155. me.props.lastHeight = me.dom.root.offsetHeight;
  9156. }
  9157. this.watchTimer = setInterval(this._onResize, 1000);
  9158. };
  9159. /**
  9160. * Stop watching for a resize of the frame.
  9161. * @private
  9162. */
  9163. Core.prototype._stopAutoResize = function () {
  9164. if (this.watchTimer) {
  9165. clearInterval(this.watchTimer);
  9166. this.watchTimer = undefined;
  9167. }
  9168. // remove event listener on window.resize
  9169. if (this._onResize) {
  9170. util.removeEventListener(window, 'resize', this._onResize);
  9171. this._onResize = null;
  9172. }
  9173. };
  9174. /**
  9175. * Start moving the timeline vertically
  9176. * @param {Event} event
  9177. * @private
  9178. */
  9179. Core.prototype._onTouch = function (event) {
  9180. // eslint-disable-line no-unused-vars
  9181. this.touch.allowDragging = true;
  9182. this.touch.initialScrollTop = this.props.scrollTop;
  9183. };
  9184. /**
  9185. * Start moving the timeline vertically
  9186. * @param {Event} event
  9187. * @private
  9188. */
  9189. Core.prototype._onPinch = function (event) {
  9190. // eslint-disable-line no-unused-vars
  9191. this.touch.allowDragging = false;
  9192. };
  9193. /**
  9194. * Move the timeline vertically
  9195. * @param {Event} event
  9196. * @private
  9197. */
  9198. Core.prototype._onDrag = function (event) {
  9199. if (!event) return;
  9200. // refuse to drag when we where pinching to prevent the timeline make a jump
  9201. // when releasing the fingers in opposite order from the touch screen
  9202. if (!this.touch.allowDragging) return;
  9203. var delta = event.deltaY;
  9204. var oldScrollTop = this._getScrollTop();
  9205. var newScrollTop = this._setScrollTop(this.touch.initialScrollTop + delta);
  9206. if (this.options.verticalScroll) {
  9207. this.dom.left.parentNode.scrollTop = -this.props.scrollTop;
  9208. this.dom.right.parentNode.scrollTop = -this.props.scrollTop;
  9209. }
  9210. if (newScrollTop != oldScrollTop) {
  9211. this.emit("verticalDrag");
  9212. }
  9213. };
  9214. /**
  9215. * Apply a scrollTop
  9216. * @param {number} scrollTop
  9217. * @returns {number} scrollTop Returns the applied scrollTop
  9218. * @private
  9219. */
  9220. Core.prototype._setScrollTop = function (scrollTop) {
  9221. this.props.scrollTop = scrollTop;
  9222. this._updateScrollTop();
  9223. return this.props.scrollTop;
  9224. };
  9225. /**
  9226. * Update the current scrollTop when the height of the containers has been changed
  9227. * @returns {number} scrollTop Returns the applied scrollTop
  9228. * @private
  9229. */
  9230. Core.prototype._updateScrollTop = function () {
  9231. // recalculate the scrollTopMin
  9232. var scrollTopMin = Math.min(this.props.centerContainer.height - this.props.center.height, 0); // is negative or zero
  9233. if (scrollTopMin != this.props.scrollTopMin) {
  9234. // in case of bottom orientation, change the scrollTop such that the contents
  9235. // do not move relative to the time axis at the bottom
  9236. if (this.options.orientation.item != 'top') {
  9237. this.props.scrollTop += scrollTopMin - this.props.scrollTopMin;
  9238. }
  9239. this.props.scrollTopMin = scrollTopMin;
  9240. }
  9241. // limit the scrollTop to the feasible scroll range
  9242. if (this.props.scrollTop > 0) this.props.scrollTop = 0;
  9243. if (this.props.scrollTop < scrollTopMin) this.props.scrollTop = scrollTopMin;
  9244. if (this.options.verticalScroll) {
  9245. this.dom.left.parentNode.scrollTop = -this.props.scrollTop;
  9246. this.dom.right.parentNode.scrollTop = -this.props.scrollTop;
  9247. }
  9248. return this.props.scrollTop;
  9249. };
  9250. /**
  9251. * Get the current scrollTop
  9252. * @returns {number} scrollTop
  9253. * @private
  9254. */
  9255. Core.prototype._getScrollTop = function () {
  9256. return this.props.scrollTop;
  9257. };
  9258. /**
  9259. * Load a configurator
  9260. * [at]returns {Object}
  9261. * @private
  9262. */
  9263. Core.prototype._createConfigurator = function () {
  9264. throw new Error('Cannot invoke abstract method _createConfigurator');
  9265. };
  9266. module.exports = Core;
  9267. /***/ }),
  9268. /* 66 */
  9269. /***/ (function(module, exports, __webpack_require__) {
  9270. "use strict";
  9271. var moment = __webpack_require__(9);
  9272. var DateUtil = __webpack_require__(36);
  9273. var util = __webpack_require__(2);
  9274. /**
  9275. * The class TimeStep is an iterator for dates. You provide a start date and an
  9276. * end date. The class itself determines the best scale (step size) based on the
  9277. * provided start Date, end Date, and minimumStep.
  9278. *
  9279. * If minimumStep is provided, the step size is chosen as close as possible
  9280. * to the minimumStep but larger than minimumStep. If minimumStep is not
  9281. * provided, the scale is set to 1 DAY.
  9282. * The minimumStep should correspond with the onscreen size of about 6 characters
  9283. *
  9284. * Alternatively, you can set a scale by hand.
  9285. * After creation, you can initialize the class by executing first(). Then you
  9286. * can iterate from the start date to the end date via next(). You can check if
  9287. * the end date is reached with the function hasNext(). After each step, you can
  9288. * retrieve the current date via getCurrent().
  9289. * The TimeStep has scales ranging from milliseconds, seconds, minutes, hours,
  9290. * days, to years.
  9291. *
  9292. * Version: 1.2
  9293. *
  9294. * @param {Date} [start] The start date, for example new Date(2010, 9, 21)
  9295. * or new Date(2010, 9, 21, 23, 45, 00)
  9296. * @param {Date} [end] The end date
  9297. * @param {number} [minimumStep] Optional. Minimum step size in milliseconds
  9298. * @param {Date|Array.<Date>} [hiddenDates] Optional.
  9299. * @param {{showMajorLabels: boolean}} [options] Optional.
  9300. * @constructor TimeStep
  9301. */
  9302. function TimeStep(start, end, minimumStep, hiddenDates, options) {
  9303. this.moment = moment;
  9304. // variables
  9305. this.current = this.moment();
  9306. this._start = this.moment();
  9307. this._end = this.moment();
  9308. this.autoScale = true;
  9309. this.scale = 'day';
  9310. this.step = 1;
  9311. // initialize the range
  9312. this.setRange(start, end, minimumStep);
  9313. // hidden Dates options
  9314. this.switchedDay = false;
  9315. this.switchedMonth = false;
  9316. this.switchedYear = false;
  9317. if (Array.isArray(hiddenDates)) {
  9318. this.hiddenDates = hiddenDates;
  9319. } else if (hiddenDates != undefined) {
  9320. this.hiddenDates = [hiddenDates];
  9321. } else {
  9322. this.hiddenDates = [];
  9323. }
  9324. this.format = TimeStep.FORMAT; // default formatting
  9325. this.options = options ? options : {};
  9326. }
  9327. // Time formatting
  9328. TimeStep.FORMAT = {
  9329. minorLabels: {
  9330. millisecond: 'SSS',
  9331. second: 's',
  9332. minute: 'HH:mm',
  9333. hour: 'HH:mm',
  9334. weekday: 'ddd D',
  9335. day: 'D',
  9336. week: 'w',
  9337. month: 'MMM',
  9338. year: 'YYYY'
  9339. },
  9340. majorLabels: {
  9341. millisecond: 'HH:mm:ss',
  9342. second: 'D MMMM HH:mm',
  9343. minute: 'ddd D MMMM',
  9344. hour: 'ddd D MMMM',
  9345. weekday: 'MMMM YYYY',
  9346. day: 'MMMM YYYY',
  9347. week: 'MMMM YYYY',
  9348. month: 'YYYY',
  9349. year: ''
  9350. }
  9351. };
  9352. /**
  9353. * Set custom constructor function for moment. Can be used to set dates
  9354. * to UTC or to set a utcOffset.
  9355. * @param {function} moment
  9356. */
  9357. TimeStep.prototype.setMoment = function (moment) {
  9358. this.moment = moment;
  9359. // update the date properties, can have a new utcOffset
  9360. this.current = this.moment(this.current.valueOf());
  9361. this._start = this.moment(this._start.valueOf());
  9362. this._end = this.moment(this._end.valueOf());
  9363. };
  9364. /**
  9365. * Set custom formatting for the minor an major labels of the TimeStep.
  9366. * Both `minorLabels` and `majorLabels` are an Object with properties:
  9367. * 'millisecond', 'second', 'minute', 'hour', 'weekday', 'day', 'week', 'month', 'year'.
  9368. * @param {{minorLabels: Object, majorLabels: Object}} format
  9369. */
  9370. TimeStep.prototype.setFormat = function (format) {
  9371. var defaultFormat = util.deepExtend({}, TimeStep.FORMAT);
  9372. this.format = util.deepExtend(defaultFormat, format);
  9373. };
  9374. /**
  9375. * Set a new range
  9376. * If minimumStep is provided, the step size is chosen as close as possible
  9377. * to the minimumStep but larger than minimumStep. If minimumStep is not
  9378. * provided, the scale is set to 1 DAY.
  9379. * The minimumStep should correspond with the onscreen size of about 6 characters
  9380. * @param {Date} [start] The start date and time.
  9381. * @param {Date} [end] The end date and time.
  9382. * @param {int} [minimumStep] Optional. Minimum step size in milliseconds
  9383. */
  9384. TimeStep.prototype.setRange = function (start, end, minimumStep) {
  9385. if (!(start instanceof Date) || !(end instanceof Date)) {
  9386. throw "No legal start or end date in method setRange";
  9387. }
  9388. this._start = start != undefined ? this.moment(start.valueOf()) : new Date();
  9389. this._end = end != undefined ? this.moment(end.valueOf()) : new Date();
  9390. if (this.autoScale) {
  9391. this.setMinimumStep(minimumStep);
  9392. }
  9393. };
  9394. /**
  9395. * Set the range iterator to the start date.
  9396. */
  9397. TimeStep.prototype.start = function () {
  9398. this.current = this._start.clone();
  9399. this.roundToMinor();
  9400. };
  9401. /**
  9402. * Round the current date to the first minor date value
  9403. * This must be executed once when the current date is set to start Date
  9404. */
  9405. TimeStep.prototype.roundToMinor = function () {
  9406. // round to floor
  9407. // to prevent year & month scales rounding down to the first day of week we perform this separately
  9408. if (this.scale == 'week') {
  9409. this.current.weekday(0);
  9410. }
  9411. // IMPORTANT: we have no breaks in this switch! (this is no bug)
  9412. // noinspection FallThroughInSwitchStatementJS
  9413. switch (this.scale) {
  9414. case 'year':
  9415. this.current.year(this.step * Math.floor(this.current.year() / this.step));
  9416. this.current.month(0);
  9417. case 'month':
  9418. this.current.date(1); // eslint-disable-line no-fallthrough
  9419. case 'week': // eslint-disable-line no-fallthrough
  9420. case 'day': // eslint-disable-line no-fallthrough
  9421. case 'weekday':
  9422. this.current.hours(0); // eslint-disable-line no-fallthrough
  9423. case 'hour':
  9424. this.current.minutes(0); // eslint-disable-line no-fallthrough
  9425. case 'minute':
  9426. this.current.seconds(0); // eslint-disable-line no-fallthrough
  9427. case 'second':
  9428. this.current.milliseconds(0); // eslint-disable-line no-fallthrough
  9429. //case 'millisecond': // nothing to do for milliseconds
  9430. }
  9431. if (this.step != 1) {
  9432. // round down to the first minor value that is a multiple of the current step size
  9433. switch (this.scale) {
  9434. case 'millisecond':
  9435. this.current.subtract(this.current.milliseconds() % this.step, 'milliseconds');break;
  9436. case 'second':
  9437. this.current.subtract(this.current.seconds() % this.step, 'seconds');break;
  9438. case 'minute':
  9439. this.current.subtract(this.current.minutes() % this.step, 'minutes');break;
  9440. case 'hour':
  9441. this.current.subtract(this.current.hours() % this.step, 'hours');break;
  9442. case 'weekday': // intentional fall through
  9443. case 'day':
  9444. this.current.subtract((this.current.date() - 1) % this.step, 'day');break;
  9445. case 'week':
  9446. this.current.subtract(this.current.week() % this.step, 'week');break;
  9447. case 'month':
  9448. this.current.subtract(this.current.month() % this.step, 'month');break;
  9449. case 'year':
  9450. this.current.subtract(this.current.year() % this.step, 'year');break;
  9451. default:
  9452. break;
  9453. }
  9454. }
  9455. };
  9456. /**
  9457. * Check if the there is a next step
  9458. * @return {boolean} true if the current date has not passed the end date
  9459. */
  9460. TimeStep.prototype.hasNext = function () {
  9461. return this.current.valueOf() <= this._end.valueOf();
  9462. };
  9463. /**
  9464. * Do the next step
  9465. */
  9466. TimeStep.prototype.next = function () {
  9467. var prev = this.current.valueOf();
  9468. // Two cases, needed to prevent issues with switching daylight savings
  9469. // (end of March and end of October)
  9470. switch (this.scale) {
  9471. case 'millisecond':
  9472. this.current.add(this.step, 'millisecond');break;
  9473. case 'second':
  9474. this.current.add(this.step, 'second');break;
  9475. case 'minute':
  9476. this.current.add(this.step, 'minute');break;
  9477. case 'hour':
  9478. this.current.add(this.step, 'hour');
  9479. if (this.current.month() < 6) {
  9480. this.current.subtract(this.current.hours() % this.step, 'hour');
  9481. } else {
  9482. if (this.current.hours() % this.step !== 0) {
  9483. this.current.add(this.step - this.current.hours() % this.step, 'hour');
  9484. }
  9485. }
  9486. break;
  9487. case 'weekday': // intentional fall through
  9488. case 'day':
  9489. this.current.add(this.step, 'day');break;
  9490. case 'week':
  9491. if (this.current.weekday() !== 0) {
  9492. // we had a month break not correlating with a week's start before
  9493. this.current.weekday(0); // switch back to week cycles
  9494. this.current.add(this.step, 'week');
  9495. } else if (this.options.showMajorLabels === false) {
  9496. this.current.add(this.step, 'week'); // the default case
  9497. } else {
  9498. // first day of the week
  9499. var nextWeek = this.current.clone();
  9500. nextWeek.add(1, 'week');
  9501. if (nextWeek.isSame(this.current, 'month')) {
  9502. // is the first day of the next week in the same month?
  9503. this.current.add(this.step, 'week'); // the default case
  9504. } else {
  9505. // inject a step at each first day of the month
  9506. this.current.add(this.step, 'week');
  9507. this.current.date(1);
  9508. }
  9509. }
  9510. break;
  9511. case 'month':
  9512. this.current.add(this.step, 'month');break;
  9513. case 'year':
  9514. this.current.add(this.step, 'year');break;
  9515. default:
  9516. break;
  9517. }
  9518. if (this.step != 1) {
  9519. // round down to the correct major value
  9520. switch (this.scale) {
  9521. case 'millisecond':
  9522. if (this.current.milliseconds() > 0 && this.current.milliseconds() < this.step) this.current.milliseconds(0);break;
  9523. case 'second':
  9524. if (this.current.seconds() > 0 && this.current.seconds() < this.step) this.current.seconds(0);break;
  9525. case 'minute':
  9526. if (this.current.minutes() > 0 && this.current.minutes() < this.step) this.current.minutes(0);break;
  9527. case 'hour':
  9528. if (this.current.hours() > 0 && this.current.hours() < this.step) this.current.hours(0);break;
  9529. case 'weekday': // intentional fall through
  9530. case 'day':
  9531. if (this.current.date() < this.step + 1) this.current.date(1);break;
  9532. case 'week':
  9533. if (this.current.week() < this.step) this.current.week(1);break; // week numbering starts at 1, not 0
  9534. case 'month':
  9535. if (this.current.month() < this.step) this.current.month(0);break;
  9536. case 'year':
  9537. break; // nothing to do for year
  9538. default:
  9539. break;
  9540. }
  9541. }
  9542. // safety mechanism: if current time is still unchanged, move to the end
  9543. if (this.current.valueOf() == prev) {
  9544. this.current = this._end.clone();
  9545. }
  9546. // Reset switches for year, month and day. Will get set to true where appropriate in DateUtil.stepOverHiddenDates
  9547. this.switchedDay = false;
  9548. this.switchedMonth = false;
  9549. this.switchedYear = false;
  9550. DateUtil.stepOverHiddenDates(this.moment, this, prev);
  9551. };
  9552. /**
  9553. * Get the current datetime
  9554. * @return {Moment} current The current date
  9555. */
  9556. TimeStep.prototype.getCurrent = function () {
  9557. return this.current;
  9558. };
  9559. /**
  9560. * Set a custom scale. Autoscaling will be disabled.
  9561. * For example setScale('minute', 5) will result
  9562. * in minor steps of 5 minutes, and major steps of an hour.
  9563. *
  9564. * @param {{scale: string, step: number}} params
  9565. * An object containing two properties:
  9566. * - A string 'scale'. Choose from 'millisecond', 'second',
  9567. * 'minute', 'hour', 'weekday', 'day', 'week', 'month', 'year'.
  9568. * - A number 'step'. A step size, by default 1.
  9569. * Choose for example 1, 2, 5, or 10.
  9570. */
  9571. TimeStep.prototype.setScale = function (params) {
  9572. if (params && typeof params.scale == 'string') {
  9573. this.scale = params.scale;
  9574. this.step = params.step > 0 ? params.step : 1;
  9575. this.autoScale = false;
  9576. }
  9577. };
  9578. /**
  9579. * Enable or disable autoscaling
  9580. * @param {boolean} enable If true, autoascaling is set true
  9581. */
  9582. TimeStep.prototype.setAutoScale = function (enable) {
  9583. this.autoScale = enable;
  9584. };
  9585. /**
  9586. * Automatically determine the scale that bests fits the provided minimum step
  9587. * @param {number} [minimumStep] The minimum step size in milliseconds
  9588. */
  9589. TimeStep.prototype.setMinimumStep = function (minimumStep) {
  9590. if (minimumStep == undefined) {
  9591. return;
  9592. }
  9593. //var b = asc + ds;
  9594. var stepYear = 1000 * 60 * 60 * 24 * 30 * 12;
  9595. var stepMonth = 1000 * 60 * 60 * 24 * 30;
  9596. var stepDay = 1000 * 60 * 60 * 24;
  9597. var stepHour = 1000 * 60 * 60;
  9598. var stepMinute = 1000 * 60;
  9599. var stepSecond = 1000;
  9600. var stepMillisecond = 1;
  9601. // find the smallest step that is larger than the provided minimumStep
  9602. if (stepYear * 1000 > minimumStep) {
  9603. this.scale = 'year';this.step = 1000;
  9604. }
  9605. if (stepYear * 500 > minimumStep) {
  9606. this.scale = 'year';this.step = 500;
  9607. }
  9608. if (stepYear * 100 > minimumStep) {
  9609. this.scale = 'year';this.step = 100;
  9610. }
  9611. if (stepYear * 50 > minimumStep) {
  9612. this.scale = 'year';this.step = 50;
  9613. }
  9614. if (stepYear * 10 > minimumStep) {
  9615. this.scale = 'year';this.step = 10;
  9616. }
  9617. if (stepYear * 5 > minimumStep) {
  9618. this.scale = 'year';this.step = 5;
  9619. }
  9620. if (stepYear > minimumStep) {
  9621. this.scale = 'year';this.step = 1;
  9622. }
  9623. if (stepMonth * 3 > minimumStep) {
  9624. this.scale = 'month';this.step = 3;
  9625. }
  9626. if (stepMonth > minimumStep) {
  9627. this.scale = 'month';this.step = 1;
  9628. }
  9629. if (stepDay * 5 > minimumStep) {
  9630. this.scale = 'day';this.step = 5;
  9631. }
  9632. if (stepDay * 2 > minimumStep) {
  9633. this.scale = 'day';this.step = 2;
  9634. }
  9635. if (stepDay > minimumStep) {
  9636. this.scale = 'day';this.step = 1;
  9637. }
  9638. if (stepDay / 2 > minimumStep) {
  9639. this.scale = 'weekday';this.step = 1;
  9640. }
  9641. if (stepHour * 4 > minimumStep) {
  9642. this.scale = 'hour';this.step = 4;
  9643. }
  9644. if (stepHour > minimumStep) {
  9645. this.scale = 'hour';this.step = 1;
  9646. }
  9647. if (stepMinute * 15 > minimumStep) {
  9648. this.scale = 'minute';this.step = 15;
  9649. }
  9650. if (stepMinute * 10 > minimumStep) {
  9651. this.scale = 'minute';this.step = 10;
  9652. }
  9653. if (stepMinute * 5 > minimumStep) {
  9654. this.scale = 'minute';this.step = 5;
  9655. }
  9656. if (stepMinute > minimumStep) {
  9657. this.scale = 'minute';this.step = 1;
  9658. }
  9659. if (stepSecond * 15 > minimumStep) {
  9660. this.scale = 'second';this.step = 15;
  9661. }
  9662. if (stepSecond * 10 > minimumStep) {
  9663. this.scale = 'second';this.step = 10;
  9664. }
  9665. if (stepSecond * 5 > minimumStep) {
  9666. this.scale = 'second';this.step = 5;
  9667. }
  9668. if (stepSecond > minimumStep) {
  9669. this.scale = 'second';this.step = 1;
  9670. }
  9671. if (stepMillisecond * 200 > minimumStep) {
  9672. this.scale = 'millisecond';this.step = 200;
  9673. }
  9674. if (stepMillisecond * 100 > minimumStep) {
  9675. this.scale = 'millisecond';this.step = 100;
  9676. }
  9677. if (stepMillisecond * 50 > minimumStep) {
  9678. this.scale = 'millisecond';this.step = 50;
  9679. }
  9680. if (stepMillisecond * 10 > minimumStep) {
  9681. this.scale = 'millisecond';this.step = 10;
  9682. }
  9683. if (stepMillisecond * 5 > minimumStep) {
  9684. this.scale = 'millisecond';this.step = 5;
  9685. }
  9686. if (stepMillisecond > minimumStep) {
  9687. this.scale = 'millisecond';this.step = 1;
  9688. }
  9689. };
  9690. /**
  9691. * Snap a date to a rounded value.
  9692. * The snap intervals are dependent on the current scale and step.
  9693. * Static function
  9694. * @param {Date} date the date to be snapped.
  9695. * @param {string} scale Current scale, can be 'millisecond', 'second',
  9696. * 'minute', 'hour', 'weekday, 'day', 'week', 'month', 'year'.
  9697. * @param {number} step Current step (1, 2, 4, 5, ...
  9698. * @return {Date} snappedDate
  9699. */
  9700. TimeStep.snap = function (date, scale, step) {
  9701. var clone = moment(date);
  9702. if (scale == 'year') {
  9703. var year = clone.year() + Math.round(clone.month() / 12);
  9704. clone.year(Math.round(year / step) * step);
  9705. clone.month(0);
  9706. clone.date(0);
  9707. clone.hours(0);
  9708. clone.minutes(0);
  9709. clone.seconds(0);
  9710. clone.milliseconds(0);
  9711. } else if (scale == 'month') {
  9712. if (clone.date() > 15) {
  9713. clone.date(1);
  9714. clone.add(1, 'month');
  9715. // important: first set Date to 1, after that change the month.
  9716. } else {
  9717. clone.date(1);
  9718. }
  9719. clone.hours(0);
  9720. clone.minutes(0);
  9721. clone.seconds(0);
  9722. clone.milliseconds(0);
  9723. } else if (scale == 'week') {
  9724. if (clone.weekday() > 2) {
  9725. // doing it the momentjs locale aware way
  9726. clone.weekday(0);
  9727. clone.add(1, 'week');
  9728. } else {
  9729. clone.weekday(0);
  9730. }
  9731. clone.hours(0);
  9732. clone.minutes(0);
  9733. clone.seconds(0);
  9734. clone.milliseconds(0);
  9735. } else if (scale == 'day') {
  9736. //noinspection FallthroughInSwitchStatementJS
  9737. switch (step) {
  9738. case 5:
  9739. case 2:
  9740. clone.hours(Math.round(clone.hours() / 24) * 24);break;
  9741. default:
  9742. clone.hours(Math.round(clone.hours() / 12) * 12);break;
  9743. }
  9744. clone.minutes(0);
  9745. clone.seconds(0);
  9746. clone.milliseconds(0);
  9747. } else if (scale == 'weekday') {
  9748. //noinspection FallthroughInSwitchStatementJS
  9749. switch (step) {
  9750. case 5:
  9751. case 2:
  9752. clone.hours(Math.round(clone.hours() / 12) * 12);break;
  9753. default:
  9754. clone.hours(Math.round(clone.hours() / 6) * 6);break;
  9755. }
  9756. clone.minutes(0);
  9757. clone.seconds(0);
  9758. clone.milliseconds(0);
  9759. } else if (scale == 'hour') {
  9760. switch (step) {
  9761. case 4:
  9762. clone.minutes(Math.round(clone.minutes() / 60) * 60);break;
  9763. default:
  9764. clone.minutes(Math.round(clone.minutes() / 30) * 30);break;
  9765. }
  9766. clone.seconds(0);
  9767. clone.milliseconds(0);
  9768. } else if (scale == 'minute') {
  9769. //noinspection FallthroughInSwitchStatementJS
  9770. switch (step) {
  9771. case 15:
  9772. case 10:
  9773. clone.minutes(Math.round(clone.minutes() / 5) * 5);
  9774. clone.seconds(0);
  9775. break;
  9776. case 5:
  9777. clone.seconds(Math.round(clone.seconds() / 60) * 60);break;
  9778. default:
  9779. clone.seconds(Math.round(clone.seconds() / 30) * 30);break;
  9780. }
  9781. clone.milliseconds(0);
  9782. } else if (scale == 'second') {
  9783. //noinspection FallthroughInSwitchStatementJS
  9784. switch (step) {
  9785. case 15:
  9786. case 10:
  9787. clone.seconds(Math.round(clone.seconds() / 5) * 5);
  9788. clone.milliseconds(0);
  9789. break;
  9790. case 5:
  9791. clone.milliseconds(Math.round(clone.milliseconds() / 1000) * 1000);break;
  9792. default:
  9793. clone.milliseconds(Math.round(clone.milliseconds() / 500) * 500);break;
  9794. }
  9795. } else if (scale == 'millisecond') {
  9796. var _step = step > 5 ? step / 2 : 1;
  9797. clone.milliseconds(Math.round(clone.milliseconds() / _step) * _step);
  9798. }
  9799. return clone;
  9800. };
  9801. /**
  9802. * Check if the current value is a major value (for example when the step
  9803. * is DAY, a major value is each first day of the MONTH)
  9804. * @return {boolean} true if current date is major, else false.
  9805. */
  9806. TimeStep.prototype.isMajor = function () {
  9807. if (this.switchedYear == true) {
  9808. switch (this.scale) {
  9809. case 'year':
  9810. case 'month':
  9811. case 'week':
  9812. case 'weekday':
  9813. case 'day':
  9814. case 'hour':
  9815. case 'minute':
  9816. case 'second':
  9817. case 'millisecond':
  9818. return true;
  9819. default:
  9820. return false;
  9821. }
  9822. } else if (this.switchedMonth == true) {
  9823. switch (this.scale) {
  9824. case 'week':
  9825. case 'weekday':
  9826. case 'day':
  9827. case 'hour':
  9828. case 'minute':
  9829. case 'second':
  9830. case 'millisecond':
  9831. return true;
  9832. default:
  9833. return false;
  9834. }
  9835. } else if (this.switchedDay == true) {
  9836. switch (this.scale) {
  9837. case 'millisecond':
  9838. case 'second':
  9839. case 'minute':
  9840. case 'hour':
  9841. return true;
  9842. default:
  9843. return false;
  9844. }
  9845. }
  9846. var date = this.moment(this.current);
  9847. switch (this.scale) {
  9848. case 'millisecond':
  9849. return date.milliseconds() == 0;
  9850. case 'second':
  9851. return date.seconds() == 0;
  9852. case 'minute':
  9853. return date.hours() == 0 && date.minutes() == 0;
  9854. case 'hour':
  9855. return date.hours() == 0;
  9856. case 'weekday': // intentional fall through
  9857. case 'day':
  9858. return date.date() == 1;
  9859. case 'week':
  9860. return date.date() == 1;
  9861. case 'month':
  9862. return date.month() == 0;
  9863. case 'year':
  9864. return false;
  9865. default:
  9866. return false;
  9867. }
  9868. };
  9869. /**
  9870. * Returns formatted text for the minor axislabel, depending on the current
  9871. * date and the scale. For example when scale is MINUTE, the current time is
  9872. * formatted as "hh:mm".
  9873. * @param {Date} [date=this.current] custom date. if not provided, current date is taken
  9874. * @returns {String}
  9875. */
  9876. TimeStep.prototype.getLabelMinor = function (date) {
  9877. if (date == undefined) {
  9878. date = this.current;
  9879. }
  9880. if (date instanceof Date) {
  9881. date = this.moment(date);
  9882. }
  9883. if (typeof this.format.minorLabels === "function") {
  9884. return this.format.minorLabels(date, this.scale, this.step);
  9885. }
  9886. var format = this.format.minorLabels[this.scale];
  9887. // noinspection FallThroughInSwitchStatementJS
  9888. switch (this.scale) {
  9889. case 'week':
  9890. if (this.isMajor() && date.weekday() !== 0) {
  9891. return "";
  9892. }
  9893. default:
  9894. // eslint-disable-line no-fallthrough
  9895. return format && format.length > 0 ? this.moment(date).format(format) : '';
  9896. }
  9897. };
  9898. /**
  9899. * Returns formatted text for the major axis label, depending on the current
  9900. * date and the scale. For example when scale is MINUTE, the major scale is
  9901. * hours, and the hour will be formatted as "hh".
  9902. * @param {Date} [date=this.current] custom date. if not provided, current date is taken
  9903. * @returns {String}
  9904. */
  9905. TimeStep.prototype.getLabelMajor = function (date) {
  9906. if (date == undefined) {
  9907. date = this.current;
  9908. }
  9909. if (date instanceof Date) {
  9910. date = this.moment(date);
  9911. }
  9912. if (typeof this.format.majorLabels === "function") {
  9913. return this.format.majorLabels(date, this.scale, this.step);
  9914. }
  9915. var format = this.format.majorLabels[this.scale];
  9916. return format && format.length > 0 ? this.moment(date).format(format) : '';
  9917. };
  9918. TimeStep.prototype.getClassName = function () {
  9919. var _moment = this.moment;
  9920. var m = this.moment(this.current);
  9921. var current = m.locale ? m.locale('en') : m.lang('en'); // old versions of moment have .lang() function
  9922. var step = this.step;
  9923. var classNames = [];
  9924. /**
  9925. *
  9926. * @param {number} value
  9927. * @returns {String}
  9928. */
  9929. function even(value) {
  9930. return value / step % 2 == 0 ? ' vis-even' : ' vis-odd';
  9931. }
  9932. /**
  9933. *
  9934. * @param {Date} date
  9935. * @returns {String}
  9936. */
  9937. function today(date) {
  9938. if (date.isSame(new Date(), 'day')) {
  9939. return ' vis-today';
  9940. }
  9941. if (date.isSame(_moment().add(1, 'day'), 'day')) {
  9942. return ' vis-tomorrow';
  9943. }
  9944. if (date.isSame(_moment().add(-1, 'day'), 'day')) {
  9945. return ' vis-yesterday';
  9946. }
  9947. return '';
  9948. }
  9949. /**
  9950. *
  9951. * @param {Date} date
  9952. * @returns {String}
  9953. */
  9954. function currentWeek(date) {
  9955. return date.isSame(new Date(), 'week') ? ' vis-current-week' : '';
  9956. }
  9957. /**
  9958. *
  9959. * @param {Date} date
  9960. * @returns {String}
  9961. */
  9962. function currentMonth(date) {
  9963. return date.isSame(new Date(), 'month') ? ' vis-current-month' : '';
  9964. }
  9965. /**
  9966. *
  9967. * @param {Date} date
  9968. * @returns {String}
  9969. */
  9970. function currentYear(date) {
  9971. return date.isSame(new Date(), 'year') ? ' vis-current-year' : '';
  9972. }
  9973. switch (this.scale) {
  9974. case 'millisecond':
  9975. classNames.push(today(current));
  9976. classNames.push(even(current.milliseconds()));
  9977. break;
  9978. case 'second':
  9979. classNames.push(today(current));
  9980. classNames.push(even(current.seconds()));
  9981. break;
  9982. case 'minute':
  9983. classNames.push(today(current));
  9984. classNames.push(even(current.minutes()));
  9985. break;
  9986. case 'hour':
  9987. classNames.push('vis-h' + current.hours() + (this.step == 4 ? '-h' + (current.hours() + 4) : ''));
  9988. classNames.push(today(current));
  9989. classNames.push(even(current.hours()));
  9990. break;
  9991. case 'weekday':
  9992. classNames.push('vis-' + current.format('dddd').toLowerCase());
  9993. classNames.push(today(current));
  9994. classNames.push(currentWeek(current));
  9995. classNames.push(even(current.date()));
  9996. break;
  9997. case 'day':
  9998. classNames.push('vis-day' + current.date());
  9999. classNames.push('vis-' + current.format('MMMM').toLowerCase());
  10000. classNames.push(today(current));
  10001. classNames.push(currentMonth(current));
  10002. classNames.push(this.step <= 2 ? today(current) : '');
  10003. classNames.push(this.step <= 2 ? 'vis-' + current.format('dddd').toLowerCase() : '');
  10004. classNames.push(even(current.date() - 1));
  10005. break;
  10006. case 'week':
  10007. classNames.push('vis-week' + current.format('w'));
  10008. classNames.push(currentWeek(current));
  10009. classNames.push(even(current.week()));
  10010. break;
  10011. case 'month':
  10012. classNames.push('vis-' + current.format('MMMM').toLowerCase());
  10013. classNames.push(currentMonth(current));
  10014. classNames.push(even(current.month()));
  10015. break;
  10016. case 'year':
  10017. classNames.push('vis-year' + current.year());
  10018. classNames.push(currentYear(current));
  10019. classNames.push(even(current.year()));
  10020. break;
  10021. }
  10022. return classNames.filter(String).join(" ");
  10023. };
  10024. module.exports = TimeStep;
  10025. /***/ }),
  10026. /* 67 */
  10027. /***/ (function(module, exports, __webpack_require__) {
  10028. "use strict";
  10029. var util = __webpack_require__(2);
  10030. var Component = __webpack_require__(16);
  10031. var moment = __webpack_require__(9);
  10032. var locales = __webpack_require__(98);
  10033. /**
  10034. * A current time bar
  10035. * @param {{range: Range, dom: Object, domProps: Object}} body
  10036. * @param {Object} [options] Available parameters:
  10037. * {Boolean} [showCurrentTime]
  10038. * @constructor CurrentTime
  10039. * @extends Component
  10040. */
  10041. function CurrentTime(body, options) {
  10042. this.body = body;
  10043. // default options
  10044. this.defaultOptions = {
  10045. rtl: false,
  10046. showCurrentTime: true,
  10047. moment: moment,
  10048. locales: locales,
  10049. locale: 'en'
  10050. };
  10051. this.options = util.extend({}, this.defaultOptions);
  10052. this.offset = 0;
  10053. this._create();
  10054. this.setOptions(options);
  10055. }
  10056. CurrentTime.prototype = new Component();
  10057. /**
  10058. * Create the HTML DOM for the current time bar
  10059. * @private
  10060. */
  10061. CurrentTime.prototype._create = function () {
  10062. var bar = document.createElement('div');
  10063. bar.className = 'vis-current-time';
  10064. bar.style.position = 'absolute';
  10065. bar.style.top = '0px';
  10066. bar.style.height = '100%';
  10067. this.bar = bar;
  10068. };
  10069. /**
  10070. * Destroy the CurrentTime bar
  10071. */
  10072. CurrentTime.prototype.destroy = function () {
  10073. this.options.showCurrentTime = false;
  10074. this.redraw(); // will remove the bar from the DOM and stop refreshing
  10075. this.body = null;
  10076. };
  10077. /**
  10078. * Set options for the component. Options will be merged in current options.
  10079. * @param {Object} options Available parameters:
  10080. * {boolean} [showCurrentTime]
  10081. */
  10082. CurrentTime.prototype.setOptions = function (options) {
  10083. if (options) {
  10084. // copy all options that we know
  10085. util.selectiveExtend(['rtl', 'showCurrentTime', 'moment', 'locale', 'locales'], this.options, options);
  10086. }
  10087. };
  10088. /**
  10089. * Repaint the component
  10090. * @return {boolean} Returns true if the component is resized
  10091. */
  10092. CurrentTime.prototype.redraw = function () {
  10093. if (this.options.showCurrentTime) {
  10094. var parent = this.body.dom.backgroundVertical;
  10095. if (this.bar.parentNode != parent) {
  10096. // attach to the dom
  10097. if (this.bar.parentNode) {
  10098. this.bar.parentNode.removeChild(this.bar);
  10099. }
  10100. parent.appendChild(this.bar);
  10101. this.start();
  10102. }
  10103. var now = this.options.moment(new Date().valueOf() + this.offset);
  10104. var x = this.body.util.toScreen(now);
  10105. var locale = this.options.locales[this.options.locale];
  10106. if (!locale) {
  10107. if (!this.warned) {
  10108. console.log('WARNING: options.locales[\'' + this.options.locale + '\'] not found. See http://visjs.org/docs/timeline/#Localization');
  10109. this.warned = true;
  10110. }
  10111. locale = this.options.locales['en']; // fall back on english when not available
  10112. }
  10113. var title = locale.current + ' ' + locale.time + ': ' + now.format('dddd, MMMM Do YYYY, H:mm:ss');
  10114. title = title.charAt(0).toUpperCase() + title.substring(1);
  10115. if (this.options.rtl) {
  10116. this.bar.style.right = x + 'px';
  10117. } else {
  10118. this.bar.style.left = x + 'px';
  10119. }
  10120. this.bar.title = title;
  10121. } else {
  10122. // remove the line from the DOM
  10123. if (this.bar.parentNode) {
  10124. this.bar.parentNode.removeChild(this.bar);
  10125. }
  10126. this.stop();
  10127. }
  10128. return false;
  10129. };
  10130. /**
  10131. * Start auto refreshing the current time bar
  10132. */
  10133. CurrentTime.prototype.start = function () {
  10134. var me = this;
  10135. /**
  10136. * Updates the current time.
  10137. */
  10138. function update() {
  10139. me.stop();
  10140. // determine interval to refresh
  10141. var scale = me.body.range.conversion(me.body.domProps.center.width).scale;
  10142. var interval = 1 / scale / 10;
  10143. if (interval < 30) interval = 30;
  10144. if (interval > 1000) interval = 1000;
  10145. me.redraw();
  10146. me.body.emitter.emit('currentTimeTick');
  10147. // start a renderTimer to adjust for the new time
  10148. me.currentTimeTimer = setTimeout(update, interval);
  10149. }
  10150. update();
  10151. };
  10152. /**
  10153. * Stop auto refreshing the current time bar
  10154. */
  10155. CurrentTime.prototype.stop = function () {
  10156. if (this.currentTimeTimer !== undefined) {
  10157. clearTimeout(this.currentTimeTimer);
  10158. delete this.currentTimeTimer;
  10159. }
  10160. };
  10161. /**
  10162. * Set a current time. This can be used for example to ensure that a client's
  10163. * time is synchronized with a shared server time.
  10164. * @param {Date | string | number} time A Date, unix timestamp, or
  10165. * ISO date string.
  10166. */
  10167. CurrentTime.prototype.setCurrentTime = function (time) {
  10168. var t = util.convert(time, 'Date').valueOf();
  10169. var now = new Date().valueOf();
  10170. this.offset = t - now;
  10171. this.redraw();
  10172. };
  10173. /**
  10174. * Get the current time.
  10175. * @return {Date} Returns the current time.
  10176. */
  10177. CurrentTime.prototype.getCurrentTime = function () {
  10178. return new Date(new Date().valueOf() + this.offset);
  10179. };
  10180. module.exports = CurrentTime;
  10181. /***/ }),
  10182. /* 68 */
  10183. /***/ (function(module, exports, __webpack_require__) {
  10184. "use strict";
  10185. var _keys = __webpack_require__(8);
  10186. var _keys2 = _interopRequireDefault(_keys);
  10187. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  10188. var util = __webpack_require__(2);
  10189. var stack = __webpack_require__(100);
  10190. /**
  10191. * @param {number | string} groupId
  10192. * @param {Object} data
  10193. * @param {ItemSet} itemSet
  10194. * @constructor Group
  10195. */
  10196. function Group(groupId, data, itemSet) {
  10197. this.groupId = groupId;
  10198. this.subgroups = {};
  10199. this.subgroupStack = {};
  10200. this.subgroupStackAll = false;
  10201. this.doInnerStack = false;
  10202. this.subgroupIndex = 0;
  10203. this.subgroupOrderer = data && data.subgroupOrder;
  10204. this.itemSet = itemSet;
  10205. this.isVisible = null;
  10206. this.stackDirty = true; // if true, items will be restacked on next redraw
  10207. if (data && data.nestedGroups) {
  10208. this.nestedGroups = data.nestedGroups;
  10209. if (data.showNested == false) {
  10210. this.showNested = false;
  10211. } else {
  10212. this.showNested = true;
  10213. }
  10214. }
  10215. if (data && data.subgroupStack) {
  10216. if (typeof data.subgroupStack === "boolean") {
  10217. this.doInnerStack = data.subgroupStack;
  10218. this.subgroupStackAll = data.subgroupStack;
  10219. } else {
  10220. // We might be doing stacking on specific sub groups, but only
  10221. // if at least one is set to do stacking
  10222. for (var key in data.subgroupStack) {
  10223. this.subgroupStack[key] = data.subgroupStack[key];
  10224. this.doInnerStack = this.doInnerStack || data.subgroupStack[key];
  10225. }
  10226. }
  10227. }
  10228. this.nestedInGroup = null;
  10229. this.dom = {};
  10230. this.props = {
  10231. label: {
  10232. width: 0,
  10233. height: 0
  10234. }
  10235. };
  10236. this.className = null;
  10237. this.items = {}; // items filtered by groupId of this group
  10238. this.visibleItems = []; // items currently visible in window
  10239. this.itemsInRange = []; // items currently in range
  10240. this.orderedItems = {
  10241. byStart: [],
  10242. byEnd: []
  10243. };
  10244. this.checkRangedItems = false; // needed to refresh the ranged items if the window is programatically changed with NO overlap.
  10245. var me = this;
  10246. this.itemSet.body.emitter.on("checkRangedItems", function () {
  10247. me.checkRangedItems = true;
  10248. });
  10249. this._create();
  10250. this.setData(data);
  10251. }
  10252. /**
  10253. * Create DOM elements for the group
  10254. * @private
  10255. */
  10256. Group.prototype._create = function () {
  10257. var label = document.createElement('div');
  10258. if (this.itemSet.options.groupEditable.order) {
  10259. label.className = 'vis-label draggable';
  10260. } else {
  10261. label.className = 'vis-label';
  10262. }
  10263. this.dom.label = label;
  10264. var inner = document.createElement('div');
  10265. inner.className = 'vis-inner';
  10266. label.appendChild(inner);
  10267. this.dom.inner = inner;
  10268. var foreground = document.createElement('div');
  10269. foreground.className = 'vis-group';
  10270. foreground['timeline-group'] = this;
  10271. this.dom.foreground = foreground;
  10272. this.dom.background = document.createElement('div');
  10273. this.dom.background.className = 'vis-group';
  10274. this.dom.axis = document.createElement('div');
  10275. this.dom.axis.className = 'vis-group';
  10276. // create a hidden marker to detect when the Timelines container is attached
  10277. // to the DOM, or the style of a parent of the Timeline is changed from
  10278. // display:none is changed to visible.
  10279. this.dom.marker = document.createElement('div');
  10280. this.dom.marker.style.visibility = 'hidden';
  10281. this.dom.marker.style.position = 'absolute';
  10282. this.dom.marker.innerHTML = '';
  10283. this.dom.background.appendChild(this.dom.marker);
  10284. };
  10285. /**
  10286. * Set the group data for this group
  10287. * @param {Object} data Group data, can contain properties content and className
  10288. */
  10289. Group.prototype.setData = function (data) {
  10290. // update contents
  10291. var content;
  10292. var templateFunction;
  10293. if (this.itemSet.options && this.itemSet.options.groupTemplate) {
  10294. templateFunction = this.itemSet.options.groupTemplate.bind(this);
  10295. content = templateFunction(data, this.dom.inner);
  10296. } else {
  10297. content = data && data.content;
  10298. }
  10299. if (content instanceof Element) {
  10300. this.dom.inner.appendChild(content);
  10301. while (this.dom.inner.firstChild) {
  10302. this.dom.inner.removeChild(this.dom.inner.firstChild);
  10303. }
  10304. this.dom.inner.appendChild(content);
  10305. } else if (content instanceof Object) {
  10306. templateFunction(data, this.dom.inner);
  10307. } else if (content !== undefined && content !== null) {
  10308. this.dom.inner.innerHTML = content;
  10309. } else {
  10310. this.dom.inner.innerHTML = this.groupId || ''; // groupId can be null
  10311. }
  10312. // update title
  10313. this.dom.label.title = data && data.title || '';
  10314. if (!this.dom.inner.firstChild) {
  10315. util.addClassName(this.dom.inner, 'vis-hidden');
  10316. } else {
  10317. util.removeClassName(this.dom.inner, 'vis-hidden');
  10318. }
  10319. if (data && data.nestedGroups) {
  10320. if (!this.nestedGroups || this.nestedGroups != data.nestedGroups) {
  10321. this.nestedGroups = data.nestedGroups;
  10322. }
  10323. if (data.showNested !== undefined || this.showNested === undefined) {
  10324. if (data.showNested == false) {
  10325. this.showNested = false;
  10326. } else {
  10327. this.showNested = true;
  10328. }
  10329. }
  10330. util.addClassName(this.dom.label, 'vis-nesting-group');
  10331. var collapsedDirClassName = this.itemSet.options.rtl ? 'collapsed-rtl' : 'collapsed';
  10332. if (this.showNested) {
  10333. util.removeClassName(this.dom.label, collapsedDirClassName);
  10334. util.addClassName(this.dom.label, 'expanded');
  10335. } else {
  10336. util.removeClassName(this.dom.label, 'expanded');
  10337. util.addClassName(this.dom.label, collapsedDirClassName);
  10338. }
  10339. } else if (this.nestedGroups) {
  10340. this.nestedGroups = null;
  10341. collapsedDirClassName = this.itemSet.options.rtl ? 'collapsed-rtl' : 'collapsed';
  10342. util.removeClassName(this.dom.label, collapsedDirClassName);
  10343. util.removeClassName(this.dom.label, 'expanded');
  10344. util.removeClassName(this.dom.label, 'vis-nesting-group');
  10345. }
  10346. if (data && data.nestedInGroup) {
  10347. util.addClassName(this.dom.label, 'vis-nested-group');
  10348. if (this.itemSet.options && this.itemSet.options.rtl) {
  10349. this.dom.inner.style.paddingRight = '30px';
  10350. } else {
  10351. this.dom.inner.style.paddingLeft = '30px';
  10352. }
  10353. }
  10354. // update className
  10355. var className = data && data.className || null;
  10356. if (className != this.className) {
  10357. if (this.className) {
  10358. util.removeClassName(this.dom.label, this.className);
  10359. util.removeClassName(this.dom.foreground, this.className);
  10360. util.removeClassName(this.dom.background, this.className);
  10361. util.removeClassName(this.dom.axis, this.className);
  10362. }
  10363. util.addClassName(this.dom.label, className);
  10364. util.addClassName(this.dom.foreground, className);
  10365. util.addClassName(this.dom.background, className);
  10366. util.addClassName(this.dom.axis, className);
  10367. this.className = className;
  10368. }
  10369. // update style
  10370. if (this.style) {
  10371. util.removeCssText(this.dom.label, this.style);
  10372. this.style = null;
  10373. }
  10374. if (data && data.style) {
  10375. util.addCssText(this.dom.label, data.style);
  10376. this.style = data.style;
  10377. }
  10378. };
  10379. /**
  10380. * Get the width of the group label
  10381. * @return {number} width
  10382. */
  10383. Group.prototype.getLabelWidth = function () {
  10384. return this.props.label.width;
  10385. };
  10386. Group.prototype._didMarkerHeightChange = function () {
  10387. var markerHeight = this.dom.marker.clientHeight;
  10388. if (markerHeight != this.lastMarkerHeight) {
  10389. this.lastMarkerHeight = markerHeight;
  10390. var redrawQueue = {};
  10391. var redrawQueueLength = 0;
  10392. util.forEach(this.items, function (item, key) {
  10393. item.dirty = true;
  10394. if (item.displayed) {
  10395. var returnQueue = true;
  10396. redrawQueue[key] = item.redraw(returnQueue);
  10397. redrawQueueLength = redrawQueue[key].length;
  10398. }
  10399. });
  10400. var needRedraw = redrawQueueLength > 0;
  10401. if (needRedraw) {
  10402. // redraw all regular items
  10403. for (var i = 0; i < redrawQueueLength; i++) {
  10404. util.forEach(redrawQueue, function (fns) {
  10405. fns[i]();
  10406. });
  10407. }
  10408. }
  10409. return true;
  10410. }
  10411. };
  10412. Group.prototype._calculateGroupSizeAndPosition = function () {
  10413. var offsetTop = this.dom.foreground.offsetTop;
  10414. var offsetLeft = this.dom.foreground.offsetLeft;
  10415. var offsetWidth = this.dom.foreground.offsetWidth;
  10416. this.top = offsetTop;
  10417. this.right = offsetLeft;
  10418. this.width = offsetWidth;
  10419. };
  10420. Group.prototype._redrawItems = function (forceRestack, lastIsVisible, margin, range) {
  10421. var restack = forceRestack || this.stackDirty || this.isVisible && !lastIsVisible;
  10422. // if restacking, reposition visible items vertically
  10423. if (restack) {
  10424. var visibleSubgroups = {};
  10425. var subgroup = null;
  10426. if (typeof this.itemSet.options.order === 'function') {
  10427. // a custom order function
  10428. // brute force restack of all items
  10429. // show all items
  10430. var me = this;
  10431. var limitSize = false;
  10432. var redrawQueue = {};
  10433. var redrawQueueLength = 0;
  10434. util.forEach(this.items, function (item, key) {
  10435. if (!item.displayed) {
  10436. var returnQueue = true;
  10437. redrawQueue[key] = item.redraw(returnQueue);
  10438. redrawQueueLength = redrawQueue[key].length;
  10439. me.visibleItems.push(item);
  10440. }
  10441. });
  10442. var needRedraw = redrawQueueLength > 0;
  10443. if (needRedraw) {
  10444. // redraw all regular items
  10445. for (var i = 0; i < redrawQueueLength; i++) {
  10446. util.forEach(redrawQueue, function (fns) {
  10447. fns[i]();
  10448. });
  10449. }
  10450. }
  10451. util.forEach(this.items, function (item) {
  10452. item.repositionX(limitSize);
  10453. });
  10454. if (this.doInnerStack && this.itemSet.options.stackSubgroups) {
  10455. // Order the items within each subgroup
  10456. for (subgroup in this.subgroups) {
  10457. visibleSubgroups[subgroup] = this.subgroups[subgroup].items.slice().sort(function (a, b) {
  10458. return me.itemSet.options.order(a.data, b.data);
  10459. });
  10460. }
  10461. stack.stackSubgroupsWithInnerStack(visibleSubgroups, margin, this.subgroups);
  10462. } else {
  10463. // order all items and force a restacking
  10464. var customOrderedItems = this.orderedItems.byStart.slice().sort(function (a, b) {
  10465. return me.itemSet.options.order(a.data, b.data);
  10466. });
  10467. stack.stack(customOrderedItems, margin, true /* restack=true */);
  10468. }
  10469. this.visibleItems = this._updateItemsInRange(this.orderedItems, this.visibleItems, range);
  10470. } else {
  10471. // no custom order function, lazy stacking
  10472. this.visibleItems = this._updateItemsInRange(this.orderedItems, this.visibleItems, range);
  10473. if (this.itemSet.options.stack) {
  10474. if (this.doInnerStack && this.itemSet.options.stackSubgroups) {
  10475. for (subgroup in this.subgroups) {
  10476. visibleSubgroups[subgroup] = this.subgroups[subgroup].items;
  10477. }
  10478. stack.stackSubgroupsWithInnerStack(visibleSubgroups, margin, this.subgroups);
  10479. } else {
  10480. // TODO: ugly way to access options...
  10481. stack.stack(this.visibleItems, margin, true /* restack=true */);
  10482. }
  10483. } else {
  10484. // no stacking
  10485. stack.nostack(this.visibleItems, margin, this.subgroups, this.itemSet.options.stackSubgroups);
  10486. }
  10487. }
  10488. this.stackDirty = false;
  10489. }
  10490. };
  10491. Group.prototype._didResize = function (resized, height) {
  10492. resized = util.updateProperty(this, 'height', height) || resized;
  10493. // recalculate size of label
  10494. var labelWidth = this.dom.inner.clientWidth;
  10495. var labelHeight = this.dom.inner.clientHeight;
  10496. resized = util.updateProperty(this.props.label, 'width', labelWidth) || resized;
  10497. resized = util.updateProperty(this.props.label, 'height', labelHeight) || resized;
  10498. return resized;
  10499. };
  10500. Group.prototype._applyGroupHeight = function (height) {
  10501. this.dom.background.style.height = height + 'px';
  10502. this.dom.foreground.style.height = height + 'px';
  10503. this.dom.label.style.height = height + 'px';
  10504. };
  10505. // update vertical position of items after they are re-stacked and the height of the group is calculated
  10506. Group.prototype._updateItemsVerticalPosition = function (margin) {
  10507. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  10508. var item = this.visibleItems[i];
  10509. item.repositionY(margin);
  10510. if (!this.isVisible && this.groupId != "__background__") {
  10511. if (item.displayed) item.hide();
  10512. }
  10513. }
  10514. };
  10515. /**
  10516. * Repaint this group
  10517. * @param {{start: number, end: number}} range
  10518. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  10519. * @param {boolean} [forceRestack=false] Force restacking of all items
  10520. * @param {boolean} [returnQueue=false] return the queue or if the group resized
  10521. * @return {boolean} Returns true if the group is resized or the redraw queue if returnQueue=true
  10522. */
  10523. Group.prototype.redraw = function (range, margin, forceRestack, returnQueue) {
  10524. var resized = false;
  10525. var lastIsVisible = this.isVisible;
  10526. var height;
  10527. var queue = [
  10528. // force recalculation of the height of the items when the marker height changed
  10529. // (due to the Timeline being attached to the DOM or changed from display:none to visible)
  10530. function () {
  10531. forceRestack = this._didMarkerHeightChange.bind(this);
  10532. }.bind(this),
  10533. // recalculate the height of the subgroups
  10534. this._updateSubGroupHeights.bind(this, margin),
  10535. // calculate actual size and position
  10536. this._calculateGroupSizeAndPosition.bind(this),
  10537. // check if group is visible
  10538. function () {
  10539. this.isVisible = this._isGroupVisible.bind(this)(range, margin);
  10540. }.bind(this),
  10541. // redraw Items if needed
  10542. function () {
  10543. this._redrawItems.bind(this)(forceRestack, lastIsVisible, margin, range);
  10544. }.bind(this),
  10545. // update subgroups
  10546. this._updateSubgroupsSizes.bind(this),
  10547. // recalculate the height of the group
  10548. function () {
  10549. height = this._calculateHeight.bind(this)(margin);
  10550. }.bind(this),
  10551. // calculate actual size and position again
  10552. this._calculateGroupSizeAndPosition.bind(this),
  10553. // check if resized
  10554. function () {
  10555. resized = this._didResize.bind(this)(resized, height);
  10556. }.bind(this),
  10557. // apply group height
  10558. function () {
  10559. this._applyGroupHeight.bind(this)(height);
  10560. }.bind(this),
  10561. // update vertical position of items after they are re-stacked and the height of the group is calculated
  10562. function () {
  10563. this._updateItemsVerticalPosition.bind(this)(margin);
  10564. }.bind(this), function () {
  10565. if (!this.isVisible && this.height) {
  10566. resized = false;
  10567. }
  10568. return resized;
  10569. }];
  10570. if (returnQueue) {
  10571. return queue;
  10572. } else {
  10573. var result;
  10574. queue.forEach(function (fn) {
  10575. result = fn();
  10576. });
  10577. return result;
  10578. }
  10579. };
  10580. /**
  10581. * recalculate the height of the subgroups
  10582. *
  10583. * @param {{item: vis.Item}} margin
  10584. * @private
  10585. */
  10586. Group.prototype._updateSubGroupHeights = function (margin) {
  10587. if ((0, _keys2['default'])(this.subgroups).length > 0) {
  10588. var me = this;
  10589. this.resetSubgroups();
  10590. util.forEach(this.visibleItems, function (item) {
  10591. if (item.data.subgroup !== undefined) {
  10592. me.subgroups[item.data.subgroup].height = Math.max(me.subgroups[item.data.subgroup].height, item.height + margin.item.vertical);
  10593. me.subgroups[item.data.subgroup].visible = true;
  10594. }
  10595. });
  10596. }
  10597. };
  10598. /**
  10599. * check if group is visible
  10600. *
  10601. * @param {vis.Range} range
  10602. * @param {{axis: vis.DataAxis}} margin
  10603. * @returns {boolean} is visible
  10604. * @private
  10605. */
  10606. Group.prototype._isGroupVisible = function (range, margin) {
  10607. return this.top <= range.body.domProps.centerContainer.height - range.body.domProps.scrollTop + margin.axis && this.top + this.height + margin.axis >= -range.body.domProps.scrollTop;
  10608. };
  10609. /**
  10610. * recalculate the height of the group
  10611. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  10612. * @returns {number} Returns the height
  10613. * @private
  10614. */
  10615. Group.prototype._calculateHeight = function (margin) {
  10616. // recalculate the height of the group
  10617. var height;
  10618. var itemsInRange = this.visibleItems;
  10619. if (itemsInRange.length > 0) {
  10620. var min = itemsInRange[0].top;
  10621. var max = itemsInRange[0].top + itemsInRange[0].height;
  10622. util.forEach(itemsInRange, function (item) {
  10623. min = Math.min(min, item.top);
  10624. max = Math.max(max, item.top + item.height);
  10625. });
  10626. if (min > margin.axis) {
  10627. // there is an empty gap between the lowest item and the axis
  10628. var offset = min - margin.axis;
  10629. max -= offset;
  10630. util.forEach(itemsInRange, function (item) {
  10631. item.top -= offset;
  10632. });
  10633. }
  10634. height = max + margin.item.vertical / 2;
  10635. } else {
  10636. height = 0;
  10637. }
  10638. height = Math.max(height, this.props.label.height);
  10639. return height;
  10640. };
  10641. /**
  10642. * Show this group: attach to the DOM
  10643. */
  10644. Group.prototype.show = function () {
  10645. if (!this.dom.label.parentNode) {
  10646. this.itemSet.dom.labelSet.appendChild(this.dom.label);
  10647. }
  10648. if (!this.dom.foreground.parentNode) {
  10649. this.itemSet.dom.foreground.appendChild(this.dom.foreground);
  10650. }
  10651. if (!this.dom.background.parentNode) {
  10652. this.itemSet.dom.background.appendChild(this.dom.background);
  10653. }
  10654. if (!this.dom.axis.parentNode) {
  10655. this.itemSet.dom.axis.appendChild(this.dom.axis);
  10656. }
  10657. };
  10658. /**
  10659. * Hide this group: remove from the DOM
  10660. */
  10661. Group.prototype.hide = function () {
  10662. var label = this.dom.label;
  10663. if (label.parentNode) {
  10664. label.parentNode.removeChild(label);
  10665. }
  10666. var foreground = this.dom.foreground;
  10667. if (foreground.parentNode) {
  10668. foreground.parentNode.removeChild(foreground);
  10669. }
  10670. var background = this.dom.background;
  10671. if (background.parentNode) {
  10672. background.parentNode.removeChild(background);
  10673. }
  10674. var axis = this.dom.axis;
  10675. if (axis.parentNode) {
  10676. axis.parentNode.removeChild(axis);
  10677. }
  10678. };
  10679. /**
  10680. * Add an item to the group
  10681. * @param {Item} item
  10682. */
  10683. Group.prototype.add = function (item) {
  10684. this.items[item.id] = item;
  10685. item.setParent(this);
  10686. this.stackDirty = true;
  10687. // add to
  10688. if (item.data.subgroup !== undefined) {
  10689. this._addToSubgroup(item);
  10690. this.orderSubgroups();
  10691. }
  10692. if (this.visibleItems.indexOf(item) == -1) {
  10693. var range = this.itemSet.body.range; // TODO: not nice accessing the range like this
  10694. this._checkIfVisible(item, this.visibleItems, range);
  10695. }
  10696. };
  10697. Group.prototype._addToSubgroup = function (item, subgroupId) {
  10698. subgroupId = subgroupId || item.data.subgroup;
  10699. if (subgroupId != undefined && this.subgroups[subgroupId] === undefined) {
  10700. this.subgroups[subgroupId] = {
  10701. height: 0,
  10702. top: 0,
  10703. start: item.data.start,
  10704. end: item.data.end || item.data.start,
  10705. visible: false,
  10706. index: this.subgroupIndex,
  10707. items: [],
  10708. stack: this.subgroupStackAll || this.subgroupStack[subgroupId] || false
  10709. };
  10710. this.subgroupIndex++;
  10711. }
  10712. if (new Date(item.data.start) < new Date(this.subgroups[subgroupId].start)) {
  10713. this.subgroups[subgroupId].start = item.data.start;
  10714. }
  10715. var itemEnd = item.data.end || item.data.start;
  10716. if (new Date(itemEnd) > new Date(this.subgroups[subgroupId].end)) {
  10717. this.subgroups[subgroupId].end = itemEnd;
  10718. }
  10719. this.subgroups[subgroupId].items.push(item);
  10720. };
  10721. Group.prototype._updateSubgroupsSizes = function () {
  10722. var me = this;
  10723. if (me.subgroups) {
  10724. for (var subgroup in me.subgroups) {
  10725. var initialEnd = me.subgroups[subgroup].items[0].data.end || me.subgroups[subgroup].items[0].data.start;
  10726. var newStart = me.subgroups[subgroup].items[0].data.start;
  10727. var newEnd = initialEnd - 1;
  10728. me.subgroups[subgroup].items.forEach(function (item) {
  10729. if (new Date(item.data.start) < new Date(newStart)) {
  10730. newStart = item.data.start;
  10731. }
  10732. var itemEnd = item.data.end || item.data.start;
  10733. if (new Date(itemEnd) > new Date(newEnd)) {
  10734. newEnd = itemEnd;
  10735. }
  10736. });
  10737. me.subgroups[subgroup].start = newStart;
  10738. me.subgroups[subgroup].end = new Date(newEnd - 1); // -1 to compensate for colliding end to start subgroups;
  10739. }
  10740. }
  10741. };
  10742. Group.prototype.orderSubgroups = function () {
  10743. if (this.subgroupOrderer !== undefined) {
  10744. var sortArray = [];
  10745. var subgroup;
  10746. if (typeof this.subgroupOrderer == 'string') {
  10747. for (subgroup in this.subgroups) {
  10748. sortArray.push({ subgroup: subgroup, sortField: this.subgroups[subgroup].items[0].data[this.subgroupOrderer] });
  10749. }
  10750. sortArray.sort(function (a, b) {
  10751. return a.sortField - b.sortField;
  10752. });
  10753. } else if (typeof this.subgroupOrderer == 'function') {
  10754. for (subgroup in this.subgroups) {
  10755. sortArray.push(this.subgroups[subgroup].items[0].data);
  10756. }
  10757. sortArray.sort(this.subgroupOrderer);
  10758. }
  10759. if (sortArray.length > 0) {
  10760. for (var i = 0; i < sortArray.length; i++) {
  10761. this.subgroups[sortArray[i].subgroup].index = i;
  10762. }
  10763. }
  10764. }
  10765. };
  10766. Group.prototype.resetSubgroups = function () {
  10767. for (var subgroup in this.subgroups) {
  10768. if (this.subgroups.hasOwnProperty(subgroup)) {
  10769. this.subgroups[subgroup].visible = false;
  10770. this.subgroups[subgroup].height = 0;
  10771. }
  10772. }
  10773. };
  10774. /**
  10775. * Remove an item from the group
  10776. * @param {Item} item
  10777. */
  10778. Group.prototype.remove = function (item) {
  10779. delete this.items[item.id];
  10780. item.setParent(null);
  10781. this.stackDirty = true;
  10782. // remove from visible items
  10783. var index = this.visibleItems.indexOf(item);
  10784. if (index != -1) this.visibleItems.splice(index, 1);
  10785. if (item.data.subgroup !== undefined) {
  10786. this._removeFromSubgroup(item);
  10787. this.orderSubgroups();
  10788. }
  10789. };
  10790. Group.prototype._removeFromSubgroup = function (item, subgroupId) {
  10791. subgroupId = subgroupId || item.data.subgroup;
  10792. if (subgroupId != undefined) {
  10793. var subgroup = this.subgroups[subgroupId];
  10794. if (subgroup) {
  10795. var itemIndex = subgroup.items.indexOf(item);
  10796. // Check the item is actually in this subgroup. How should items not in the group be handled?
  10797. if (itemIndex >= 0) {
  10798. subgroup.items.splice(itemIndex, 1);
  10799. if (!subgroup.items.length) {
  10800. delete this.subgroups[subgroupId];
  10801. } else {
  10802. this._updateSubgroupsSizes();
  10803. }
  10804. }
  10805. }
  10806. }
  10807. };
  10808. /**
  10809. * Remove an item from the corresponding DataSet
  10810. * @param {Item} item
  10811. */
  10812. Group.prototype.removeFromDataSet = function (item) {
  10813. this.itemSet.removeItem(item.id);
  10814. };
  10815. /**
  10816. * Reorder the items
  10817. */
  10818. Group.prototype.order = function () {
  10819. var array = util.toArray(this.items);
  10820. var startArray = [];
  10821. var endArray = [];
  10822. for (var i = 0; i < array.length; i++) {
  10823. if (array[i].data.end !== undefined) {
  10824. endArray.push(array[i]);
  10825. }
  10826. startArray.push(array[i]);
  10827. }
  10828. this.orderedItems = {
  10829. byStart: startArray,
  10830. byEnd: endArray
  10831. };
  10832. stack.orderByStart(this.orderedItems.byStart);
  10833. stack.orderByEnd(this.orderedItems.byEnd);
  10834. };
  10835. /**
  10836. * Update the visible items
  10837. * @param {{byStart: Item[], byEnd: Item[]}} orderedItems All items ordered by start date and by end date
  10838. * @param {Item[]} oldVisibleItems The previously visible items.
  10839. * @param {{start: number, end: number}} range Visible range
  10840. * @return {Item[]} visibleItems The new visible items.
  10841. * @private
  10842. */
  10843. Group.prototype._updateItemsInRange = function (orderedItems, oldVisibleItems, range) {
  10844. var visibleItems = [];
  10845. var visibleItemsLookup = {}; // we keep this to quickly look up if an item already exists in the list without using indexOf on visibleItems
  10846. var interval = (range.end - range.start) / 4;
  10847. var lowerBound = range.start - interval;
  10848. var upperBound = range.end + interval;
  10849. // this function is used to do the binary search.
  10850. var searchFunction = function searchFunction(value) {
  10851. if (value < lowerBound) {
  10852. return -1;
  10853. } else if (value <= upperBound) {
  10854. return 0;
  10855. } else {
  10856. return 1;
  10857. }
  10858. };
  10859. // first check if the items that were in view previously are still in view.
  10860. // IMPORTANT: this handles the case for the items with startdate before the window and enddate after the window!
  10861. // also cleans up invisible items.
  10862. if (oldVisibleItems.length > 0) {
  10863. for (var i = 0; i < oldVisibleItems.length; i++) {
  10864. this._checkIfVisibleWithReference(oldVisibleItems[i], visibleItems, visibleItemsLookup, range);
  10865. }
  10866. }
  10867. // we do a binary search for the items that have only start values.
  10868. var initialPosByStart = util.binarySearchCustom(orderedItems.byStart, searchFunction, 'data', 'start');
  10869. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the start values.
  10870. this._traceVisible(initialPosByStart, orderedItems.byStart, visibleItems, visibleItemsLookup, function (item) {
  10871. return item.data.start < lowerBound || item.data.start > upperBound;
  10872. });
  10873. // if the window has changed programmatically without overlapping the old window, the ranged items with start < lowerBound and end > upperbound are not shown.
  10874. // We therefore have to brute force check all items in the byEnd list
  10875. if (this.checkRangedItems == true) {
  10876. this.checkRangedItems = false;
  10877. for (i = 0; i < orderedItems.byEnd.length; i++) {
  10878. this._checkIfVisibleWithReference(orderedItems.byEnd[i], visibleItems, visibleItemsLookup, range);
  10879. }
  10880. } else {
  10881. // we do a binary search for the items that have defined end times.
  10882. var initialPosByEnd = util.binarySearchCustom(orderedItems.byEnd, searchFunction, 'data', 'end');
  10883. // trace the visible items from the inital start pos both ways until an invisible item is found, we only look at the end values.
  10884. this._traceVisible(initialPosByEnd, orderedItems.byEnd, visibleItems, visibleItemsLookup, function (item) {
  10885. return item.data.end < lowerBound || item.data.end > upperBound;
  10886. });
  10887. }
  10888. var redrawQueue = {};
  10889. var redrawQueueLength = 0;
  10890. for (i = 0; i < visibleItems.length; i++) {
  10891. var item = visibleItems[i];
  10892. if (!item.displayed) {
  10893. var returnQueue = true;
  10894. redrawQueue[i] = item.redraw(returnQueue);
  10895. redrawQueueLength = redrawQueue[i].length;
  10896. }
  10897. }
  10898. var needRedraw = redrawQueueLength > 0;
  10899. if (needRedraw) {
  10900. // redraw all regular items
  10901. for (var j = 0; j < redrawQueueLength; j++) {
  10902. util.forEach(redrawQueue, function (fns) {
  10903. fns[j]();
  10904. });
  10905. }
  10906. }
  10907. for (i = 0; i < visibleItems.length; i++) {
  10908. visibleItems[i].repositionX();
  10909. }
  10910. return visibleItems;
  10911. };
  10912. Group.prototype._traceVisible = function (initialPos, items, visibleItems, visibleItemsLookup, breakCondition) {
  10913. if (initialPos != -1) {
  10914. var i, item;
  10915. for (i = initialPos; i >= 0; i--) {
  10916. item = items[i];
  10917. if (breakCondition(item)) {
  10918. break;
  10919. } else {
  10920. if (visibleItemsLookup[item.id] === undefined) {
  10921. visibleItemsLookup[item.id] = true;
  10922. visibleItems.push(item);
  10923. }
  10924. }
  10925. }
  10926. for (i = initialPos + 1; i < items.length; i++) {
  10927. item = items[i];
  10928. if (breakCondition(item)) {
  10929. break;
  10930. } else {
  10931. if (visibleItemsLookup[item.id] === undefined) {
  10932. visibleItemsLookup[item.id] = true;
  10933. visibleItems.push(item);
  10934. }
  10935. }
  10936. }
  10937. }
  10938. };
  10939. /**
  10940. * this function is very similar to the _checkIfInvisible() but it does not
  10941. * return booleans, hides the item if it should not be seen and always adds to
  10942. * the visibleItems.
  10943. * this one is for brute forcing and hiding.
  10944. *
  10945. * @param {Item} item
  10946. * @param {Array} visibleItems
  10947. * @param {{start:number, end:number}} range
  10948. * @private
  10949. */
  10950. Group.prototype._checkIfVisible = function (item, visibleItems, range) {
  10951. if (item.isVisible(range)) {
  10952. if (!item.displayed) item.show();
  10953. // reposition item horizontally
  10954. item.repositionX();
  10955. visibleItems.push(item);
  10956. } else {
  10957. if (item.displayed) item.hide();
  10958. }
  10959. };
  10960. /**
  10961. * this function is very similar to the _checkIfInvisible() but it does not
  10962. * return booleans, hides the item if it should not be seen and always adds to
  10963. * the visibleItems.
  10964. * this one is for brute forcing and hiding.
  10965. *
  10966. * @param {Item} item
  10967. * @param {Array.<vis.Item>} visibleItems
  10968. * @param {Object<number, boolean>} visibleItemsLookup
  10969. * @param {{start:number, end:number}} range
  10970. * @private
  10971. */
  10972. Group.prototype._checkIfVisibleWithReference = function (item, visibleItems, visibleItemsLookup, range) {
  10973. if (item.isVisible(range)) {
  10974. if (visibleItemsLookup[item.id] === undefined) {
  10975. visibleItemsLookup[item.id] = true;
  10976. visibleItems.push(item);
  10977. }
  10978. } else {
  10979. if (item.displayed) item.hide();
  10980. }
  10981. };
  10982. Group.prototype.changeSubgroup = function (item, oldSubgroup, newSubgroup) {
  10983. this._removeFromSubgroup(item, oldSubgroup);
  10984. this._addToSubgroup(item, newSubgroup);
  10985. this.orderSubgroups();
  10986. };
  10987. module.exports = Group;
  10988. /***/ }),
  10989. /* 69 */
  10990. /***/ (function(module, exports, __webpack_require__) {
  10991. "use strict";
  10992. var _create = __webpack_require__(29);
  10993. var _create2 = _interopRequireDefault(_create);
  10994. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  10995. var Group = __webpack_require__(68);
  10996. /**
  10997. * @constructor BackgroundGroup
  10998. * @param {number | string} groupId
  10999. * @param {Object} data
  11000. * @param {ItemSet} itemSet
  11001. * @extends Group
  11002. */
  11003. function BackgroundGroup(groupId, data, itemSet) {
  11004. Group.call(this, groupId, data, itemSet);
  11005. this.width = 0;
  11006. this.height = 0;
  11007. this.top = 0;
  11008. this.left = 0;
  11009. }
  11010. BackgroundGroup.prototype = (0, _create2['default'])(Group.prototype);
  11011. /**
  11012. * Repaint this group
  11013. * @param {{start: number, end: number}} range
  11014. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  11015. * @param {boolean} [forceRestack=false] Force restacking of all items
  11016. * @return {boolean} Returns true if the group is resized
  11017. */
  11018. BackgroundGroup.prototype.redraw = function (range, margin, forceRestack) {
  11019. // eslint-disable-line no-unused-vars
  11020. var resized = false;
  11021. this.visibleItems = this._updateItemsInRange(this.orderedItems, this.visibleItems, range);
  11022. // calculate actual size
  11023. this.width = this.dom.background.offsetWidth;
  11024. // apply new height (just always zero for BackgroundGroup
  11025. this.dom.background.style.height = '0';
  11026. // update vertical position of items after they are re-stacked and the height of the group is calculated
  11027. for (var i = 0, ii = this.visibleItems.length; i < ii; i++) {
  11028. var item = this.visibleItems[i];
  11029. item.repositionY(margin);
  11030. }
  11031. return resized;
  11032. };
  11033. /**
  11034. * Show this group: attach to the DOM
  11035. */
  11036. BackgroundGroup.prototype.show = function () {
  11037. if (!this.dom.background.parentNode) {
  11038. this.itemSet.dom.background.appendChild(this.dom.background);
  11039. }
  11040. };
  11041. module.exports = BackgroundGroup;
  11042. /***/ }),
  11043. /* 70 */
  11044. /***/ (function(module, exports, __webpack_require__) {
  11045. "use strict";
  11046. var Item = __webpack_require__(38);
  11047. /**
  11048. * @constructor RangeItem
  11049. * @extends Item
  11050. * @param {Object} data Object containing parameters start, end
  11051. * content, className.
  11052. * @param {{toScreen: function, toTime: function}} conversion
  11053. * Conversion functions from time to screen and vice versa
  11054. * @param {Object} [options] Configuration options
  11055. * // TODO: describe options
  11056. */
  11057. function RangeItem(data, conversion, options) {
  11058. this.props = {
  11059. content: {
  11060. width: 0
  11061. }
  11062. };
  11063. this.overflow = false; // if contents can overflow (css styling), this flag is set to true
  11064. this.options = options;
  11065. // validate data
  11066. if (data) {
  11067. if (data.start == undefined) {
  11068. throw new Error('Property "start" missing in item ' + data.id);
  11069. }
  11070. if (data.end == undefined) {
  11071. throw new Error('Property "end" missing in item ' + data.id);
  11072. }
  11073. }
  11074. Item.call(this, data, conversion, options);
  11075. }
  11076. RangeItem.prototype = new Item(null, null, null);
  11077. RangeItem.prototype.baseClassName = 'vis-item vis-range';
  11078. /**
  11079. * Check whether this item is visible inside given range
  11080. *
  11081. * @param {vis.Range} range with a timestamp for start and end
  11082. * @returns {boolean} True if visible
  11083. */
  11084. RangeItem.prototype.isVisible = function (range) {
  11085. // determine visibility
  11086. return this.data.start < range.end && this.data.end > range.start;
  11087. };
  11088. RangeItem.prototype._createDomElement = function () {
  11089. if (!this.dom) {
  11090. // create DOM
  11091. this.dom = {};
  11092. // background box
  11093. this.dom.box = document.createElement('div');
  11094. // className is updated in redraw()
  11095. // frame box (to prevent the item contents from overflowing)
  11096. this.dom.frame = document.createElement('div');
  11097. this.dom.frame.className = 'vis-item-overflow';
  11098. this.dom.box.appendChild(this.dom.frame);
  11099. // visible frame box (showing the frame that is always visible)
  11100. this.dom.visibleFrame = document.createElement('div');
  11101. this.dom.visibleFrame.className = 'vis-item-visible-frame';
  11102. this.dom.box.appendChild(this.dom.visibleFrame);
  11103. // contents box
  11104. this.dom.content = document.createElement('div');
  11105. this.dom.content.className = 'vis-item-content';
  11106. this.dom.frame.appendChild(this.dom.content);
  11107. // attach this item as attribute
  11108. this.dom.box['timeline-item'] = this;
  11109. this.dirty = true;
  11110. }
  11111. };
  11112. RangeItem.prototype._appendDomElement = function () {
  11113. if (!this.parent) {
  11114. throw new Error('Cannot redraw item: no parent attached');
  11115. }
  11116. if (!this.dom.box.parentNode) {
  11117. var foreground = this.parent.dom.foreground;
  11118. if (!foreground) {
  11119. throw new Error('Cannot redraw item: parent has no foreground container element');
  11120. }
  11121. foreground.appendChild(this.dom.box);
  11122. }
  11123. this.displayed = true;
  11124. };
  11125. RangeItem.prototype._updateDirtyDomComponents = function () {
  11126. // update dirty DOM. An item is marked dirty when:
  11127. // - the item is not yet rendered
  11128. // - the item's data is changed
  11129. // - the item is selected/deselected
  11130. if (this.dirty) {
  11131. this._updateContents(this.dom.content);
  11132. this._updateDataAttributes(this.dom.box);
  11133. this._updateStyle(this.dom.box);
  11134. var editable = this.editable.updateTime || this.editable.updateGroup;
  11135. // update class
  11136. var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : '') + (editable ? ' vis-editable' : ' vis-readonly');
  11137. this.dom.box.className = this.baseClassName + className;
  11138. // turn off max-width to be able to calculate the real width
  11139. // this causes an extra browser repaint/reflow, but so be it
  11140. this.dom.content.style.maxWidth = 'none';
  11141. }
  11142. };
  11143. RangeItem.prototype._getDomComponentsSizes = function () {
  11144. // determine from css whether this box has overflow
  11145. this.overflow = window.getComputedStyle(this.dom.frame).overflow !== 'hidden';
  11146. return {
  11147. content: {
  11148. width: this.dom.content.offsetWidth
  11149. },
  11150. box: {
  11151. height: this.dom.box.offsetHeight
  11152. }
  11153. };
  11154. };
  11155. RangeItem.prototype._updateDomComponentsSizes = function (sizes) {
  11156. this.props.content.width = sizes.content.width;
  11157. this.height = sizes.box.height;
  11158. this.dom.content.style.maxWidth = '';
  11159. this.dirty = false;
  11160. };
  11161. RangeItem.prototype._repaintDomAdditionals = function () {
  11162. this._repaintOnItemUpdateTimeTooltip(this.dom.box);
  11163. this._repaintDeleteButton(this.dom.box);
  11164. this._repaintDragCenter();
  11165. this._repaintDragLeft();
  11166. this._repaintDragRight();
  11167. };
  11168. /**
  11169. * Repaint the item
  11170. * @param {boolean} [returnQueue=false] return the queue
  11171. * @return {boolean} the redraw queue if returnQueue=true
  11172. */
  11173. RangeItem.prototype.redraw = function (returnQueue) {
  11174. var sizes;
  11175. var queue = [
  11176. // create item DOM
  11177. this._createDomElement.bind(this),
  11178. // append DOM to parent DOM
  11179. this._appendDomElement.bind(this),
  11180. // update dirty DOM
  11181. this._updateDirtyDomComponents.bind(this), function () {
  11182. if (this.dirty) {
  11183. sizes = this._getDomComponentsSizes.bind(this)();
  11184. }
  11185. }.bind(this), function () {
  11186. if (this.dirty) {
  11187. this._updateDomComponentsSizes.bind(this)(sizes);
  11188. }
  11189. }.bind(this),
  11190. // repaint DOM additionals
  11191. this._repaintDomAdditionals.bind(this)];
  11192. if (returnQueue) {
  11193. return queue;
  11194. } else {
  11195. var result;
  11196. queue.forEach(function (fn) {
  11197. result = fn();
  11198. });
  11199. return result;
  11200. }
  11201. };
  11202. /**
  11203. * Show the item in the DOM (when not already visible). The items DOM will
  11204. * be created when needed.
  11205. */
  11206. RangeItem.prototype.show = function () {
  11207. if (!this.displayed) {
  11208. this.redraw();
  11209. }
  11210. };
  11211. /**
  11212. * Hide the item from the DOM (when visible)
  11213. */
  11214. RangeItem.prototype.hide = function () {
  11215. if (this.displayed) {
  11216. var box = this.dom.box;
  11217. if (box.parentNode) {
  11218. box.parentNode.removeChild(box);
  11219. }
  11220. this.displayed = false;
  11221. }
  11222. };
  11223. /**
  11224. * Reposition the item horizontally
  11225. * @param {boolean} [limitSize=true] If true (default), the width of the range
  11226. * item will be limited, as the browser cannot
  11227. * display very wide divs. This means though
  11228. * that the applied left and width may
  11229. * not correspond to the ranges start and end
  11230. * @Override
  11231. */
  11232. RangeItem.prototype.repositionX = function (limitSize) {
  11233. var parentWidth = this.parent.width;
  11234. var start = this.conversion.toScreen(this.data.start);
  11235. var end = this.conversion.toScreen(this.data.end);
  11236. var align = this.data.align === undefined ? this.options.align : this.data.align;
  11237. var contentStartPosition;
  11238. var contentWidth;
  11239. // limit the width of the range, as browsers cannot draw very wide divs
  11240. // unless limitSize: false is explicitly set in item data
  11241. if (this.data.limitSize !== false && (limitSize === undefined || limitSize === true)) {
  11242. if (start < -parentWidth) {
  11243. start = -parentWidth;
  11244. }
  11245. if (end > 2 * parentWidth) {
  11246. end = 2 * parentWidth;
  11247. }
  11248. }
  11249. // add 0.5 to compensate floating-point values rounding
  11250. var boxWidth = Math.max(end - start + 0.5, 1);
  11251. if (this.overflow) {
  11252. if (this.options.rtl) {
  11253. this.right = start;
  11254. } else {
  11255. this.left = start;
  11256. }
  11257. this.width = boxWidth + this.props.content.width;
  11258. contentWidth = this.props.content.width;
  11259. // Note: The calculation of width is an optimistic calculation, giving
  11260. // a width which will not change when moving the Timeline
  11261. // So no re-stacking needed, which is nicer for the eye;
  11262. } else {
  11263. if (this.options.rtl) {
  11264. this.right = start;
  11265. } else {
  11266. this.left = start;
  11267. }
  11268. this.width = boxWidth;
  11269. contentWidth = Math.min(end - start, this.props.content.width);
  11270. }
  11271. if (this.options.rtl) {
  11272. this.dom.box.style.right = this.right + 'px';
  11273. } else {
  11274. this.dom.box.style.left = this.left + 'px';
  11275. }
  11276. this.dom.box.style.width = boxWidth + 'px';
  11277. switch (align) {
  11278. case 'left':
  11279. if (this.options.rtl) {
  11280. this.dom.content.style.right = '0';
  11281. } else {
  11282. this.dom.content.style.left = '0';
  11283. }
  11284. break;
  11285. case 'right':
  11286. if (this.options.rtl) {
  11287. this.dom.content.style.right = Math.max(boxWidth - contentWidth, 0) + 'px';
  11288. } else {
  11289. this.dom.content.style.left = Math.max(boxWidth - contentWidth, 0) + 'px';
  11290. }
  11291. break;
  11292. case 'center':
  11293. if (this.options.rtl) {
  11294. this.dom.content.style.right = Math.max((boxWidth - contentWidth) / 2, 0) + 'px';
  11295. } else {
  11296. this.dom.content.style.left = Math.max((boxWidth - contentWidth) / 2, 0) + 'px';
  11297. }
  11298. break;
  11299. default:
  11300. // 'auto'
  11301. // when range exceeds left of the window, position the contents at the left of the visible area
  11302. if (this.overflow) {
  11303. if (end > 0) {
  11304. contentStartPosition = Math.max(-start, 0);
  11305. } else {
  11306. contentStartPosition = -contentWidth; // ensure it's not visible anymore
  11307. }
  11308. } else {
  11309. if (start < 0) {
  11310. contentStartPosition = -start;
  11311. } else {
  11312. contentStartPosition = 0;
  11313. }
  11314. }
  11315. if (this.options.rtl) {
  11316. this.dom.content.style.right = contentStartPosition + 'px';
  11317. } else {
  11318. this.dom.content.style.left = contentStartPosition + 'px';
  11319. this.dom.content.style.width = 'calc(100% - ' + contentStartPosition + 'px)';
  11320. }
  11321. }
  11322. };
  11323. /**
  11324. * Reposition the item vertically
  11325. * @Override
  11326. */
  11327. RangeItem.prototype.repositionY = function () {
  11328. var orientation = this.options.orientation.item;
  11329. var box = this.dom.box;
  11330. if (orientation == 'top') {
  11331. box.style.top = this.top + 'px';
  11332. } else {
  11333. box.style.top = this.parent.height - this.top - this.height + 'px';
  11334. }
  11335. };
  11336. /**
  11337. * Repaint a drag area on the left side of the range when the range is selected
  11338. * @protected
  11339. */
  11340. RangeItem.prototype._repaintDragLeft = function () {
  11341. if ((this.selected || this.options.itemsAlwaysDraggable.range) && this.options.editable.updateTime && !this.dom.dragLeft) {
  11342. // create and show drag area
  11343. var dragLeft = document.createElement('div');
  11344. dragLeft.className = 'vis-drag-left';
  11345. dragLeft.dragLeftItem = this;
  11346. this.dom.box.appendChild(dragLeft);
  11347. this.dom.dragLeft = dragLeft;
  11348. } else if (!this.selected && !this.options.itemsAlwaysDraggable.range && this.dom.dragLeft) {
  11349. // delete drag area
  11350. if (this.dom.dragLeft.parentNode) {
  11351. this.dom.dragLeft.parentNode.removeChild(this.dom.dragLeft);
  11352. }
  11353. this.dom.dragLeft = null;
  11354. }
  11355. };
  11356. /**
  11357. * Repaint a drag area on the right side of the range when the range is selected
  11358. * @protected
  11359. */
  11360. RangeItem.prototype._repaintDragRight = function () {
  11361. if ((this.selected || this.options.itemsAlwaysDraggable.range) && this.options.editable.updateTime && !this.dom.dragRight) {
  11362. // create and show drag area
  11363. var dragRight = document.createElement('div');
  11364. dragRight.className = 'vis-drag-right';
  11365. dragRight.dragRightItem = this;
  11366. this.dom.box.appendChild(dragRight);
  11367. this.dom.dragRight = dragRight;
  11368. } else if (!this.selected && !this.options.itemsAlwaysDraggable.range && this.dom.dragRight) {
  11369. // delete drag area
  11370. if (this.dom.dragRight.parentNode) {
  11371. this.dom.dragRight.parentNode.removeChild(this.dom.dragRight);
  11372. }
  11373. this.dom.dragRight = null;
  11374. }
  11375. };
  11376. module.exports = RangeItem;
  11377. /***/ }),
  11378. /* 71 */
  11379. /***/ (function(module, exports, __webpack_require__) {
  11380. "use strict";
  11381. Object.defineProperty(exports, "__esModule", {
  11382. value: true
  11383. });
  11384. var _stringify = __webpack_require__(19);
  11385. var _stringify2 = _interopRequireDefault(_stringify);
  11386. var _typeof2 = __webpack_require__(6);
  11387. var _typeof3 = _interopRequireDefault(_typeof2);
  11388. var _classCallCheck2 = __webpack_require__(0);
  11389. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  11390. var _createClass2 = __webpack_require__(1);
  11391. var _createClass3 = _interopRequireDefault(_createClass2);
  11392. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  11393. var util = __webpack_require__(2);
  11394. var ColorPicker = __webpack_require__(179)['default'];
  11395. /**
  11396. * 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.
  11397. * Boolean options are recognised as Boolean
  11398. * Number options should be written as array: [default value, min value, max value, stepsize]
  11399. * Colors should be written as array: ['color', '#ffffff']
  11400. * Strings with should be written as array: [option1, option2, option3, ..]
  11401. *
  11402. * The options are matched with their counterparts in each of the modules and the values used in the configuration are
  11403. */
  11404. var Configurator = function () {
  11405. /**
  11406. * @param {Object} parentModule | the location where parentModule.setOptions() can be called
  11407. * @param {Object} defaultContainer | the default container of the module
  11408. * @param {Object} configureOptions | the fully configured and predefined options set found in allOptions.js
  11409. * @param {number} pixelRatio | canvas pixel ratio
  11410. */
  11411. function Configurator(parentModule, defaultContainer, configureOptions) {
  11412. var pixelRatio = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
  11413. (0, _classCallCheck3['default'])(this, Configurator);
  11414. this.parent = parentModule;
  11415. this.changedOptions = [];
  11416. this.container = defaultContainer;
  11417. this.allowCreation = false;
  11418. this.options = {};
  11419. this.initialized = false;
  11420. this.popupCounter = 0;
  11421. this.defaultOptions = {
  11422. enabled: false,
  11423. filter: true,
  11424. container: undefined,
  11425. showButton: true
  11426. };
  11427. util.extend(this.options, this.defaultOptions);
  11428. this.configureOptions = configureOptions;
  11429. this.moduleOptions = {};
  11430. this.domElements = [];
  11431. this.popupDiv = {};
  11432. this.popupLimit = 5;
  11433. this.popupHistory = {};
  11434. this.colorPicker = new ColorPicker(pixelRatio);
  11435. this.wrapper = undefined;
  11436. }
  11437. /**
  11438. * refresh all options.
  11439. * Because all modules parse their options by themselves, we just use their options. We copy them here.
  11440. *
  11441. * @param {Object} options
  11442. */
  11443. (0, _createClass3['default'])(Configurator, [{
  11444. key: 'setOptions',
  11445. value: function setOptions(options) {
  11446. if (options !== undefined) {
  11447. // reset the popup history because the indices may have been changed.
  11448. this.popupHistory = {};
  11449. this._removePopup();
  11450. var enabled = true;
  11451. if (typeof options === 'string') {
  11452. this.options.filter = options;
  11453. } else if (options instanceof Array) {
  11454. this.options.filter = options.join();
  11455. } else if ((typeof options === 'undefined' ? 'undefined' : (0, _typeof3['default'])(options)) === 'object') {
  11456. if (options.container !== undefined) {
  11457. this.options.container = options.container;
  11458. }
  11459. if (options.filter !== undefined) {
  11460. this.options.filter = options.filter;
  11461. }
  11462. if (options.showButton !== undefined) {
  11463. this.options.showButton = options.showButton;
  11464. }
  11465. if (options.enabled !== undefined) {
  11466. enabled = options.enabled;
  11467. }
  11468. } else if (typeof options === 'boolean') {
  11469. this.options.filter = true;
  11470. enabled = options;
  11471. } else if (typeof options === 'function') {
  11472. this.options.filter = options;
  11473. enabled = true;
  11474. }
  11475. if (this.options.filter === false) {
  11476. enabled = false;
  11477. }
  11478. this.options.enabled = enabled;
  11479. }
  11480. this._clean();
  11481. }
  11482. /**
  11483. *
  11484. * @param {Object} moduleOptions
  11485. */
  11486. }, {
  11487. key: 'setModuleOptions',
  11488. value: function setModuleOptions(moduleOptions) {
  11489. this.moduleOptions = moduleOptions;
  11490. if (this.options.enabled === true) {
  11491. this._clean();
  11492. if (this.options.container !== undefined) {
  11493. this.container = this.options.container;
  11494. }
  11495. this._create();
  11496. }
  11497. }
  11498. /**
  11499. * Create all DOM elements
  11500. * @private
  11501. */
  11502. }, {
  11503. key: '_create',
  11504. value: function _create() {
  11505. var _this = this;
  11506. this._clean();
  11507. this.changedOptions = [];
  11508. var filter = this.options.filter;
  11509. var counter = 0;
  11510. var show = false;
  11511. for (var option in this.configureOptions) {
  11512. if (this.configureOptions.hasOwnProperty(option)) {
  11513. this.allowCreation = false;
  11514. show = false;
  11515. if (typeof filter === 'function') {
  11516. show = filter(option, []);
  11517. show = show || this._handleObject(this.configureOptions[option], [option], true);
  11518. } else if (filter === true || filter.indexOf(option) !== -1) {
  11519. show = true;
  11520. }
  11521. if (show !== false) {
  11522. this.allowCreation = true;
  11523. // linebreak between categories
  11524. if (counter > 0) {
  11525. this._makeItem([]);
  11526. }
  11527. // a header for the category
  11528. this._makeHeader(option);
  11529. // get the sub options
  11530. this._handleObject(this.configureOptions[option], [option]);
  11531. }
  11532. counter++;
  11533. }
  11534. }
  11535. if (this.options.showButton === true) {
  11536. var generateButton = document.createElement('div');
  11537. generateButton.className = 'vis-configuration vis-config-button';
  11538. generateButton.innerHTML = 'generate options';
  11539. generateButton.onclick = function () {
  11540. _this._printOptions();
  11541. };
  11542. generateButton.onmouseover = function () {
  11543. generateButton.className = 'vis-configuration vis-config-button hover';
  11544. };
  11545. generateButton.onmouseout = function () {
  11546. generateButton.className = 'vis-configuration vis-config-button';
  11547. };
  11548. this.optionsContainer = document.createElement('div');
  11549. this.optionsContainer.className = 'vis-configuration vis-config-option-container';
  11550. this.domElements.push(this.optionsContainer);
  11551. this.domElements.push(generateButton);
  11552. }
  11553. this._push();
  11554. //~ this.colorPicker.insertTo(this.container);
  11555. }
  11556. /**
  11557. * draw all DOM elements on the screen
  11558. * @private
  11559. */
  11560. }, {
  11561. key: '_push',
  11562. value: function _push() {
  11563. this.wrapper = document.createElement('div');
  11564. this.wrapper.className = 'vis-configuration-wrapper';
  11565. this.container.appendChild(this.wrapper);
  11566. for (var i = 0; i < this.domElements.length; i++) {
  11567. this.wrapper.appendChild(this.domElements[i]);
  11568. }
  11569. this._showPopupIfNeeded();
  11570. }
  11571. /**
  11572. * delete all DOM elements
  11573. * @private
  11574. */
  11575. }, {
  11576. key: '_clean',
  11577. value: function _clean() {
  11578. for (var i = 0; i < this.domElements.length; i++) {
  11579. this.wrapper.removeChild(this.domElements[i]);
  11580. }
  11581. if (this.wrapper !== undefined) {
  11582. this.container.removeChild(this.wrapper);
  11583. this.wrapper = undefined;
  11584. }
  11585. this.domElements = [];
  11586. this._removePopup();
  11587. }
  11588. /**
  11589. * get the value from the actualOptions if it exists
  11590. * @param {array} path | where to look for the actual option
  11591. * @returns {*}
  11592. * @private
  11593. */
  11594. }, {
  11595. key: '_getValue',
  11596. value: function _getValue(path) {
  11597. var base = this.moduleOptions;
  11598. for (var i = 0; i < path.length; i++) {
  11599. if (base[path[i]] !== undefined) {
  11600. base = base[path[i]];
  11601. } else {
  11602. base = undefined;
  11603. break;
  11604. }
  11605. }
  11606. return base;
  11607. }
  11608. /**
  11609. * all option elements are wrapped in an item
  11610. * @param {Array} path | where to look for the actual option
  11611. * @param {Array.<Element>} domElements
  11612. * @returns {number}
  11613. * @private
  11614. */
  11615. }, {
  11616. key: '_makeItem',
  11617. value: function _makeItem(path) {
  11618. if (this.allowCreation === true) {
  11619. var item = document.createElement('div');
  11620. item.className = 'vis-configuration vis-config-item vis-config-s' + path.length;
  11621. for (var _len = arguments.length, domElements = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  11622. domElements[_key - 1] = arguments[_key];
  11623. }
  11624. domElements.forEach(function (element) {
  11625. item.appendChild(element);
  11626. });
  11627. this.domElements.push(item);
  11628. return this.domElements.length;
  11629. }
  11630. return 0;
  11631. }
  11632. /**
  11633. * header for major subjects
  11634. * @param {string} name
  11635. * @private
  11636. */
  11637. }, {
  11638. key: '_makeHeader',
  11639. value: function _makeHeader(name) {
  11640. var div = document.createElement('div');
  11641. div.className = 'vis-configuration vis-config-header';
  11642. div.innerHTML = name;
  11643. this._makeItem([], div);
  11644. }
  11645. /**
  11646. * make a label, if it is an object label, it gets different styling.
  11647. * @param {string} name
  11648. * @param {array} path | where to look for the actual option
  11649. * @param {string} objectLabel
  11650. * @returns {HTMLElement}
  11651. * @private
  11652. */
  11653. }, {
  11654. key: '_makeLabel',
  11655. value: function _makeLabel(name, path) {
  11656. var objectLabel = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  11657. var div = document.createElement('div');
  11658. div.className = 'vis-configuration vis-config-label vis-config-s' + path.length;
  11659. if (objectLabel === true) {
  11660. div.innerHTML = '<i><b>' + name + ':</b></i>';
  11661. } else {
  11662. div.innerHTML = name + ':';
  11663. }
  11664. return div;
  11665. }
  11666. /**
  11667. * make a dropdown list for multiple possible string optoins
  11668. * @param {Array.<number>} arr
  11669. * @param {number} value
  11670. * @param {array} path | where to look for the actual option
  11671. * @private
  11672. */
  11673. }, {
  11674. key: '_makeDropdown',
  11675. value: function _makeDropdown(arr, value, path) {
  11676. var select = document.createElement('select');
  11677. select.className = 'vis-configuration vis-config-select';
  11678. var selectedValue = 0;
  11679. if (value !== undefined) {
  11680. if (arr.indexOf(value) !== -1) {
  11681. selectedValue = arr.indexOf(value);
  11682. }
  11683. }
  11684. for (var i = 0; i < arr.length; i++) {
  11685. var option = document.createElement('option');
  11686. option.value = arr[i];
  11687. if (i === selectedValue) {
  11688. option.selected = 'selected';
  11689. }
  11690. option.innerHTML = arr[i];
  11691. select.appendChild(option);
  11692. }
  11693. var me = this;
  11694. select.onchange = function () {
  11695. me._update(this.value, path);
  11696. };
  11697. var label = this._makeLabel(path[path.length - 1], path);
  11698. this._makeItem(path, label, select);
  11699. }
  11700. /**
  11701. * make a range object for numeric options
  11702. * @param {Array.<number>} arr
  11703. * @param {number} value
  11704. * @param {array} path | where to look for the actual option
  11705. * @private
  11706. */
  11707. }, {
  11708. key: '_makeRange',
  11709. value: function _makeRange(arr, value, path) {
  11710. var defaultValue = arr[0];
  11711. var min = arr[1];
  11712. var max = arr[2];
  11713. var step = arr[3];
  11714. var range = document.createElement('input');
  11715. range.className = 'vis-configuration vis-config-range';
  11716. try {
  11717. range.type = 'range'; // not supported on IE9
  11718. range.min = min;
  11719. range.max = max;
  11720. }
  11721. // TODO: Add some error handling and remove this lint exception
  11722. catch (err) {} // eslint-disable-line no-empty
  11723. range.step = step;
  11724. // set up the popup settings in case they are needed.
  11725. var popupString = '';
  11726. var popupValue = 0;
  11727. if (value !== undefined) {
  11728. var factor = 1.20;
  11729. if (value < 0 && value * factor < min) {
  11730. range.min = Math.ceil(value * factor);
  11731. popupValue = range.min;
  11732. popupString = 'range increased';
  11733. } else if (value / factor < min) {
  11734. range.min = Math.ceil(value / factor);
  11735. popupValue = range.min;
  11736. popupString = 'range increased';
  11737. }
  11738. if (value * factor > max && max !== 1) {
  11739. range.max = Math.ceil(value * factor);
  11740. popupValue = range.max;
  11741. popupString = 'range increased';
  11742. }
  11743. range.value = value;
  11744. } else {
  11745. range.value = defaultValue;
  11746. }
  11747. var input = document.createElement('input');
  11748. input.className = 'vis-configuration vis-config-rangeinput';
  11749. input.value = range.value;
  11750. var me = this;
  11751. range.onchange = function () {
  11752. input.value = this.value;me._update(Number(this.value), path);
  11753. };
  11754. range.oninput = function () {
  11755. input.value = this.value;
  11756. };
  11757. var label = this._makeLabel(path[path.length - 1], path);
  11758. var itemIndex = this._makeItem(path, label, range, input);
  11759. // if a popup is needed AND it has not been shown for this value, show it.
  11760. if (popupString !== '' && this.popupHistory[itemIndex] !== popupValue) {
  11761. this.popupHistory[itemIndex] = popupValue;
  11762. this._setupPopup(popupString, itemIndex);
  11763. }
  11764. }
  11765. /**
  11766. * prepare the popup
  11767. * @param {string} string
  11768. * @param {number} index
  11769. * @private
  11770. */
  11771. }, {
  11772. key: '_setupPopup',
  11773. value: function _setupPopup(string, index) {
  11774. var _this2 = this;
  11775. if (this.initialized === true && this.allowCreation === true && this.popupCounter < this.popupLimit) {
  11776. var div = document.createElement("div");
  11777. div.id = "vis-configuration-popup";
  11778. div.className = "vis-configuration-popup";
  11779. div.innerHTML = string;
  11780. div.onclick = function () {
  11781. _this2._removePopup();
  11782. };
  11783. this.popupCounter += 1;
  11784. this.popupDiv = { html: div, index: index };
  11785. }
  11786. }
  11787. /**
  11788. * remove the popup from the dom
  11789. * @private
  11790. */
  11791. }, {
  11792. key: '_removePopup',
  11793. value: function _removePopup() {
  11794. if (this.popupDiv.html !== undefined) {
  11795. this.popupDiv.html.parentNode.removeChild(this.popupDiv.html);
  11796. clearTimeout(this.popupDiv.hideTimeout);
  11797. clearTimeout(this.popupDiv.deleteTimeout);
  11798. this.popupDiv = {};
  11799. }
  11800. }
  11801. /**
  11802. * Show the popup if it is needed.
  11803. * @private
  11804. */
  11805. }, {
  11806. key: '_showPopupIfNeeded',
  11807. value: function _showPopupIfNeeded() {
  11808. var _this3 = this;
  11809. if (this.popupDiv.html !== undefined) {
  11810. var correspondingElement = this.domElements[this.popupDiv.index];
  11811. var rect = correspondingElement.getBoundingClientRect();
  11812. this.popupDiv.html.style.left = rect.left + "px";
  11813. this.popupDiv.html.style.top = rect.top - 30 + "px"; // 30 is the height;
  11814. document.body.appendChild(this.popupDiv.html);
  11815. this.popupDiv.hideTimeout = setTimeout(function () {
  11816. _this3.popupDiv.html.style.opacity = 0;
  11817. }, 1500);
  11818. this.popupDiv.deleteTimeout = setTimeout(function () {
  11819. _this3._removePopup();
  11820. }, 1800);
  11821. }
  11822. }
  11823. /**
  11824. * make a checkbox for boolean options.
  11825. * @param {number} defaultValue
  11826. * @param {number} value
  11827. * @param {array} path | where to look for the actual option
  11828. * @private
  11829. */
  11830. }, {
  11831. key: '_makeCheckbox',
  11832. value: function _makeCheckbox(defaultValue, value, path) {
  11833. var checkbox = document.createElement('input');
  11834. checkbox.type = 'checkbox';
  11835. checkbox.className = 'vis-configuration vis-config-checkbox';
  11836. checkbox.checked = defaultValue;
  11837. if (value !== undefined) {
  11838. checkbox.checked = value;
  11839. if (value !== defaultValue) {
  11840. if ((typeof defaultValue === 'undefined' ? 'undefined' : (0, _typeof3['default'])(defaultValue)) === 'object') {
  11841. if (value !== defaultValue.enabled) {
  11842. this.changedOptions.push({ path: path, value: value });
  11843. }
  11844. } else {
  11845. this.changedOptions.push({ path: path, value: value });
  11846. }
  11847. }
  11848. }
  11849. var me = this;
  11850. checkbox.onchange = function () {
  11851. me._update(this.checked, path);
  11852. };
  11853. var label = this._makeLabel(path[path.length - 1], path);
  11854. this._makeItem(path, label, checkbox);
  11855. }
  11856. /**
  11857. * make a text input field for string options.
  11858. * @param {number} defaultValue
  11859. * @param {number} value
  11860. * @param {array} path | where to look for the actual option
  11861. * @private
  11862. */
  11863. }, {
  11864. key: '_makeTextInput',
  11865. value: function _makeTextInput(defaultValue, value, path) {
  11866. var checkbox = document.createElement('input');
  11867. checkbox.type = 'text';
  11868. checkbox.className = 'vis-configuration vis-config-text';
  11869. checkbox.value = value;
  11870. if (value !== defaultValue) {
  11871. this.changedOptions.push({ path: path, value: value });
  11872. }
  11873. var me = this;
  11874. checkbox.onchange = function () {
  11875. me._update(this.value, path);
  11876. };
  11877. var label = this._makeLabel(path[path.length - 1], path);
  11878. this._makeItem(path, label, checkbox);
  11879. }
  11880. /**
  11881. * make a color field with a color picker for color fields
  11882. * @param {Array.<number>} arr
  11883. * @param {number} value
  11884. * @param {array} path | where to look for the actual option
  11885. * @private
  11886. */
  11887. }, {
  11888. key: '_makeColorField',
  11889. value: function _makeColorField(arr, value, path) {
  11890. var _this4 = this;
  11891. var defaultColor = arr[1];
  11892. var div = document.createElement('div');
  11893. value = value === undefined ? defaultColor : value;
  11894. if (value !== 'none') {
  11895. div.className = 'vis-configuration vis-config-colorBlock';
  11896. div.style.backgroundColor = value;
  11897. } else {
  11898. div.className = 'vis-configuration vis-config-colorBlock none';
  11899. }
  11900. value = value === undefined ? defaultColor : value;
  11901. div.onclick = function () {
  11902. _this4._showColorPicker(value, div, path);
  11903. };
  11904. var label = this._makeLabel(path[path.length - 1], path);
  11905. this._makeItem(path, label, div);
  11906. }
  11907. /**
  11908. * used by the color buttons to call the color picker.
  11909. * @param {number} value
  11910. * @param {HTMLElement} div
  11911. * @param {array} path | where to look for the actual option
  11912. * @private
  11913. */
  11914. }, {
  11915. key: '_showColorPicker',
  11916. value: function _showColorPicker(value, div, path) {
  11917. var _this5 = this;
  11918. // clear the callback from this div
  11919. div.onclick = function () {};
  11920. this.colorPicker.insertTo(div);
  11921. this.colorPicker.show();
  11922. this.colorPicker.setColor(value);
  11923. this.colorPicker.setUpdateCallback(function (color) {
  11924. var colorString = 'rgba(' + color.r + ',' + color.g + ',' + color.b + ',' + color.a + ')';
  11925. div.style.backgroundColor = colorString;
  11926. _this5._update(colorString, path);
  11927. });
  11928. // on close of the colorpicker, restore the callback.
  11929. this.colorPicker.setCloseCallback(function () {
  11930. div.onclick = function () {
  11931. _this5._showColorPicker(value, div, path);
  11932. };
  11933. });
  11934. }
  11935. /**
  11936. * parse an object and draw the correct items
  11937. * @param {Object} obj
  11938. * @param {array} [path=[]] | where to look for the actual option
  11939. * @param {boolean} [checkOnly=false]
  11940. * @returns {boolean}
  11941. * @private
  11942. */
  11943. }, {
  11944. key: '_handleObject',
  11945. value: function _handleObject(obj) {
  11946. var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  11947. var checkOnly = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  11948. var show = false;
  11949. var filter = this.options.filter;
  11950. var visibleInSet = false;
  11951. for (var subObj in obj) {
  11952. if (obj.hasOwnProperty(subObj)) {
  11953. show = true;
  11954. var item = obj[subObj];
  11955. var newPath = util.copyAndExtendArray(path, subObj);
  11956. if (typeof filter === 'function') {
  11957. show = filter(subObj, path);
  11958. // if needed we must go deeper into the object.
  11959. if (show === false) {
  11960. if (!(item instanceof Array) && typeof item !== 'string' && typeof item !== 'boolean' && item instanceof Object) {
  11961. this.allowCreation = false;
  11962. show = this._handleObject(item, newPath, true);
  11963. this.allowCreation = checkOnly === false;
  11964. }
  11965. }
  11966. }
  11967. if (show !== false) {
  11968. visibleInSet = true;
  11969. var value = this._getValue(newPath);
  11970. if (item instanceof Array) {
  11971. this._handleArray(item, value, newPath);
  11972. } else if (typeof item === 'string') {
  11973. this._makeTextInput(item, value, newPath);
  11974. } else if (typeof item === 'boolean') {
  11975. this._makeCheckbox(item, value, newPath);
  11976. } else if (item instanceof Object) {
  11977. // collapse the physics options that are not enabled
  11978. var draw = true;
  11979. if (path.indexOf('physics') !== -1) {
  11980. if (this.moduleOptions.physics.solver !== subObj) {
  11981. draw = false;
  11982. }
  11983. }
  11984. if (draw === true) {
  11985. // initially collapse options with an disabled enabled option.
  11986. if (item.enabled !== undefined) {
  11987. var enabledPath = util.copyAndExtendArray(newPath, 'enabled');
  11988. var enabledValue = this._getValue(enabledPath);
  11989. if (enabledValue === true) {
  11990. var label = this._makeLabel(subObj, newPath, true);
  11991. this._makeItem(newPath, label);
  11992. visibleInSet = this._handleObject(item, newPath) || visibleInSet;
  11993. } else {
  11994. this._makeCheckbox(item, enabledValue, newPath);
  11995. }
  11996. } else {
  11997. var _label = this._makeLabel(subObj, newPath, true);
  11998. this._makeItem(newPath, _label);
  11999. visibleInSet = this._handleObject(item, newPath) || visibleInSet;
  12000. }
  12001. }
  12002. } else {
  12003. console.error('dont know how to handle', item, subObj, newPath);
  12004. }
  12005. }
  12006. }
  12007. }
  12008. return visibleInSet;
  12009. }
  12010. /**
  12011. * handle the array type of option
  12012. * @param {Array.<number>} arr
  12013. * @param {number} value
  12014. * @param {array} path | where to look for the actual option
  12015. * @private
  12016. */
  12017. }, {
  12018. key: '_handleArray',
  12019. value: function _handleArray(arr, value, path) {
  12020. if (typeof arr[0] === 'string' && arr[0] === 'color') {
  12021. this._makeColorField(arr, value, path);
  12022. if (arr[1] !== value) {
  12023. this.changedOptions.push({ path: path, value: value });
  12024. }
  12025. } else if (typeof arr[0] === 'string') {
  12026. this._makeDropdown(arr, value, path);
  12027. if (arr[0] !== value) {
  12028. this.changedOptions.push({ path: path, value: value });
  12029. }
  12030. } else if (typeof arr[0] === 'number') {
  12031. this._makeRange(arr, value, path);
  12032. if (arr[0] !== value) {
  12033. this.changedOptions.push({ path: path, value: Number(value) });
  12034. }
  12035. }
  12036. }
  12037. /**
  12038. * called to update the network with the new settings.
  12039. * @param {number} value
  12040. * @param {array} path | where to look for the actual option
  12041. * @private
  12042. */
  12043. }, {
  12044. key: '_update',
  12045. value: function _update(value, path) {
  12046. var options = this._constructOptions(value, path);
  12047. if (this.parent.body && this.parent.body.emitter && this.parent.body.emitter.emit) {
  12048. this.parent.body.emitter.emit("configChange", options);
  12049. }
  12050. this.initialized = true;
  12051. this.parent.setOptions(options);
  12052. }
  12053. /**
  12054. *
  12055. * @param {string|Boolean} value
  12056. * @param {Array.<string>} path
  12057. * @param {{}} optionsObj
  12058. * @returns {{}}
  12059. * @private
  12060. */
  12061. }, {
  12062. key: '_constructOptions',
  12063. value: function _constructOptions(value, path) {
  12064. var optionsObj = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  12065. var pointer = optionsObj;
  12066. // when dropdown boxes can be string or boolean, we typecast it into correct types
  12067. value = value === 'true' ? true : value;
  12068. value = value === 'false' ? false : value;
  12069. for (var i = 0; i < path.length; i++) {
  12070. if (path[i] !== 'global') {
  12071. if (pointer[path[i]] === undefined) {
  12072. pointer[path[i]] = {};
  12073. }
  12074. if (i !== path.length - 1) {
  12075. pointer = pointer[path[i]];
  12076. } else {
  12077. pointer[path[i]] = value;
  12078. }
  12079. }
  12080. }
  12081. return optionsObj;
  12082. }
  12083. /**
  12084. * @private
  12085. */
  12086. }, {
  12087. key: '_printOptions',
  12088. value: function _printOptions() {
  12089. var options = this.getOptions();
  12090. this.optionsContainer.innerHTML = '<pre>var options = ' + (0, _stringify2['default'])(options, null, 2) + '</pre>';
  12091. }
  12092. /**
  12093. *
  12094. * @returns {{}} options
  12095. */
  12096. }, {
  12097. key: 'getOptions',
  12098. value: function getOptions() {
  12099. var options = {};
  12100. for (var i = 0; i < this.changedOptions.length; i++) {
  12101. this._constructOptions(this.changedOptions[i].value, this.changedOptions[i].path, options);
  12102. }
  12103. return options;
  12104. }
  12105. }]);
  12106. return Configurator;
  12107. }();
  12108. exports['default'] = Configurator;
  12109. /***/ }),
  12110. /* 72 */
  12111. /***/ (function(module, exports, __webpack_require__) {
  12112. "use strict";
  12113. var _typeof2 = __webpack_require__(6);
  12114. var _typeof3 = _interopRequireDefault(_typeof2);
  12115. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  12116. var DOMutil = __webpack_require__(14);
  12117. /**
  12118. *
  12119. * @param {number | string} groupId
  12120. * @param {Object} options // TODO: Describe options
  12121. *
  12122. * @constructor Points
  12123. */
  12124. function Points(groupId, options) {} // eslint-disable-line no-unused-vars
  12125. /**
  12126. * draw the data points
  12127. *
  12128. * @param {Array} dataset
  12129. * @param {GraphGroup} group
  12130. * @param {Object} framework | SVG DOM element
  12131. * @param {number} [offset]
  12132. */
  12133. Points.draw = function (dataset, group, framework, offset) {
  12134. offset = offset || 0;
  12135. var callback = getCallback(framework, group);
  12136. for (var i = 0; i < dataset.length; i++) {
  12137. if (!callback) {
  12138. // draw the point the simple way.
  12139. DOMutil.drawPoint(dataset[i].screen_x + offset, dataset[i].screen_y, getGroupTemplate(group), framework.svgElements, framework.svg, dataset[i].label);
  12140. } else {
  12141. var callbackResult = callback(dataset[i], group); // result might be true, false or an object
  12142. if (callbackResult === true || (typeof callbackResult === 'undefined' ? 'undefined' : (0, _typeof3['default'])(callbackResult)) === 'object') {
  12143. DOMutil.drawPoint(dataset[i].screen_x + offset, dataset[i].screen_y, getGroupTemplate(group, callbackResult), framework.svgElements, framework.svg, dataset[i].label);
  12144. }
  12145. }
  12146. }
  12147. };
  12148. Points.drawIcon = function (group, x, y, iconWidth, iconHeight, framework) {
  12149. var fillHeight = iconHeight * 0.5;
  12150. var outline = DOMutil.getSVGElement("rect", framework.svgElements, framework.svg);
  12151. outline.setAttributeNS(null, "x", x);
  12152. outline.setAttributeNS(null, "y", y - fillHeight);
  12153. outline.setAttributeNS(null, "width", iconWidth);
  12154. outline.setAttributeNS(null, "height", 2 * fillHeight);
  12155. outline.setAttributeNS(null, "class", "vis-outline");
  12156. //Don't call callback on icon
  12157. DOMutil.drawPoint(x + 0.5 * iconWidth, y, getGroupTemplate(group), framework.svgElements, framework.svg);
  12158. };
  12159. /**
  12160. *
  12161. * @param {vis.Group} group
  12162. * @param {any} callbackResult
  12163. * @returns {{style: *, styles: (*|string), size: *, className: *}}
  12164. */
  12165. function getGroupTemplate(group, callbackResult) {
  12166. callbackResult = typeof callbackResult === 'undefined' ? {} : callbackResult;
  12167. return {
  12168. style: callbackResult.style || group.options.drawPoints.style,
  12169. styles: callbackResult.styles || group.options.drawPoints.styles,
  12170. size: callbackResult.size || group.options.drawPoints.size,
  12171. className: callbackResult.className || group.className
  12172. };
  12173. }
  12174. /**
  12175. *
  12176. * @param {Object} framework | SVG DOM element
  12177. * @param {vis.Group} group
  12178. * @returns {function}
  12179. */
  12180. function getCallback(framework, group) {
  12181. var callback = undefined;
  12182. // check for the graph2d onRender
  12183. if (framework.options && framework.options.drawPoints && framework.options.drawPoints.onRender && typeof framework.options.drawPoints.onRender == 'function') {
  12184. callback = framework.options.drawPoints.onRender;
  12185. }
  12186. // override it with the group onRender if defined
  12187. if (group.group.options && group.group.options.drawPoints && group.group.options.drawPoints.onRender && typeof group.group.options.drawPoints.onRender == 'function') {
  12188. callback = group.group.options.drawPoints.onRender;
  12189. }
  12190. return callback;
  12191. }
  12192. module.exports = Points;
  12193. /***/ }),
  12194. /* 73 */
  12195. /***/ (function(module, exports, __webpack_require__) {
  12196. "use strict";
  12197. Object.defineProperty(exports, "__esModule", {
  12198. value: true
  12199. });
  12200. var _getPrototypeOf = __webpack_require__(3);
  12201. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  12202. var _classCallCheck2 = __webpack_require__(0);
  12203. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  12204. var _createClass2 = __webpack_require__(1);
  12205. var _createClass3 = _interopRequireDefault(_createClass2);
  12206. var _possibleConstructorReturn2 = __webpack_require__(4);
  12207. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  12208. var _inherits2 = __webpack_require__(5);
  12209. var _inherits3 = _interopRequireDefault(_inherits2);
  12210. var _NodeBase2 = __webpack_require__(23);
  12211. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  12212. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  12213. /**
  12214. * NOTE: This is a bad base class
  12215. *
  12216. * Child classes are:
  12217. *
  12218. * Image - uses *only* image methods
  12219. * Circle - uses *only* _drawRawCircle
  12220. * CircleImage - uses all
  12221. *
  12222. * TODO: Refactor, move _drawRawCircle to different module, derive Circle from NodeBase
  12223. * Rename this to ImageBase
  12224. * Consolidate common code in Image and CircleImage to base class
  12225. *
  12226. * @extends NodeBase
  12227. */
  12228. var CircleImageBase = function (_NodeBase) {
  12229. (0, _inherits3['default'])(CircleImageBase, _NodeBase);
  12230. /**
  12231. * @param {Object} options
  12232. * @param {Object} body
  12233. * @param {Label} labelModule
  12234. */
  12235. function CircleImageBase(options, body, labelModule) {
  12236. (0, _classCallCheck3['default'])(this, CircleImageBase);
  12237. var _this = (0, _possibleConstructorReturn3['default'])(this, (CircleImageBase.__proto__ || (0, _getPrototypeOf2['default'])(CircleImageBase)).call(this, options, body, labelModule));
  12238. _this.labelOffset = 0;
  12239. _this.selected = false;
  12240. return _this;
  12241. }
  12242. /**
  12243. *
  12244. * @param {Object} options
  12245. * @param {Object} [imageObj]
  12246. * @param {Object} [imageObjAlt]
  12247. */
  12248. (0, _createClass3['default'])(CircleImageBase, [{
  12249. key: 'setOptions',
  12250. value: function setOptions(options, imageObj, imageObjAlt) {
  12251. this.options = options;
  12252. if (!(imageObj === undefined && imageObjAlt === undefined)) {
  12253. this.setImages(imageObj, imageObjAlt);
  12254. }
  12255. }
  12256. /**
  12257. * Set the images for this node.
  12258. *
  12259. * The images can be updated after the initial setting of options;
  12260. * therefore, this method needs to be reentrant.
  12261. *
  12262. * For correct working in error cases, it is necessary to properly set
  12263. * field 'nodes.brokenImage' in the options.
  12264. *
  12265. * @param {Image} imageObj required; main image to show for this node
  12266. * @param {Image|undefined} imageObjAlt optional; image to show when node is selected
  12267. */
  12268. }, {
  12269. key: 'setImages',
  12270. value: function setImages(imageObj, imageObjAlt) {
  12271. if (imageObjAlt && this.selected) {
  12272. this.imageObj = imageObjAlt;
  12273. this.imageObjAlt = imageObj;
  12274. } else {
  12275. this.imageObj = imageObj;
  12276. this.imageObjAlt = imageObjAlt;
  12277. }
  12278. }
  12279. /**
  12280. * Set selection and switch between the base and the selected image.
  12281. *
  12282. * Do the switch only if imageObjAlt exists.
  12283. *
  12284. * @param {boolean} selected value of new selected state for current node
  12285. */
  12286. }, {
  12287. key: 'switchImages',
  12288. value: function switchImages(selected) {
  12289. var selection_changed = selected && !this.selected || !selected && this.selected;
  12290. this.selected = selected; // Remember new selection
  12291. if (this.imageObjAlt !== undefined && selection_changed) {
  12292. var imageTmp = this.imageObj;
  12293. this.imageObj = this.imageObjAlt;
  12294. this.imageObjAlt = imageTmp;
  12295. }
  12296. }
  12297. /**
  12298. * Adjust the node dimensions for a loaded image.
  12299. *
  12300. * Pre: this.imageObj is valid
  12301. */
  12302. }, {
  12303. key: '_resizeImage',
  12304. value: function _resizeImage() {
  12305. var width, height;
  12306. if (this.options.shapeProperties.useImageSize === false) {
  12307. // Use the size property
  12308. var ratio_width = 1;
  12309. var ratio_height = 1;
  12310. // Only calculate the proper ratio if both width and height not zero
  12311. if (this.imageObj.width && this.imageObj.height) {
  12312. if (this.imageObj.width > this.imageObj.height) {
  12313. ratio_width = this.imageObj.width / this.imageObj.height;
  12314. } else {
  12315. ratio_height = this.imageObj.height / this.imageObj.width;
  12316. }
  12317. }
  12318. width = this.options.size * 2 * ratio_width;
  12319. height = this.options.size * 2 * ratio_height;
  12320. } else {
  12321. // Use the image size
  12322. width = this.imageObj.width;
  12323. height = this.imageObj.height;
  12324. }
  12325. this.width = width;
  12326. this.height = height;
  12327. this.radius = 0.5 * this.width;
  12328. }
  12329. /**
  12330. *
  12331. * @param {CanvasRenderingContext2D} ctx
  12332. * @param {number} x width
  12333. * @param {number} y height
  12334. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  12335. * @private
  12336. */
  12337. }, {
  12338. key: '_drawRawCircle',
  12339. value: function _drawRawCircle(ctx, x, y, values) {
  12340. this.initContextForDraw(ctx, values);
  12341. ctx.circle(x, y, values.size);
  12342. this.performFill(ctx, values);
  12343. }
  12344. /**
  12345. *
  12346. * @param {CanvasRenderingContext2D} ctx
  12347. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  12348. * @private
  12349. */
  12350. }, {
  12351. key: '_drawImageAtPosition',
  12352. value: function _drawImageAtPosition(ctx, values) {
  12353. if (this.imageObj.width != 0) {
  12354. // draw the image
  12355. ctx.globalAlpha = 1.0;
  12356. // draw shadow if enabled
  12357. this.enableShadow(ctx, values);
  12358. var factor = 1;
  12359. if (this.options.shapeProperties.interpolation === true) {
  12360. factor = this.imageObj.width / this.width / this.body.view.scale;
  12361. }
  12362. this.imageObj.drawImageAtPosition(ctx, factor, this.left, this.top, this.width, this.height);
  12363. // disable shadows for other elements.
  12364. this.disableShadow(ctx, values);
  12365. }
  12366. }
  12367. /**
  12368. *
  12369. * @param {CanvasRenderingContext2D} ctx
  12370. * @param {number} x width
  12371. * @param {number} y height
  12372. * @param {boolean} selected
  12373. * @param {boolean} hover
  12374. * @private
  12375. */
  12376. }, {
  12377. key: '_drawImageLabel',
  12378. value: function _drawImageLabel(ctx, x, y, selected, hover) {
  12379. var yLabel;
  12380. var offset = 0;
  12381. if (this.height !== undefined) {
  12382. offset = this.height * 0.5;
  12383. var labelDimensions = this.labelModule.getTextSize(ctx, selected, hover);
  12384. if (labelDimensions.lineCount >= 1) {
  12385. offset += labelDimensions.height / 2;
  12386. }
  12387. }
  12388. yLabel = y + offset;
  12389. if (this.options.label) {
  12390. this.labelOffset = offset;
  12391. }
  12392. this.labelModule.draw(ctx, x, yLabel, selected, hover, 'hanging');
  12393. }
  12394. }]);
  12395. return CircleImageBase;
  12396. }(_NodeBase3['default']);
  12397. exports['default'] = CircleImageBase;
  12398. /***/ }),
  12399. /* 74 */
  12400. /***/ (function(module, exports, __webpack_require__) {
  12401. "use strict";
  12402. Object.defineProperty(exports, "__esModule", {
  12403. value: true
  12404. });
  12405. var _stringify = __webpack_require__(19);
  12406. var _stringify2 = _interopRequireDefault(_stringify);
  12407. var _typeof2 = __webpack_require__(6);
  12408. var _typeof3 = _interopRequireDefault(_typeof2);
  12409. var _create = __webpack_require__(29);
  12410. var _create2 = _interopRequireDefault(_create);
  12411. var _classCallCheck2 = __webpack_require__(0);
  12412. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  12413. var _createClass2 = __webpack_require__(1);
  12414. var _createClass3 = _interopRequireDefault(_createClass2);
  12415. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  12416. var util = __webpack_require__(2);
  12417. var Label = __webpack_require__(117)['default'];
  12418. var ComponentUtil = __webpack_require__(48)['default'];
  12419. var CubicBezierEdge = __webpack_require__(215)['default'];
  12420. var BezierEdgeDynamic = __webpack_require__(217)['default'];
  12421. var BezierEdgeStatic = __webpack_require__(218)['default'];
  12422. var StraightEdge = __webpack_require__(219)['default'];
  12423. /**
  12424. * An edge connects two nodes and has a specific direction.
  12425. */
  12426. var Edge = function () {
  12427. /**
  12428. * @param {Object} options values specific to this edge, must contain at least 'from' and 'to'
  12429. * @param {Object} body shared state from Network instance
  12430. * @param {Object} globalOptions options from the EdgesHandler instance
  12431. * @param {Object} defaultOptions default options from the EdgeHandler instance. Value and reference are constant
  12432. */
  12433. function Edge(options, body, globalOptions, defaultOptions) {
  12434. (0, _classCallCheck3['default'])(this, Edge);
  12435. if (body === undefined) {
  12436. throw new Error("No body provided");
  12437. }
  12438. // Since globalOptions is constant in values as well as reference,
  12439. // Following needs to be done only once.
  12440. this.options = util.bridgeObject(globalOptions);
  12441. this.globalOptions = globalOptions;
  12442. this.defaultOptions = defaultOptions;
  12443. this.body = body;
  12444. // initialize variables
  12445. this.id = undefined;
  12446. this.fromId = undefined;
  12447. this.toId = undefined;
  12448. this.selected = false;
  12449. this.hover = false;
  12450. this.labelDirty = true;
  12451. this.baseWidth = this.options.width;
  12452. this.baseFontSize = this.options.font.size;
  12453. this.from = undefined; // a node
  12454. this.to = undefined; // a node
  12455. this.edgeType = undefined;
  12456. this.connected = false;
  12457. this.labelModule = new Label(this.body, this.options, true /* It's an edge label */);
  12458. this.setOptions(options);
  12459. }
  12460. /**
  12461. * Set or overwrite options for the edge
  12462. * @param {Object} options an object with options
  12463. * @returns {null|boolean} null if no options, boolean if date changed
  12464. */
  12465. (0, _createClass3['default'])(Edge, [{
  12466. key: 'setOptions',
  12467. value: function setOptions(options) {
  12468. if (!options) {
  12469. return;
  12470. }
  12471. Edge.parseOptions(this.options, options, true, this.globalOptions);
  12472. if (options.id !== undefined) {
  12473. this.id = options.id;
  12474. }
  12475. if (options.from !== undefined) {
  12476. this.fromId = options.from;
  12477. }
  12478. if (options.to !== undefined) {
  12479. this.toId = options.to;
  12480. }
  12481. if (options.title !== undefined) {
  12482. this.title = options.title;
  12483. }
  12484. if (options.value !== undefined) {
  12485. options.value = parseFloat(options.value);
  12486. }
  12487. var pile = [options, this.options, this.defaultOptions];
  12488. this.chooser = ComponentUtil.choosify('edge', pile);
  12489. // update label Module
  12490. this.updateLabelModule(options);
  12491. var dataChanged = this.updateEdgeType();
  12492. // if anything has been updates, reset the selection width and the hover width
  12493. this._setInteractionWidths();
  12494. // A node is connected when it has a from and to node that both exist in the network.body.nodes.
  12495. this.connect();
  12496. if (options.hidden !== undefined || options.physics !== undefined) {
  12497. dataChanged = true;
  12498. }
  12499. return dataChanged;
  12500. }
  12501. /**
  12502. *
  12503. * @param {Object} parentOptions
  12504. * @param {Object} newOptions
  12505. * @param {boolean} [allowDeletion=false]
  12506. * @param {Object} [globalOptions={}]
  12507. * @param {boolean} [copyFromGlobals=false]
  12508. */
  12509. }, {
  12510. key: 'getFormattingValues',
  12511. /**
  12512. *
  12513. * @returns {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}}
  12514. */
  12515. value: function getFormattingValues() {
  12516. var toArrow = this.options.arrows.to === true || this.options.arrows.to.enabled === true;
  12517. var fromArrow = this.options.arrows.from === true || this.options.arrows.from.enabled === true;
  12518. var middleArrow = this.options.arrows.middle === true || this.options.arrows.middle.enabled === true;
  12519. var inheritsColor = this.options.color.inherit;
  12520. var values = {
  12521. toArrow: toArrow,
  12522. toArrowScale: this.options.arrows.to.scaleFactor,
  12523. toArrowType: this.options.arrows.to.type,
  12524. middleArrow: middleArrow,
  12525. middleArrowScale: this.options.arrows.middle.scaleFactor,
  12526. middleArrowType: this.options.arrows.middle.type,
  12527. fromArrow: fromArrow,
  12528. fromArrowScale: this.options.arrows.from.scaleFactor,
  12529. fromArrowType: this.options.arrows.from.type,
  12530. arrowStrikethrough: this.options.arrowStrikethrough,
  12531. color: inheritsColor ? undefined : this.options.color.color,
  12532. inheritsColor: inheritsColor,
  12533. opacity: this.options.color.opacity,
  12534. hidden: this.options.hidden,
  12535. length: this.options.length,
  12536. shadow: this.options.shadow.enabled,
  12537. shadowColor: this.options.shadow.color,
  12538. shadowSize: this.options.shadow.size,
  12539. shadowX: this.options.shadow.x,
  12540. shadowY: this.options.shadow.y,
  12541. dashes: this.options.dashes,
  12542. width: this.options.width
  12543. };
  12544. if (this.selected || this.hover) {
  12545. if (this.chooser === true) {
  12546. if (this.selected) {
  12547. var selectedWidth = this.options.selectionWidth;
  12548. if (typeof selectedWidth === 'function') {
  12549. values.width = selectedWidth(values.width);
  12550. } else if (typeof selectedWidth === 'number') {
  12551. values.width += selectedWidth;
  12552. }
  12553. values.width = Math.max(values.width, 0.3 / this.body.view.scale);
  12554. values.color = this.options.color.highlight;
  12555. values.shadow = this.options.shadow.enabled;
  12556. } else if (this.hover) {
  12557. var hoverWidth = this.options.hoverWidth;
  12558. if (typeof hoverWidth === 'function') {
  12559. values.width = hoverWidth(values.width);
  12560. } else if (typeof hoverWidth === 'number') {
  12561. values.width += hoverWidth;
  12562. }
  12563. values.width = Math.max(values.width, 0.3 / this.body.view.scale);
  12564. values.color = this.options.color.hover;
  12565. values.shadow = this.options.shadow.enabled;
  12566. }
  12567. } else if (typeof this.chooser === 'function') {
  12568. this.chooser(values, this.options.id, this.selected, this.hover);
  12569. if (values.color !== undefined) {
  12570. values.inheritsColor = false;
  12571. }
  12572. if (values.shadow === false) {
  12573. if (values.shadowColor !== this.options.shadow.color || values.shadowSize !== this.options.shadow.size || values.shadowX !== this.options.shadow.x || values.shadowY !== this.options.shadow.y) {
  12574. values.shadow = true;
  12575. }
  12576. }
  12577. }
  12578. } else {
  12579. values.shadow = this.options.shadow.enabled;
  12580. values.width = Math.max(values.width, 0.3 / this.body.view.scale);
  12581. }
  12582. return values;
  12583. }
  12584. /**
  12585. * update the options in the label module
  12586. *
  12587. * @param {Object} options
  12588. */
  12589. }, {
  12590. key: 'updateLabelModule',
  12591. value: function updateLabelModule(options) {
  12592. var pile = [options, this.options, this.globalOptions, // Currently set global edge options
  12593. this.defaultOptions];
  12594. this.labelModule.update(this.options, pile);
  12595. if (this.labelModule.baseSize !== undefined) {
  12596. this.baseFontSize = this.labelModule.baseSize;
  12597. }
  12598. }
  12599. /**
  12600. * update the edge type, set the options
  12601. * @returns {boolean}
  12602. */
  12603. }, {
  12604. key: 'updateEdgeType',
  12605. value: function updateEdgeType() {
  12606. var smooth = this.options.smooth;
  12607. var dataChanged = false;
  12608. var changeInType = true;
  12609. if (this.edgeType !== undefined) {
  12610. if (this.edgeType instanceof BezierEdgeDynamic && smooth.enabled === true && smooth.type === 'dynamic' || this.edgeType instanceof CubicBezierEdge && smooth.enabled === true && smooth.type === 'cubicBezier' || this.edgeType instanceof BezierEdgeStatic && smooth.enabled === true && smooth.type !== 'dynamic' && smooth.type !== 'cubicBezier' || this.edgeType instanceof StraightEdge && smooth.type.enabled === false) {
  12611. changeInType = false;
  12612. }
  12613. if (changeInType === true) {
  12614. dataChanged = this.cleanup();
  12615. }
  12616. }
  12617. if (changeInType === true) {
  12618. if (smooth.enabled === true) {
  12619. if (smooth.type === 'dynamic') {
  12620. dataChanged = true;
  12621. this.edgeType = new BezierEdgeDynamic(this.options, this.body, this.labelModule);
  12622. } else if (smooth.type === 'cubicBezier') {
  12623. this.edgeType = new CubicBezierEdge(this.options, this.body, this.labelModule);
  12624. } else {
  12625. this.edgeType = new BezierEdgeStatic(this.options, this.body, this.labelModule);
  12626. }
  12627. } else {
  12628. this.edgeType = new StraightEdge(this.options, this.body, this.labelModule);
  12629. }
  12630. } else {
  12631. // if nothing changes, we just set the options.
  12632. this.edgeType.setOptions(this.options);
  12633. }
  12634. return dataChanged;
  12635. }
  12636. /**
  12637. * Connect an edge to its nodes
  12638. */
  12639. }, {
  12640. key: 'connect',
  12641. value: function connect() {
  12642. this.disconnect();
  12643. this.from = this.body.nodes[this.fromId] || undefined;
  12644. this.to = this.body.nodes[this.toId] || undefined;
  12645. this.connected = this.from !== undefined && this.to !== undefined;
  12646. if (this.connected === true) {
  12647. this.from.attachEdge(this);
  12648. this.to.attachEdge(this);
  12649. } else {
  12650. if (this.from) {
  12651. this.from.detachEdge(this);
  12652. }
  12653. if (this.to) {
  12654. this.to.detachEdge(this);
  12655. }
  12656. }
  12657. this.edgeType.connect();
  12658. }
  12659. /**
  12660. * Disconnect an edge from its nodes
  12661. */
  12662. }, {
  12663. key: 'disconnect',
  12664. value: function disconnect() {
  12665. if (this.from) {
  12666. this.from.detachEdge(this);
  12667. this.from = undefined;
  12668. }
  12669. if (this.to) {
  12670. this.to.detachEdge(this);
  12671. this.to = undefined;
  12672. }
  12673. this.connected = false;
  12674. }
  12675. /**
  12676. * get the title of this edge.
  12677. * @return {string} title The title of the edge, or undefined when no title
  12678. * has been set.
  12679. */
  12680. }, {
  12681. key: 'getTitle',
  12682. value: function getTitle() {
  12683. return this.title;
  12684. }
  12685. /**
  12686. * check if this node is selecte
  12687. * @return {boolean} selected True if node is selected, else false
  12688. */
  12689. }, {
  12690. key: 'isSelected',
  12691. value: function isSelected() {
  12692. return this.selected;
  12693. }
  12694. /**
  12695. * Retrieve the value of the edge. Can be undefined
  12696. * @return {number} value
  12697. */
  12698. }, {
  12699. key: 'getValue',
  12700. value: function getValue() {
  12701. return this.options.value;
  12702. }
  12703. /**
  12704. * Adjust the value range of the edge. The edge will adjust it's width
  12705. * based on its value.
  12706. * @param {number} min
  12707. * @param {number} max
  12708. * @param {number} total
  12709. */
  12710. }, {
  12711. key: 'setValueRange',
  12712. value: function setValueRange(min, max, total) {
  12713. if (this.options.value !== undefined) {
  12714. var scale = this.options.scaling.customScalingFunction(min, max, total, this.options.value);
  12715. var widthDiff = this.options.scaling.max - this.options.scaling.min;
  12716. if (this.options.scaling.label.enabled === true) {
  12717. var fontDiff = this.options.scaling.label.max - this.options.scaling.label.min;
  12718. this.options.font.size = this.options.scaling.label.min + scale * fontDiff;
  12719. }
  12720. this.options.width = this.options.scaling.min + scale * widthDiff;
  12721. } else {
  12722. this.options.width = this.baseWidth;
  12723. this.options.font.size = this.baseFontSize;
  12724. }
  12725. this._setInteractionWidths();
  12726. this.updateLabelModule();
  12727. }
  12728. /**
  12729. *
  12730. * @private
  12731. */
  12732. }, {
  12733. key: '_setInteractionWidths',
  12734. value: function _setInteractionWidths() {
  12735. if (typeof this.options.hoverWidth === 'function') {
  12736. this.edgeType.hoverWidth = this.options.hoverWidth(this.options.width);
  12737. } else {
  12738. this.edgeType.hoverWidth = this.options.hoverWidth + this.options.width;
  12739. }
  12740. if (typeof this.options.selectionWidth === 'function') {
  12741. this.edgeType.selectionWidth = this.options.selectionWidth(this.options.width);
  12742. } else {
  12743. this.edgeType.selectionWidth = this.options.selectionWidth + this.options.width;
  12744. }
  12745. }
  12746. /**
  12747. * Redraw a edge
  12748. * Draw this edge in the given canvas
  12749. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  12750. * @param {CanvasRenderingContext2D} ctx
  12751. */
  12752. }, {
  12753. key: 'draw',
  12754. value: function draw(ctx) {
  12755. var values = this.getFormattingValues();
  12756. if (values.hidden) {
  12757. return;
  12758. }
  12759. // get the via node from the edge type
  12760. var viaNode = this.edgeType.getViaNode();
  12761. var arrowData = {};
  12762. // restore edge targets to defaults
  12763. this.edgeType.fromPoint = this.edgeType.from;
  12764. this.edgeType.toPoint = this.edgeType.to;
  12765. // from and to arrows give a different end point for edges. we set them here
  12766. if (values.fromArrow) {
  12767. arrowData.from = this.edgeType.getArrowData(ctx, 'from', viaNode, this.selected, this.hover, values);
  12768. if (values.arrowStrikethrough === false) this.edgeType.fromPoint = arrowData.from.core;
  12769. }
  12770. if (values.toArrow) {
  12771. arrowData.to = this.edgeType.getArrowData(ctx, 'to', viaNode, this.selected, this.hover, values);
  12772. if (values.arrowStrikethrough === false) this.edgeType.toPoint = arrowData.to.core;
  12773. }
  12774. // the middle arrow depends on the line, which can depend on the to and from arrows so we do this one lastly.
  12775. if (values.middleArrow) {
  12776. arrowData.middle = this.edgeType.getArrowData(ctx, 'middle', viaNode, this.selected, this.hover, values);
  12777. }
  12778. // draw everything
  12779. this.edgeType.drawLine(ctx, values, this.selected, this.hover, viaNode);
  12780. this.drawArrows(ctx, arrowData, values);
  12781. this.drawLabel(ctx, viaNode);
  12782. }
  12783. /**
  12784. *
  12785. * @param {CanvasRenderingContext2D} ctx
  12786. * @param {Object} arrowData
  12787. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  12788. */
  12789. }, {
  12790. key: 'drawArrows',
  12791. value: function drawArrows(ctx, arrowData, values) {
  12792. if (values.fromArrow) {
  12793. this.edgeType.drawArrowHead(ctx, values, this.selected, this.hover, arrowData.from);
  12794. }
  12795. if (values.middleArrow) {
  12796. this.edgeType.drawArrowHead(ctx, values, this.selected, this.hover, arrowData.middle);
  12797. }
  12798. if (values.toArrow) {
  12799. this.edgeType.drawArrowHead(ctx, values, this.selected, this.hover, arrowData.to);
  12800. }
  12801. }
  12802. /**
  12803. *
  12804. * @param {CanvasRenderingContext2D} ctx
  12805. * @param {Node} viaNode
  12806. */
  12807. }, {
  12808. key: 'drawLabel',
  12809. value: function drawLabel(ctx, viaNode) {
  12810. if (this.options.label !== undefined) {
  12811. // set style
  12812. var node1 = this.from;
  12813. var node2 = this.to;
  12814. if (this.labelModule.differentState(this.selected, this.hover)) {
  12815. this.labelModule.getTextSize(ctx, this.selected, this.hover);
  12816. }
  12817. if (node1.id != node2.id) {
  12818. this.labelModule.pointToSelf = false;
  12819. var point = this.edgeType.getPoint(0.5, viaNode);
  12820. ctx.save();
  12821. var rotationPoint = this._getRotation(ctx);
  12822. if (rotationPoint.angle != 0) {
  12823. ctx.translate(rotationPoint.x, rotationPoint.y);
  12824. ctx.rotate(rotationPoint.angle);
  12825. }
  12826. // draw the label
  12827. this.labelModule.draw(ctx, point.x, point.y, this.selected, this.hover);
  12828. /*
  12829. // Useful debug code: draw a border around the label
  12830. // This should **not** be enabled in production!
  12831. var size = this.labelModule.getSize();; // ;; intentional so lint catches it
  12832. ctx.strokeStyle = "#ff0000";
  12833. ctx.strokeRect(size.left, size.top, size.width, size.height);
  12834. // End debug code
  12835. */
  12836. ctx.restore();
  12837. } else {
  12838. // Ignore the orientations.
  12839. this.labelModule.pointToSelf = true;
  12840. var x, y;
  12841. var radius = this.options.selfReferenceSize;
  12842. if (node1.shape.width > node1.shape.height) {
  12843. x = node1.x + node1.shape.width * 0.5;
  12844. y = node1.y - radius;
  12845. } else {
  12846. x = node1.x + radius;
  12847. y = node1.y - node1.shape.height * 0.5;
  12848. }
  12849. point = this._pointOnCircle(x, y, radius, 0.125);
  12850. this.labelModule.draw(ctx, point.x, point.y, this.selected, this.hover);
  12851. }
  12852. }
  12853. }
  12854. /**
  12855. * Determine all visual elements of this edge instance, in which the given
  12856. * point falls within the bounding shape.
  12857. *
  12858. * @param {point} point
  12859. * @returns {Array.<edgeClickItem|edgeLabelClickItem>} list with the items which are on the point
  12860. */
  12861. }, {
  12862. key: 'getItemsOnPoint',
  12863. value: function getItemsOnPoint(point) {
  12864. var ret = [];
  12865. if (this.labelModule.visible()) {
  12866. var rotationPoint = this._getRotation();
  12867. if (ComponentUtil.pointInRect(this.labelModule.getSize(), point, rotationPoint)) {
  12868. ret.push({ edgeId: this.id, labelId: 0 });
  12869. }
  12870. }
  12871. var obj = {
  12872. left: point.x,
  12873. top: point.y
  12874. };
  12875. if (this.isOverlappingWith(obj)) {
  12876. ret.push({ edgeId: this.id });
  12877. }
  12878. return ret;
  12879. }
  12880. /**
  12881. * Check if this object is overlapping with the provided object
  12882. * @param {Object} obj an object with parameters left, top
  12883. * @return {boolean} True if location is located on the edge
  12884. */
  12885. }, {
  12886. key: 'isOverlappingWith',
  12887. value: function isOverlappingWith(obj) {
  12888. if (this.connected) {
  12889. var distMax = 10;
  12890. var xFrom = this.from.x;
  12891. var yFrom = this.from.y;
  12892. var xTo = this.to.x;
  12893. var yTo = this.to.y;
  12894. var xObj = obj.left;
  12895. var yObj = obj.top;
  12896. var dist = this.edgeType.getDistanceToEdge(xFrom, yFrom, xTo, yTo, xObj, yObj);
  12897. return dist < distMax;
  12898. } else {
  12899. return false;
  12900. }
  12901. }
  12902. /**
  12903. * Determine the rotation point, if any.
  12904. *
  12905. * @param {CanvasRenderingContext2D} [ctx] if passed, do a recalculation of the label size
  12906. * @returns {rotationPoint} the point to rotate around and the angle in radians to rotate
  12907. * @private
  12908. */
  12909. }, {
  12910. key: '_getRotation',
  12911. value: function _getRotation(ctx) {
  12912. var viaNode = this.edgeType.getViaNode();
  12913. var point = this.edgeType.getPoint(0.5, viaNode);
  12914. if (ctx !== undefined) {
  12915. this.labelModule.calculateLabelSize(ctx, this.selected, this.hover, point.x, point.y);
  12916. }
  12917. var ret = {
  12918. x: point.x,
  12919. y: this.labelModule.size.yLine,
  12920. angle: 0
  12921. };
  12922. if (!this.labelModule.visible()) {
  12923. return ret; // Don't even bother doing the atan2, there's nothing to draw
  12924. }
  12925. if (this.options.font.align === "horizontal") {
  12926. return ret; // No need to calculate angle
  12927. }
  12928. var dy = this.from.y - this.to.y;
  12929. var dx = this.from.x - this.to.x;
  12930. var angle = Math.atan2(dy, dx); // radians
  12931. // rotate so that label is readable
  12932. if (angle < -1 && dx < 0 || angle > 0 && dx < 0) {
  12933. angle += Math.PI;
  12934. }
  12935. ret.angle = angle;
  12936. return ret;
  12937. }
  12938. /**
  12939. * Get a point on a circle
  12940. * @param {number} x
  12941. * @param {number} y
  12942. * @param {number} radius
  12943. * @param {number} percentage Value between 0 (line start) and 1 (line end)
  12944. * @return {Object} point
  12945. * @private
  12946. */
  12947. }, {
  12948. key: '_pointOnCircle',
  12949. value: function _pointOnCircle(x, y, radius, percentage) {
  12950. var angle = percentage * 2 * Math.PI;
  12951. return {
  12952. x: x + radius * Math.cos(angle),
  12953. y: y - radius * Math.sin(angle)
  12954. };
  12955. }
  12956. /**
  12957. * Sets selected state to true
  12958. */
  12959. }, {
  12960. key: 'select',
  12961. value: function select() {
  12962. this.selected = true;
  12963. }
  12964. /**
  12965. * Sets selected state to false
  12966. */
  12967. }, {
  12968. key: 'unselect',
  12969. value: function unselect() {
  12970. this.selected = false;
  12971. }
  12972. /**
  12973. * cleans all required things on delete
  12974. * @returns {*}
  12975. */
  12976. }, {
  12977. key: 'cleanup',
  12978. value: function cleanup() {
  12979. return this.edgeType.cleanup();
  12980. }
  12981. /**
  12982. * Remove edge from the list and perform necessary cleanup.
  12983. */
  12984. }, {
  12985. key: 'remove',
  12986. value: function remove() {
  12987. this.cleanup();
  12988. this.disconnect();
  12989. delete this.body.edges[this.id];
  12990. }
  12991. /**
  12992. * Check if both connecting nodes exist
  12993. * @returns {boolean}
  12994. */
  12995. }, {
  12996. key: 'endPointsValid',
  12997. value: function endPointsValid() {
  12998. return this.body.nodes[this.fromId] !== undefined && this.body.nodes[this.toId] !== undefined;
  12999. }
  13000. }], [{
  13001. key: 'parseOptions',
  13002. value: function parseOptions(parentOptions, newOptions) {
  13003. var allowDeletion = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  13004. var globalOptions = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  13005. var copyFromGlobals = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  13006. var fields = ['arrowStrikethrough', 'id', 'from', 'hidden', 'hoverWidth', 'labelHighlightBold', 'length', 'line', 'opacity', 'physics', 'scaling', 'selectionWidth', 'selfReferenceSize', 'to', 'title', 'value', 'width', 'font', 'chosen', 'widthConstraint'];
  13007. // only deep extend the items in the field array. These do not have shorthand.
  13008. util.selectiveDeepExtend(fields, parentOptions, newOptions, allowDeletion);
  13009. // Only copy label if it's a legal value.
  13010. if (ComponentUtil.isValidLabel(newOptions.label)) {
  13011. parentOptions.label = newOptions.label;
  13012. } else {
  13013. parentOptions.label = undefined;
  13014. }
  13015. util.mergeOptions(parentOptions, newOptions, 'smooth', globalOptions);
  13016. util.mergeOptions(parentOptions, newOptions, 'shadow', globalOptions);
  13017. if (newOptions.dashes !== undefined && newOptions.dashes !== null) {
  13018. parentOptions.dashes = newOptions.dashes;
  13019. } else if (allowDeletion === true && newOptions.dashes === null) {
  13020. parentOptions.dashes = (0, _create2['default'])(globalOptions.dashes); // this sets the pointer of the option back to the global option.
  13021. }
  13022. // set the scaling newOptions
  13023. if (newOptions.scaling !== undefined && newOptions.scaling !== null) {
  13024. if (newOptions.scaling.min !== undefined) {
  13025. parentOptions.scaling.min = newOptions.scaling.min;
  13026. }
  13027. if (newOptions.scaling.max !== undefined) {
  13028. parentOptions.scaling.max = newOptions.scaling.max;
  13029. }
  13030. util.mergeOptions(parentOptions.scaling, newOptions.scaling, 'label', globalOptions.scaling);
  13031. } else if (allowDeletion === true && newOptions.scaling === null) {
  13032. parentOptions.scaling = (0, _create2['default'])(globalOptions.scaling); // this sets the pointer of the option back to the global option.
  13033. }
  13034. // handle multiple input cases for arrows
  13035. if (newOptions.arrows !== undefined && newOptions.arrows !== null) {
  13036. if (typeof newOptions.arrows === 'string') {
  13037. var arrows = newOptions.arrows.toLowerCase();
  13038. parentOptions.arrows.to.enabled = arrows.indexOf("to") != -1;
  13039. parentOptions.arrows.middle.enabled = arrows.indexOf("middle") != -1;
  13040. parentOptions.arrows.from.enabled = arrows.indexOf("from") != -1;
  13041. } else if ((0, _typeof3['default'])(newOptions.arrows) === 'object') {
  13042. util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'to', globalOptions.arrows);
  13043. util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'middle', globalOptions.arrows);
  13044. util.mergeOptions(parentOptions.arrows, newOptions.arrows, 'from', globalOptions.arrows);
  13045. } else {
  13046. throw new Error("The arrow newOptions can only be an object or a string. Refer to the documentation. You used:" + (0, _stringify2['default'])(newOptions.arrows));
  13047. }
  13048. } else if (allowDeletion === true && newOptions.arrows === null) {
  13049. parentOptions.arrows = (0, _create2['default'])(globalOptions.arrows); // this sets the pointer of the option back to the global option.
  13050. }
  13051. // handle multiple input cases for color
  13052. if (newOptions.color !== undefined && newOptions.color !== null) {
  13053. var fromColor = newOptions.color;
  13054. var toColor = parentOptions.color;
  13055. // If passed, fill in values from default options - required in the case of no prototype bridging
  13056. if (copyFromGlobals) {
  13057. util.deepExtend(toColor, globalOptions.color, false, allowDeletion);
  13058. } else {
  13059. // Clear local properties - need to do it like this in order to retain prototype bridges
  13060. for (var i in toColor) {
  13061. if (toColor.hasOwnProperty(i)) {
  13062. delete toColor[i];
  13063. }
  13064. }
  13065. }
  13066. if (util.isString(toColor)) {
  13067. toColor.color = toColor;
  13068. toColor.highlight = toColor;
  13069. toColor.hover = toColor;
  13070. toColor.inherit = false;
  13071. if (fromColor.opacity === undefined) {
  13072. toColor.opacity = 1.0; // set default
  13073. }
  13074. } else {
  13075. var colorsDefined = false;
  13076. if (fromColor.color !== undefined) {
  13077. toColor.color = fromColor.color;colorsDefined = true;
  13078. }
  13079. if (fromColor.highlight !== undefined) {
  13080. toColor.highlight = fromColor.highlight;colorsDefined = true;
  13081. }
  13082. if (fromColor.hover !== undefined) {
  13083. toColor.hover = fromColor.hover;colorsDefined = true;
  13084. }
  13085. if (fromColor.inherit !== undefined) {
  13086. toColor.inherit = fromColor.inherit;
  13087. }
  13088. if (fromColor.opacity !== undefined) {
  13089. toColor.opacity = Math.min(1, Math.max(0, fromColor.opacity));
  13090. }
  13091. if (colorsDefined === true) {
  13092. toColor.inherit = false;
  13093. } else {
  13094. if (toColor.inherit === undefined) {
  13095. toColor.inherit = 'from'; // Set default
  13096. }
  13097. }
  13098. }
  13099. } else if (allowDeletion === true && newOptions.color === null) {
  13100. parentOptions.color = util.bridgeObject(globalOptions.color); // set the object back to the global options
  13101. }
  13102. if (allowDeletion === true && newOptions.font === null) {
  13103. parentOptions.font = util.bridgeObject(globalOptions.font); // set the object back to the global options
  13104. }
  13105. }
  13106. }]);
  13107. return Edge;
  13108. }();
  13109. exports['default'] = Edge;
  13110. /***/ }),
  13111. /* 75 */
  13112. /***/ (function(module, exports, __webpack_require__) {
  13113. "use strict";
  13114. Object.defineProperty(exports, "__esModule", {
  13115. value: true
  13116. });
  13117. var _getPrototypeOf = __webpack_require__(3);
  13118. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  13119. var _classCallCheck2 = __webpack_require__(0);
  13120. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  13121. var _createClass2 = __webpack_require__(1);
  13122. var _createClass3 = _interopRequireDefault(_createClass2);
  13123. var _possibleConstructorReturn2 = __webpack_require__(4);
  13124. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  13125. var _inherits2 = __webpack_require__(5);
  13126. var _inherits3 = _interopRequireDefault(_inherits2);
  13127. var _EdgeBase2 = __webpack_require__(118);
  13128. var _EdgeBase3 = _interopRequireDefault(_EdgeBase2);
  13129. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  13130. /**
  13131. * The Base Class for all Bezier edges. Bezier curves are used to model smooth
  13132. * gradual curves in paths between nodes.
  13133. *
  13134. * @extends EdgeBase
  13135. */
  13136. var BezierEdgeBase = function (_EdgeBase) {
  13137. (0, _inherits3['default'])(BezierEdgeBase, _EdgeBase);
  13138. /**
  13139. * @param {Object} options
  13140. * @param {Object} body
  13141. * @param {Label} labelModule
  13142. */
  13143. function BezierEdgeBase(options, body, labelModule) {
  13144. (0, _classCallCheck3['default'])(this, BezierEdgeBase);
  13145. return (0, _possibleConstructorReturn3['default'])(this, (BezierEdgeBase.__proto__ || (0, _getPrototypeOf2['default'])(BezierEdgeBase)).call(this, options, body, labelModule));
  13146. }
  13147. /**
  13148. * This function uses binary search to look for the point where the bezier curve crosses the border of the node.
  13149. *
  13150. * @param {Node} nearNode
  13151. * @param {CanvasRenderingContext2D} ctx
  13152. * @param {Node} viaNode
  13153. * @returns {*}
  13154. * @private
  13155. */
  13156. (0, _createClass3['default'])(BezierEdgeBase, [{
  13157. key: '_findBorderPositionBezier',
  13158. value: function _findBorderPositionBezier(nearNode, ctx) {
  13159. var viaNode = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this._getViaCoordinates();
  13160. var maxIterations = 10;
  13161. var iteration = 0;
  13162. var low = 0;
  13163. var high = 1;
  13164. var pos, angle, distanceToBorder, distanceToPoint, difference;
  13165. var threshold = 0.2;
  13166. var node = this.to;
  13167. var from = false;
  13168. if (nearNode.id === this.from.id) {
  13169. node = this.from;
  13170. from = true;
  13171. }
  13172. while (low <= high && iteration < maxIterations) {
  13173. var middle = (low + high) * 0.5;
  13174. pos = this.getPoint(middle, viaNode);
  13175. angle = Math.atan2(node.y - pos.y, node.x - pos.x);
  13176. distanceToBorder = node.distanceToBorder(ctx, angle);
  13177. distanceToPoint = Math.sqrt(Math.pow(pos.x - node.x, 2) + Math.pow(pos.y - node.y, 2));
  13178. difference = distanceToBorder - distanceToPoint;
  13179. if (Math.abs(difference) < threshold) {
  13180. break; // found
  13181. } else if (difference < 0) {
  13182. // distance to nodes is larger than distance to border --> t needs to be bigger if we're looking at the to node.
  13183. if (from === false) {
  13184. low = middle;
  13185. } else {
  13186. high = middle;
  13187. }
  13188. } else {
  13189. if (from === false) {
  13190. high = middle;
  13191. } else {
  13192. low = middle;
  13193. }
  13194. }
  13195. iteration++;
  13196. }
  13197. pos.t = middle;
  13198. return pos;
  13199. }
  13200. /**
  13201. * Calculate the distance between a point (x3,y3) and a line segment from
  13202. * (x1,y1) to (x2,y2).
  13203. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  13204. * @param {number} x1 from x
  13205. * @param {number} y1 from y
  13206. * @param {number} x2 to x
  13207. * @param {number} y2 to y
  13208. * @param {number} x3 point to check x
  13209. * @param {number} y3 point to check y
  13210. * @param {Node} via
  13211. * @returns {number}
  13212. * @private
  13213. */
  13214. }, {
  13215. key: '_getDistanceToBezierEdge',
  13216. value: function _getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via) {
  13217. // x3,y3 is the point
  13218. var minDistance = 1e9;
  13219. var distance = void 0;
  13220. var i = void 0,
  13221. t = void 0,
  13222. x = void 0,
  13223. y = void 0;
  13224. var lastX = x1;
  13225. var lastY = y1;
  13226. for (i = 1; i < 10; i++) {
  13227. t = 0.1 * i;
  13228. x = Math.pow(1 - t, 2) * x1 + 2 * t * (1 - t) * via.x + Math.pow(t, 2) * x2;
  13229. y = Math.pow(1 - t, 2) * y1 + 2 * t * (1 - t) * via.y + Math.pow(t, 2) * y2;
  13230. if (i > 0) {
  13231. distance = this._getDistanceToLine(lastX, lastY, x, y, x3, y3);
  13232. minDistance = distance < minDistance ? distance : minDistance;
  13233. }
  13234. lastX = x;
  13235. lastY = y;
  13236. }
  13237. return minDistance;
  13238. }
  13239. /**
  13240. * Draw a bezier curve between two nodes
  13241. *
  13242. * The method accepts zero, one or two control points.
  13243. * Passing zero control points just draws a straight line
  13244. *
  13245. * @param {CanvasRenderingContext2D} ctx
  13246. * @param {Object} values | options for shadow drawing
  13247. * @param {Object|undefined} viaNode1 | first control point for curve drawing
  13248. * @param {Object|undefined} viaNode2 | second control point for curve drawing
  13249. *
  13250. * @protected
  13251. */
  13252. }, {
  13253. key: '_bezierCurve',
  13254. value: function _bezierCurve(ctx, values, viaNode1, viaNode2) {
  13255. var hasNode1 = viaNode1 !== undefined && viaNode1.x !== undefined;
  13256. var hasNode2 = viaNode2 !== undefined && viaNode2.x !== undefined;
  13257. ctx.beginPath();
  13258. ctx.moveTo(this.fromPoint.x, this.fromPoint.y);
  13259. if (hasNode1 && hasNode2) {
  13260. ctx.bezierCurveTo(viaNode1.x, viaNode1.y, viaNode2.x, viaNode2.y, this.toPoint.x, this.toPoint.y);
  13261. } else if (hasNode1) {
  13262. ctx.quadraticCurveTo(viaNode1.x, viaNode1.y, this.toPoint.x, this.toPoint.y);
  13263. } else {
  13264. // fallback to normal straight edge
  13265. ctx.lineTo(this.toPoint.x, this.toPoint.y);
  13266. }
  13267. // draw shadow if enabled
  13268. this.enableShadow(ctx, values);
  13269. ctx.stroke();
  13270. this.disableShadow(ctx, values);
  13271. }
  13272. /**
  13273. *
  13274. * @returns {*|{x, y}|{x: undefined, y: undefined}}
  13275. */
  13276. }, {
  13277. key: 'getViaNode',
  13278. value: function getViaNode() {
  13279. return this._getViaCoordinates();
  13280. }
  13281. }]);
  13282. return BezierEdgeBase;
  13283. }(_EdgeBase3['default']);
  13284. exports['default'] = BezierEdgeBase;
  13285. /***/ }),
  13286. /* 76 */
  13287. /***/ (function(module, exports, __webpack_require__) {
  13288. "use strict";
  13289. Object.defineProperty(exports, "__esModule", {
  13290. value: true
  13291. });
  13292. var _classCallCheck2 = __webpack_require__(0);
  13293. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  13294. var _createClass2 = __webpack_require__(1);
  13295. var _createClass3 = _interopRequireDefault(_createClass2);
  13296. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  13297. var util = __webpack_require__(2);
  13298. /**
  13299. * Utility Class
  13300. */
  13301. var NetworkUtil = function () {
  13302. /**
  13303. * @ignore
  13304. */
  13305. function NetworkUtil() {
  13306. (0, _classCallCheck3["default"])(this, NetworkUtil);
  13307. }
  13308. /**
  13309. * Find the center position of the network considering the bounding boxes
  13310. *
  13311. * @param {Array.<Node>} allNodes
  13312. * @param {Array.<Node>} [specificNodes=[]]
  13313. * @returns {{minX: number, maxX: number, minY: number, maxY: number}}
  13314. * @static
  13315. */
  13316. (0, _createClass3["default"])(NetworkUtil, null, [{
  13317. key: "getRange",
  13318. value: function getRange(allNodes) {
  13319. var specificNodes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  13320. var minY = 1e9,
  13321. maxY = -1e9,
  13322. minX = 1e9,
  13323. maxX = -1e9,
  13324. node;
  13325. if (specificNodes.length > 0) {
  13326. for (var i = 0; i < specificNodes.length; i++) {
  13327. node = allNodes[specificNodes[i]];
  13328. if (minX > node.shape.boundingBox.left) {
  13329. minX = node.shape.boundingBox.left;
  13330. }
  13331. if (maxX < node.shape.boundingBox.right) {
  13332. maxX = node.shape.boundingBox.right;
  13333. }
  13334. if (minY > node.shape.boundingBox.top) {
  13335. minY = node.shape.boundingBox.top;
  13336. } // top is negative, bottom is positive
  13337. if (maxY < node.shape.boundingBox.bottom) {
  13338. maxY = node.shape.boundingBox.bottom;
  13339. } // top is negative, bottom is positive
  13340. }
  13341. }
  13342. if (minX === 1e9 && maxX === -1e9 && minY === 1e9 && maxY === -1e9) {
  13343. minY = 0, maxY = 0, minX = 0, maxX = 0;
  13344. }
  13345. return { minX: minX, maxX: maxX, minY: minY, maxY: maxY };
  13346. }
  13347. /**
  13348. * Find the center position of the network
  13349. *
  13350. * @param {Array.<Node>} allNodes
  13351. * @param {Array.<Node>} [specificNodes=[]]
  13352. * @returns {{minX: number, maxX: number, minY: number, maxY: number}}
  13353. * @static
  13354. */
  13355. }, {
  13356. key: "getRangeCore",
  13357. value: function getRangeCore(allNodes) {
  13358. var specificNodes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  13359. var minY = 1e9,
  13360. maxY = -1e9,
  13361. minX = 1e9,
  13362. maxX = -1e9,
  13363. node;
  13364. if (specificNodes.length > 0) {
  13365. for (var i = 0; i < specificNodes.length; i++) {
  13366. node = allNodes[specificNodes[i]];
  13367. if (minX > node.x) {
  13368. minX = node.x;
  13369. }
  13370. if (maxX < node.x) {
  13371. maxX = node.x;
  13372. }
  13373. if (minY > node.y) {
  13374. minY = node.y;
  13375. } // top is negative, bottom is positive
  13376. if (maxY < node.y) {
  13377. maxY = node.y;
  13378. } // top is negative, bottom is positive
  13379. }
  13380. }
  13381. if (minX === 1e9 && maxX === -1e9 && minY === 1e9 && maxY === -1e9) {
  13382. minY = 0, maxY = 0, minX = 0, maxX = 0;
  13383. }
  13384. return { minX: minX, maxX: maxX, minY: minY, maxY: maxY };
  13385. }
  13386. /**
  13387. * @param {object} range = {minX: minX, maxX: maxX, minY: minY, maxY: maxY};
  13388. * @returns {{x: number, y: number}}
  13389. * @static
  13390. */
  13391. }, {
  13392. key: "findCenter",
  13393. value: function findCenter(range) {
  13394. return { x: 0.5 * (range.maxX + range.minX),
  13395. y: 0.5 * (range.maxY + range.minY) };
  13396. }
  13397. /**
  13398. * 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.
  13399. * @param {vis.Item} item
  13400. * @param {'node'|undefined} type
  13401. * @returns {{}}
  13402. * @static
  13403. */
  13404. }, {
  13405. key: "cloneOptions",
  13406. value: function cloneOptions(item, type) {
  13407. var clonedOptions = {};
  13408. if (type === undefined || type === 'node') {
  13409. util.deepExtend(clonedOptions, item.options, true);
  13410. clonedOptions.x = item.x;
  13411. clonedOptions.y = item.y;
  13412. clonedOptions.amountOfConnections = item.edges.length;
  13413. } else {
  13414. util.deepExtend(clonedOptions, item.options, true);
  13415. }
  13416. return clonedOptions;
  13417. }
  13418. }]);
  13419. return NetworkUtil;
  13420. }();
  13421. exports["default"] = NetworkUtil;
  13422. /***/ }),
  13423. /* 77 */
  13424. /***/ (function(module, exports, __webpack_require__) {
  13425. module.exports = { "default": __webpack_require__(124), __esModule: true };
  13426. /***/ }),
  13427. /* 78 */
  13428. /***/ (function(module, exports, __webpack_require__) {
  13429. // fallback for non-array-like ES3 and non-enumerable old V8 strings
  13430. var cof = __webpack_require__(50);
  13431. // eslint-disable-next-line no-prototype-builtins
  13432. module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) {
  13433. return cof(it) == 'String' ? it.split('') : Object(it);
  13434. };
  13435. /***/ }),
  13436. /* 79 */
  13437. /***/ (function(module, exports, __webpack_require__) {
  13438. "use strict";
  13439. var LIBRARY = __webpack_require__(52);
  13440. var $export = __webpack_require__(17);
  13441. var redefine = __webpack_require__(83);
  13442. var hide = __webpack_require__(26);
  13443. var has = __webpack_require__(22);
  13444. var Iterators = __webpack_require__(31);
  13445. var $iterCreate = __webpack_require__(129);
  13446. var setToStringTag = __webpack_require__(59);
  13447. var getPrototypeOf = __webpack_require__(85);
  13448. var ITERATOR = __webpack_require__(13)('iterator');
  13449. var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
  13450. var FF_ITERATOR = '@@iterator';
  13451. var KEYS = 'keys';
  13452. var VALUES = 'values';
  13453. var returnThis = function () { return this; };
  13454. module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
  13455. $iterCreate(Constructor, NAME, next);
  13456. var getMethod = function (kind) {
  13457. if (!BUGGY && kind in proto) return proto[kind];
  13458. switch (kind) {
  13459. case KEYS: return function keys() { return new Constructor(this, kind); };
  13460. case VALUES: return function values() { return new Constructor(this, kind); };
  13461. } return function entries() { return new Constructor(this, kind); };
  13462. };
  13463. var TAG = NAME + ' Iterator';
  13464. var DEF_VALUES = DEFAULT == VALUES;
  13465. var VALUES_BUG = false;
  13466. var proto = Base.prototype;
  13467. var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT];
  13468. var $default = $native || getMethod(DEFAULT);
  13469. var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined;
  13470. var $anyNative = NAME == 'Array' ? proto.entries || $native : $native;
  13471. var methods, key, IteratorPrototype;
  13472. // Fix native
  13473. if ($anyNative) {
  13474. IteratorPrototype = getPrototypeOf($anyNative.call(new Base()));
  13475. if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) {
  13476. // Set @@toStringTag to native iterators
  13477. setToStringTag(IteratorPrototype, TAG, true);
  13478. // fix for some old engines
  13479. if (!LIBRARY && !has(IteratorPrototype, ITERATOR)) hide(IteratorPrototype, ITERATOR, returnThis);
  13480. }
  13481. }
  13482. // fix Array#{values, @@iterator}.name in V8 / FF
  13483. if (DEF_VALUES && $native && $native.name !== VALUES) {
  13484. VALUES_BUG = true;
  13485. $default = function values() { return $native.call(this); };
  13486. }
  13487. // Define iterator
  13488. if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) {
  13489. hide(proto, ITERATOR, $default);
  13490. }
  13491. // Plug for library
  13492. Iterators[NAME] = $default;
  13493. Iterators[TAG] = returnThis;
  13494. if (DEFAULT) {
  13495. methods = {
  13496. values: DEF_VALUES ? $default : getMethod(VALUES),
  13497. keys: IS_SET ? $default : getMethod(KEYS),
  13498. entries: $entries
  13499. };
  13500. if (FORCED) for (key in methods) {
  13501. if (!(key in proto)) redefine(proto, key, methods[key]);
  13502. } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
  13503. }
  13504. return methods;
  13505. };
  13506. /***/ }),
  13507. /* 80 */
  13508. /***/ (function(module, exports, __webpack_require__) {
  13509. // optional / simple context binding
  13510. var aFunction = __webpack_require__(128);
  13511. module.exports = function (fn, that, length) {
  13512. aFunction(fn);
  13513. if (that === undefined) return fn;
  13514. switch (length) {
  13515. case 1: return function (a) {
  13516. return fn.call(that, a);
  13517. };
  13518. case 2: return function (a, b) {
  13519. return fn.call(that, a, b);
  13520. };
  13521. case 3: return function (a, b, c) {
  13522. return fn.call(that, a, b, c);
  13523. };
  13524. }
  13525. return function (/* ...args */) {
  13526. return fn.apply(that, arguments);
  13527. };
  13528. };
  13529. /***/ }),
  13530. /* 81 */
  13531. /***/ (function(module, exports, __webpack_require__) {
  13532. module.exports = !__webpack_require__(21) && !__webpack_require__(28)(function () {
  13533. return Object.defineProperty(__webpack_require__(82)('div'), 'a', { get: function () { return 7; } }).a != 7;
  13534. });
  13535. /***/ }),
  13536. /* 82 */
  13537. /***/ (function(module, exports, __webpack_require__) {
  13538. var isObject = __webpack_require__(32);
  13539. var document = __webpack_require__(18).document;
  13540. // typeof document.createElement is 'object' in old IE
  13541. var is = isObject(document) && isObject(document.createElement);
  13542. module.exports = function (it) {
  13543. return is ? document.createElement(it) : {};
  13544. };
  13545. /***/ }),
  13546. /* 83 */
  13547. /***/ (function(module, exports, __webpack_require__) {
  13548. module.exports = __webpack_require__(26);
  13549. /***/ }),
  13550. /* 84 */
  13551. /***/ (function(module, exports, __webpack_require__) {
  13552. var has = __webpack_require__(22);
  13553. var toIObject = __webpack_require__(25);
  13554. var arrayIndexOf = __webpack_require__(131)(false);
  13555. var IE_PROTO = __webpack_require__(56)('IE_PROTO');
  13556. module.exports = function (object, names) {
  13557. var O = toIObject(object);
  13558. var i = 0;
  13559. var result = [];
  13560. var key;
  13561. for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key);
  13562. // Don't enum bug & hidden keys
  13563. while (names.length > i) if (has(O, key = names[i++])) {
  13564. ~arrayIndexOf(result, key) || result.push(key);
  13565. }
  13566. return result;
  13567. };
  13568. /***/ }),
  13569. /* 85 */
  13570. /***/ (function(module, exports, __webpack_require__) {
  13571. // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
  13572. var has = __webpack_require__(22);
  13573. var toObject = __webpack_require__(41);
  13574. var IE_PROTO = __webpack_require__(56)('IE_PROTO');
  13575. var ObjectProto = Object.prototype;
  13576. module.exports = Object.getPrototypeOf || function (O) {
  13577. O = toObject(O);
  13578. if (has(O, IE_PROTO)) return O[IE_PROTO];
  13579. if (typeof O.constructor == 'function' && O instanceof O.constructor) {
  13580. return O.constructor.prototype;
  13581. } return O instanceof Object ? ObjectProto : null;
  13582. };
  13583. /***/ }),
  13584. /* 86 */
  13585. /***/ (function(module, exports, __webpack_require__) {
  13586. // getting tag from 19.1.3.6 Object.prototype.toString()
  13587. var cof = __webpack_require__(50);
  13588. var TAG = __webpack_require__(13)('toStringTag');
  13589. // ES3 wrong here
  13590. var ARG = cof(function () { return arguments; }()) == 'Arguments';
  13591. // fallback for IE11 Script Access Denied error
  13592. var tryGet = function (it, key) {
  13593. try {
  13594. return it[key];
  13595. } catch (e) { /* empty */ }
  13596. };
  13597. module.exports = function (it) {
  13598. var O, T, B;
  13599. return it === undefined ? 'Undefined' : it === null ? 'Null'
  13600. // @@toStringTag case
  13601. : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
  13602. // builtinTag case
  13603. : ARG ? cof(O)
  13604. // ES3 arguments fallback
  13605. : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
  13606. };
  13607. /***/ }),
  13608. /* 87 */
  13609. /***/ (function(module, exports, __webpack_require__) {
  13610. // most Object methods by ES6 should accept primitives
  13611. var $export = __webpack_require__(17);
  13612. var core = __webpack_require__(7);
  13613. var fails = __webpack_require__(28);
  13614. module.exports = function (KEY, exec) {
  13615. var fn = (core.Object || {})[KEY] || Object[KEY];
  13616. var exp = {};
  13617. exp[KEY] = exec(fn);
  13618. $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp);
  13619. };
  13620. /***/ }),
  13621. /* 88 */
  13622. /***/ (function(module, exports, __webpack_require__) {
  13623. // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
  13624. var $keys = __webpack_require__(84);
  13625. var hiddenKeys = __webpack_require__(58).concat('length', 'prototype');
  13626. exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
  13627. return $keys(O, hiddenKeys);
  13628. };
  13629. /***/ }),
  13630. /* 89 */
  13631. /***/ (function(module, exports, __webpack_require__) {
  13632. var pIE = __webpack_require__(42);
  13633. var createDesc = __webpack_require__(39);
  13634. var toIObject = __webpack_require__(25);
  13635. var toPrimitive = __webpack_require__(53);
  13636. var has = __webpack_require__(22);
  13637. var IE8_DOM_DEFINE = __webpack_require__(81);
  13638. var gOPD = Object.getOwnPropertyDescriptor;
  13639. exports.f = __webpack_require__(21) ? gOPD : function getOwnPropertyDescriptor(O, P) {
  13640. O = toIObject(O);
  13641. P = toPrimitive(P, true);
  13642. if (IE8_DOM_DEFINE) try {
  13643. return gOPD(O, P);
  13644. } catch (e) { /* empty */ }
  13645. if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]);
  13646. };
  13647. /***/ }),
  13648. /* 90 */
  13649. /***/ (function(module, exports, __webpack_require__) {
  13650. module.exports = { "default": __webpack_require__(162), __esModule: true };
  13651. /***/ }),
  13652. /* 91 */
  13653. /***/ (function(module, exports, __webpack_require__) {
  13654. "use strict";
  13655. /**
  13656. * @prototype Point2d
  13657. * @param {number} [x]
  13658. * @param {number} [y]
  13659. */
  13660. function Point2d(x, y) {
  13661. this.x = x !== undefined ? x : 0;
  13662. this.y = y !== undefined ? y : 0;
  13663. }
  13664. module.exports = Point2d;
  13665. /***/ }),
  13666. /* 92 */
  13667. /***/ (function(module, exports, __webpack_require__) {
  13668. "use strict";
  13669. var util = __webpack_require__(2);
  13670. /**
  13671. * An html slider control with start/stop/prev/next buttons
  13672. *
  13673. * @constructor Slider
  13674. * @param {Element} container The element where the slider will be created
  13675. * @param {Object} options Available options:
  13676. * {boolean} visible If true (default) the
  13677. * slider is visible.
  13678. */
  13679. function Slider(container, options) {
  13680. if (container === undefined) {
  13681. throw new Error('No container element defined');
  13682. }
  13683. this.container = container;
  13684. this.visible = options && options.visible != undefined ? options.visible : true;
  13685. if (this.visible) {
  13686. this.frame = document.createElement('DIV');
  13687. //this.frame.style.backgroundColor = '#E5E5E5';
  13688. this.frame.style.width = '100%';
  13689. this.frame.style.position = 'relative';
  13690. this.container.appendChild(this.frame);
  13691. this.frame.prev = document.createElement('INPUT');
  13692. this.frame.prev.type = 'BUTTON';
  13693. this.frame.prev.value = 'Prev';
  13694. this.frame.appendChild(this.frame.prev);
  13695. this.frame.play = document.createElement('INPUT');
  13696. this.frame.play.type = 'BUTTON';
  13697. this.frame.play.value = 'Play';
  13698. this.frame.appendChild(this.frame.play);
  13699. this.frame.next = document.createElement('INPUT');
  13700. this.frame.next.type = 'BUTTON';
  13701. this.frame.next.value = 'Next';
  13702. this.frame.appendChild(this.frame.next);
  13703. this.frame.bar = document.createElement('INPUT');
  13704. this.frame.bar.type = 'BUTTON';
  13705. this.frame.bar.style.position = 'absolute';
  13706. this.frame.bar.style.border = '1px solid red';
  13707. this.frame.bar.style.width = '100px';
  13708. this.frame.bar.style.height = '6px';
  13709. this.frame.bar.style.borderRadius = '2px';
  13710. this.frame.bar.style.MozBorderRadius = '2px';
  13711. this.frame.bar.style.border = '1px solid #7F7F7F';
  13712. this.frame.bar.style.backgroundColor = '#E5E5E5';
  13713. this.frame.appendChild(this.frame.bar);
  13714. this.frame.slide = document.createElement('INPUT');
  13715. this.frame.slide.type = 'BUTTON';
  13716. this.frame.slide.style.margin = '0px';
  13717. this.frame.slide.value = ' ';
  13718. this.frame.slide.style.position = 'relative';
  13719. this.frame.slide.style.left = '-100px';
  13720. this.frame.appendChild(this.frame.slide);
  13721. // create events
  13722. var me = this;
  13723. this.frame.slide.onmousedown = function (event) {
  13724. me._onMouseDown(event);
  13725. };
  13726. this.frame.prev.onclick = function (event) {
  13727. me.prev(event);
  13728. };
  13729. this.frame.play.onclick = function (event) {
  13730. me.togglePlay(event);
  13731. };
  13732. this.frame.next.onclick = function (event) {
  13733. me.next(event);
  13734. };
  13735. }
  13736. this.onChangeCallback = undefined;
  13737. this.values = [];
  13738. this.index = undefined;
  13739. this.playTimeout = undefined;
  13740. this.playInterval = 1000; // milliseconds
  13741. this.playLoop = true;
  13742. }
  13743. /**
  13744. * Select the previous index
  13745. */
  13746. Slider.prototype.prev = function () {
  13747. var index = this.getIndex();
  13748. if (index > 0) {
  13749. index--;
  13750. this.setIndex(index);
  13751. }
  13752. };
  13753. /**
  13754. * Select the next index
  13755. */
  13756. Slider.prototype.next = function () {
  13757. var index = this.getIndex();
  13758. if (index < this.values.length - 1) {
  13759. index++;
  13760. this.setIndex(index);
  13761. }
  13762. };
  13763. /**
  13764. * Select the next index
  13765. */
  13766. Slider.prototype.playNext = function () {
  13767. var start = new Date();
  13768. var index = this.getIndex();
  13769. if (index < this.values.length - 1) {
  13770. index++;
  13771. this.setIndex(index);
  13772. } else if (this.playLoop) {
  13773. // jump to the start
  13774. index = 0;
  13775. this.setIndex(index);
  13776. }
  13777. var end = new Date();
  13778. var diff = end - start;
  13779. // calculate how much time it to to set the index and to execute the callback
  13780. // function.
  13781. var interval = Math.max(this.playInterval - diff, 0);
  13782. // document.title = diff // TODO: cleanup
  13783. var me = this;
  13784. this.playTimeout = setTimeout(function () {
  13785. me.playNext();
  13786. }, interval);
  13787. };
  13788. /**
  13789. * Toggle start or stop playing
  13790. */
  13791. Slider.prototype.togglePlay = function () {
  13792. if (this.playTimeout === undefined) {
  13793. this.play();
  13794. } else {
  13795. this.stop();
  13796. }
  13797. };
  13798. /**
  13799. * Start playing
  13800. */
  13801. Slider.prototype.play = function () {
  13802. // Test whether already playing
  13803. if (this.playTimeout) return;
  13804. this.playNext();
  13805. if (this.frame) {
  13806. this.frame.play.value = 'Stop';
  13807. }
  13808. };
  13809. /**
  13810. * Stop playing
  13811. */
  13812. Slider.prototype.stop = function () {
  13813. clearInterval(this.playTimeout);
  13814. this.playTimeout = undefined;
  13815. if (this.frame) {
  13816. this.frame.play.value = 'Play';
  13817. }
  13818. };
  13819. /**
  13820. * Set a callback function which will be triggered when the value of the
  13821. * slider bar has changed.
  13822. *
  13823. * @param {function} callback
  13824. */
  13825. Slider.prototype.setOnChangeCallback = function (callback) {
  13826. this.onChangeCallback = callback;
  13827. };
  13828. /**
  13829. * Set the interval for playing the list
  13830. * @param {number} interval The interval in milliseconds
  13831. */
  13832. Slider.prototype.setPlayInterval = function (interval) {
  13833. this.playInterval = interval;
  13834. };
  13835. /**
  13836. * Retrieve the current play interval
  13837. * @return {number} interval The interval in milliseconds
  13838. */
  13839. Slider.prototype.getPlayInterval = function () {
  13840. return this.playInterval;
  13841. };
  13842. /**
  13843. * Set looping on or off
  13844. * @param {boolean} doLoop If true, the slider will jump to the start when
  13845. * the end is passed, and will jump to the end
  13846. * when the start is passed.
  13847. *
  13848. */
  13849. Slider.prototype.setPlayLoop = function (doLoop) {
  13850. this.playLoop = doLoop;
  13851. };
  13852. /**
  13853. * Execute the onchange callback function
  13854. */
  13855. Slider.prototype.onChange = function () {
  13856. if (this.onChangeCallback !== undefined) {
  13857. this.onChangeCallback();
  13858. }
  13859. };
  13860. /**
  13861. * redraw the slider on the correct place
  13862. */
  13863. Slider.prototype.redraw = function () {
  13864. if (this.frame) {
  13865. // resize the bar
  13866. this.frame.bar.style.top = this.frame.clientHeight / 2 - this.frame.bar.offsetHeight / 2 + 'px';
  13867. this.frame.bar.style.width = this.frame.clientWidth - this.frame.prev.clientWidth - this.frame.play.clientWidth - this.frame.next.clientWidth - 30 + 'px';
  13868. // position the slider button
  13869. var left = this.indexToLeft(this.index);
  13870. this.frame.slide.style.left = left + 'px';
  13871. }
  13872. };
  13873. /**
  13874. * Set the list with values for the slider
  13875. * @param {Array} values A javascript array with values (any type)
  13876. */
  13877. Slider.prototype.setValues = function (values) {
  13878. this.values = values;
  13879. if (this.values.length > 0) this.setIndex(0);else this.index = undefined;
  13880. };
  13881. /**
  13882. * Select a value by its index
  13883. * @param {number} index
  13884. */
  13885. Slider.prototype.setIndex = function (index) {
  13886. if (index < this.values.length) {
  13887. this.index = index;
  13888. this.redraw();
  13889. this.onChange();
  13890. } else {
  13891. throw new Error('Index out of range');
  13892. }
  13893. };
  13894. /**
  13895. * retrieve the index of the currently selected vaue
  13896. * @return {number} index
  13897. */
  13898. Slider.prototype.getIndex = function () {
  13899. return this.index;
  13900. };
  13901. /**
  13902. * retrieve the currently selected value
  13903. * @return {*} value
  13904. */
  13905. Slider.prototype.get = function () {
  13906. return this.values[this.index];
  13907. };
  13908. Slider.prototype._onMouseDown = function (event) {
  13909. // only react on left mouse button down
  13910. var leftButtonDown = event.which ? event.which === 1 : event.button === 1;
  13911. if (!leftButtonDown) return;
  13912. this.startClientX = event.clientX;
  13913. this.startSlideX = parseFloat(this.frame.slide.style.left);
  13914. this.frame.style.cursor = 'move';
  13915. // add event listeners to handle moving the contents
  13916. // we store the function onmousemove and onmouseup in the graph, so we can
  13917. // remove the eventlisteners lateron in the function mouseUp()
  13918. var me = this;
  13919. this.onmousemove = function (event) {
  13920. me._onMouseMove(event);
  13921. };
  13922. this.onmouseup = function (event) {
  13923. me._onMouseUp(event);
  13924. };
  13925. util.addEventListener(document, 'mousemove', this.onmousemove);
  13926. util.addEventListener(document, 'mouseup', this.onmouseup);
  13927. util.preventDefault(event);
  13928. };
  13929. Slider.prototype.leftToIndex = function (left) {
  13930. var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10;
  13931. var x = left - 3;
  13932. var index = Math.round(x / width * (this.values.length - 1));
  13933. if (index < 0) index = 0;
  13934. if (index > this.values.length - 1) index = this.values.length - 1;
  13935. return index;
  13936. };
  13937. Slider.prototype.indexToLeft = function (index) {
  13938. var width = parseFloat(this.frame.bar.style.width) - this.frame.slide.clientWidth - 10;
  13939. var x = index / (this.values.length - 1) * width;
  13940. var left = x + 3;
  13941. return left;
  13942. };
  13943. Slider.prototype._onMouseMove = function (event) {
  13944. var diff = event.clientX - this.startClientX;
  13945. var x = this.startSlideX + diff;
  13946. var index = this.leftToIndex(x);
  13947. this.setIndex(index);
  13948. util.preventDefault();
  13949. };
  13950. Slider.prototype._onMouseUp = function (event) {
  13951. // eslint-disable-line no-unused-vars
  13952. this.frame.style.cursor = 'auto';
  13953. // remove event listeners
  13954. util.removeEventListener(document, 'mousemove', this.onmousemove);
  13955. util.removeEventListener(document, 'mouseup', this.onmouseup);
  13956. util.preventDefault();
  13957. };
  13958. module.exports = Slider;
  13959. /***/ }),
  13960. /* 93 */
  13961. /***/ (function(module, exports, __webpack_require__) {
  13962. "use strict";
  13963. /**
  13964. * @prototype StepNumber
  13965. * The class StepNumber is an iterator for Numbers. You provide a start and end
  13966. * value, and a best step size. StepNumber itself rounds to fixed values and
  13967. * a finds the step that best fits the provided step.
  13968. *
  13969. * If prettyStep is true, the step size is chosen as close as possible to the
  13970. * provided step, but being a round value like 1, 2, 5, 10, 20, 50, ....
  13971. *
  13972. * Example usage:
  13973. * var step = new StepNumber(0, 10, 2.5, true);
  13974. * step.start();
  13975. * while (!step.end()) {
  13976. * alert(step.getCurrent());
  13977. * step.next();
  13978. * }
  13979. *
  13980. * Version: 1.0
  13981. *
  13982. * @param {number} start The start value
  13983. * @param {number} end The end value
  13984. * @param {number} step Optional. Step size. Must be a positive value.
  13985. * @param {boolean} prettyStep Optional. If true, the step size is rounded
  13986. * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  13987. */
  13988. function StepNumber(start, end, step, prettyStep) {
  13989. // set default values
  13990. this._start = 0;
  13991. this._end = 0;
  13992. this._step = 1;
  13993. this.prettyStep = true;
  13994. this.precision = 5;
  13995. this._current = 0;
  13996. this.setRange(start, end, step, prettyStep);
  13997. }
  13998. /**
  13999. * Check for input values, to prevent disasters from happening
  14000. *
  14001. * Source: http://stackoverflow.com/a/1830844
  14002. *
  14003. * @param {string} n
  14004. * @returns {boolean}
  14005. */
  14006. StepNumber.prototype.isNumeric = function (n) {
  14007. return !isNaN(parseFloat(n)) && isFinite(n);
  14008. };
  14009. /**
  14010. * Set a new range: start, end and step.
  14011. *
  14012. * @param {number} start The start value
  14013. * @param {number} end The end value
  14014. * @param {number} step Optional. Step size. Must be a positive value.
  14015. * @param {boolean} prettyStep Optional. If true, the step size is rounded
  14016. * To a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  14017. */
  14018. StepNumber.prototype.setRange = function (start, end, step, prettyStep) {
  14019. if (!this.isNumeric(start)) {
  14020. throw new Error('Parameter \'start\' is not numeric; value: ' + start);
  14021. }
  14022. if (!this.isNumeric(end)) {
  14023. throw new Error('Parameter \'end\' is not numeric; value: ' + start);
  14024. }
  14025. if (!this.isNumeric(step)) {
  14026. throw new Error('Parameter \'step\' is not numeric; value: ' + start);
  14027. }
  14028. this._start = start ? start : 0;
  14029. this._end = end ? end : 0;
  14030. this.setStep(step, prettyStep);
  14031. };
  14032. /**
  14033. * Set a new step size
  14034. * @param {number} step New step size. Must be a positive value
  14035. * @param {boolean} prettyStep Optional. If true, the provided step is rounded
  14036. * to a pretty step size (like 1, 2, 5, 10, 20, 50, ...)
  14037. */
  14038. StepNumber.prototype.setStep = function (step, prettyStep) {
  14039. if (step === undefined || step <= 0) return;
  14040. if (prettyStep !== undefined) this.prettyStep = prettyStep;
  14041. if (this.prettyStep === true) this._step = StepNumber.calculatePrettyStep(step);else this._step = step;
  14042. };
  14043. /**
  14044. * Calculate a nice step size, closest to the desired step size.
  14045. * Returns a value in one of the ranges 1*10^n, 2*10^n, or 5*10^n, where n is an
  14046. * integer Number. For example 1, 2, 5, 10, 20, 50, etc...
  14047. * @param {number} step Desired step size
  14048. * @return {number} Nice step size
  14049. */
  14050. StepNumber.calculatePrettyStep = function (step) {
  14051. var log10 = function log10(x) {
  14052. return Math.log(x) / Math.LN10;
  14053. };
  14054. // try three steps (multiple of 1, 2, or 5
  14055. var step1 = Math.pow(10, Math.round(log10(step))),
  14056. step2 = 2 * Math.pow(10, Math.round(log10(step / 2))),
  14057. step5 = 5 * Math.pow(10, Math.round(log10(step / 5)));
  14058. // choose the best step (closest to minimum step)
  14059. var prettyStep = step1;
  14060. if (Math.abs(step2 - step) <= Math.abs(prettyStep - step)) prettyStep = step2;
  14061. if (Math.abs(step5 - step) <= Math.abs(prettyStep - step)) prettyStep = step5;
  14062. // for safety
  14063. if (prettyStep <= 0) {
  14064. prettyStep = 1;
  14065. }
  14066. return prettyStep;
  14067. };
  14068. /**
  14069. * returns the current value of the step
  14070. * @return {number} current value
  14071. */
  14072. StepNumber.prototype.getCurrent = function () {
  14073. return parseFloat(this._current.toPrecision(this.precision));
  14074. };
  14075. /**
  14076. * returns the current step size
  14077. * @return {number} current step size
  14078. */
  14079. StepNumber.prototype.getStep = function () {
  14080. return this._step;
  14081. };
  14082. /**
  14083. * Set the current to its starting value.
  14084. *
  14085. * By default, this will be the largest value smaller than start, which
  14086. * is a multiple of the step size.
  14087. *
  14088. * Parameters checkFirst is optional, default false.
  14089. * If set to true, move the current value one step if smaller than start.
  14090. *
  14091. * @param {boolean} [checkFirst=false]
  14092. */
  14093. StepNumber.prototype.start = function (checkFirst) {
  14094. if (checkFirst === undefined) {
  14095. checkFirst = false;
  14096. }
  14097. this._current = this._start - this._start % this._step;
  14098. if (checkFirst) {
  14099. if (this.getCurrent() < this._start) {
  14100. this.next();
  14101. }
  14102. }
  14103. };
  14104. /**
  14105. * Do a step, add the step size to the current value
  14106. */
  14107. StepNumber.prototype.next = function () {
  14108. this._current += this._step;
  14109. };
  14110. /**
  14111. * Returns true whether the end is reached
  14112. * @return {boolean} True if the current value has passed the end value.
  14113. */
  14114. StepNumber.prototype.end = function () {
  14115. return this._current > this._end;
  14116. };
  14117. module.exports = StepNumber;
  14118. /***/ }),
  14119. /* 94 */
  14120. /***/ (function(module, exports, __webpack_require__) {
  14121. "use strict";
  14122. var _typeof2 = __webpack_require__(6);
  14123. var _typeof3 = _interopRequireDefault(_typeof2);
  14124. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  14125. ////////////////////////////////////////////////////////////////////////////////
  14126. // This modules handles the options for Graph3d.
  14127. //
  14128. ////////////////////////////////////////////////////////////////////////////////
  14129. var util = __webpack_require__(2);
  14130. var Camera = __webpack_require__(95);
  14131. var Point3d = __webpack_require__(34);
  14132. // enumerate the available styles
  14133. var STYLE = {
  14134. BAR: 0,
  14135. BARCOLOR: 1,
  14136. BARSIZE: 2,
  14137. DOT: 3,
  14138. DOTLINE: 4,
  14139. DOTCOLOR: 5,
  14140. DOTSIZE: 6,
  14141. GRID: 7,
  14142. LINE: 8,
  14143. SURFACE: 9
  14144. };
  14145. // The string representations of the styles
  14146. var STYLENAME = {
  14147. 'dot': STYLE.DOT,
  14148. 'dot-line': STYLE.DOTLINE,
  14149. 'dot-color': STYLE.DOTCOLOR,
  14150. 'dot-size': STYLE.DOTSIZE,
  14151. 'line': STYLE.LINE,
  14152. 'grid': STYLE.GRID,
  14153. 'surface': STYLE.SURFACE,
  14154. 'bar': STYLE.BAR,
  14155. 'bar-color': STYLE.BARCOLOR,
  14156. 'bar-size': STYLE.BARSIZE
  14157. };
  14158. /**
  14159. * Field names in the options hash which are of relevance to the user.
  14160. *
  14161. * Specifically, these are the fields which require no special handling,
  14162. * and can be directly copied over.
  14163. */
  14164. var OPTIONKEYS = ['width', 'height', 'filterLabel', 'legendLabel', 'xLabel', 'yLabel', 'zLabel', 'xValueLabel', 'yValueLabel', 'zValueLabel', 'showXAxis', 'showYAxis', 'showZAxis', 'showGrid', 'showPerspective', 'showShadow', 'keepAspectRatio', 'verticalRatio', 'dotSizeRatio', 'dotSizeMinFraction', 'dotSizeMaxFraction', 'showAnimationControls', 'animationInterval', 'animationPreload', 'animationAutoStart', 'axisColor', 'gridColor', 'xCenter', 'yCenter'];
  14165. /**
  14166. * Field names in the options hash which are of relevance to the user.
  14167. *
  14168. * Same as OPTIONKEYS, but internally these fields are stored with
  14169. * prefix 'default' in the name.
  14170. */
  14171. var PREFIXEDOPTIONKEYS = ['xBarWidth', 'yBarWidth', 'valueMin', 'valueMax', 'xMin', 'xMax', 'xStep', 'yMin', 'yMax', 'yStep', 'zMin', 'zMax', 'zStep'];
  14172. // Placeholder for DEFAULTS reference
  14173. var DEFAULTS = undefined;
  14174. /**
  14175. * Check if given hash is empty.
  14176. *
  14177. * Source: http://stackoverflow.com/a/679937
  14178. *
  14179. * @param {object} obj
  14180. * @returns {boolean}
  14181. */
  14182. function isEmpty(obj) {
  14183. for (var prop in obj) {
  14184. if (obj.hasOwnProperty(prop)) return false;
  14185. }
  14186. return true;
  14187. }
  14188. /**
  14189. * Make first letter of parameter upper case.
  14190. *
  14191. * Source: http://stackoverflow.com/a/1026087
  14192. *
  14193. * @param {string} str
  14194. * @returns {string}
  14195. */
  14196. function capitalize(str) {
  14197. if (str === undefined || str === "" || typeof str != "string") {
  14198. return str;
  14199. }
  14200. return str.charAt(0).toUpperCase() + str.slice(1);
  14201. }
  14202. /**
  14203. * Add a prefix to a field name, taking style guide into account
  14204. *
  14205. * @param {string} prefix
  14206. * @param {string} fieldName
  14207. * @returns {string}
  14208. */
  14209. function prefixFieldName(prefix, fieldName) {
  14210. if (prefix === undefined || prefix === "") {
  14211. return fieldName;
  14212. }
  14213. return prefix + capitalize(fieldName);
  14214. }
  14215. /**
  14216. * Forcibly copy fields from src to dst in a controlled manner.
  14217. *
  14218. * A given field in dst will always be overwitten. If this field
  14219. * is undefined or not present in src, the field in dst will
  14220. * be explicitly set to undefined.
  14221. *
  14222. * The intention here is to be able to reset all option fields.
  14223. *
  14224. * Only the fields mentioned in array 'fields' will be handled.
  14225. *
  14226. * @param {object} src
  14227. * @param {object} dst
  14228. * @param {array<string>} fields array with names of fields to copy
  14229. * @param {string} [prefix] prefix to use for the target fields.
  14230. */
  14231. function forceCopy(src, dst, fields, prefix) {
  14232. var srcKey;
  14233. var dstKey;
  14234. for (var i = 0; i < fields.length; ++i) {
  14235. srcKey = fields[i];
  14236. dstKey = prefixFieldName(prefix, srcKey);
  14237. dst[dstKey] = src[srcKey];
  14238. }
  14239. }
  14240. /**
  14241. * Copy fields from src to dst in a safe and controlled manner.
  14242. *
  14243. * Only the fields mentioned in array 'fields' will be copied over,
  14244. * and only if these are actually defined.
  14245. *
  14246. * @param {object} src
  14247. * @param {object} dst
  14248. * @param {array<string>} fields array with names of fields to copy
  14249. * @param {string} [prefix] prefix to use for the target fields.
  14250. */
  14251. function safeCopy(src, dst, fields, prefix) {
  14252. var srcKey;
  14253. var dstKey;
  14254. for (var i = 0; i < fields.length; ++i) {
  14255. srcKey = fields[i];
  14256. if (src[srcKey] === undefined) continue;
  14257. dstKey = prefixFieldName(prefix, srcKey);
  14258. dst[dstKey] = src[srcKey];
  14259. }
  14260. }
  14261. /**
  14262. * Initialize dst with the values in src.
  14263. *
  14264. * src is the hash with the default values.
  14265. * A reference DEFAULTS to this hash is stored locally for
  14266. * further handling.
  14267. *
  14268. * For now, dst is assumed to be a Graph3d instance.
  14269. * @param {object} src
  14270. * @param {object} dst
  14271. */
  14272. function setDefaults(src, dst) {
  14273. if (src === undefined || isEmpty(src)) {
  14274. throw new Error('No DEFAULTS passed');
  14275. }
  14276. if (dst === undefined) {
  14277. throw new Error('No dst passed');
  14278. }
  14279. // Remember defaults for future reference
  14280. DEFAULTS = src;
  14281. // Handle the defaults which can be simply copied over
  14282. forceCopy(src, dst, OPTIONKEYS);
  14283. forceCopy(src, dst, PREFIXEDOPTIONKEYS, 'default');
  14284. // Handle the more complex ('special') fields
  14285. setSpecialSettings(src, dst);
  14286. // Following are internal fields, not part of the user settings
  14287. dst.margin = 10; // px
  14288. dst.showGrayBottom = false; // TODO: this does not work correctly
  14289. dst.showTooltip = false;
  14290. dst.onclick_callback = null;
  14291. dst.eye = new Point3d(0, 0, -1); // TODO: set eye.z about 3/4 of the width of the window?
  14292. }
  14293. /**
  14294. *
  14295. * @param {object} options
  14296. * @param {object} dst
  14297. */
  14298. function setOptions(options, dst) {
  14299. if (options === undefined) {
  14300. return;
  14301. }
  14302. if (dst === undefined) {
  14303. throw new Error('No dst passed');
  14304. }
  14305. if (DEFAULTS === undefined || isEmpty(DEFAULTS)) {
  14306. throw new Error('DEFAULTS not set for module Settings');
  14307. }
  14308. // Handle the parameters which can be simply copied over
  14309. safeCopy(options, dst, OPTIONKEYS);
  14310. safeCopy(options, dst, PREFIXEDOPTIONKEYS, 'default');
  14311. // Handle the more complex ('special') fields
  14312. setSpecialSettings(options, dst);
  14313. }
  14314. /**
  14315. * Special handling for certain parameters
  14316. *
  14317. * 'Special' here means: setting requires more than a simple copy
  14318. *
  14319. * @param {object} src
  14320. * @param {object} dst
  14321. */
  14322. function setSpecialSettings(src, dst) {
  14323. if (src.backgroundColor !== undefined) {
  14324. setBackgroundColor(src.backgroundColor, dst);
  14325. }
  14326. setDataColor(src.dataColor, dst);
  14327. setStyle(src.style, dst);
  14328. setShowLegend(src.showLegend, dst);
  14329. setCameraPosition(src.cameraPosition, dst);
  14330. // As special fields go, this is an easy one; just a translation of the name.
  14331. // Can't use this.tooltip directly, because that field exists internally
  14332. if (src.tooltip !== undefined) {
  14333. dst.showTooltip = src.tooltip;
  14334. }
  14335. if (src.onclick != undefined) {
  14336. dst.onclick_callback = src.onclick;
  14337. }
  14338. if (src.tooltipStyle !== undefined) {
  14339. util.selectiveDeepExtend(['tooltipStyle'], dst, src);
  14340. }
  14341. }
  14342. /**
  14343. * Set the value of setting 'showLegend'
  14344. *
  14345. * This depends on the value of the style fields, so it must be called
  14346. * after the style field has been initialized.
  14347. *
  14348. * @param {boolean} showLegend
  14349. * @param {object} dst
  14350. */
  14351. function setShowLegend(showLegend, dst) {
  14352. if (showLegend === undefined) {
  14353. // If the default was auto, make a choice for this field
  14354. var isAutoByDefault = DEFAULTS.showLegend === undefined;
  14355. if (isAutoByDefault) {
  14356. // these styles default to having legends
  14357. var isLegendGraphStyle = dst.style === STYLE.DOTCOLOR || dst.style === STYLE.DOTSIZE;
  14358. dst.showLegend = isLegendGraphStyle;
  14359. } else {
  14360. // Leave current value as is
  14361. }
  14362. } else {
  14363. dst.showLegend = showLegend;
  14364. }
  14365. }
  14366. /**
  14367. * Retrieve the style index from given styleName
  14368. * @param {string} styleName Style name such as 'dot', 'grid', 'dot-line'
  14369. * @return {number} styleNumber Enumeration value representing the style, or -1
  14370. * when not found
  14371. */
  14372. function getStyleNumberByName(styleName) {
  14373. var number = STYLENAME[styleName];
  14374. if (number === undefined) {
  14375. return -1;
  14376. }
  14377. return number;
  14378. }
  14379. /**
  14380. * Check if given number is a valid style number.
  14381. *
  14382. * @param {string | number} style
  14383. * @return {boolean} true if valid, false otherwise
  14384. */
  14385. function checkStyleNumber(style) {
  14386. var valid = false;
  14387. for (var n in STYLE) {
  14388. if (STYLE[n] === style) {
  14389. valid = true;
  14390. break;
  14391. }
  14392. }
  14393. return valid;
  14394. }
  14395. /**
  14396. *
  14397. * @param {string | number} style
  14398. * @param {Object} dst
  14399. */
  14400. function setStyle(style, dst) {
  14401. if (style === undefined) {
  14402. return; // Nothing to do
  14403. }
  14404. var styleNumber;
  14405. if (typeof style === 'string') {
  14406. styleNumber = getStyleNumberByName(style);
  14407. if (styleNumber === -1) {
  14408. throw new Error('Style \'' + style + '\' is invalid');
  14409. }
  14410. } else {
  14411. // Do a pedantic check on style number value
  14412. if (!checkStyleNumber(style)) {
  14413. throw new Error('Style \'' + style + '\' is invalid');
  14414. }
  14415. styleNumber = style;
  14416. }
  14417. dst.style = styleNumber;
  14418. }
  14419. /**
  14420. * Set the background styling for the graph
  14421. * @param {string | {fill: string, stroke: string, strokeWidth: string}} backgroundColor
  14422. * @param {Object} dst
  14423. */
  14424. function setBackgroundColor(backgroundColor, dst) {
  14425. var fill = 'white';
  14426. var stroke = 'gray';
  14427. var strokeWidth = 1;
  14428. if (typeof backgroundColor === 'string') {
  14429. fill = backgroundColor;
  14430. stroke = 'none';
  14431. strokeWidth = 0;
  14432. } else if ((typeof backgroundColor === 'undefined' ? 'undefined' : (0, _typeof3['default'])(backgroundColor)) === 'object') {
  14433. if (backgroundColor.fill !== undefined) fill = backgroundColor.fill;
  14434. if (backgroundColor.stroke !== undefined) stroke = backgroundColor.stroke;
  14435. if (backgroundColor.strokeWidth !== undefined) strokeWidth = backgroundColor.strokeWidth;
  14436. } else {
  14437. throw new Error('Unsupported type of backgroundColor');
  14438. }
  14439. dst.frame.style.backgroundColor = fill;
  14440. dst.frame.style.borderColor = stroke;
  14441. dst.frame.style.borderWidth = strokeWidth + 'px';
  14442. dst.frame.style.borderStyle = 'solid';
  14443. }
  14444. /**
  14445. *
  14446. * @param {string | Object} dataColor
  14447. * @param {Object} dst
  14448. */
  14449. function setDataColor(dataColor, dst) {
  14450. if (dataColor === undefined) {
  14451. return; // Nothing to do
  14452. }
  14453. if (dst.dataColor === undefined) {
  14454. dst.dataColor = {};
  14455. }
  14456. if (typeof dataColor === 'string') {
  14457. dst.dataColor.fill = dataColor;
  14458. dst.dataColor.stroke = dataColor;
  14459. } else {
  14460. if (dataColor.fill) {
  14461. dst.dataColor.fill = dataColor.fill;
  14462. }
  14463. if (dataColor.stroke) {
  14464. dst.dataColor.stroke = dataColor.stroke;
  14465. }
  14466. if (dataColor.strokeWidth !== undefined) {
  14467. dst.dataColor.strokeWidth = dataColor.strokeWidth;
  14468. }
  14469. }
  14470. }
  14471. /**
  14472. *
  14473. * @param {Object} cameraPosition
  14474. * @param {Object} dst
  14475. */
  14476. function setCameraPosition(cameraPosition, dst) {
  14477. var camPos = cameraPosition;
  14478. if (camPos === undefined) {
  14479. return;
  14480. }
  14481. if (dst.camera === undefined) {
  14482. dst.camera = new Camera();
  14483. }
  14484. dst.camera.setArmRotation(camPos.horizontal, camPos.vertical);
  14485. dst.camera.setArmLength(camPos.distance);
  14486. }
  14487. module.exports.STYLE = STYLE;
  14488. module.exports.setDefaults = setDefaults;
  14489. module.exports.setOptions = setOptions;
  14490. module.exports.setCameraPosition = setCameraPosition;
  14491. /***/ }),
  14492. /* 95 */
  14493. /***/ (function(module, exports, __webpack_require__) {
  14494. "use strict";
  14495. var _sign = __webpack_require__(165);
  14496. var _sign2 = _interopRequireDefault(_sign);
  14497. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  14498. var Point3d = __webpack_require__(34);
  14499. /**
  14500. * The camera is mounted on a (virtual) camera arm. The camera arm can rotate
  14501. * The camera is always looking in the direction of the origin of the arm.
  14502. * This way, the camera always rotates around one fixed point, the location
  14503. * of the camera arm.
  14504. *
  14505. * Documentation:
  14506. * http://en.wikipedia.org/wiki/3D_projection
  14507. * @class Camera
  14508. */
  14509. function Camera() {
  14510. this.armLocation = new Point3d();
  14511. this.armRotation = {};
  14512. this.armRotation.horizontal = 0;
  14513. this.armRotation.vertical = 0;
  14514. this.armLength = 1.7;
  14515. this.cameraOffset = new Point3d();
  14516. this.offsetMultiplier = 0.6;
  14517. this.cameraLocation = new Point3d();
  14518. this.cameraRotation = new Point3d(0.5 * Math.PI, 0, 0);
  14519. this.calculateCameraOrientation();
  14520. }
  14521. /**
  14522. * Set offset camera in camera coordinates
  14523. * @param {number} x offset by camera horisontal
  14524. * @param {number} y offset by camera vertical
  14525. */
  14526. Camera.prototype.setOffset = function (x, y) {
  14527. var abs = Math.abs,
  14528. sign = _sign2['default'],
  14529. mul = this.offsetMultiplier,
  14530. border = this.armLength * mul;
  14531. if (abs(x) > border) {
  14532. x = sign(x) * border;
  14533. }
  14534. if (abs(y) > border) {
  14535. y = sign(y) * border;
  14536. }
  14537. this.cameraOffset.x = x;
  14538. this.cameraOffset.y = y;
  14539. this.calculateCameraOrientation();
  14540. };
  14541. /**
  14542. * Get camera offset by horizontal and vertical
  14543. * @returns {number}
  14544. */
  14545. Camera.prototype.getOffset = function () {
  14546. return this.cameraOffset;
  14547. };
  14548. /**
  14549. * Set the location (origin) of the arm
  14550. * @param {number} x Normalized value of x
  14551. * @param {number} y Normalized value of y
  14552. * @param {number} z Normalized value of z
  14553. */
  14554. Camera.prototype.setArmLocation = function (x, y, z) {
  14555. this.armLocation.x = x;
  14556. this.armLocation.y = y;
  14557. this.armLocation.z = z;
  14558. this.calculateCameraOrientation();
  14559. };
  14560. /**
  14561. * Set the rotation of the camera arm
  14562. * @param {number} horizontal The horizontal rotation, between 0 and 2*PI.
  14563. * Optional, can be left undefined.
  14564. * @param {number} vertical The vertical rotation, between 0 and 0.5*PI
  14565. * if vertical=0.5*PI, the graph is shown from the
  14566. * top. Optional, can be left undefined.
  14567. */
  14568. Camera.prototype.setArmRotation = function (horizontal, vertical) {
  14569. if (horizontal !== undefined) {
  14570. this.armRotation.horizontal = horizontal;
  14571. }
  14572. if (vertical !== undefined) {
  14573. this.armRotation.vertical = vertical;
  14574. if (this.armRotation.vertical < 0) this.armRotation.vertical = 0;
  14575. if (this.armRotation.vertical > 0.5 * Math.PI) this.armRotation.vertical = 0.5 * Math.PI;
  14576. }
  14577. if (horizontal !== undefined || vertical !== undefined) {
  14578. this.calculateCameraOrientation();
  14579. }
  14580. };
  14581. /**
  14582. * Retrieve the current arm rotation
  14583. * @return {object} An object with parameters horizontal and vertical
  14584. */
  14585. Camera.prototype.getArmRotation = function () {
  14586. var rot = {};
  14587. rot.horizontal = this.armRotation.horizontal;
  14588. rot.vertical = this.armRotation.vertical;
  14589. return rot;
  14590. };
  14591. /**
  14592. * Set the (normalized) length of the camera arm.
  14593. * @param {number} length A length between 0.71 and 5.0
  14594. */
  14595. Camera.prototype.setArmLength = function (length) {
  14596. if (length === undefined) return;
  14597. this.armLength = length;
  14598. // Radius must be larger than the corner of the graph,
  14599. // which has a distance of sqrt(0.5^2+0.5^2) = 0.71 from the center of the
  14600. // graph
  14601. if (this.armLength < 0.71) this.armLength = 0.71;
  14602. if (this.armLength > 5.0) this.armLength = 5.0;
  14603. this.setOffset(this.cameraOffset.x, this.cameraOffset.y);
  14604. this.calculateCameraOrientation();
  14605. };
  14606. /**
  14607. * Retrieve the arm length
  14608. * @return {number} length
  14609. */
  14610. Camera.prototype.getArmLength = function () {
  14611. return this.armLength;
  14612. };
  14613. /**
  14614. * Retrieve the camera location
  14615. * @return {Point3d} cameraLocation
  14616. */
  14617. Camera.prototype.getCameraLocation = function () {
  14618. return this.cameraLocation;
  14619. };
  14620. /**
  14621. * Retrieve the camera rotation
  14622. * @return {Point3d} cameraRotation
  14623. */
  14624. Camera.prototype.getCameraRotation = function () {
  14625. return this.cameraRotation;
  14626. };
  14627. /**
  14628. * Calculate the location and rotation of the camera based on the
  14629. * position and orientation of the camera arm
  14630. */
  14631. Camera.prototype.calculateCameraOrientation = function () {
  14632. // calculate location of the camera
  14633. this.cameraLocation.x = this.armLocation.x - this.armLength * Math.sin(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
  14634. this.cameraLocation.y = this.armLocation.y - this.armLength * Math.cos(this.armRotation.horizontal) * Math.cos(this.armRotation.vertical);
  14635. this.cameraLocation.z = this.armLocation.z + this.armLength * Math.sin(this.armRotation.vertical);
  14636. // calculate rotation of the camera
  14637. this.cameraRotation.x = Math.PI / 2 - this.armRotation.vertical;
  14638. this.cameraRotation.y = 0;
  14639. this.cameraRotation.z = -this.armRotation.horizontal;
  14640. var xa = this.cameraRotation.x;
  14641. var za = this.cameraRotation.z;
  14642. var dx = this.cameraOffset.x;
  14643. var dy = this.cameraOffset.y;
  14644. var sin = Math.sin,
  14645. cos = Math.cos;
  14646. this.cameraLocation.x = this.cameraLocation.x + dx * cos(za) + dy * -sin(za) * cos(xa);
  14647. this.cameraLocation.y = this.cameraLocation.y + dx * sin(za) + dy * cos(za) * cos(xa);
  14648. this.cameraLocation.z = this.cameraLocation.z + dy * sin(xa);
  14649. };
  14650. module.exports = Camera;
  14651. /***/ }),
  14652. /* 96 */
  14653. /***/ (function(module, exports, __webpack_require__) {
  14654. "use strict";
  14655. var DataView = __webpack_require__(12);
  14656. /**
  14657. * @class Filter
  14658. *
  14659. * @param {DataGroup} dataGroup the data group
  14660. * @param {number} column The index of the column to be filtered
  14661. * @param {Graph3d} graph The graph
  14662. */
  14663. function Filter(dataGroup, column, graph) {
  14664. this.dataGroup = dataGroup;
  14665. this.column = column;
  14666. this.graph = graph; // the parent graph
  14667. this.index = undefined;
  14668. this.value = undefined;
  14669. // read all distinct values and select the first one
  14670. this.values = dataGroup.getDistinctValues(this.column);
  14671. if (this.values.length > 0) {
  14672. this.selectValue(0);
  14673. }
  14674. // create an array with the filtered datapoints. this will be loaded afterwards
  14675. this.dataPoints = [];
  14676. this.loaded = false;
  14677. this.onLoadCallback = undefined;
  14678. if (graph.animationPreload) {
  14679. this.loaded = false;
  14680. this.loadInBackground();
  14681. } else {
  14682. this.loaded = true;
  14683. }
  14684. }
  14685. /**
  14686. * Return the label
  14687. * @return {string} label
  14688. */
  14689. Filter.prototype.isLoaded = function () {
  14690. return this.loaded;
  14691. };
  14692. /**
  14693. * Return the loaded progress
  14694. * @return {number} percentage between 0 and 100
  14695. */
  14696. Filter.prototype.getLoadedProgress = function () {
  14697. var len = this.values.length;
  14698. var i = 0;
  14699. while (this.dataPoints[i]) {
  14700. i++;
  14701. }
  14702. return Math.round(i / len * 100);
  14703. };
  14704. /**
  14705. * Return the label
  14706. * @return {string} label
  14707. */
  14708. Filter.prototype.getLabel = function () {
  14709. return this.graph.filterLabel;
  14710. };
  14711. /**
  14712. * Return the columnIndex of the filter
  14713. * @return {number} columnIndex
  14714. */
  14715. Filter.prototype.getColumn = function () {
  14716. return this.column;
  14717. };
  14718. /**
  14719. * Return the currently selected value. Returns undefined if there is no selection
  14720. * @return {*} value
  14721. */
  14722. Filter.prototype.getSelectedValue = function () {
  14723. if (this.index === undefined) return undefined;
  14724. return this.values[this.index];
  14725. };
  14726. /**
  14727. * Retrieve all values of the filter
  14728. * @return {Array} values
  14729. */
  14730. Filter.prototype.getValues = function () {
  14731. return this.values;
  14732. };
  14733. /**
  14734. * Retrieve one value of the filter
  14735. * @param {number} index
  14736. * @return {*} value
  14737. */
  14738. Filter.prototype.getValue = function (index) {
  14739. if (index >= this.values.length) throw new Error('Index out of range');
  14740. return this.values[index];
  14741. };
  14742. /**
  14743. * Retrieve the (filtered) dataPoints for the currently selected filter index
  14744. * @param {number} [index] (optional)
  14745. * @return {Array} dataPoints
  14746. */
  14747. Filter.prototype._getDataPoints = function (index) {
  14748. if (index === undefined) index = this.index;
  14749. if (index === undefined) return [];
  14750. var dataPoints;
  14751. if (this.dataPoints[index]) {
  14752. dataPoints = this.dataPoints[index];
  14753. } else {
  14754. var f = {};
  14755. f.column = this.column;
  14756. f.value = this.values[index];
  14757. var dataView = new DataView(this.dataGroup.getDataSet(), { filter: function filter(item) {
  14758. return item[f.column] == f.value;
  14759. } }).get();
  14760. dataPoints = this.dataGroup._getDataPoints(dataView);
  14761. this.dataPoints[index] = dataPoints;
  14762. }
  14763. return dataPoints;
  14764. };
  14765. /**
  14766. * Set a callback function when the filter is fully loaded.
  14767. *
  14768. * @param {function} callback
  14769. */
  14770. Filter.prototype.setOnLoadCallback = function (callback) {
  14771. this.onLoadCallback = callback;
  14772. };
  14773. /**
  14774. * Add a value to the list with available values for this filter
  14775. * No double entries will be created.
  14776. * @param {number} index
  14777. */
  14778. Filter.prototype.selectValue = function (index) {
  14779. if (index >= this.values.length) throw new Error('Index out of range');
  14780. this.index = index;
  14781. this.value = this.values[index];
  14782. };
  14783. /**
  14784. * Load all filtered rows in the background one by one
  14785. * Start this method without providing an index!
  14786. *
  14787. * @param {number} [index=0]
  14788. */
  14789. Filter.prototype.loadInBackground = function (index) {
  14790. if (index === undefined) index = 0;
  14791. var frame = this.graph.frame;
  14792. if (index < this.values.length) {
  14793. // create a progress box
  14794. if (frame.progress === undefined) {
  14795. frame.progress = document.createElement('DIV');
  14796. frame.progress.style.position = 'absolute';
  14797. frame.progress.style.color = 'gray';
  14798. frame.appendChild(frame.progress);
  14799. }
  14800. var progress = this.getLoadedProgress();
  14801. frame.progress.innerHTML = 'Loading animation... ' + progress + '%';
  14802. // TODO: this is no nice solution...
  14803. frame.progress.style.bottom = 60 + 'px'; // TODO: use height of slider
  14804. frame.progress.style.left = 10 + 'px';
  14805. var me = this;
  14806. setTimeout(function () {
  14807. me.loadInBackground(index + 1);
  14808. }, 10);
  14809. this.loaded = false;
  14810. } else {
  14811. this.loaded = true;
  14812. // remove the progress box
  14813. if (frame.progress !== undefined) {
  14814. frame.removeChild(frame.progress);
  14815. frame.progress = undefined;
  14816. }
  14817. if (this.onLoadCallback) this.onLoadCallback();
  14818. }
  14819. };
  14820. module.exports = Filter;
  14821. /***/ }),
  14822. /* 97 */
  14823. /***/ (function(module, exports, __webpack_require__) {
  14824. "use strict";
  14825. var keycharm = __webpack_require__(35);
  14826. var Emitter = __webpack_require__(44);
  14827. var Hammer = __webpack_require__(10);
  14828. var util = __webpack_require__(2);
  14829. /**
  14830. * Turn an element into an clickToUse element.
  14831. * When not active, the element has a transparent overlay. When the overlay is
  14832. * clicked, the mode is changed to active.
  14833. * When active, the element is displayed with a blue border around it, and
  14834. * the interactive contents of the element can be used. When clicked outside
  14835. * the element, the elements mode is changed to inactive.
  14836. * @param {Element} container
  14837. * @constructor Activator
  14838. */
  14839. function Activator(container) {
  14840. this.active = false;
  14841. this.dom = {
  14842. container: container
  14843. };
  14844. this.dom.overlay = document.createElement('div');
  14845. this.dom.overlay.className = 'vis-overlay';
  14846. this.dom.container.appendChild(this.dom.overlay);
  14847. this.hammer = Hammer(this.dom.overlay);
  14848. this.hammer.on('tap', this._onTapOverlay.bind(this));
  14849. // block all touch events (except tap)
  14850. var me = this;
  14851. var events = ['tap', 'doubletap', 'press', 'pinch', 'pan', 'panstart', 'panmove', 'panend'];
  14852. events.forEach(function (event) {
  14853. me.hammer.on(event, function (event) {
  14854. event.stopPropagation();
  14855. });
  14856. });
  14857. // attach a click event to the window, in order to deactivate when clicking outside the timeline
  14858. if (document && document.body) {
  14859. this.onClick = function (event) {
  14860. if (!_hasParent(event.target, container)) {
  14861. me.deactivate();
  14862. }
  14863. };
  14864. document.body.addEventListener('click', this.onClick);
  14865. }
  14866. if (this.keycharm !== undefined) {
  14867. this.keycharm.destroy();
  14868. }
  14869. this.keycharm = keycharm();
  14870. // keycharm listener only bounded when active)
  14871. this.escListener = this.deactivate.bind(this);
  14872. }
  14873. // turn into an event emitter
  14874. Emitter(Activator.prototype);
  14875. // The currently active activator
  14876. Activator.current = null;
  14877. /**
  14878. * Destroy the activator. Cleans up all created DOM and event listeners
  14879. */
  14880. Activator.prototype.destroy = function () {
  14881. this.deactivate();
  14882. // remove dom
  14883. this.dom.overlay.parentNode.removeChild(this.dom.overlay);
  14884. // remove global event listener
  14885. if (this.onClick) {
  14886. document.body.removeEventListener('click', this.onClick);
  14887. }
  14888. // cleanup hammer instances
  14889. this.hammer.destroy();
  14890. this.hammer = null;
  14891. // FIXME: cleaning up hammer instances doesn't work (Timeline not removed from memory)
  14892. };
  14893. /**
  14894. * Activate the element
  14895. * Overlay is hidden, element is decorated with a blue shadow border
  14896. */
  14897. Activator.prototype.activate = function () {
  14898. // we allow only one active activator at a time
  14899. if (Activator.current) {
  14900. Activator.current.deactivate();
  14901. }
  14902. Activator.current = this;
  14903. this.active = true;
  14904. this.dom.overlay.style.display = 'none';
  14905. util.addClassName(this.dom.container, 'vis-active');
  14906. this.emit('change');
  14907. this.emit('activate');
  14908. // ugly hack: bind ESC after emitting the events, as the Network rebinds all
  14909. // keyboard events on a 'change' event
  14910. this.keycharm.bind('esc', this.escListener);
  14911. };
  14912. /**
  14913. * Deactivate the element
  14914. * Overlay is displayed on top of the element
  14915. */
  14916. Activator.prototype.deactivate = function () {
  14917. this.active = false;
  14918. this.dom.overlay.style.display = '';
  14919. util.removeClassName(this.dom.container, 'vis-active');
  14920. this.keycharm.unbind('esc', this.escListener);
  14921. this.emit('change');
  14922. this.emit('deactivate');
  14923. };
  14924. /**
  14925. * Handle a tap event: activate the container
  14926. * @param {Event} event The event
  14927. * @private
  14928. */
  14929. Activator.prototype._onTapOverlay = function (event) {
  14930. // activate the container
  14931. this.activate();
  14932. event.stopPropagation();
  14933. };
  14934. /**
  14935. * Test whether the element has the requested parent element somewhere in
  14936. * its chain of parent nodes.
  14937. * @param {HTMLElement} element
  14938. * @param {HTMLElement} parent
  14939. * @returns {boolean} Returns true when the parent is found somewhere in the
  14940. * chain of parent nodes.
  14941. * @private
  14942. */
  14943. function _hasParent(element, parent) {
  14944. while (element) {
  14945. if (element === parent) {
  14946. return true;
  14947. }
  14948. element = element.parentNode;
  14949. }
  14950. return false;
  14951. }
  14952. module.exports = Activator;
  14953. /***/ }),
  14954. /* 98 */
  14955. /***/ (function(module, exports, __webpack_require__) {
  14956. "use strict";
  14957. // English
  14958. exports['en'] = {
  14959. current: 'current',
  14960. time: 'time'
  14961. };
  14962. exports['en_EN'] = exports['en'];
  14963. exports['en_US'] = exports['en'];
  14964. // Italiano
  14965. exports['it'] = {
  14966. current: 'attuale',
  14967. time: 'tempo'
  14968. };
  14969. exports['it_IT'] = exports['it'];
  14970. exports['it_CH'] = exports['it'];
  14971. // Dutch
  14972. exports['nl'] = {
  14973. current: 'huidige',
  14974. time: 'tijd'
  14975. };
  14976. exports['nl_NL'] = exports['nl'];
  14977. exports['nl_BE'] = exports['nl'];
  14978. // German
  14979. exports['de'] = {
  14980. current: 'Aktuelle',
  14981. time: 'Zeit'
  14982. };
  14983. exports['de_DE'] = exports['de'];
  14984. // French
  14985. exports['fr'] = {
  14986. current: 'actuel',
  14987. time: 'heure'
  14988. };
  14989. exports['fr_FR'] = exports['fr'];
  14990. exports['fr_CA'] = exports['fr'];
  14991. exports['fr_BE'] = exports['fr'];
  14992. // Espanol
  14993. exports['es'] = {
  14994. current: 'corriente',
  14995. time: 'hora'
  14996. };
  14997. exports['es_ES'] = exports['es'];
  14998. /***/ }),
  14999. /* 99 */
  15000. /***/ (function(module, exports, __webpack_require__) {
  15001. "use strict";
  15002. var _create = __webpack_require__(29);
  15003. var _create2 = _interopRequireDefault(_create);
  15004. var _typeof2 = __webpack_require__(6);
  15005. var _typeof3 = _interopRequireDefault(_typeof2);
  15006. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  15007. var Hammer = __webpack_require__(10);
  15008. var util = __webpack_require__(2);
  15009. var DataSet = __webpack_require__(11);
  15010. var DataView = __webpack_require__(12);
  15011. var TimeStep = __webpack_require__(66);
  15012. var Component = __webpack_require__(16);
  15013. var Group = __webpack_require__(68);
  15014. var BackgroundGroup = __webpack_require__(69);
  15015. var BoxItem = __webpack_require__(101);
  15016. var PointItem = __webpack_require__(102);
  15017. var RangeItem = __webpack_require__(70);
  15018. var BackgroundItem = __webpack_require__(103);
  15019. var Popup = __webpack_require__(104)['default'];
  15020. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  15021. var BACKGROUND = '__background__'; // reserved group id for background items without group
  15022. /**
  15023. * An ItemSet holds a set of items and ranges which can be displayed in a
  15024. * range. The width is determined by the parent of the ItemSet, and the height
  15025. * is determined by the size of the items.
  15026. * @param {{dom: Object, domProps: Object, emitter: Emitter, range: Range}} body
  15027. * @param {Object} [options] See ItemSet.setOptions for the available options.
  15028. * @constructor ItemSet
  15029. * @extends Component
  15030. */
  15031. function ItemSet(body, options) {
  15032. this.body = body;
  15033. this.defaultOptions = {
  15034. type: null, // 'box', 'point', 'range', 'background'
  15035. orientation: {
  15036. item: 'bottom' // item orientation: 'top' or 'bottom'
  15037. },
  15038. align: 'auto', // alignment of box items
  15039. stack: true,
  15040. stackSubgroups: true,
  15041. groupOrderSwap: function groupOrderSwap(fromGroup, toGroup, groups) {
  15042. // eslint-disable-line no-unused-vars
  15043. var targetOrder = toGroup.order;
  15044. toGroup.order = fromGroup.order;
  15045. fromGroup.order = targetOrder;
  15046. },
  15047. groupOrder: 'order',
  15048. selectable: true,
  15049. multiselect: false,
  15050. itemsAlwaysDraggable: {
  15051. item: false,
  15052. range: false
  15053. },
  15054. editable: {
  15055. updateTime: false,
  15056. updateGroup: false,
  15057. add: false,
  15058. remove: false,
  15059. overrideItems: false
  15060. },
  15061. groupEditable: {
  15062. order: false,
  15063. add: false,
  15064. remove: false
  15065. },
  15066. snap: TimeStep.snap,
  15067. // Only called when `objectData.target === 'item'.
  15068. onDropObjectOnItem: function onDropObjectOnItem(objectData, item, callback) {
  15069. callback(item);
  15070. },
  15071. onAdd: function onAdd(item, callback) {
  15072. callback(item);
  15073. },
  15074. onUpdate: function onUpdate(item, callback) {
  15075. callback(item);
  15076. },
  15077. onMove: function onMove(item, callback) {
  15078. callback(item);
  15079. },
  15080. onRemove: function onRemove(item, callback) {
  15081. callback(item);
  15082. },
  15083. onMoving: function onMoving(item, callback) {
  15084. callback(item);
  15085. },
  15086. onAddGroup: function onAddGroup(item, callback) {
  15087. callback(item);
  15088. },
  15089. onMoveGroup: function onMoveGroup(item, callback) {
  15090. callback(item);
  15091. },
  15092. onRemoveGroup: function onRemoveGroup(item, callback) {
  15093. callback(item);
  15094. },
  15095. margin: {
  15096. item: {
  15097. horizontal: 10,
  15098. vertical: 10
  15099. },
  15100. axis: 20
  15101. },
  15102. showTooltips: true,
  15103. tooltip: {
  15104. followMouse: false,
  15105. overflowMethod: 'flip'
  15106. },
  15107. tooltipOnItemUpdateTime: false
  15108. };
  15109. // options is shared by this ItemSet and all its items
  15110. this.options = util.extend({}, this.defaultOptions);
  15111. this.options.rtl = options.rtl;
  15112. // options for getting items from the DataSet with the correct type
  15113. this.itemOptions = {
  15114. type: { start: 'Date', end: 'Date' }
  15115. };
  15116. this.conversion = {
  15117. toScreen: body.util.toScreen,
  15118. toTime: body.util.toTime
  15119. };
  15120. this.dom = {};
  15121. this.props = {};
  15122. this.hammer = null;
  15123. var me = this;
  15124. this.itemsData = null; // DataSet
  15125. this.groupsData = null; // DataSet
  15126. // listeners for the DataSet of the items
  15127. this.itemListeners = {
  15128. 'add': function add(event, params, senderId) {
  15129. // eslint-disable-line no-unused-vars
  15130. me._onAdd(params.items);
  15131. },
  15132. 'update': function update(event, params, senderId) {
  15133. // eslint-disable-line no-unused-vars
  15134. me._onUpdate(params.items);
  15135. },
  15136. 'remove': function remove(event, params, senderId) {
  15137. // eslint-disable-line no-unused-vars
  15138. me._onRemove(params.items);
  15139. }
  15140. };
  15141. // listeners for the DataSet of the groups
  15142. this.groupListeners = {
  15143. 'add': function add(event, params, senderId) {
  15144. // eslint-disable-line no-unused-vars
  15145. me._onAddGroups(params.items);
  15146. if (me.groupsData && me.groupsData.length > 0) {
  15147. var groupsData = me.groupsData.getDataSet();
  15148. groupsData.get().forEach(function (groupData) {
  15149. if (groupData.nestedGroups) {
  15150. if (groupData.showNested != false) {
  15151. groupData.showNested = true;
  15152. }
  15153. var updatedGroups = [];
  15154. groupData.nestedGroups.forEach(function (nestedGroupId) {
  15155. var updatedNestedGroup = groupsData.get(nestedGroupId);
  15156. if (!updatedNestedGroup) {
  15157. return;
  15158. }
  15159. updatedNestedGroup.nestedInGroup = groupData.id;
  15160. if (groupData.showNested == false) {
  15161. updatedNestedGroup.visible = false;
  15162. }
  15163. updatedGroups = updatedGroups.concat(updatedNestedGroup);
  15164. });
  15165. groupsData.update(updatedGroups, senderId);
  15166. }
  15167. });
  15168. }
  15169. },
  15170. 'update': function update(event, params, senderId) {
  15171. // eslint-disable-line no-unused-vars
  15172. me._onUpdateGroups(params.items);
  15173. },
  15174. 'remove': function remove(event, params, senderId) {
  15175. // eslint-disable-line no-unused-vars
  15176. me._onRemoveGroups(params.items);
  15177. }
  15178. };
  15179. this.items = {}; // object with an Item for every data item
  15180. this.groups = {}; // Group object for every group
  15181. this.groupIds = [];
  15182. this.selection = []; // list with the ids of all selected nodes
  15183. this.popup = null;
  15184. this.touchParams = {}; // stores properties while dragging
  15185. this.groupTouchParams = {};
  15186. // create the HTML DOM
  15187. this._create();
  15188. this.setOptions(options);
  15189. }
  15190. ItemSet.prototype = new Component();
  15191. // available item types will be registered here
  15192. ItemSet.types = {
  15193. background: BackgroundItem,
  15194. box: BoxItem,
  15195. range: RangeItem,
  15196. point: PointItem
  15197. };
  15198. /**
  15199. * Create the HTML DOM for the ItemSet
  15200. */
  15201. ItemSet.prototype._create = function () {
  15202. var frame = document.createElement('div');
  15203. frame.className = 'vis-itemset';
  15204. frame['timeline-itemset'] = this;
  15205. this.dom.frame = frame;
  15206. // create background panel
  15207. var background = document.createElement('div');
  15208. background.className = 'vis-background';
  15209. frame.appendChild(background);
  15210. this.dom.background = background;
  15211. // create foreground panel
  15212. var foreground = document.createElement('div');
  15213. foreground.className = 'vis-foreground';
  15214. frame.appendChild(foreground);
  15215. this.dom.foreground = foreground;
  15216. // create axis panel
  15217. var axis = document.createElement('div');
  15218. axis.className = 'vis-axis';
  15219. this.dom.axis = axis;
  15220. // create labelset
  15221. var labelSet = document.createElement('div');
  15222. labelSet.className = 'vis-labelset';
  15223. this.dom.labelSet = labelSet;
  15224. // create ungrouped Group
  15225. this._updateUngrouped();
  15226. // create background Group
  15227. var backgroundGroup = new BackgroundGroup(BACKGROUND, null, this);
  15228. backgroundGroup.show();
  15229. this.groups[BACKGROUND] = backgroundGroup;
  15230. // attach event listeners
  15231. // Note: we bind to the centerContainer for the case where the height
  15232. // of the center container is larger than of the ItemSet, so we
  15233. // can click in the empty area to create a new item or deselect an item.
  15234. this.hammer = new Hammer(this.body.dom.centerContainer);
  15235. // drag items when selected
  15236. this.hammer.on('hammer.input', function (event) {
  15237. if (event.isFirst) {
  15238. this._onTouch(event);
  15239. }
  15240. }.bind(this));
  15241. this.hammer.on('panstart', this._onDragStart.bind(this));
  15242. this.hammer.on('panmove', this._onDrag.bind(this));
  15243. this.hammer.on('panend', this._onDragEnd.bind(this));
  15244. this.hammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_HORIZONTAL });
  15245. // single select (or unselect) when tapping an item
  15246. this.hammer.on('tap', this._onSelectItem.bind(this));
  15247. // multi select when holding mouse/touch, or on ctrl+click
  15248. this.hammer.on('press', this._onMultiSelectItem.bind(this));
  15249. // add item on doubletap
  15250. this.hammer.on('doubletap', this._onAddItem.bind(this));
  15251. if (this.options.rtl) {
  15252. this.groupHammer = new Hammer(this.body.dom.rightContainer);
  15253. } else {
  15254. this.groupHammer = new Hammer(this.body.dom.leftContainer);
  15255. }
  15256. this.groupHammer.on('tap', this._onGroupClick.bind(this));
  15257. this.groupHammer.on('panstart', this._onGroupDragStart.bind(this));
  15258. this.groupHammer.on('panmove', this._onGroupDrag.bind(this));
  15259. this.groupHammer.on('panend', this._onGroupDragEnd.bind(this));
  15260. this.groupHammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_VERTICAL });
  15261. this.body.dom.centerContainer.addEventListener('mouseover', this._onMouseOver.bind(this));
  15262. this.body.dom.centerContainer.addEventListener('mouseout', this._onMouseOut.bind(this));
  15263. this.body.dom.centerContainer.addEventListener('mousemove', this._onMouseMove.bind(this));
  15264. // right-click on timeline
  15265. this.body.dom.centerContainer.addEventListener('contextmenu', this._onDragEnd.bind(this));
  15266. this.body.dom.centerContainer.addEventListener('mousewheel', this._onMouseWheel.bind(this));
  15267. // attach to the DOM
  15268. this.show();
  15269. };
  15270. /**
  15271. * Set options for the ItemSet. Existing options will be extended/overwritten.
  15272. * @param {Object} [options] The following options are available:
  15273. * {string} type
  15274. * Default type for the items. Choose from 'box'
  15275. * (default), 'point', 'range', or 'background'.
  15276. * The default style can be overwritten by
  15277. * individual items.
  15278. * {string} align
  15279. * Alignment for the items, only applicable for
  15280. * BoxItem. Choose 'center' (default), 'left', or
  15281. * 'right'.
  15282. * {string} orientation.item
  15283. * Orientation of the item set. Choose 'top' or
  15284. * 'bottom' (default).
  15285. * {Function} groupOrder
  15286. * A sorting function for ordering groups
  15287. * {boolean} stack
  15288. * If true (default), items will be stacked on
  15289. * top of each other.
  15290. * {number} margin.axis
  15291. * Margin between the axis and the items in pixels.
  15292. * Default is 20.
  15293. * {number} margin.item.horizontal
  15294. * Horizontal margin between items in pixels.
  15295. * Default is 10.
  15296. * {number} margin.item.vertical
  15297. * Vertical Margin between items in pixels.
  15298. * Default is 10.
  15299. * {number} margin.item
  15300. * Margin between items in pixels in both horizontal
  15301. * and vertical direction. Default is 10.
  15302. * {number} margin
  15303. * Set margin for both axis and items in pixels.
  15304. * {boolean} selectable
  15305. * If true (default), items can be selected.
  15306. * {boolean} multiselect
  15307. * If true, multiple items can be selected.
  15308. * False by default.
  15309. * {boolean} editable
  15310. * Set all editable options to true or false
  15311. * {boolean} editable.updateTime
  15312. * Allow dragging an item to an other moment in time
  15313. * {boolean} editable.updateGroup
  15314. * Allow dragging an item to an other group
  15315. * {boolean} editable.add
  15316. * Allow creating new items on double tap
  15317. * {boolean} editable.remove
  15318. * Allow removing items by clicking the delete button
  15319. * top right of a selected item.
  15320. * {Function(item: Item, callback: Function)} onAdd
  15321. * Callback function triggered when an item is about to be added:
  15322. * when the user double taps an empty space in the Timeline.
  15323. * {Function(item: Item, callback: Function)} onUpdate
  15324. * Callback function fired when an item is about to be updated.
  15325. * This function typically has to show a dialog where the user
  15326. * change the item. If not implemented, nothing happens.
  15327. * {Function(item: Item, callback: Function)} onMove
  15328. * Fired when an item has been moved. If not implemented,
  15329. * the move action will be accepted.
  15330. * {Function(item: Item, callback: Function)} onRemove
  15331. * Fired when an item is about to be deleted.
  15332. * If not implemented, the item will be always removed.
  15333. */
  15334. ItemSet.prototype.setOptions = function (options) {
  15335. if (options) {
  15336. // copy all options that we know
  15337. var fields = ['type', 'rtl', 'align', 'order', 'stack', 'stackSubgroups', 'selectable', 'multiselect', 'multiselectPerGroup', 'groupOrder', 'dataAttributes', 'template', 'groupTemplate', 'visibleFrameTemplate', 'hide', 'snap', 'groupOrderSwap', 'showTooltips', 'tooltip', 'tooltipOnItemUpdateTime'];
  15338. util.selectiveExtend(fields, this.options, options);
  15339. if ('itemsAlwaysDraggable' in options) {
  15340. if (typeof options.itemsAlwaysDraggable === 'boolean') {
  15341. this.options.itemsAlwaysDraggable.item = options.itemsAlwaysDraggable;
  15342. this.options.itemsAlwaysDraggable.range = false;
  15343. } else if ((0, _typeof3['default'])(options.itemsAlwaysDraggable) === 'object') {
  15344. util.selectiveExtend(['item', 'range'], this.options.itemsAlwaysDraggable, options.itemsAlwaysDraggable);
  15345. // only allow range always draggable when item is always draggable as well
  15346. if (!this.options.itemsAlwaysDraggable.item) {
  15347. this.options.itemsAlwaysDraggable.range = false;
  15348. }
  15349. }
  15350. }
  15351. if ('orientation' in options) {
  15352. if (typeof options.orientation === 'string') {
  15353. this.options.orientation.item = options.orientation === 'top' ? 'top' : 'bottom';
  15354. } else if ((0, _typeof3['default'])(options.orientation) === 'object' && 'item' in options.orientation) {
  15355. this.options.orientation.item = options.orientation.item;
  15356. }
  15357. }
  15358. if ('margin' in options) {
  15359. if (typeof options.margin === 'number') {
  15360. this.options.margin.axis = options.margin;
  15361. this.options.margin.item.horizontal = options.margin;
  15362. this.options.margin.item.vertical = options.margin;
  15363. } else if ((0, _typeof3['default'])(options.margin) === 'object') {
  15364. util.selectiveExtend(['axis'], this.options.margin, options.margin);
  15365. if ('item' in options.margin) {
  15366. if (typeof options.margin.item === 'number') {
  15367. this.options.margin.item.horizontal = options.margin.item;
  15368. this.options.margin.item.vertical = options.margin.item;
  15369. } else if ((0, _typeof3['default'])(options.margin.item) === 'object') {
  15370. util.selectiveExtend(['horizontal', 'vertical'], this.options.margin.item, options.margin.item);
  15371. }
  15372. }
  15373. }
  15374. }
  15375. if ('editable' in options) {
  15376. if (typeof options.editable === 'boolean') {
  15377. this.options.editable.updateTime = options.editable;
  15378. this.options.editable.updateGroup = options.editable;
  15379. this.options.editable.add = options.editable;
  15380. this.options.editable.remove = options.editable;
  15381. this.options.editable.overrideItems = false;
  15382. } else if ((0, _typeof3['default'])(options.editable) === 'object') {
  15383. util.selectiveExtend(['updateTime', 'updateGroup', 'add', 'remove', 'overrideItems'], this.options.editable, options.editable);
  15384. }
  15385. }
  15386. if ('groupEditable' in options) {
  15387. if (typeof options.groupEditable === 'boolean') {
  15388. this.options.groupEditable.order = options.groupEditable;
  15389. this.options.groupEditable.add = options.groupEditable;
  15390. this.options.groupEditable.remove = options.groupEditable;
  15391. } else if ((0, _typeof3['default'])(options.groupEditable) === 'object') {
  15392. util.selectiveExtend(['order', 'add', 'remove'], this.options.groupEditable, options.groupEditable);
  15393. }
  15394. }
  15395. // callback functions
  15396. var addCallback = function (name) {
  15397. var fn = options[name];
  15398. if (fn) {
  15399. if (!(fn instanceof Function)) {
  15400. throw new Error('option ' + name + ' must be a function ' + name + '(item, callback)');
  15401. }
  15402. this.options[name] = fn;
  15403. }
  15404. }.bind(this);
  15405. ['onDropObjectOnItem', 'onAdd', 'onUpdate', 'onRemove', 'onMove', 'onMoving', 'onAddGroup', 'onMoveGroup', 'onRemoveGroup'].forEach(addCallback);
  15406. // force the itemSet to refresh: options like orientation and margins may be changed
  15407. this.markDirty();
  15408. }
  15409. };
  15410. /**
  15411. * Mark the ItemSet dirty so it will refresh everything with next redraw.
  15412. * Optionally, all items can be marked as dirty and be refreshed.
  15413. * @param {{refreshItems: boolean}} [options]
  15414. */
  15415. ItemSet.prototype.markDirty = function (options) {
  15416. this.groupIds = [];
  15417. if (options && options.refreshItems) {
  15418. util.forEach(this.items, function (item) {
  15419. item.dirty = true;
  15420. if (item.displayed) item.redraw();
  15421. });
  15422. }
  15423. };
  15424. /**
  15425. * Destroy the ItemSet
  15426. */
  15427. ItemSet.prototype.destroy = function () {
  15428. this.hide();
  15429. this.setItems(null);
  15430. this.setGroups(null);
  15431. this.hammer = null;
  15432. this.body = null;
  15433. this.conversion = null;
  15434. };
  15435. /**
  15436. * Hide the component from the DOM
  15437. */
  15438. ItemSet.prototype.hide = function () {
  15439. // remove the frame containing the items
  15440. if (this.dom.frame.parentNode) {
  15441. this.dom.frame.parentNode.removeChild(this.dom.frame);
  15442. }
  15443. // remove the axis with dots
  15444. if (this.dom.axis.parentNode) {
  15445. this.dom.axis.parentNode.removeChild(this.dom.axis);
  15446. }
  15447. // remove the labelset containing all group labels
  15448. if (this.dom.labelSet.parentNode) {
  15449. this.dom.labelSet.parentNode.removeChild(this.dom.labelSet);
  15450. }
  15451. };
  15452. /**
  15453. * Show the component in the DOM (when not already visible).
  15454. */
  15455. ItemSet.prototype.show = function () {
  15456. // show frame containing the items
  15457. if (!this.dom.frame.parentNode) {
  15458. this.body.dom.center.appendChild(this.dom.frame);
  15459. }
  15460. // show axis with dots
  15461. if (!this.dom.axis.parentNode) {
  15462. this.body.dom.backgroundVertical.appendChild(this.dom.axis);
  15463. }
  15464. // show labelset containing labels
  15465. if (!this.dom.labelSet.parentNode) {
  15466. if (this.options.rtl) {
  15467. this.body.dom.right.appendChild(this.dom.labelSet);
  15468. } else {
  15469. this.body.dom.left.appendChild(this.dom.labelSet);
  15470. }
  15471. }
  15472. };
  15473. /**
  15474. * Set selected items by their id. Replaces the current selection
  15475. * Unknown id's are silently ignored.
  15476. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  15477. * selected, or a single item id. If ids is undefined
  15478. * or an empty array, all items will be unselected.
  15479. */
  15480. ItemSet.prototype.setSelection = function (ids) {
  15481. var i, ii, id, item;
  15482. if (ids == undefined) ids = [];
  15483. if (!Array.isArray(ids)) ids = [ids];
  15484. // unselect currently selected items
  15485. for (i = 0, ii = this.selection.length; i < ii; i++) {
  15486. id = this.selection[i];
  15487. item = this.items[id];
  15488. if (item) item.unselect();
  15489. }
  15490. // select items
  15491. this.selection = [];
  15492. for (i = 0, ii = ids.length; i < ii; i++) {
  15493. id = ids[i];
  15494. item = this.items[id];
  15495. if (item) {
  15496. this.selection.push(id);
  15497. item.select();
  15498. }
  15499. }
  15500. };
  15501. /**
  15502. * Get the selected items by their id
  15503. * @return {Array} ids The ids of the selected items
  15504. */
  15505. ItemSet.prototype.getSelection = function () {
  15506. return this.selection.concat([]);
  15507. };
  15508. /**
  15509. * Get the id's of the currently visible items.
  15510. * @returns {Array} The ids of the visible items
  15511. */
  15512. ItemSet.prototype.getVisibleItems = function () {
  15513. var range = this.body.range.getRange();
  15514. var right, left;
  15515. if (this.options.rtl) {
  15516. right = this.body.util.toScreen(range.start);
  15517. left = this.body.util.toScreen(range.end);
  15518. } else {
  15519. left = this.body.util.toScreen(range.start);
  15520. right = this.body.util.toScreen(range.end);
  15521. }
  15522. var ids = [];
  15523. for (var groupId in this.groups) {
  15524. if (this.groups.hasOwnProperty(groupId)) {
  15525. var group = this.groups[groupId];
  15526. var rawVisibleItems = group.isVisible ? group.visibleItems : [];
  15527. // filter the "raw" set with visibleItems into a set which is really
  15528. // visible by pixels
  15529. for (var i = 0; i < rawVisibleItems.length; i++) {
  15530. var item = rawVisibleItems[i];
  15531. // TODO: also check whether visible vertically
  15532. if (this.options.rtl) {
  15533. if (item.right < left && item.right + item.width > right) {
  15534. ids.push(item.id);
  15535. }
  15536. } else {
  15537. if (item.left < right && item.left + item.width > left) {
  15538. ids.push(item.id);
  15539. }
  15540. }
  15541. }
  15542. }
  15543. }
  15544. return ids;
  15545. };
  15546. /**
  15547. * Deselect a selected item
  15548. * @param {string | number} id
  15549. * @private
  15550. */
  15551. ItemSet.prototype._deselect = function (id) {
  15552. var selection = this.selection;
  15553. for (var i = 0, ii = selection.length; i < ii; i++) {
  15554. if (selection[i] == id) {
  15555. // non-strict comparison!
  15556. selection.splice(i, 1);
  15557. break;
  15558. }
  15559. }
  15560. };
  15561. /**
  15562. * Repaint the component
  15563. * @return {boolean} Returns true if the component is resized
  15564. */
  15565. ItemSet.prototype.redraw = function () {
  15566. var margin = this.options.margin,
  15567. range = this.body.range,
  15568. asSize = util.option.asSize,
  15569. options = this.options,
  15570. orientation = options.orientation.item,
  15571. resized = false,
  15572. frame = this.dom.frame;
  15573. // recalculate absolute position (before redrawing groups)
  15574. this.props.top = this.body.domProps.top.height + this.body.domProps.border.top;
  15575. if (this.options.rtl) {
  15576. this.props.right = this.body.domProps.right.width + this.body.domProps.border.right;
  15577. } else {
  15578. this.props.left = this.body.domProps.left.width + this.body.domProps.border.left;
  15579. }
  15580. // update class name
  15581. frame.className = 'vis-itemset';
  15582. // reorder the groups (if needed)
  15583. resized = this._orderGroups() || resized;
  15584. // check whether zoomed (in that case we need to re-stack everything)
  15585. // TODO: would be nicer to get this as a trigger from Range
  15586. var visibleInterval = range.end - range.start;
  15587. var zoomed = visibleInterval != this.lastVisibleInterval || this.props.width != this.props.lastWidth;
  15588. var scrolled = range.start != this.lastRangeStart;
  15589. var changedStackOption = options.stack != this.lastStack;
  15590. var changedStackSubgroupsOption = options.stackSubgroups != this.lastStackSubgroups;
  15591. var forceRestack = zoomed || scrolled || changedStackOption || changedStackSubgroupsOption;
  15592. this.lastVisibleInterval = visibleInterval;
  15593. this.lastRangeStart = range.start;
  15594. this.lastStack = options.stack;
  15595. this.lastStackSubgroups = options.stackSubgroups;
  15596. this.props.lastWidth = this.props.width;
  15597. var firstGroup = this._firstGroup();
  15598. var firstMargin = {
  15599. item: margin.item,
  15600. axis: margin.axis
  15601. };
  15602. var nonFirstMargin = {
  15603. item: margin.item,
  15604. axis: margin.item.vertical / 2
  15605. };
  15606. var height = 0;
  15607. var minHeight = margin.axis + margin.item.vertical;
  15608. // redraw the background group
  15609. this.groups[BACKGROUND].redraw(range, nonFirstMargin, forceRestack);
  15610. var redrawQueue = {};
  15611. var redrawQueueLength = 0;
  15612. // collect redraw functions
  15613. util.forEach(this.groups, function (group, key) {
  15614. if (key === BACKGROUND) return;
  15615. var groupMargin = group == firstGroup ? firstMargin : nonFirstMargin;
  15616. var returnQueue = true;
  15617. redrawQueue[key] = group.redraw(range, groupMargin, forceRestack, returnQueue);
  15618. redrawQueueLength = redrawQueue[key].length;
  15619. });
  15620. var needRedraw = redrawQueueLength > 0;
  15621. if (needRedraw) {
  15622. var redrawResults = {};
  15623. for (var i = 0; i < redrawQueueLength; i++) {
  15624. util.forEach(redrawQueue, function (fns, key) {
  15625. redrawResults[key] = fns[i]();
  15626. });
  15627. }
  15628. // redraw all regular groups
  15629. util.forEach(this.groups, function (group, key) {
  15630. if (key === BACKGROUND) return;
  15631. var groupResized = redrawResults[key];
  15632. resized = groupResized || resized;
  15633. height += group.height;
  15634. });
  15635. height = Math.max(height, minHeight);
  15636. }
  15637. height = Math.max(height, minHeight);
  15638. // update frame height
  15639. frame.style.height = asSize(height);
  15640. // calculate actual size
  15641. this.props.width = frame.offsetWidth;
  15642. this.props.height = height;
  15643. // reposition axis
  15644. 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);
  15645. if (this.options.rtl) {
  15646. this.dom.axis.style.right = '0';
  15647. } else {
  15648. this.dom.axis.style.left = '0';
  15649. }
  15650. this.initialItemSetDrawn = true;
  15651. // check if this component is resized
  15652. resized = this._isResized() || resized;
  15653. return resized;
  15654. };
  15655. /**
  15656. * Get the first group, aligned with the axis
  15657. * @return {Group | null} firstGroup
  15658. * @private
  15659. */
  15660. ItemSet.prototype._firstGroup = function () {
  15661. var firstGroupIndex = this.options.orientation.item == 'top' ? 0 : this.groupIds.length - 1;
  15662. var firstGroupId = this.groupIds[firstGroupIndex];
  15663. var firstGroup = this.groups[firstGroupId] || this.groups[UNGROUPED];
  15664. return firstGroup || null;
  15665. };
  15666. /**
  15667. * Create or delete the group holding all ungrouped items. This group is used when
  15668. * there are no groups specified.
  15669. * @protected
  15670. */
  15671. ItemSet.prototype._updateUngrouped = function () {
  15672. var ungrouped = this.groups[UNGROUPED];
  15673. var item, itemId;
  15674. if (this.groupsData) {
  15675. // remove the group holding all ungrouped items
  15676. if (ungrouped) {
  15677. ungrouped.hide();
  15678. delete this.groups[UNGROUPED];
  15679. for (itemId in this.items) {
  15680. if (this.items.hasOwnProperty(itemId)) {
  15681. item = this.items[itemId];
  15682. item.parent && item.parent.remove(item);
  15683. var groupId = this._getGroupId(item.data);
  15684. var group = this.groups[groupId];
  15685. group && group.add(item) || item.hide();
  15686. }
  15687. }
  15688. }
  15689. } else {
  15690. // create a group holding all (unfiltered) items
  15691. if (!ungrouped) {
  15692. var id = null;
  15693. var data = null;
  15694. ungrouped = new Group(id, data, this);
  15695. this.groups[UNGROUPED] = ungrouped;
  15696. for (itemId in this.items) {
  15697. if (this.items.hasOwnProperty(itemId)) {
  15698. item = this.items[itemId];
  15699. ungrouped.add(item);
  15700. }
  15701. }
  15702. ungrouped.show();
  15703. }
  15704. }
  15705. };
  15706. /**
  15707. * Get the element for the labelset
  15708. * @return {HTMLElement} labelSet
  15709. */
  15710. ItemSet.prototype.getLabelSet = function () {
  15711. return this.dom.labelSet;
  15712. };
  15713. /**
  15714. * Set items
  15715. * @param {vis.DataSet | null} items
  15716. */
  15717. ItemSet.prototype.setItems = function (items) {
  15718. var me = this,
  15719. ids,
  15720. oldItemsData = this.itemsData;
  15721. // replace the dataset
  15722. if (!items) {
  15723. this.itemsData = null;
  15724. } else if (items instanceof DataSet || items instanceof DataView) {
  15725. this.itemsData = items;
  15726. } else {
  15727. throw new TypeError('Data must be an instance of DataSet or DataView');
  15728. }
  15729. if (oldItemsData) {
  15730. // unsubscribe from old dataset
  15731. util.forEach(this.itemListeners, function (callback, event) {
  15732. oldItemsData.off(event, callback);
  15733. });
  15734. // remove all drawn items
  15735. ids = oldItemsData.getIds();
  15736. this._onRemove(ids);
  15737. }
  15738. if (this.itemsData) {
  15739. // subscribe to new dataset
  15740. var id = this.id;
  15741. util.forEach(this.itemListeners, function (callback, event) {
  15742. me.itemsData.on(event, callback, id);
  15743. });
  15744. // add all new items
  15745. ids = this.itemsData.getIds();
  15746. this._onAdd(ids);
  15747. // update the group holding all ungrouped items
  15748. this._updateUngrouped();
  15749. }
  15750. this.body.emitter.emit('_change', { queue: true });
  15751. };
  15752. /**
  15753. * Get the current items
  15754. * @returns {vis.DataSet | null}
  15755. */
  15756. ItemSet.prototype.getItems = function () {
  15757. return this.itemsData;
  15758. };
  15759. /**
  15760. * Set groups
  15761. * @param {vis.DataSet} groups
  15762. */
  15763. ItemSet.prototype.setGroups = function (groups) {
  15764. var me = this,
  15765. ids;
  15766. // unsubscribe from current dataset
  15767. if (this.groupsData) {
  15768. util.forEach(this.groupListeners, function (callback, event) {
  15769. me.groupsData.off(event, callback);
  15770. });
  15771. // remove all drawn groups
  15772. ids = this.groupsData.getIds();
  15773. this.groupsData = null;
  15774. this._onRemoveGroups(ids); // note: this will cause a redraw
  15775. }
  15776. // replace the dataset
  15777. if (!groups) {
  15778. this.groupsData = null;
  15779. } else if (groups instanceof DataSet || groups instanceof DataView) {
  15780. this.groupsData = groups;
  15781. } else {
  15782. throw new TypeError('Data must be an instance of DataSet or DataView');
  15783. }
  15784. if (this.groupsData) {
  15785. // go over all groups nesting
  15786. var groupsData = this.groupsData;
  15787. if (this.groupsData instanceof DataView) {
  15788. groupsData = this.groupsData.getDataSet();
  15789. }
  15790. groupsData.get().forEach(function (group) {
  15791. if (group.nestedGroups) {
  15792. group.nestedGroups.forEach(function (nestedGroupId) {
  15793. var updatedNestedGroup = groupsData.get(nestedGroupId);
  15794. updatedNestedGroup.nestedInGroup = group.id;
  15795. if (group.showNested == false) {
  15796. updatedNestedGroup.visible = false;
  15797. }
  15798. groupsData.update(updatedNestedGroup);
  15799. });
  15800. }
  15801. });
  15802. // subscribe to new dataset
  15803. var id = this.id;
  15804. util.forEach(this.groupListeners, function (callback, event) {
  15805. me.groupsData.on(event, callback, id);
  15806. });
  15807. // draw all ms
  15808. ids = this.groupsData.getIds();
  15809. this._onAddGroups(ids);
  15810. }
  15811. // update the group holding all ungrouped items
  15812. this._updateUngrouped();
  15813. // update the order of all items in each group
  15814. this._order();
  15815. this.body.emitter.emit('_change', { queue: true });
  15816. };
  15817. /**
  15818. * Get the current groups
  15819. * @returns {vis.DataSet | null} groups
  15820. */
  15821. ItemSet.prototype.getGroups = function () {
  15822. return this.groupsData;
  15823. };
  15824. /**
  15825. * Remove an item by its id
  15826. * @param {string | number} id
  15827. */
  15828. ItemSet.prototype.removeItem = function (id) {
  15829. var item = this.itemsData.get(id),
  15830. dataset = this.itemsData.getDataSet();
  15831. if (item) {
  15832. // confirm deletion
  15833. this.options.onRemove(item, function (item) {
  15834. if (item) {
  15835. // remove by id here, it is possible that an item has no id defined
  15836. // itself, so better not delete by the item itself
  15837. dataset.remove(id);
  15838. }
  15839. });
  15840. }
  15841. };
  15842. /**
  15843. * Get the time of an item based on it's data and options.type
  15844. * @param {Object} itemData
  15845. * @returns {string} Returns the type
  15846. * @private
  15847. */
  15848. ItemSet.prototype._getType = function (itemData) {
  15849. return itemData.type || this.options.type || (itemData.end ? 'range' : 'box');
  15850. };
  15851. /**
  15852. * Get the group id for an item
  15853. * @param {Object} itemData
  15854. * @returns {string} Returns the groupId
  15855. * @private
  15856. */
  15857. ItemSet.prototype._getGroupId = function (itemData) {
  15858. var type = this._getType(itemData);
  15859. if (type == 'background' && itemData.group == undefined) {
  15860. return BACKGROUND;
  15861. } else {
  15862. return this.groupsData ? itemData.group : UNGROUPED;
  15863. }
  15864. };
  15865. /**
  15866. * Handle updated items
  15867. * @param {number[]} ids
  15868. * @protected
  15869. */
  15870. ItemSet.prototype._onUpdate = function (ids) {
  15871. var me = this;
  15872. ids.forEach(function (id) {
  15873. var itemData = me.itemsData.get(id, me.itemOptions);
  15874. var item = me.items[id];
  15875. var type = itemData ? me._getType(itemData) : null;
  15876. var constructor = ItemSet.types[type];
  15877. var selected;
  15878. if (item) {
  15879. // update item
  15880. if (!constructor || !(item instanceof constructor)) {
  15881. // item type has changed, delete the item and recreate it
  15882. selected = item.selected; // preserve selection of this item
  15883. me._removeItem(item);
  15884. item = null;
  15885. } else {
  15886. me._updateItem(item, itemData);
  15887. }
  15888. }
  15889. if (!item && itemData) {
  15890. // create item
  15891. if (constructor) {
  15892. item = new constructor(itemData, me.conversion, me.options);
  15893. item.id = id; // TODO: not so nice setting id afterwards
  15894. me._addItem(item);
  15895. if (selected) {
  15896. this.selection.push(id);
  15897. item.select();
  15898. }
  15899. } else if (type == 'rangeoverflow') {
  15900. // TODO: deprecated since version 2.1.0 (or 3.0.0?). cleanup some day
  15901. throw new TypeError('Item type "rangeoverflow" is deprecated. Use css styling instead: ' + '.vis-item.vis-range .vis-item-content {overflow: visible;}');
  15902. } else {
  15903. throw new TypeError('Unknown item type "' + type + '"');
  15904. }
  15905. }
  15906. }.bind(this));
  15907. this._order();
  15908. this.body.emitter.emit('_change', { queue: true });
  15909. };
  15910. /**
  15911. * Handle added items
  15912. * @param {number[]} ids
  15913. * @protected
  15914. */
  15915. ItemSet.prototype._onAdd = ItemSet.prototype._onUpdate;
  15916. /**
  15917. * Handle removed items
  15918. * @param {number[]} ids
  15919. * @protected
  15920. */
  15921. ItemSet.prototype._onRemove = function (ids) {
  15922. var count = 0;
  15923. var me = this;
  15924. ids.forEach(function (id) {
  15925. var item = me.items[id];
  15926. if (item) {
  15927. count++;
  15928. me._removeItem(item);
  15929. }
  15930. });
  15931. if (count) {
  15932. // update order
  15933. this._order();
  15934. this.body.emitter.emit('_change', { queue: true });
  15935. }
  15936. };
  15937. /**
  15938. * Update the order of item in all groups
  15939. * @private
  15940. */
  15941. ItemSet.prototype._order = function () {
  15942. // reorder the items in all groups
  15943. // TODO: optimization: only reorder groups affected by the changed items
  15944. util.forEach(this.groups, function (group) {
  15945. group.order();
  15946. });
  15947. };
  15948. /**
  15949. * Handle updated groups
  15950. * @param {number[]} ids
  15951. * @private
  15952. */
  15953. ItemSet.prototype._onUpdateGroups = function (ids) {
  15954. this._onAddGroups(ids);
  15955. };
  15956. /**
  15957. * Handle changed groups (added or updated)
  15958. * @param {number[]} ids
  15959. * @private
  15960. */
  15961. ItemSet.prototype._onAddGroups = function (ids) {
  15962. var me = this;
  15963. ids.forEach(function (id) {
  15964. var groupData = me.groupsData.get(id);
  15965. var group = me.groups[id];
  15966. if (!group) {
  15967. // check for reserved ids
  15968. if (id == UNGROUPED || id == BACKGROUND) {
  15969. throw new Error('Illegal group id. ' + id + ' is a reserved id.');
  15970. }
  15971. var groupOptions = (0, _create2['default'])(me.options);
  15972. util.extend(groupOptions, {
  15973. height: null
  15974. });
  15975. group = new Group(id, groupData, me);
  15976. me.groups[id] = group;
  15977. // add items with this groupId to the new group
  15978. for (var itemId in me.items) {
  15979. if (me.items.hasOwnProperty(itemId)) {
  15980. var item = me.items[itemId];
  15981. if (item.data.group == id) {
  15982. group.add(item);
  15983. }
  15984. }
  15985. }
  15986. group.order();
  15987. group.show();
  15988. } else {
  15989. // update group
  15990. group.setData(groupData);
  15991. }
  15992. });
  15993. this.body.emitter.emit('_change', { queue: true });
  15994. };
  15995. /**
  15996. * Handle removed groups
  15997. * @param {number[]} ids
  15998. * @private
  15999. */
  16000. ItemSet.prototype._onRemoveGroups = function (ids) {
  16001. var groups = this.groups;
  16002. ids.forEach(function (id) {
  16003. var group = groups[id];
  16004. if (group) {
  16005. group.hide();
  16006. delete groups[id];
  16007. }
  16008. });
  16009. this.markDirty();
  16010. this.body.emitter.emit('_change', { queue: true });
  16011. };
  16012. /**
  16013. * Reorder the groups if needed
  16014. * @return {boolean} changed
  16015. * @private
  16016. */
  16017. ItemSet.prototype._orderGroups = function () {
  16018. if (this.groupsData) {
  16019. // reorder the groups
  16020. var groupIds = this.groupsData.getIds({
  16021. order: this.options.groupOrder
  16022. });
  16023. groupIds = this._orderNestedGroups(groupIds);
  16024. var changed = !util.equalArray(groupIds, this.groupIds);
  16025. if (changed) {
  16026. // hide all groups, removes them from the DOM
  16027. var groups = this.groups;
  16028. groupIds.forEach(function (groupId) {
  16029. groups[groupId].hide();
  16030. });
  16031. // show the groups again, attach them to the DOM in correct order
  16032. groupIds.forEach(function (groupId) {
  16033. groups[groupId].show();
  16034. });
  16035. this.groupIds = groupIds;
  16036. }
  16037. return changed;
  16038. } else {
  16039. return false;
  16040. }
  16041. };
  16042. /**
  16043. * Reorder the nested groups
  16044. *
  16045. * @param {Array.<number>} groupIds
  16046. * @returns {Array.<number>}
  16047. * @private
  16048. */
  16049. ItemSet.prototype._orderNestedGroups = function (groupIds) {
  16050. var newGroupIdsOrder = [];
  16051. groupIds.forEach(function (groupId) {
  16052. var groupData = this.groupsData.get(groupId);
  16053. if (!groupData.nestedInGroup) {
  16054. newGroupIdsOrder.push(groupId);
  16055. }
  16056. if (groupData.nestedGroups) {
  16057. var nestedGroups = this.groupsData.get({
  16058. filter: function filter(nestedGroup) {
  16059. return nestedGroup.nestedInGroup == groupId;
  16060. },
  16061. order: this.options.groupOrder
  16062. });
  16063. var nestedGroupIds = nestedGroups.map(function (nestedGroup) {
  16064. return nestedGroup.id;
  16065. });
  16066. newGroupIdsOrder = newGroupIdsOrder.concat(nestedGroupIds);
  16067. }
  16068. }, this);
  16069. return newGroupIdsOrder;
  16070. };
  16071. /**
  16072. * Add a new item
  16073. * @param {Item} item
  16074. * @private
  16075. */
  16076. ItemSet.prototype._addItem = function (item) {
  16077. this.items[item.id] = item;
  16078. // add to group
  16079. var groupId = this._getGroupId(item.data);
  16080. var group = this.groups[groupId];
  16081. if (!group) {
  16082. item.groupShowing = false;
  16083. } else if (group && group.data && group.data.showNested) {
  16084. item.groupShowing = true;
  16085. }
  16086. if (group) group.add(item);
  16087. };
  16088. /**
  16089. * Update an existing item
  16090. * @param {Item} item
  16091. * @param {Object} itemData
  16092. * @private
  16093. */
  16094. ItemSet.prototype._updateItem = function (item, itemData) {
  16095. // update the items data (will redraw the item when displayed)
  16096. item.setData(itemData);
  16097. var groupId = this._getGroupId(item.data);
  16098. var group = this.groups[groupId];
  16099. if (!group) {
  16100. item.groupShowing = false;
  16101. } else if (group && group.data && group.data.showNested) {
  16102. item.groupShowing = true;
  16103. }
  16104. };
  16105. /**
  16106. * Delete an item from the ItemSet: remove it from the DOM, from the map
  16107. * with items, and from the map with visible items, and from the selection
  16108. * @param {Item} item
  16109. * @private
  16110. */
  16111. ItemSet.prototype._removeItem = function (item) {
  16112. // remove from DOM
  16113. item.hide();
  16114. // remove from items
  16115. delete this.items[item.id];
  16116. // remove from selection
  16117. var index = this.selection.indexOf(item.id);
  16118. if (index != -1) this.selection.splice(index, 1);
  16119. // remove from group
  16120. item.parent && item.parent.remove(item);
  16121. };
  16122. /**
  16123. * Create an array containing all items being a range (having an end date)
  16124. * @param {Array.<Object>} array
  16125. * @returns {Array}
  16126. * @private
  16127. */
  16128. ItemSet.prototype._constructByEndArray = function (array) {
  16129. var endArray = [];
  16130. for (var i = 0; i < array.length; i++) {
  16131. if (array[i] instanceof RangeItem) {
  16132. endArray.push(array[i]);
  16133. }
  16134. }
  16135. return endArray;
  16136. };
  16137. /**
  16138. * Register the clicked item on touch, before dragStart is initiated.
  16139. *
  16140. * dragStart is initiated from a mousemove event, AFTER the mouse/touch is
  16141. * already moving. Therefore, the mouse/touch can sometimes be above an other
  16142. * DOM element than the item itself.
  16143. *
  16144. * @param {Event} event
  16145. * @private
  16146. */
  16147. ItemSet.prototype._onTouch = function (event) {
  16148. // store the touched item, used in _onDragStart
  16149. this.touchParams.item = this.itemFromTarget(event);
  16150. this.touchParams.dragLeftItem = event.target.dragLeftItem || false;
  16151. this.touchParams.dragRightItem = event.target.dragRightItem || false;
  16152. this.touchParams.itemProps = null;
  16153. };
  16154. /**
  16155. * Given an group id, returns the index it has.
  16156. *
  16157. * @param {number} groupId
  16158. * @returns {number} index / groupId
  16159. * @private
  16160. */
  16161. ItemSet.prototype._getGroupIndex = function (groupId) {
  16162. for (var i = 0; i < this.groupIds.length; i++) {
  16163. if (groupId == this.groupIds[i]) return i;
  16164. }
  16165. };
  16166. /**
  16167. * Start dragging the selected events
  16168. * @param {Event} event
  16169. * @private
  16170. */
  16171. ItemSet.prototype._onDragStart = function (event) {
  16172. if (this.touchParams.itemIsDragging) {
  16173. return;
  16174. }
  16175. var item = this.touchParams.item || null;
  16176. var me = this;
  16177. var props;
  16178. if (item && (item.selected || this.options.itemsAlwaysDraggable.item)) {
  16179. if (this.options.editable.overrideItems && !this.options.editable.updateTime && !this.options.editable.updateGroup) {
  16180. return;
  16181. }
  16182. // override options.editable
  16183. if (item.editable != null && !item.editable.updateTime && !item.editable.updateGroup && !this.options.editable.overrideItems) {
  16184. return;
  16185. }
  16186. var dragLeftItem = this.touchParams.dragLeftItem;
  16187. var dragRightItem = this.touchParams.dragRightItem;
  16188. this.touchParams.itemIsDragging = true;
  16189. this.touchParams.selectedItem = item;
  16190. if (dragLeftItem) {
  16191. props = {
  16192. item: dragLeftItem,
  16193. initialX: event.center.x,
  16194. dragLeft: true,
  16195. data: this._cloneItemData(item.data)
  16196. };
  16197. this.touchParams.itemProps = [props];
  16198. } else if (dragRightItem) {
  16199. props = {
  16200. item: dragRightItem,
  16201. initialX: event.center.x,
  16202. dragRight: true,
  16203. data: this._cloneItemData(item.data)
  16204. };
  16205. this.touchParams.itemProps = [props];
  16206. } else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  16207. // create a new range item when dragging with ctrl key down
  16208. this._onDragStartAddItem(event);
  16209. } else {
  16210. if (this.groupIds.length < 1) {
  16211. // Mitigates a race condition if _onDragStart() is
  16212. // called after markDirty() without redraw() being called between.
  16213. this.redraw();
  16214. }
  16215. var baseGroupIndex = this._getGroupIndex(item.data.group);
  16216. var itemsToDrag = this.options.itemsAlwaysDraggable.item && !item.selected ? [item.id] : this.getSelection();
  16217. this.touchParams.itemProps = itemsToDrag.map(function (id) {
  16218. var item = me.items[id];
  16219. var groupIndex = me._getGroupIndex(item.data.group);
  16220. return {
  16221. item: item,
  16222. initialX: event.center.x,
  16223. groupOffset: baseGroupIndex - groupIndex,
  16224. data: this._cloneItemData(item.data)
  16225. };
  16226. }.bind(this));
  16227. }
  16228. event.stopPropagation();
  16229. } else if (this.options.editable.add && (event.srcEvent.ctrlKey || event.srcEvent.metaKey)) {
  16230. // create a new range item when dragging with ctrl key down
  16231. this._onDragStartAddItem(event);
  16232. }
  16233. };
  16234. /**
  16235. * Start creating a new range item by dragging.
  16236. * @param {Event} event
  16237. * @private
  16238. */
  16239. ItemSet.prototype._onDragStartAddItem = function (event) {
  16240. var xAbs;
  16241. var x;
  16242. var snap = this.options.snap || null;
  16243. if (this.options.rtl) {
  16244. xAbs = util.getAbsoluteRight(this.dom.frame);
  16245. x = xAbs - event.center.x + 10; // plus 10 to compensate for the drag starting as soon as you've moved 10px
  16246. } else {
  16247. xAbs = util.getAbsoluteLeft(this.dom.frame);
  16248. x = event.center.x - xAbs - 10; // minus 10 to compensate for the drag starting as soon as you've moved 10px
  16249. }
  16250. var time = this.body.util.toTime(x);
  16251. var scale = this.body.util.getScale();
  16252. var step = this.body.util.getStep();
  16253. var start = snap ? snap(time, scale, step) : time;
  16254. var end = start;
  16255. var itemData = {
  16256. type: 'range',
  16257. start: start,
  16258. end: end,
  16259. content: 'new item'
  16260. };
  16261. var id = util.randomUUID();
  16262. itemData[this.itemsData._fieldId] = id;
  16263. var group = this.groupFromTarget(event);
  16264. if (group) {
  16265. itemData.group = group.groupId;
  16266. }
  16267. var newItem = new RangeItem(itemData, this.conversion, this.options);
  16268. newItem.id = id; // TODO: not so nice setting id afterwards
  16269. newItem.data = this._cloneItemData(itemData);
  16270. this._addItem(newItem);
  16271. this.touchParams.selectedItem = newItem;
  16272. var props = {
  16273. item: newItem,
  16274. initialX: event.center.x,
  16275. data: newItem.data
  16276. };
  16277. if (this.options.rtl) {
  16278. props.dragLeft = true;
  16279. } else {
  16280. props.dragRight = true;
  16281. }
  16282. this.touchParams.itemProps = [props];
  16283. event.stopPropagation();
  16284. };
  16285. /**
  16286. * Drag selected items
  16287. * @param {Event} event
  16288. * @private
  16289. */
  16290. ItemSet.prototype._onDrag = function (event) {
  16291. if (this.touchParams.itemProps) {
  16292. event.stopPropagation();
  16293. var me = this;
  16294. var snap = this.options.snap || null;
  16295. var xOffset;
  16296. if (this.options.rtl) {
  16297. xOffset = this.body.dom.root.offsetLeft + this.body.domProps.right.width;
  16298. } else {
  16299. xOffset = this.body.dom.root.offsetLeft + this.body.domProps.left.width;
  16300. }
  16301. var scale = this.body.util.getScale();
  16302. var step = this.body.util.getStep();
  16303. //only calculate the new group for the item that's actually dragged
  16304. var selectedItem = this.touchParams.selectedItem;
  16305. var updateGroupAllowed = (this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateGroup || !this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateGroup;
  16306. var newGroupBase = null;
  16307. if (updateGroupAllowed && selectedItem) {
  16308. if (selectedItem.data.group != undefined) {
  16309. // drag from one group to another
  16310. var group = me.groupFromTarget(event);
  16311. if (group) {
  16312. //we know the offset for all items, so the new group for all items
  16313. //will be relative to this one.
  16314. newGroupBase = this._getGroupIndex(group.groupId);
  16315. }
  16316. }
  16317. }
  16318. // move
  16319. this.touchParams.itemProps.forEach(function (props) {
  16320. var current = me.body.util.toTime(event.center.x - xOffset);
  16321. var initial = me.body.util.toTime(props.initialX - xOffset);
  16322. var offset;
  16323. var initialStart;
  16324. var initialEnd;
  16325. var start;
  16326. var end;
  16327. if (this.options.rtl) {
  16328. offset = -(current - initial); // ms
  16329. } else {
  16330. offset = current - initial; // ms
  16331. }
  16332. var itemData = this._cloneItemData(props.item.data); // clone the data
  16333. if (props.item.editable != null && !props.item.editable.updateTime && !props.item.editable.updateGroup && !me.options.editable.overrideItems) {
  16334. return;
  16335. }
  16336. var updateTimeAllowed = (this.options.editable.overrideItems || selectedItem.editable == null) && this.options.editable.updateTime || !this.options.editable.overrideItems && selectedItem.editable != null && selectedItem.editable.updateTime;
  16337. if (updateTimeAllowed) {
  16338. if (props.dragLeft) {
  16339. // drag left side of a range item
  16340. if (this.options.rtl) {
  16341. if (itemData.end != undefined) {
  16342. initialEnd = util.convert(props.data.end, 'Date');
  16343. end = new Date(initialEnd.valueOf() + offset);
  16344. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  16345. itemData.end = snap ? snap(end, scale, step) : end;
  16346. }
  16347. } else {
  16348. if (itemData.start != undefined) {
  16349. initialStart = util.convert(props.data.start, 'Date');
  16350. start = new Date(initialStart.valueOf() + offset);
  16351. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  16352. itemData.start = snap ? snap(start, scale, step) : start;
  16353. }
  16354. }
  16355. } else if (props.dragRight) {
  16356. // drag right side of a range item
  16357. if (this.options.rtl) {
  16358. if (itemData.start != undefined) {
  16359. initialStart = util.convert(props.data.start, 'Date');
  16360. start = new Date(initialStart.valueOf() + offset);
  16361. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  16362. itemData.start = snap ? snap(start, scale, step) : start;
  16363. }
  16364. } else {
  16365. if (itemData.end != undefined) {
  16366. initialEnd = util.convert(props.data.end, 'Date');
  16367. end = new Date(initialEnd.valueOf() + offset);
  16368. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  16369. itemData.end = snap ? snap(end, scale, step) : end;
  16370. }
  16371. }
  16372. } else {
  16373. // drag both start and end
  16374. if (itemData.start != undefined) {
  16375. initialStart = util.convert(props.data.start, 'Date').valueOf();
  16376. start = new Date(initialStart + offset);
  16377. if (itemData.end != undefined) {
  16378. initialEnd = util.convert(props.data.end, 'Date');
  16379. var duration = initialEnd.valueOf() - initialStart.valueOf();
  16380. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  16381. itemData.start = snap ? snap(start, scale, step) : start;
  16382. itemData.end = new Date(itemData.start.valueOf() + duration);
  16383. } else {
  16384. // TODO: pass a Moment instead of a Date to snap(). (Breaking change)
  16385. itemData.start = snap ? snap(start, scale, step) : start;
  16386. }
  16387. }
  16388. }
  16389. }
  16390. if (updateGroupAllowed && !props.dragLeft && !props.dragRight && newGroupBase != null) {
  16391. if (itemData.group != undefined) {
  16392. var newOffset = newGroupBase - props.groupOffset;
  16393. //make sure we stay in bounds
  16394. newOffset = Math.max(0, newOffset);
  16395. newOffset = Math.min(me.groupIds.length - 1, newOffset);
  16396. itemData.group = me.groupIds[newOffset];
  16397. }
  16398. }
  16399. // confirm moving the item
  16400. itemData = this._cloneItemData(itemData); // convert start and end to the correct type
  16401. me.options.onMoving(itemData, function (itemData) {
  16402. if (itemData) {
  16403. props.item.setData(this._cloneItemData(itemData, 'Date'));
  16404. }
  16405. }.bind(this));
  16406. }.bind(this));
  16407. this.body.emitter.emit('_change');
  16408. }
  16409. };
  16410. /**
  16411. * Move an item to another group
  16412. * @param {Item} item
  16413. * @param {string | number} groupId
  16414. * @private
  16415. */
  16416. ItemSet.prototype._moveToGroup = function (item, groupId) {
  16417. var group = this.groups[groupId];
  16418. if (group && group.groupId != item.data.group) {
  16419. var oldGroup = item.parent;
  16420. oldGroup.remove(item);
  16421. oldGroup.order();
  16422. item.data.group = group.groupId;
  16423. group.add(item);
  16424. group.order();
  16425. }
  16426. };
  16427. /**
  16428. * End of dragging selected items
  16429. * @param {Event} event
  16430. * @private
  16431. */
  16432. ItemSet.prototype._onDragEnd = function (event) {
  16433. this.touchParams.itemIsDragging = false;
  16434. if (this.touchParams.itemProps) {
  16435. event.stopPropagation();
  16436. var me = this;
  16437. var dataset = this.itemsData.getDataSet();
  16438. var itemProps = this.touchParams.itemProps;
  16439. this.touchParams.itemProps = null;
  16440. itemProps.forEach(function (props) {
  16441. var id = props.item.id;
  16442. var exists = me.itemsData.get(id, me.itemOptions) != null;
  16443. if (!exists) {
  16444. // add a new item
  16445. me.options.onAdd(props.item.data, function (itemData) {
  16446. me._removeItem(props.item); // remove temporary item
  16447. if (itemData) {
  16448. me.itemsData.getDataSet().add(itemData);
  16449. }
  16450. // force re-stacking of all items next redraw
  16451. me.body.emitter.emit('_change');
  16452. });
  16453. } else {
  16454. // update existing item
  16455. var itemData = this._cloneItemData(props.item.data); // convert start and end to the correct type
  16456. me.options.onMove(itemData, function (itemData) {
  16457. if (itemData) {
  16458. // apply changes
  16459. itemData[dataset._fieldId] = id; // ensure the item contains its id (can be undefined)
  16460. dataset.update(itemData);
  16461. } else {
  16462. // restore original values
  16463. props.item.setData(props.data);
  16464. me.body.emitter.emit('_change');
  16465. }
  16466. });
  16467. }
  16468. }.bind(this));
  16469. }
  16470. };
  16471. ItemSet.prototype._onGroupClick = function (event) {
  16472. var group = this.groupFromTarget(event);
  16473. if (!group || !group.nestedGroups) return;
  16474. var groupsData = this.groupsData.getDataSet();
  16475. var nestingGroup = groupsData.get(group.groupId);
  16476. if (nestingGroup.showNested == undefined) {
  16477. nestingGroup.showNested = true;
  16478. }
  16479. nestingGroup.showNested = !nestingGroup.showNested;
  16480. var nestedGroups = groupsData.get(group.nestedGroups).map(function (nestedGroup) {
  16481. nestedGroup.visible = nestingGroup.showNested;
  16482. return nestedGroup;
  16483. });
  16484. groupsData.update(nestedGroups.concat(nestingGroup));
  16485. if (nestingGroup.showNested) {
  16486. util.removeClassName(group.dom.label, 'collapsed');
  16487. util.addClassName(group.dom.label, 'expanded');
  16488. } else {
  16489. util.removeClassName(group.dom.label, 'expanded');
  16490. var collapsedDirClassName = this.options.rtl ? 'collapsed-rtl' : 'collapsed';
  16491. util.addClassName(group.dom.label, collapsedDirClassName);
  16492. }
  16493. };
  16494. ItemSet.prototype._onGroupDragStart = function (event) {
  16495. if (this.options.groupEditable.order) {
  16496. this.groupTouchParams.group = this.groupFromTarget(event);
  16497. if (this.groupTouchParams.group) {
  16498. event.stopPropagation();
  16499. this.groupTouchParams.originalOrder = this.groupsData.getIds({
  16500. order: this.options.groupOrder
  16501. });
  16502. }
  16503. }
  16504. };
  16505. ItemSet.prototype._onGroupDrag = function (event) {
  16506. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  16507. event.stopPropagation();
  16508. var groupsData = this.groupsData;
  16509. if (this.groupsData instanceof DataView) {
  16510. groupsData = this.groupsData.getDataSet();
  16511. }
  16512. // drag from one group to another
  16513. var group = this.groupFromTarget(event);
  16514. // try to avoid toggling when groups differ in height
  16515. if (group && group.height != this.groupTouchParams.group.height) {
  16516. var movingUp = group.top < this.groupTouchParams.group.top;
  16517. var clientY = event.center ? event.center.y : event.clientY;
  16518. var targetGroupTop = util.getAbsoluteTop(group.dom.foreground);
  16519. var draggedGroupHeight = this.groupTouchParams.group.height;
  16520. if (movingUp) {
  16521. // skip swapping the groups when the dragged group is not below clientY afterwards
  16522. if (targetGroupTop + draggedGroupHeight < clientY) {
  16523. return;
  16524. }
  16525. } else {
  16526. var targetGroupHeight = group.height;
  16527. // skip swapping the groups when the dragged group is not below clientY afterwards
  16528. if (targetGroupTop + targetGroupHeight - draggedGroupHeight > clientY) {
  16529. return;
  16530. }
  16531. }
  16532. }
  16533. if (group && group != this.groupTouchParams.group) {
  16534. var targetGroup = groupsData.get(group.groupId);
  16535. var draggedGroup = groupsData.get(this.groupTouchParams.group.groupId);
  16536. // switch groups
  16537. if (draggedGroup && targetGroup) {
  16538. this.options.groupOrderSwap(draggedGroup, targetGroup, groupsData);
  16539. groupsData.update(draggedGroup);
  16540. groupsData.update(targetGroup);
  16541. }
  16542. // fetch current order of groups
  16543. var newOrder = groupsData.getIds({
  16544. order: this.options.groupOrder
  16545. });
  16546. // in case of changes since _onGroupDragStart
  16547. if (!util.equalArray(newOrder, this.groupTouchParams.originalOrder)) {
  16548. var origOrder = this.groupTouchParams.originalOrder;
  16549. var draggedId = this.groupTouchParams.group.groupId;
  16550. var numGroups = Math.min(origOrder.length, newOrder.length);
  16551. var curPos = 0;
  16552. var newOffset = 0;
  16553. var orgOffset = 0;
  16554. while (curPos < numGroups) {
  16555. // as long as the groups are where they should be step down along the groups order
  16556. while (curPos + newOffset < numGroups && curPos + orgOffset < numGroups && newOrder[curPos + newOffset] == origOrder[curPos + orgOffset]) {
  16557. curPos++;
  16558. }
  16559. // all ok
  16560. if (curPos + newOffset >= numGroups) {
  16561. break;
  16562. }
  16563. // not all ok
  16564. // if dragged group was move upwards everything below should have an offset
  16565. if (newOrder[curPos + newOffset] == draggedId) {
  16566. newOffset = 1;
  16567. }
  16568. // if dragged group was move downwards everything above should have an offset
  16569. else if (origOrder[curPos + orgOffset] == draggedId) {
  16570. orgOffset = 1;
  16571. }
  16572. // found a group (apart from dragged group) that has the wrong position -> switch with the
  16573. // group at the position where other one should be, fix index arrays and continue
  16574. else {
  16575. var slippedPosition = newOrder.indexOf(origOrder[curPos + orgOffset]);
  16576. var switchGroup = groupsData.get(newOrder[curPos + newOffset]);
  16577. var shouldBeGroup = groupsData.get(origOrder[curPos + orgOffset]);
  16578. this.options.groupOrderSwap(switchGroup, shouldBeGroup, groupsData);
  16579. groupsData.update(switchGroup);
  16580. groupsData.update(shouldBeGroup);
  16581. var switchGroupId = newOrder[curPos + newOffset];
  16582. newOrder[curPos + newOffset] = origOrder[curPos + orgOffset];
  16583. newOrder[slippedPosition] = switchGroupId;
  16584. curPos++;
  16585. }
  16586. }
  16587. }
  16588. }
  16589. }
  16590. };
  16591. ItemSet.prototype._onGroupDragEnd = function (event) {
  16592. if (this.options.groupEditable.order && this.groupTouchParams.group) {
  16593. event.stopPropagation();
  16594. // update existing group
  16595. var me = this;
  16596. var id = me.groupTouchParams.group.groupId;
  16597. var dataset = me.groupsData.getDataSet();
  16598. var groupData = util.extend({}, dataset.get(id)); // clone the data
  16599. me.options.onMoveGroup(groupData, function (groupData) {
  16600. if (groupData) {
  16601. // apply changes
  16602. groupData[dataset._fieldId] = id; // ensure the group contains its id (can be undefined)
  16603. dataset.update(groupData);
  16604. } else {
  16605. // fetch current order of groups
  16606. var newOrder = dataset.getIds({
  16607. order: me.options.groupOrder
  16608. });
  16609. // restore original order
  16610. if (!util.equalArray(newOrder, me.groupTouchParams.originalOrder)) {
  16611. var origOrder = me.groupTouchParams.originalOrder;
  16612. var numGroups = Math.min(origOrder.length, newOrder.length);
  16613. var curPos = 0;
  16614. while (curPos < numGroups) {
  16615. // as long as the groups are where they should be step down along the groups order
  16616. while (curPos < numGroups && newOrder[curPos] == origOrder[curPos]) {
  16617. curPos++;
  16618. }
  16619. // all ok
  16620. if (curPos >= numGroups) {
  16621. break;
  16622. }
  16623. // found a group that has the wrong position -> switch with the
  16624. // group at the position where other one should be, fix index arrays and continue
  16625. var slippedPosition = newOrder.indexOf(origOrder[curPos]);
  16626. var switchGroup = dataset.get(newOrder[curPos]);
  16627. var shouldBeGroup = dataset.get(origOrder[curPos]);
  16628. me.options.groupOrderSwap(switchGroup, shouldBeGroup, dataset);
  16629. dataset.update(switchGroup);
  16630. dataset.update(shouldBeGroup);
  16631. var switchGroupId = newOrder[curPos];
  16632. newOrder[curPos] = origOrder[curPos];
  16633. newOrder[slippedPosition] = switchGroupId;
  16634. curPos++;
  16635. }
  16636. }
  16637. }
  16638. });
  16639. me.body.emitter.emit('groupDragged', { groupId: id });
  16640. }
  16641. };
  16642. /**
  16643. * Handle selecting/deselecting an item when tapping it
  16644. * @param {Event} event
  16645. * @private
  16646. */
  16647. ItemSet.prototype._onSelectItem = function (event) {
  16648. if (!this.options.selectable) return;
  16649. var ctrlKey = event.srcEvent && (event.srcEvent.ctrlKey || event.srcEvent.metaKey);
  16650. var shiftKey = event.srcEvent && event.srcEvent.shiftKey;
  16651. if (ctrlKey || shiftKey) {
  16652. this._onMultiSelectItem(event);
  16653. return;
  16654. }
  16655. var oldSelection = this.getSelection();
  16656. var item = this.itemFromTarget(event);
  16657. var selection = item ? [item.id] : [];
  16658. this.setSelection(selection);
  16659. var newSelection = this.getSelection();
  16660. // emit a select event,
  16661. // except when old selection is empty and new selection is still empty
  16662. if (newSelection.length > 0 || oldSelection.length > 0) {
  16663. this.body.emitter.emit('select', {
  16664. items: newSelection,
  16665. event: event
  16666. });
  16667. }
  16668. };
  16669. /**
  16670. * Handle hovering an item
  16671. * @param {Event} event
  16672. * @private
  16673. */
  16674. ItemSet.prototype._onMouseOver = function (event) {
  16675. var item = this.itemFromTarget(event);
  16676. if (!item) return;
  16677. // Item we just left
  16678. var related = this.itemFromRelatedTarget(event);
  16679. if (item === related) {
  16680. // We haven't changed item, just element in the item
  16681. return;
  16682. }
  16683. var title = item.getTitle();
  16684. if (this.options.showTooltips && title) {
  16685. if (this.popup == null) {
  16686. this.popup = new Popup(this.body.dom.root, this.options.tooltip.overflowMethod || 'flip');
  16687. }
  16688. this.popup.setText(title);
  16689. var container = this.body.dom.centerContainer;
  16690. this.popup.setPosition(event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft, event.clientY - util.getAbsoluteTop(container) + container.offsetTop);
  16691. this.popup.show();
  16692. } else {
  16693. // Hovering over item without a title, hide popup
  16694. // Needed instead of _just_ in _onMouseOut due to #2572
  16695. if (this.popup != null) {
  16696. this.popup.hide();
  16697. }
  16698. }
  16699. this.body.emitter.emit('itemover', {
  16700. item: item.id,
  16701. event: event
  16702. });
  16703. };
  16704. ItemSet.prototype._onMouseOut = function (event) {
  16705. var item = this.itemFromTarget(event);
  16706. if (!item) return;
  16707. // Item we are going to
  16708. var related = this.itemFromRelatedTarget(event);
  16709. if (item === related) {
  16710. // We aren't changing item, just element in the item
  16711. return;
  16712. }
  16713. if (this.popup != null) {
  16714. this.popup.hide();
  16715. }
  16716. this.body.emitter.emit('itemout', {
  16717. item: item.id,
  16718. event: event
  16719. });
  16720. };
  16721. ItemSet.prototype._onMouseMove = function (event) {
  16722. var item = this.itemFromTarget(event);
  16723. if (!item) return;
  16724. if (this.options.showTooltips && this.options.tooltip.followMouse) {
  16725. if (this.popup) {
  16726. if (!this.popup.hidden) {
  16727. var container = this.body.dom.centerContainer;
  16728. this.popup.setPosition(event.clientX - util.getAbsoluteLeft(container) + container.offsetLeft, event.clientY - util.getAbsoluteTop(container) + container.offsetTop);
  16729. this.popup.show(); // Redraw
  16730. }
  16731. }
  16732. }
  16733. };
  16734. /**
  16735. * Handle mousewheel
  16736. * @param {Event} event The event
  16737. * @private
  16738. */
  16739. ItemSet.prototype._onMouseWheel = function (event) {
  16740. if (this.touchParams.itemIsDragging) {
  16741. this._onDragEnd(event);
  16742. }
  16743. };
  16744. /**
  16745. * Handle updates of an item on double tap
  16746. * @param {vis.Item} item The item
  16747. * @private
  16748. */
  16749. ItemSet.prototype._onUpdateItem = function (item) {
  16750. if (!this.options.selectable) return;
  16751. if (!this.options.editable.add) return;
  16752. var me = this;
  16753. if (item) {
  16754. // execute async handler to update the item (or cancel it)
  16755. var itemData = me.itemsData.get(item.id); // get a clone of the data from the dataset
  16756. this.options.onUpdate(itemData, function (itemData) {
  16757. if (itemData) {
  16758. me.itemsData.getDataSet().update(itemData);
  16759. }
  16760. });
  16761. }
  16762. };
  16763. /**
  16764. * Handle drop event of data on item
  16765. * Only called when `objectData.target === 'item'.
  16766. * @param {Event} event The event
  16767. * @private
  16768. */
  16769. ItemSet.prototype._onDropObjectOnItem = function (event) {
  16770. var item = this.itemFromTarget(event);
  16771. var objectData = JSON.parse(event.dataTransfer.getData("text"));
  16772. this.options.onDropObjectOnItem(objectData, item);
  16773. };
  16774. /**
  16775. * Handle creation of an item on double tap or drop of a drag event
  16776. * @param {Event} event The event
  16777. * @private
  16778. */
  16779. ItemSet.prototype._onAddItem = function (event) {
  16780. if (!this.options.selectable) return;
  16781. if (!this.options.editable.add) return;
  16782. var me = this;
  16783. var snap = this.options.snap || null;
  16784. var xAbs;
  16785. var x;
  16786. // add item
  16787. if (this.options.rtl) {
  16788. xAbs = util.getAbsoluteRight(this.dom.frame);
  16789. x = xAbs - event.center.x;
  16790. } else {
  16791. xAbs = util.getAbsoluteLeft(this.dom.frame);
  16792. x = event.center.x - xAbs;
  16793. }
  16794. // var xAbs = util.getAbsoluteLeft(this.dom.frame);
  16795. // var x = event.center.x - xAbs;
  16796. var start = this.body.util.toTime(x);
  16797. var scale = this.body.util.getScale();
  16798. var step = this.body.util.getStep();
  16799. var end;
  16800. var newItemData;
  16801. if (event.type == 'drop') {
  16802. newItemData = JSON.parse(event.dataTransfer.getData("text"));
  16803. newItemData.content = newItemData.content ? newItemData.content : 'new item';
  16804. newItemData.start = newItemData.start ? newItemData.start : snap ? snap(start, scale, step) : start;
  16805. newItemData.type = newItemData.type || 'box';
  16806. newItemData[this.itemsData._fieldId] = newItemData.id || util.randomUUID();
  16807. if (newItemData.type == 'range' && !newItemData.end) {
  16808. end = this.body.util.toTime(x + this.props.width / 5);
  16809. newItemData.end = snap ? snap(end, scale, step) : end;
  16810. }
  16811. } else {
  16812. newItemData = {
  16813. start: snap ? snap(start, scale, step) : start,
  16814. content: 'new item'
  16815. };
  16816. newItemData[this.itemsData._fieldId] = util.randomUUID();
  16817. // when default type is a range, add a default end date to the new item
  16818. if (this.options.type === 'range') {
  16819. end = this.body.util.toTime(x + this.props.width / 5);
  16820. newItemData.end = snap ? snap(end, scale, step) : end;
  16821. }
  16822. }
  16823. var group = this.groupFromTarget(event);
  16824. if (group) {
  16825. newItemData.group = group.groupId;
  16826. }
  16827. // execute async handler to customize (or cancel) adding an item
  16828. newItemData = this._cloneItemData(newItemData); // convert start and end to the correct type
  16829. this.options.onAdd(newItemData, function (item) {
  16830. if (item) {
  16831. me.itemsData.getDataSet().add(item);
  16832. if (event.type == 'drop') {
  16833. me.setSelection([item.id]);
  16834. }
  16835. // TODO: need to trigger a redraw?
  16836. }
  16837. });
  16838. };
  16839. /**
  16840. * Handle selecting/deselecting multiple items when holding an item
  16841. * @param {Event} event
  16842. * @private
  16843. */
  16844. ItemSet.prototype._onMultiSelectItem = function (event) {
  16845. if (!this.options.selectable) return;
  16846. var item = this.itemFromTarget(event);
  16847. if (item) {
  16848. // multi select items (if allowed)
  16849. var selection = this.options.multiselect ? this.getSelection() // take current selection
  16850. : []; // deselect current selection
  16851. var shiftKey = event.srcEvent && event.srcEvent.shiftKey || false;
  16852. if (shiftKey && this.options.multiselect) {
  16853. // select all items between the old selection and the tapped item
  16854. var itemGroup = this.itemsData.get(item.id).group;
  16855. // when filtering get the group of the last selected item
  16856. var lastSelectedGroup = undefined;
  16857. if (this.options.multiselectPerGroup) {
  16858. if (selection.length > 0) {
  16859. lastSelectedGroup = this.itemsData.get(selection[0]).group;
  16860. }
  16861. }
  16862. // determine the selection range
  16863. if (!this.options.multiselectPerGroup || lastSelectedGroup == undefined || lastSelectedGroup == itemGroup) {
  16864. selection.push(item.id);
  16865. }
  16866. var range = ItemSet._getItemRange(this.itemsData.get(selection, this.itemOptions));
  16867. if (!this.options.multiselectPerGroup || lastSelectedGroup == itemGroup) {
  16868. // select all items within the selection range
  16869. selection = [];
  16870. for (var id in this.items) {
  16871. if (this.items.hasOwnProperty(id)) {
  16872. var _item = this.items[id];
  16873. var start = _item.data.start;
  16874. var end = _item.data.end !== undefined ? _item.data.end : start;
  16875. if (start >= range.min && end <= range.max && (!this.options.multiselectPerGroup || lastSelectedGroup == this.itemsData.get(_item.id).group) && !(_item instanceof BackgroundItem)) {
  16876. selection.push(_item.id); // do not use id but item.id, id itself is stringified
  16877. }
  16878. }
  16879. }
  16880. }
  16881. } else {
  16882. // add/remove this item from the current selection
  16883. var index = selection.indexOf(item.id);
  16884. if (index == -1) {
  16885. // item is not yet selected -> select it
  16886. selection.push(item.id);
  16887. } else {
  16888. // item is already selected -> deselect it
  16889. selection.splice(index, 1);
  16890. }
  16891. }
  16892. this.setSelection(selection);
  16893. this.body.emitter.emit('select', {
  16894. items: this.getSelection(),
  16895. event: event
  16896. });
  16897. }
  16898. };
  16899. /**
  16900. * Calculate the time range of a list of items
  16901. * @param {Array.<Object>} itemsData
  16902. * @return {{min: Date, max: Date}} Returns the range of the provided items
  16903. * @private
  16904. */
  16905. ItemSet._getItemRange = function (itemsData) {
  16906. var max = null;
  16907. var min = null;
  16908. itemsData.forEach(function (data) {
  16909. if (min == null || data.start < min) {
  16910. min = data.start;
  16911. }
  16912. if (data.end != undefined) {
  16913. if (max == null || data.end > max) {
  16914. max = data.end;
  16915. }
  16916. } else {
  16917. if (max == null || data.start > max) {
  16918. max = data.start;
  16919. }
  16920. }
  16921. });
  16922. return {
  16923. min: min,
  16924. max: max
  16925. };
  16926. };
  16927. /**
  16928. * Find an item from an element:
  16929. * searches for the attribute 'timeline-item' in the element's tree
  16930. * @param {HTMLElement} element
  16931. * @return {Item | null} item
  16932. */
  16933. ItemSet.prototype.itemFromElement = function (element) {
  16934. var cur = element;
  16935. while (cur) {
  16936. if (cur.hasOwnProperty('timeline-item')) {
  16937. return cur['timeline-item'];
  16938. }
  16939. cur = cur.parentNode;
  16940. }
  16941. return null;
  16942. };
  16943. /**
  16944. * Find an item from an event target:
  16945. * searches for the attribute 'timeline-item' in the event target's element tree
  16946. * @param {Event} event
  16947. * @return {Item | null} item
  16948. */
  16949. ItemSet.prototype.itemFromTarget = function (event) {
  16950. return this.itemFromElement(event.target);
  16951. };
  16952. /**
  16953. * Find an item from an event's related target:
  16954. * searches for the attribute 'timeline-item' in the related target's element tree
  16955. * @param {Event} event
  16956. * @return {Item | null} item
  16957. */
  16958. ItemSet.prototype.itemFromRelatedTarget = function (event) {
  16959. return this.itemFromElement(event.relatedTarget);
  16960. };
  16961. /**
  16962. * Find the Group from an event target:
  16963. * searches for the attribute 'timeline-group' in the event target's element tree
  16964. * @param {Event} event
  16965. * @return {Group | null} group
  16966. */
  16967. ItemSet.prototype.groupFromTarget = function (event) {
  16968. var clientY = event.center ? event.center.y : event.clientY;
  16969. var groupIds = this.groupIds;
  16970. if (groupIds.length <= 0 && this.groupsData) {
  16971. groupIds = this.groupsData.getIds({
  16972. order: this.options.groupOrder
  16973. });
  16974. }
  16975. for (var i = 0; i < groupIds.length; i++) {
  16976. var groupId = groupIds[i];
  16977. var group = this.groups[groupId];
  16978. var foreground = group.dom.foreground;
  16979. var top = util.getAbsoluteTop(foreground);
  16980. if (clientY > top && clientY < top + foreground.offsetHeight) {
  16981. return group;
  16982. }
  16983. if (this.options.orientation.item === 'top') {
  16984. if (i === this.groupIds.length - 1 && clientY > top) {
  16985. return group;
  16986. }
  16987. } else {
  16988. if (i === 0 && clientY < top + foreground.offset) {
  16989. return group;
  16990. }
  16991. }
  16992. }
  16993. return null;
  16994. };
  16995. /**
  16996. * Find the ItemSet from an event target:
  16997. * searches for the attribute 'timeline-itemset' in the event target's element tree
  16998. * @param {Event} event
  16999. * @return {ItemSet | null} item
  17000. */
  17001. ItemSet.itemSetFromTarget = function (event) {
  17002. var target = event.target;
  17003. while (target) {
  17004. if (target.hasOwnProperty('timeline-itemset')) {
  17005. return target['timeline-itemset'];
  17006. }
  17007. target = target.parentNode;
  17008. }
  17009. return null;
  17010. };
  17011. /**
  17012. * Clone the data of an item, and "normalize" it: convert the start and end date
  17013. * to the type (Date, Moment, ...) configured in the DataSet. If not configured,
  17014. * start and end are converted to Date.
  17015. * @param {Object} itemData, typically `item.data`
  17016. * @param {string} [type] Optional Date type. If not provided, the type from the DataSet is taken
  17017. * @return {Object} The cloned object
  17018. * @private
  17019. */
  17020. ItemSet.prototype._cloneItemData = function (itemData, type) {
  17021. var clone = util.extend({}, itemData);
  17022. if (!type) {
  17023. // convert start and end date to the type (Date, Moment, ...) configured in the DataSet
  17024. type = this.itemsData.getDataSet()._options.type;
  17025. }
  17026. if (clone.start != undefined) {
  17027. clone.start = util.convert(clone.start, type && type.start || 'Date');
  17028. }
  17029. if (clone.end != undefined) {
  17030. clone.end = util.convert(clone.end, type && type.end || 'Date');
  17031. }
  17032. return clone;
  17033. };
  17034. module.exports = ItemSet;
  17035. /***/ }),
  17036. /* 100 */
  17037. /***/ (function(module, exports, __webpack_require__) {
  17038. "use strict";
  17039. // Utility functions for ordering and stacking of items
  17040. var EPSILON = 0.001; // used when checking collisions, to prevent round-off errors
  17041. /**
  17042. * Order items by their start data
  17043. * @param {Item[]} items
  17044. */
  17045. exports.orderByStart = function (items) {
  17046. items.sort(function (a, b) {
  17047. return a.data.start - b.data.start;
  17048. });
  17049. };
  17050. /**
  17051. * Order items by their end date. If they have no end date, their start date
  17052. * is used.
  17053. * @param {Item[]} items
  17054. */
  17055. exports.orderByEnd = function (items) {
  17056. items.sort(function (a, b) {
  17057. var aTime = 'end' in a.data ? a.data.end : a.data.start,
  17058. bTime = 'end' in b.data ? b.data.end : b.data.start;
  17059. return aTime - bTime;
  17060. });
  17061. };
  17062. /**
  17063. * Adjust vertical positions of the items such that they don't overlap each
  17064. * other.
  17065. * @param {Item[]} items
  17066. * All visible items
  17067. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  17068. * Margins between items and between items and the axis.
  17069. * @param {boolean} [force=false]
  17070. * If true, all items will be repositioned. If false (default), only
  17071. * items having a top===null will be re-stacked
  17072. */
  17073. exports.stack = function (items, margin, force) {
  17074. if (force) {
  17075. // reset top position of all items
  17076. for (var i = 0; i < items.length; i++) {
  17077. items[i].top = null;
  17078. }
  17079. }
  17080. // calculate new, non-overlapping positions
  17081. for (var i = 0; i < items.length; i++) {
  17082. // eslint-disable-line no-redeclare
  17083. var item = items[i];
  17084. if (item.stack && item.top === null) {
  17085. // initialize top position
  17086. item.top = margin.axis;
  17087. do {
  17088. // TODO: optimize checking for overlap. when there is a gap without items,
  17089. // you only need to check for items from the next item on, not from zero
  17090. var collidingItem = null;
  17091. for (var j = 0, jj = items.length; j < jj; j++) {
  17092. var other = items[j];
  17093. if (other.top !== null && other !== item && other.stack && exports.collision(item, other, margin.item, other.options.rtl)) {
  17094. collidingItem = other;
  17095. break;
  17096. }
  17097. }
  17098. if (collidingItem != null) {
  17099. // There is a collision. Reposition the items above the colliding element
  17100. item.top = collidingItem.top + collidingItem.height + margin.item.vertical;
  17101. }
  17102. } while (collidingItem);
  17103. }
  17104. }
  17105. };
  17106. /**
  17107. * Adjust vertical positions of the items within a single subgroup such that they
  17108. * don't overlap each other.
  17109. * @param {Item[]} items
  17110. * All items withina subgroup
  17111. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  17112. * Margins between items and between items and the axis.
  17113. * @param {subgroup} subgroup
  17114. * The subgroup that is being stacked
  17115. */
  17116. exports.substack = function (items, margin, subgroup) {
  17117. for (var i = 0; i < items.length; i++) {
  17118. items[i].top = null;
  17119. }
  17120. // Set the initial height
  17121. var subgroupHeight = subgroup.height;
  17122. // calculate new, non-overlapping positions
  17123. for (i = 0; i < items.length; i++) {
  17124. var item = items[i];
  17125. if (item.stack && item.top === null) {
  17126. // initialize top position
  17127. item.top = item.baseTop; //margin.axis + item.baseTop;
  17128. do {
  17129. // TODO: optimize checking for overlap. when there is a gap without items,
  17130. // you only need to check for items from the next item on, not from zero
  17131. var collidingItem = null;
  17132. for (var j = 0, jj = items.length; j < jj; j++) {
  17133. var other = items[j];
  17134. if (other.top !== null && other !== item /*&& other.stack*/ && exports.collision(item, other, margin.item, other.options.rtl)) {
  17135. collidingItem = other;
  17136. break;
  17137. }
  17138. }
  17139. if (collidingItem != null) {
  17140. // There is a collision. Reposition the items above the colliding element
  17141. item.top = collidingItem.top + collidingItem.height + margin.item.vertical; // + item.baseTop;
  17142. }
  17143. if (item.top + item.height > subgroupHeight) {
  17144. subgroupHeight = item.top + item.height;
  17145. }
  17146. } while (collidingItem);
  17147. }
  17148. }
  17149. // Set the new height
  17150. subgroup.height = subgroupHeight - subgroup.top + 0.5 * margin.item.vertical;
  17151. };
  17152. /**
  17153. * Adjust vertical positions of the items without stacking them
  17154. * @param {Item[]} items
  17155. * All visible items
  17156. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  17157. * Margins between items and between items and the axis.
  17158. * @param {subgroups[]} subgroups
  17159. * All subgroups
  17160. * @param {boolean} stackSubgroups
  17161. */
  17162. exports.nostack = function (items, margin, subgroups, stackSubgroups) {
  17163. for (var i = 0; i < items.length; i++) {
  17164. if (items[i].data.subgroup == undefined) {
  17165. items[i].top = margin.item.vertical;
  17166. } else if (items[i].data.subgroup !== undefined && stackSubgroups) {
  17167. var newTop = 0;
  17168. for (var subgroup in subgroups) {
  17169. if (subgroups.hasOwnProperty(subgroup)) {
  17170. if (subgroups[subgroup].visible == true && subgroups[subgroup].index < subgroups[items[i].data.subgroup].index) {
  17171. newTop += subgroups[subgroup].height;
  17172. subgroups[items[i].data.subgroup].top = newTop;
  17173. }
  17174. }
  17175. }
  17176. items[i].top = newTop + 0.5 * margin.item.vertical;
  17177. }
  17178. }
  17179. if (!stackSubgroups) {
  17180. exports.stackSubgroups(items, margin, subgroups);
  17181. }
  17182. };
  17183. /**
  17184. * Adjust vertical positions of the subgroups such that they don't overlap each
  17185. * other.
  17186. * @param {Array.<vis.Item>} items
  17187. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin Margins between items and between items and the axis.
  17188. * @param {subgroups[]} subgroups
  17189. * All subgroups
  17190. */
  17191. exports.stackSubgroups = function (items, margin, subgroups) {
  17192. for (var subgroup in subgroups) {
  17193. if (subgroups.hasOwnProperty(subgroup)) {
  17194. subgroups[subgroup].top = 0;
  17195. do {
  17196. // TODO: optimize checking for overlap. when there is a gap without items,
  17197. // you only need to check for items from the next item on, not from zero
  17198. var collidingItem = null;
  17199. for (var otherSubgroup in subgroups) {
  17200. if (subgroups[otherSubgroup].top !== null && otherSubgroup !== subgroup && subgroups[subgroup].index > subgroups[otherSubgroup].index && exports.collisionByTimes(subgroups[subgroup], subgroups[otherSubgroup])) {
  17201. collidingItem = subgroups[otherSubgroup];
  17202. break;
  17203. }
  17204. }
  17205. if (collidingItem != null) {
  17206. // There is a collision. Reposition the subgroups above the colliding element
  17207. subgroups[subgroup].top = collidingItem.top + collidingItem.height;
  17208. }
  17209. } while (collidingItem);
  17210. }
  17211. }
  17212. for (var i = 0; i < items.length; i++) {
  17213. if (items[i].data.subgroup !== undefined) {
  17214. items[i].top = subgroups[items[i].data.subgroup].top + 0.5 * margin.item.vertical;
  17215. }
  17216. }
  17217. };
  17218. /**
  17219. * Adjust vertical positions of the subgroups such that they don't overlap each
  17220. * other, then stacks the contents of each subgroup individually.
  17221. * @param {Item[]} subgroupItems
  17222. * All the items in a subgroup
  17223. * @param {{item: {horizontal: number, vertical: number}, axis: number}} margin
  17224. * Margins between items and between items and the axis.
  17225. * @param {subgroups[]} subgroups
  17226. * All subgroups
  17227. */
  17228. exports.stackSubgroupsWithInnerStack = function (subgroupItems, margin, subgroups) {
  17229. var doSubStack = false;
  17230. // Run subgroups in their order (if any)
  17231. var subgroupOrder = [];
  17232. for (var subgroup in subgroups) {
  17233. if (subgroups[subgroup].hasOwnProperty("index")) {
  17234. subgroupOrder[subgroups[subgroup].index] = subgroup;
  17235. } else {
  17236. subgroupOrder.push(subgroup);
  17237. }
  17238. }
  17239. for (var j = 0; j < subgroupOrder.length; j++) {
  17240. subgroup = subgroupOrder[j];
  17241. if (subgroups.hasOwnProperty(subgroup)) {
  17242. doSubStack = doSubStack || subgroups[subgroup].stack;
  17243. subgroups[subgroup].top = 0;
  17244. for (var otherSubgroup in subgroups) {
  17245. if (subgroups[otherSubgroup].visible && subgroups[subgroup].index > subgroups[otherSubgroup].index) {
  17246. subgroups[subgroup].top += subgroups[otherSubgroup].height;
  17247. }
  17248. }
  17249. var items = subgroupItems[subgroup];
  17250. for (var i = 0; i < items.length; i++) {
  17251. if (items[i].data.subgroup !== undefined) {
  17252. items[i].top = subgroups[items[i].data.subgroup].top + 0.5 * margin.item.vertical;
  17253. if (subgroups[subgroup].stack) {
  17254. items[i].baseTop = items[i].top;
  17255. }
  17256. }
  17257. }
  17258. if (doSubStack && subgroups[subgroup].stack) {
  17259. exports.substack(subgroupItems[subgroup], margin, subgroups[subgroup]);
  17260. }
  17261. }
  17262. }
  17263. };
  17264. /**
  17265. * Test if the two provided items collide
  17266. * The items must have parameters left, width, top, and height.
  17267. * @param {Item} a The first item
  17268. * @param {Item} b The second item
  17269. * @param {{horizontal: number, vertical: number}} margin
  17270. * An object containing a horizontal and vertical
  17271. * minimum required margin.
  17272. * @param {boolean} rtl
  17273. * @return {boolean} true if a and b collide, else false
  17274. */
  17275. exports.collision = function (a, b, margin, rtl) {
  17276. if (rtl) {
  17277. 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;
  17278. } else {
  17279. 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;
  17280. }
  17281. };
  17282. /**
  17283. * Test if the two provided objects collide
  17284. * The objects must have parameters start, end, top, and height.
  17285. * @param {Object} a The first Object
  17286. * @param {Object} b The second Object
  17287. * @return {boolean} true if a and b collide, else false
  17288. */
  17289. exports.collisionByTimes = function (a, b) {
  17290. return a.start <= b.start && a.end >= b.start && a.top < b.top + b.height && a.top + a.height > b.top || b.start <= a.start && b.end >= a.start && b.top < a.top + a.height && b.top + b.height > a.top;
  17291. };
  17292. /***/ }),
  17293. /* 101 */
  17294. /***/ (function(module, exports, __webpack_require__) {
  17295. "use strict";
  17296. var Item = __webpack_require__(38);
  17297. /**
  17298. * @constructor BoxItem
  17299. * @extends Item
  17300. * @param {Object} data Object containing parameters start
  17301. * content, className.
  17302. * @param {{toScreen: function, toTime: function}} conversion
  17303. * Conversion functions from time to screen and vice versa
  17304. * @param {Object} [options] Configuration options
  17305. * // TODO: describe available options
  17306. */
  17307. function BoxItem(data, conversion, options) {
  17308. this.props = {
  17309. dot: {
  17310. width: 0,
  17311. height: 0
  17312. },
  17313. line: {
  17314. width: 0,
  17315. height: 0
  17316. }
  17317. };
  17318. this.options = options;
  17319. // validate data
  17320. if (data) {
  17321. if (data.start == undefined) {
  17322. throw new Error('Property "start" missing in item ' + data);
  17323. }
  17324. }
  17325. Item.call(this, data, conversion, options);
  17326. }
  17327. BoxItem.prototype = new Item(null, null, null);
  17328. /**
  17329. * Check whether this item is visible inside given range
  17330. * @param {{start: number, end: number}} range with a timestamp for start and end
  17331. * @returns {boolean} True if visible
  17332. */
  17333. BoxItem.prototype.isVisible = function (range) {
  17334. // determine visibility
  17335. var isVisible;
  17336. var align = this.options.align;
  17337. var widthInMs = this.width * range.getMillisecondsPerPixel();
  17338. if (align == 'right') {
  17339. isVisible = this.data.start.getTime() > range.start && this.data.start.getTime() - widthInMs < range.end;
  17340. } else if (align == 'left') {
  17341. isVisible = this.data.start.getTime() + widthInMs > range.start && this.data.start.getTime() < range.end;
  17342. } else {
  17343. // default or 'center'
  17344. isVisible = this.data.start.getTime() + widthInMs / 2 > range.start && this.data.start.getTime() - widthInMs / 2 < range.end;
  17345. }
  17346. return isVisible;
  17347. };
  17348. BoxItem.prototype._createDomElement = function () {
  17349. if (!this.dom) {
  17350. // create DOM
  17351. this.dom = {};
  17352. // create main box
  17353. this.dom.box = document.createElement('DIV');
  17354. // contents box (inside the background box). used for making margins
  17355. this.dom.content = document.createElement('DIV');
  17356. this.dom.content.className = 'vis-item-content';
  17357. this.dom.box.appendChild(this.dom.content);
  17358. // line to axis
  17359. this.dom.line = document.createElement('DIV');
  17360. this.dom.line.className = 'vis-line';
  17361. // dot on axis
  17362. this.dom.dot = document.createElement('DIV');
  17363. this.dom.dot.className = 'vis-dot';
  17364. // attach this item as attribute
  17365. this.dom.box['timeline-item'] = this;
  17366. this.dirty = true;
  17367. }
  17368. };
  17369. BoxItem.prototype._appendDomElement = function () {
  17370. if (!this.parent) {
  17371. throw new Error('Cannot redraw item: no parent attached');
  17372. }
  17373. if (!this.dom.box.parentNode) {
  17374. var foreground = this.parent.dom.foreground;
  17375. if (!foreground) throw new Error('Cannot redraw item: parent has no foreground container element');
  17376. foreground.appendChild(this.dom.box);
  17377. }
  17378. if (!this.dom.line.parentNode) {
  17379. var background = this.parent.dom.background;
  17380. if (!background) throw new Error('Cannot redraw item: parent has no background container element');
  17381. background.appendChild(this.dom.line);
  17382. }
  17383. if (!this.dom.dot.parentNode) {
  17384. var axis = this.parent.dom.axis;
  17385. if (!background) throw new Error('Cannot redraw item: parent has no axis container element');
  17386. axis.appendChild(this.dom.dot);
  17387. }
  17388. this.displayed = true;
  17389. };
  17390. BoxItem.prototype._updateDirtyDomComponents = function () {
  17391. // An item is marked dirty when:
  17392. // - the item is not yet rendered
  17393. // - the item's data is changed
  17394. // - the item is selected/deselected
  17395. if (this.dirty) {
  17396. this._updateContents(this.dom.content);
  17397. this._updateDataAttributes(this.dom.box);
  17398. this._updateStyle(this.dom.box);
  17399. var editable = this.editable.updateTime || this.editable.updateGroup;
  17400. // update class
  17401. var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : '') + (editable ? ' vis-editable' : ' vis-readonly');
  17402. this.dom.box.className = 'vis-item vis-box' + className;
  17403. this.dom.line.className = 'vis-item vis-line' + className;
  17404. this.dom.dot.className = 'vis-item vis-dot' + className;
  17405. }
  17406. };
  17407. BoxItem.prototype._getDomComponentsSizes = function () {
  17408. return {
  17409. previous: {
  17410. right: this.dom.box.style.right,
  17411. left: this.dom.box.style.left
  17412. },
  17413. dot: {
  17414. height: this.dom.dot.offsetHeight,
  17415. width: this.dom.dot.offsetWidth
  17416. },
  17417. line: {
  17418. width: this.dom.line.offsetWidth
  17419. },
  17420. box: {
  17421. width: this.dom.box.offsetWidth,
  17422. height: this.dom.box.offsetHeight
  17423. }
  17424. };
  17425. };
  17426. BoxItem.prototype._updateDomComponentsSizes = function (sizes) {
  17427. if (this.options.rtl) {
  17428. this.dom.box.style.right = "0px";
  17429. } else {
  17430. this.dom.box.style.left = "0px";
  17431. }
  17432. // recalculate size
  17433. this.props.dot.height = sizes.dot.height;
  17434. this.props.dot.width = sizes.dot.width;
  17435. this.props.line.width = sizes.line.width;
  17436. this.width = sizes.box.width;
  17437. this.height = sizes.box.height;
  17438. // restore previous position
  17439. if (this.options.rtl) {
  17440. this.dom.box.style.right = sizes.previous.right;
  17441. } else {
  17442. this.dom.box.style.left = sizes.previous.left;
  17443. }
  17444. this.dirty = false;
  17445. };
  17446. BoxItem.prototype._repaintDomAdditionals = function () {
  17447. this._repaintOnItemUpdateTimeTooltip(this.dom.box);
  17448. this._repaintDragCenter();
  17449. this._repaintDeleteButton(this.dom.box);
  17450. };
  17451. /**
  17452. * Repaint the item
  17453. * @param {boolean} [returnQueue=false] return the queue
  17454. * @return {boolean} the redraw queue if returnQueue=true
  17455. */
  17456. BoxItem.prototype.redraw = function (returnQueue) {
  17457. var sizes;
  17458. var queue = [
  17459. // create item DOM
  17460. this._createDomElement.bind(this),
  17461. // append DOM to parent DOM
  17462. this._appendDomElement.bind(this),
  17463. // update dirty DOM
  17464. this._updateDirtyDomComponents.bind(this), function () {
  17465. if (this.dirty) {
  17466. sizes = this._getDomComponentsSizes();
  17467. }
  17468. }.bind(this), function () {
  17469. if (this.dirty) {
  17470. this._updateDomComponentsSizes.bind(this)(sizes);
  17471. }
  17472. }.bind(this),
  17473. // repaint DOM additionals
  17474. this._repaintDomAdditionals.bind(this)];
  17475. if (returnQueue) {
  17476. return queue;
  17477. } else {
  17478. var result;
  17479. queue.forEach(function (fn) {
  17480. result = fn();
  17481. });
  17482. return result;
  17483. }
  17484. };
  17485. /**
  17486. * Show the item in the DOM (when not already displayed). The items DOM will
  17487. * be created when needed.
  17488. */
  17489. BoxItem.prototype.show = function () {
  17490. if (!this.displayed) {
  17491. this.redraw();
  17492. }
  17493. };
  17494. /**
  17495. * Hide the item from the DOM (when visible)
  17496. */
  17497. BoxItem.prototype.hide = function () {
  17498. if (this.displayed) {
  17499. var dom = this.dom;
  17500. if (dom.box.parentNode) dom.box.parentNode.removeChild(dom.box);
  17501. if (dom.line.parentNode) dom.line.parentNode.removeChild(dom.line);
  17502. if (dom.dot.parentNode) dom.dot.parentNode.removeChild(dom.dot);
  17503. this.displayed = false;
  17504. }
  17505. };
  17506. /**
  17507. * Reposition the item horizontally
  17508. * @Override
  17509. */
  17510. BoxItem.prototype.repositionX = function () {
  17511. var start = this.conversion.toScreen(this.data.start);
  17512. var align = this.options.align;
  17513. // calculate left position of the box
  17514. if (align == 'right') {
  17515. if (this.options.rtl) {
  17516. this.right = start - this.width;
  17517. // reposition box, line, and dot
  17518. this.dom.box.style.right = this.right + 'px';
  17519. this.dom.line.style.right = start - this.props.line.width + 'px';
  17520. this.dom.dot.style.right = start - this.props.line.width / 2 - this.props.dot.width / 2 + 'px';
  17521. } else {
  17522. this.left = start - this.width;
  17523. // reposition box, line, and dot
  17524. this.dom.box.style.left = this.left + 'px';
  17525. this.dom.line.style.left = start - this.props.line.width + 'px';
  17526. this.dom.dot.style.left = start - this.props.line.width / 2 - this.props.dot.width / 2 + 'px';
  17527. }
  17528. } else if (align == 'left') {
  17529. if (this.options.rtl) {
  17530. this.right = start;
  17531. // reposition box, line, and dot
  17532. this.dom.box.style.right = this.right + 'px';
  17533. this.dom.line.style.right = start + 'px';
  17534. this.dom.dot.style.right = start + this.props.line.width / 2 - this.props.dot.width / 2 + 'px';
  17535. } else {
  17536. this.left = start;
  17537. // reposition box, line, and dot
  17538. this.dom.box.style.left = this.left + 'px';
  17539. this.dom.line.style.left = start + 'px';
  17540. this.dom.dot.style.left = start + this.props.line.width / 2 - this.props.dot.width / 2 + 'px';
  17541. }
  17542. } else {
  17543. // default or 'center'
  17544. if (this.options.rtl) {
  17545. this.right = start - this.width / 2;
  17546. // reposition box, line, and dot
  17547. this.dom.box.style.right = this.right + 'px';
  17548. this.dom.line.style.right = start - this.props.line.width + 'px';
  17549. this.dom.dot.style.right = start - this.props.dot.width / 2 + 'px';
  17550. } else {
  17551. this.left = start - this.width / 2;
  17552. // reposition box, line, and dot
  17553. this.dom.box.style.left = this.left + 'px';
  17554. this.dom.line.style.left = start - this.props.line.width / 2 + 'px';
  17555. this.dom.dot.style.left = start - this.props.dot.width / 2 + 'px';
  17556. }
  17557. }
  17558. };
  17559. /**
  17560. * Reposition the item vertically
  17561. * @Override
  17562. */
  17563. BoxItem.prototype.repositionY = function () {
  17564. var orientation = this.options.orientation.item;
  17565. var box = this.dom.box;
  17566. var line = this.dom.line;
  17567. var dot = this.dom.dot;
  17568. if (orientation == 'top') {
  17569. box.style.top = (this.top || 0) + 'px';
  17570. line.style.top = '0';
  17571. line.style.height = this.parent.top + this.top + 1 + 'px';
  17572. line.style.bottom = '';
  17573. } else {
  17574. // orientation 'bottom'
  17575. var itemSetHeight = this.parent.itemSet.props.height; // TODO: this is nasty
  17576. var lineHeight = itemSetHeight - this.parent.top - this.parent.height + this.top;
  17577. box.style.top = (this.parent.height - this.top - this.height || 0) + 'px';
  17578. line.style.top = itemSetHeight - lineHeight + 'px';
  17579. line.style.bottom = '0';
  17580. }
  17581. dot.style.top = -this.props.dot.height / 2 + 'px';
  17582. };
  17583. /**
  17584. * Return the width of the item left from its start date
  17585. * @return {number}
  17586. */
  17587. BoxItem.prototype.getWidthLeft = function () {
  17588. return this.width / 2;
  17589. };
  17590. /**
  17591. * Return the width of the item right from its start date
  17592. * @return {number}
  17593. */
  17594. BoxItem.prototype.getWidthRight = function () {
  17595. return this.width / 2;
  17596. };
  17597. module.exports = BoxItem;
  17598. /***/ }),
  17599. /* 102 */
  17600. /***/ (function(module, exports, __webpack_require__) {
  17601. "use strict";
  17602. var Item = __webpack_require__(38);
  17603. /**
  17604. * @constructor PointItem
  17605. * @extends Item
  17606. * @param {Object} data Object containing parameters start
  17607. * content, className.
  17608. * @param {{toScreen: function, toTime: function}} conversion
  17609. * Conversion functions from time to screen and vice versa
  17610. * @param {Object} [options] Configuration options
  17611. * // TODO: describe available options
  17612. */
  17613. function PointItem(data, conversion, options) {
  17614. this.props = {
  17615. dot: {
  17616. top: 0,
  17617. width: 0,
  17618. height: 0
  17619. },
  17620. content: {
  17621. height: 0,
  17622. marginLeft: 0,
  17623. marginRight: 0
  17624. }
  17625. };
  17626. this.options = options;
  17627. // validate data
  17628. if (data) {
  17629. if (data.start == undefined) {
  17630. throw new Error('Property "start" missing in item ' + data);
  17631. }
  17632. }
  17633. Item.call(this, data, conversion, options);
  17634. }
  17635. PointItem.prototype = new Item(null, null, null);
  17636. /**
  17637. * Check whether this item is visible inside given range
  17638. * @param {{start: number, end: number}} range with a timestamp for start and end
  17639. * @returns {boolean} True if visible
  17640. */
  17641. PointItem.prototype.isVisible = function (range) {
  17642. // determine visibility
  17643. var widthInMs = this.width * range.getMillisecondsPerPixel();
  17644. return this.data.start.getTime() + widthInMs > range.start && this.data.start < range.end;
  17645. };
  17646. PointItem.prototype._createDomElement = function () {
  17647. if (!this.dom) {
  17648. // create DOM
  17649. this.dom = {};
  17650. // background box
  17651. this.dom.point = document.createElement('div');
  17652. // className is updated in redraw()
  17653. // contents box, right from the dot
  17654. this.dom.content = document.createElement('div');
  17655. this.dom.content.className = 'vis-item-content';
  17656. this.dom.point.appendChild(this.dom.content);
  17657. // dot at start
  17658. this.dom.dot = document.createElement('div');
  17659. this.dom.point.appendChild(this.dom.dot);
  17660. // attach this item as attribute
  17661. this.dom.point['timeline-item'] = this;
  17662. this.dirty = true;
  17663. }
  17664. };
  17665. PointItem.prototype._appendDomElement = function () {
  17666. if (!this.parent) {
  17667. throw new Error('Cannot redraw item: no parent attached');
  17668. }
  17669. if (!this.dom.point.parentNode) {
  17670. var foreground = this.parent.dom.foreground;
  17671. if (!foreground) {
  17672. throw new Error('Cannot redraw item: parent has no foreground container element');
  17673. }
  17674. foreground.appendChild(this.dom.point);
  17675. }
  17676. this.displayed = true;
  17677. };
  17678. PointItem.prototype._updateDirtyDomComponents = function () {
  17679. // An item is marked dirty when:
  17680. // - the item is not yet rendered
  17681. // - the item's data is changed
  17682. // - the item is selected/deselected
  17683. if (this.dirty) {
  17684. this._updateContents(this.dom.content);
  17685. this._updateDataAttributes(this.dom.point);
  17686. this._updateStyle(this.dom.point);
  17687. var editable = this.editable.updateTime || this.editable.updateGroup;
  17688. // update class
  17689. var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : '') + (editable ? ' vis-editable' : ' vis-readonly');
  17690. this.dom.point.className = 'vis-item vis-point' + className;
  17691. this.dom.dot.className = 'vis-item vis-dot' + className;
  17692. }
  17693. };
  17694. PointItem.prototype._getDomComponentsSizes = function () {
  17695. return {
  17696. dot: {
  17697. width: this.dom.dot.offsetWidth,
  17698. height: this.dom.dot.offsetHeight
  17699. },
  17700. content: {
  17701. width: this.dom.content.offsetWidth,
  17702. height: this.dom.content.offsetHeight
  17703. },
  17704. point: {
  17705. width: this.dom.point.offsetWidth,
  17706. height: this.dom.point.offsetHeight
  17707. }
  17708. };
  17709. };
  17710. PointItem.prototype._updateDomComponentsSizes = function (sizes) {
  17711. // recalculate size of dot and contents
  17712. this.props.dot.width = sizes.dot.width;
  17713. this.props.dot.height = sizes.dot.height;
  17714. this.props.content.height = sizes.content.height;
  17715. // resize contents
  17716. if (this.options.rtl) {
  17717. this.dom.content.style.marginRight = 2 * this.props.dot.width + 'px';
  17718. } else {
  17719. this.dom.content.style.marginLeft = 2 * this.props.dot.width + 'px';
  17720. }
  17721. //this.dom.content.style.marginRight = ... + 'px'; // TODO: margin right
  17722. // recalculate size
  17723. this.width = sizes.point.width;
  17724. this.height = sizes.point.height;
  17725. // reposition the dot
  17726. this.dom.dot.style.top = (this.height - this.props.dot.height) / 2 + 'px';
  17727. if (this.options.rtl) {
  17728. this.dom.dot.style.right = this.props.dot.width / 2 + 'px';
  17729. } else {
  17730. this.dom.dot.style.left = this.props.dot.width / 2 + 'px';
  17731. }
  17732. this.dirty = false;
  17733. };
  17734. PointItem.prototype._repaintDomAdditionals = function () {
  17735. this._repaintOnItemUpdateTimeTooltip(this.dom.point);
  17736. this._repaintDragCenter();
  17737. this._repaintDeleteButton(this.dom.point);
  17738. };
  17739. /**
  17740. * Repaint the item
  17741. * @param {boolean} [returnQueue=false] return the queue
  17742. * @return {boolean} the redraw queue if returnQueue=true
  17743. */
  17744. PointItem.prototype.redraw = function (returnQueue) {
  17745. var sizes;
  17746. var queue = [
  17747. // create item DOM
  17748. this._createDomElement.bind(this),
  17749. // append DOM to parent DOM
  17750. this._appendDomElement.bind(this),
  17751. // update dirty DOM
  17752. this._updateDirtyDomComponents.bind(this), function () {
  17753. if (this.dirty) {
  17754. sizes = this._getDomComponentsSizes();
  17755. }
  17756. }.bind(this), function () {
  17757. if (this.dirty) {
  17758. this._updateDomComponentsSizes.bind(this)(sizes);
  17759. }
  17760. }.bind(this),
  17761. // repaint DOM additionals
  17762. this._repaintDomAdditionals.bind(this)];
  17763. if (returnQueue) {
  17764. return queue;
  17765. } else {
  17766. var result;
  17767. queue.forEach(function (fn) {
  17768. result = fn();
  17769. });
  17770. return result;
  17771. }
  17772. };
  17773. /**
  17774. * Show the item in the DOM (when not already visible). The items DOM will
  17775. * be created when needed.
  17776. */
  17777. PointItem.prototype.show = function () {
  17778. if (!this.displayed) {
  17779. this.redraw();
  17780. }
  17781. };
  17782. /**
  17783. * Hide the item from the DOM (when visible)
  17784. */
  17785. PointItem.prototype.hide = function () {
  17786. if (this.displayed) {
  17787. if (this.dom.point.parentNode) {
  17788. this.dom.point.parentNode.removeChild(this.dom.point);
  17789. }
  17790. this.displayed = false;
  17791. }
  17792. };
  17793. /**
  17794. * Reposition the item horizontally
  17795. * @Override
  17796. */
  17797. PointItem.prototype.repositionX = function () {
  17798. var start = this.conversion.toScreen(this.data.start);
  17799. if (this.options.rtl) {
  17800. this.right = start - this.props.dot.width;
  17801. // reposition point
  17802. this.dom.point.style.right = this.right + 'px';
  17803. } else {
  17804. this.left = start - this.props.dot.width;
  17805. // reposition point
  17806. this.dom.point.style.left = this.left + 'px';
  17807. }
  17808. };
  17809. /**
  17810. * Reposition the item vertically
  17811. * @Override
  17812. */
  17813. PointItem.prototype.repositionY = function () {
  17814. var orientation = this.options.orientation.item;
  17815. var point = this.dom.point;
  17816. if (orientation == 'top') {
  17817. point.style.top = this.top + 'px';
  17818. } else {
  17819. point.style.top = this.parent.height - this.top - this.height + 'px';
  17820. }
  17821. };
  17822. /**
  17823. * Return the width of the item left from its start date
  17824. * @return {number}
  17825. */
  17826. PointItem.prototype.getWidthLeft = function () {
  17827. return this.props.dot.width;
  17828. };
  17829. /**
  17830. * Return the width of the item right from its start date
  17831. * @return {number}
  17832. */
  17833. PointItem.prototype.getWidthRight = function () {
  17834. return this.props.dot.width;
  17835. };
  17836. module.exports = PointItem;
  17837. /***/ }),
  17838. /* 103 */
  17839. /***/ (function(module, exports, __webpack_require__) {
  17840. "use strict";
  17841. var Item = __webpack_require__(38);
  17842. var BackgroundGroup = __webpack_require__(69);
  17843. var RangeItem = __webpack_require__(70);
  17844. /**
  17845. * @constructor BackgroundItem
  17846. * @extends Item
  17847. * @param {Object} data Object containing parameters start, end
  17848. * content, className.
  17849. * @param {{toScreen: function, toTime: function}} conversion
  17850. * Conversion functions from time to screen and vice versa
  17851. * @param {Object} [options] Configuration options
  17852. * // TODO: describe options
  17853. * // TODO: implement support for the BackgroundItem just having a start, then being displayed as a sort of an annotation
  17854. */
  17855. function BackgroundItem(data, conversion, options) {
  17856. this.props = {
  17857. content: {
  17858. width: 0
  17859. }
  17860. };
  17861. this.overflow = false; // if contents can overflow (css styling), this flag is set to true
  17862. // validate data
  17863. if (data) {
  17864. if (data.start == undefined) {
  17865. throw new Error('Property "start" missing in item ' + data.id);
  17866. }
  17867. if (data.end == undefined) {
  17868. throw new Error('Property "end" missing in item ' + data.id);
  17869. }
  17870. }
  17871. Item.call(this, data, conversion, options);
  17872. }
  17873. BackgroundItem.prototype = new Item(null, null, null);
  17874. BackgroundItem.prototype.baseClassName = 'vis-item vis-background';
  17875. BackgroundItem.prototype.stack = false;
  17876. /**
  17877. * Check whether this item is visible inside given range
  17878. * @param {vis.Range} range with a timestamp for start and end
  17879. * @returns {boolean} True if visible
  17880. */
  17881. BackgroundItem.prototype.isVisible = function (range) {
  17882. // determine visibility
  17883. return this.data.start < range.end && this.data.end > range.start;
  17884. };
  17885. BackgroundItem.prototype._createDomElement = function () {
  17886. if (!this.dom) {
  17887. // create DOM
  17888. this.dom = {};
  17889. // background box
  17890. this.dom.box = document.createElement('div');
  17891. // className is updated in redraw()
  17892. // frame box (to prevent the item contents from overflowing
  17893. this.dom.frame = document.createElement('div');
  17894. this.dom.frame.className = 'vis-item-overflow';
  17895. this.dom.box.appendChild(this.dom.frame);
  17896. // contents box
  17897. this.dom.content = document.createElement('div');
  17898. this.dom.content.className = 'vis-item-content';
  17899. this.dom.frame.appendChild(this.dom.content);
  17900. // Note: we do NOT attach this item as attribute to the DOM,
  17901. // such that background items cannot be selected
  17902. //this.dom.box['timeline-item'] = this;
  17903. this.dirty = true;
  17904. }
  17905. };
  17906. BackgroundItem.prototype._appendDomElement = function () {
  17907. if (!this.parent) {
  17908. throw new Error('Cannot redraw item: no parent attached');
  17909. }
  17910. if (!this.dom.box.parentNode) {
  17911. var background = this.parent.dom.background;
  17912. if (!background) {
  17913. throw new Error('Cannot redraw item: parent has no background container element');
  17914. }
  17915. background.appendChild(this.dom.box);
  17916. }
  17917. this.displayed = true;
  17918. };
  17919. BackgroundItem.prototype._updateDirtyDomComponents = function () {
  17920. // update dirty DOM. An item is marked dirty when:
  17921. // - the item is not yet rendered
  17922. // - the item's data is changed
  17923. // - the item is selected/deselected
  17924. if (this.dirty) {
  17925. this._updateContents(this.dom.content);
  17926. this._updateDataAttributes(this.dom.content);
  17927. this._updateStyle(this.dom.box);
  17928. // update class
  17929. var className = (this.data.className ? ' ' + this.data.className : '') + (this.selected ? ' vis-selected' : '');
  17930. this.dom.box.className = this.baseClassName + className;
  17931. }
  17932. };
  17933. BackgroundItem.prototype._getDomComponentsSizes = function () {
  17934. // determine from css whether this box has overflow
  17935. this.overflow = window.getComputedStyle(this.dom.content).overflow !== 'hidden';
  17936. return {
  17937. content: {
  17938. width: this.dom.content.offsetWidth
  17939. }
  17940. };
  17941. };
  17942. BackgroundItem.prototype._updateDomComponentsSizes = function (sizes) {
  17943. // recalculate size
  17944. this.props.content.width = sizes.content.width;
  17945. this.height = 0; // set height zero, so this item will be ignored when stacking items
  17946. this.dirty = false;
  17947. };
  17948. BackgroundItem.prototype._repaintDomAdditionals = function () {};
  17949. /**
  17950. * Repaint the item
  17951. * @param {boolean} [returnQueue=false] return the queue
  17952. * @return {boolean} the redraw result or the redraw queue if returnQueue=true
  17953. */
  17954. BackgroundItem.prototype.redraw = function (returnQueue) {
  17955. var sizes;
  17956. var queue = [
  17957. // create item DOM
  17958. this._createDomElement.bind(this),
  17959. // append DOM to parent DOM
  17960. this._appendDomElement.bind(this), this._updateDirtyDomComponents.bind(this), function () {
  17961. if (this.dirty) {
  17962. sizes = this._getDomComponentsSizes.bind(this)();
  17963. }
  17964. }.bind(this), function () {
  17965. if (this.dirty) {
  17966. this._updateDomComponentsSizes.bind(this)(sizes);
  17967. }
  17968. }.bind(this),
  17969. // repaint DOM additionals
  17970. this._repaintDomAdditionals.bind(this)];
  17971. if (returnQueue) {
  17972. return queue;
  17973. } else {
  17974. var result;
  17975. queue.forEach(function (fn) {
  17976. result = fn();
  17977. });
  17978. return result;
  17979. }
  17980. };
  17981. /**
  17982. * Show the item in the DOM (when not already visible). The items DOM will
  17983. * be created when needed.
  17984. */
  17985. BackgroundItem.prototype.show = RangeItem.prototype.show;
  17986. /**
  17987. * Hide the item from the DOM (when visible)
  17988. * @return {Boolean} changed
  17989. */
  17990. BackgroundItem.prototype.hide = RangeItem.prototype.hide;
  17991. /**
  17992. * Reposition the item horizontally
  17993. * @Override
  17994. */
  17995. BackgroundItem.prototype.repositionX = RangeItem.prototype.repositionX;
  17996. /**
  17997. * Reposition the item vertically
  17998. * @Override
  17999. */
  18000. BackgroundItem.prototype.repositionY = function (margin) {
  18001. // eslint-disable-line no-unused-vars
  18002. var height;
  18003. var orientation = this.options.orientation.item;
  18004. // special positioning for subgroups
  18005. if (this.data.subgroup !== undefined) {
  18006. // TODO: instead of calculating the top position of the subgroups here for every BackgroundItem, calculate the top of the subgroup once in Itemset
  18007. var itemSubgroup = this.data.subgroup;
  18008. this.dom.box.style.height = this.parent.subgroups[itemSubgroup].height + 'px';
  18009. if (orientation == 'top') {
  18010. this.dom.box.style.top = this.parent.top + this.parent.subgroups[itemSubgroup].top + 'px';
  18011. } else {
  18012. this.dom.box.style.top = this.parent.top + this.parent.height - this.parent.subgroups[itemSubgroup].top - this.parent.subgroups[itemSubgroup].height + 'px';
  18013. }
  18014. this.dom.box.style.bottom = '';
  18015. }
  18016. // and in the case of no subgroups:
  18017. else {
  18018. // we want backgrounds with groups to only show in groups.
  18019. if (this.parent instanceof BackgroundGroup) {
  18020. // if the item is not in a group:
  18021. height = Math.max(this.parent.height, this.parent.itemSet.body.domProps.center.height, this.parent.itemSet.body.domProps.centerContainer.height);
  18022. this.dom.box.style.bottom = orientation == 'bottom' ? '0' : '';
  18023. this.dom.box.style.top = orientation == 'top' ? '0' : '';
  18024. } else {
  18025. height = this.parent.height;
  18026. // same alignment for items when orientation is top or bottom
  18027. this.dom.box.style.top = this.parent.top + 'px';
  18028. this.dom.box.style.bottom = '';
  18029. }
  18030. }
  18031. this.dom.box.style.height = height + 'px';
  18032. };
  18033. module.exports = BackgroundItem;
  18034. /***/ }),
  18035. /* 104 */
  18036. /***/ (function(module, exports, __webpack_require__) {
  18037. "use strict";
  18038. Object.defineProperty(exports, "__esModule", {
  18039. value: true
  18040. });
  18041. var _classCallCheck2 = __webpack_require__(0);
  18042. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  18043. var _createClass2 = __webpack_require__(1);
  18044. var _createClass3 = _interopRequireDefault(_createClass2);
  18045. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  18046. /**
  18047. * Popup is a class to create a popup window with some text
  18048. */
  18049. var Popup = function () {
  18050. /**
  18051. * @param {Element} container The container object.
  18052. * @param {string} overflowMethod How the popup should act to overflowing ('flip' or 'cap')
  18053. */
  18054. function Popup(container, overflowMethod) {
  18055. (0, _classCallCheck3['default'])(this, Popup);
  18056. this.container = container;
  18057. this.overflowMethod = overflowMethod || 'cap';
  18058. this.x = 0;
  18059. this.y = 0;
  18060. this.padding = 5;
  18061. this.hidden = false;
  18062. // create the frame
  18063. this.frame = document.createElement('div');
  18064. this.frame.className = 'vis-tooltip';
  18065. this.container.appendChild(this.frame);
  18066. }
  18067. /**
  18068. * @param {number} x Horizontal position of the popup window
  18069. * @param {number} y Vertical position of the popup window
  18070. */
  18071. (0, _createClass3['default'])(Popup, [{
  18072. key: 'setPosition',
  18073. value: function setPosition(x, y) {
  18074. this.x = parseInt(x);
  18075. this.y = parseInt(y);
  18076. }
  18077. /**
  18078. * Set the content for the popup window. This can be HTML code or text.
  18079. * @param {string | Element} content
  18080. */
  18081. }, {
  18082. key: 'setText',
  18083. value: function setText(content) {
  18084. if (content instanceof Element) {
  18085. this.frame.innerHTML = '';
  18086. this.frame.appendChild(content);
  18087. } else {
  18088. this.frame.innerHTML = content; // string containing text or HTML
  18089. }
  18090. }
  18091. /**
  18092. * Show the popup window
  18093. * @param {boolean} [doShow] Show or hide the window
  18094. */
  18095. }, {
  18096. key: 'show',
  18097. value: function show(doShow) {
  18098. if (doShow === undefined) {
  18099. doShow = true;
  18100. }
  18101. if (doShow === true) {
  18102. var height = this.frame.clientHeight;
  18103. var width = this.frame.clientWidth;
  18104. var maxHeight = this.frame.parentNode.clientHeight;
  18105. var maxWidth = this.frame.parentNode.clientWidth;
  18106. var left = 0,
  18107. top = 0;
  18108. if (this.overflowMethod == 'flip') {
  18109. var isLeft = false,
  18110. isTop = true; // Where around the position it's located
  18111. if (this.y - height < this.padding) {
  18112. isTop = false;
  18113. }
  18114. if (this.x + width > maxWidth - this.padding) {
  18115. isLeft = true;
  18116. }
  18117. if (isLeft) {
  18118. left = this.x - width;
  18119. } else {
  18120. left = this.x;
  18121. }
  18122. if (isTop) {
  18123. top = this.y - height;
  18124. } else {
  18125. top = this.y;
  18126. }
  18127. } else {
  18128. top = this.y - height;
  18129. if (top + height + this.padding > maxHeight) {
  18130. top = maxHeight - height - this.padding;
  18131. }
  18132. if (top < this.padding) {
  18133. top = this.padding;
  18134. }
  18135. left = this.x;
  18136. if (left + width + this.padding > maxWidth) {
  18137. left = maxWidth - width - this.padding;
  18138. }
  18139. if (left < this.padding) {
  18140. left = this.padding;
  18141. }
  18142. }
  18143. this.frame.style.left = left + "px";
  18144. this.frame.style.top = top + "px";
  18145. this.frame.style.visibility = "visible";
  18146. this.hidden = false;
  18147. } else {
  18148. this.hide();
  18149. }
  18150. }
  18151. /**
  18152. * Hide the popup window
  18153. */
  18154. }, {
  18155. key: 'hide',
  18156. value: function hide() {
  18157. this.hidden = true;
  18158. this.frame.style.left = "0";
  18159. this.frame.style.top = "0";
  18160. this.frame.style.visibility = "hidden";
  18161. }
  18162. /**
  18163. * Remove the popup window
  18164. */
  18165. }, {
  18166. key: 'destroy',
  18167. value: function destroy() {
  18168. this.frame.parentNode.removeChild(this.frame); // Remove element from DOM
  18169. }
  18170. }]);
  18171. return Popup;
  18172. }();
  18173. exports['default'] = Popup;
  18174. /***/ }),
  18175. /* 105 */
  18176. /***/ (function(module, exports, __webpack_require__) {
  18177. "use strict";
  18178. Object.defineProperty(exports, "__esModule", {
  18179. value: true
  18180. });
  18181. /**
  18182. * This object contains all possible options. It will check if the types are correct, if required if the option is one
  18183. * of the allowed values.
  18184. *
  18185. * __any__ means that the name of the property does not matter.
  18186. * __type__ is a required field for all objects and contains the allowed types of all objects
  18187. */
  18188. var string = 'string';
  18189. var bool = 'boolean';
  18190. var number = 'number';
  18191. var array = 'array';
  18192. var date = 'date';
  18193. var object = 'object'; // should only be in a __type__ property
  18194. var dom = 'dom';
  18195. var moment = 'moment';
  18196. var any = 'any';
  18197. var allOptions = {
  18198. configure: {
  18199. enabled: { 'boolean': bool },
  18200. filter: { 'boolean': bool, 'function': 'function' },
  18201. container: { dom: dom },
  18202. __type__: { object: object, 'boolean': bool, 'function': 'function' }
  18203. },
  18204. //globals :
  18205. align: { string: string },
  18206. rtl: { 'boolean': bool, 'undefined': 'undefined' },
  18207. rollingMode: {
  18208. follow: { 'boolean': bool },
  18209. offset: { number: number, 'undefined': 'undefined' },
  18210. __type__: { object: object }
  18211. },
  18212. verticalScroll: { 'boolean': bool, 'undefined': 'undefined' },
  18213. horizontalScroll: { 'boolean': bool, 'undefined': 'undefined' },
  18214. autoResize: { 'boolean': bool },
  18215. throttleRedraw: { number: number }, // TODO: DEPRICATED see https://github.com/almende/vis/issues/2511
  18216. clickToUse: { 'boolean': bool },
  18217. dataAttributes: { string: string, array: array },
  18218. editable: {
  18219. add: { 'boolean': bool, 'undefined': 'undefined' },
  18220. remove: { 'boolean': bool, 'undefined': 'undefined' },
  18221. updateGroup: { 'boolean': bool, 'undefined': 'undefined' },
  18222. updateTime: { 'boolean': bool, 'undefined': 'undefined' },
  18223. overrideItems: { 'boolean': bool, 'undefined': 'undefined' },
  18224. __type__: { 'boolean': bool, object: object }
  18225. },
  18226. end: { number: number, date: date, string: string, moment: moment },
  18227. format: {
  18228. minorLabels: {
  18229. millisecond: { string: string, 'undefined': 'undefined' },
  18230. second: { string: string, 'undefined': 'undefined' },
  18231. minute: { string: string, 'undefined': 'undefined' },
  18232. hour: { string: string, 'undefined': 'undefined' },
  18233. weekday: { string: string, 'undefined': 'undefined' },
  18234. day: { string: string, 'undefined': 'undefined' },
  18235. week: { string: string, 'undefined': 'undefined' },
  18236. month: { string: string, 'undefined': 'undefined' },
  18237. year: { string: string, 'undefined': 'undefined' },
  18238. __type__: { object: object, 'function': 'function' }
  18239. },
  18240. majorLabels: {
  18241. millisecond: { string: string, 'undefined': 'undefined' },
  18242. second: { string: string, 'undefined': 'undefined' },
  18243. minute: { string: string, 'undefined': 'undefined' },
  18244. hour: { string: string, 'undefined': 'undefined' },
  18245. weekday: { string: string, 'undefined': 'undefined' },
  18246. day: { string: string, 'undefined': 'undefined' },
  18247. week: { string: string, 'undefined': 'undefined' },
  18248. month: { string: string, 'undefined': 'undefined' },
  18249. year: { string: string, 'undefined': 'undefined' },
  18250. __type__: { object: object, 'function': 'function' }
  18251. },
  18252. __type__: { object: object }
  18253. },
  18254. moment: { 'function': 'function' },
  18255. groupOrder: { string: string, 'function': 'function' },
  18256. groupEditable: {
  18257. add: { 'boolean': bool, 'undefined': 'undefined' },
  18258. remove: { 'boolean': bool, 'undefined': 'undefined' },
  18259. order: { 'boolean': bool, 'undefined': 'undefined' },
  18260. __type__: { 'boolean': bool, object: object }
  18261. },
  18262. groupOrderSwap: { 'function': 'function' },
  18263. height: { string: string, number: number },
  18264. hiddenDates: {
  18265. start: { date: date, number: number, string: string, moment: moment },
  18266. end: { date: date, number: number, string: string, moment: moment },
  18267. repeat: { string: string },
  18268. __type__: { object: object, array: array }
  18269. },
  18270. itemsAlwaysDraggable: {
  18271. item: { 'boolean': bool, 'undefined': 'undefined' },
  18272. range: { 'boolean': bool, 'undefined': 'undefined' },
  18273. __type__: { 'boolean': bool, object: object }
  18274. },
  18275. limitSize: { 'boolean': bool },
  18276. locale: { string: string },
  18277. locales: {
  18278. __any__: { any: any },
  18279. __type__: { object: object }
  18280. },
  18281. margin: {
  18282. axis: { number: number },
  18283. item: {
  18284. horizontal: { number: number, 'undefined': 'undefined' },
  18285. vertical: { number: number, 'undefined': 'undefined' },
  18286. __type__: { object: object, number: number }
  18287. },
  18288. __type__: { object: object, number: number }
  18289. },
  18290. max: { date: date, number: number, string: string, moment: moment },
  18291. maxHeight: { number: number, string: string },
  18292. maxMinorChars: { number: number },
  18293. min: { date: date, number: number, string: string, moment: moment },
  18294. minHeight: { number: number, string: string },
  18295. moveable: { 'boolean': bool },
  18296. multiselect: { 'boolean': bool },
  18297. multiselectPerGroup: { 'boolean': bool },
  18298. onAdd: { 'function': 'function' },
  18299. onDropObjectOnItem: { 'function': 'function' },
  18300. onUpdate: { 'function': 'function' },
  18301. onMove: { 'function': 'function' },
  18302. onMoving: { 'function': 'function' },
  18303. onRemove: { 'function': 'function' },
  18304. onAddGroup: { 'function': 'function' },
  18305. onMoveGroup: { 'function': 'function' },
  18306. onRemoveGroup: { 'function': 'function' },
  18307. onInitialDrawComplete: { 'function': 'function' },
  18308. order: { 'function': 'function' },
  18309. orientation: {
  18310. axis: { string: string, 'undefined': 'undefined' },
  18311. item: { string: string, 'undefined': 'undefined' },
  18312. __type__: { string: string, object: object }
  18313. },
  18314. selectable: { 'boolean': bool },
  18315. showCurrentTime: { 'boolean': bool },
  18316. showMajorLabels: { 'boolean': bool },
  18317. showMinorLabels: { 'boolean': bool },
  18318. stack: { 'boolean': bool },
  18319. stackSubgroups: { 'boolean': bool },
  18320. snap: { 'function': 'function', 'null': 'null' },
  18321. start: { date: date, number: number, string: string, moment: moment },
  18322. template: { 'function': 'function' },
  18323. groupTemplate: { 'function': 'function' },
  18324. visibleFrameTemplate: { string: string, 'function': 'function' },
  18325. showTooltips: { 'boolean': bool },
  18326. tooltip: {
  18327. followMouse: { 'boolean': bool },
  18328. overflowMethod: { 'string': ['cap', 'flip'] },
  18329. __type__: { object: object }
  18330. },
  18331. tooltipOnItemUpdateTime: {
  18332. template: { 'function': 'function' },
  18333. __type__: { 'boolean': bool, object: object }
  18334. },
  18335. timeAxis: {
  18336. scale: { string: string, 'undefined': 'undefined' },
  18337. step: { number: number, 'undefined': 'undefined' },
  18338. __type__: { object: object }
  18339. },
  18340. type: { string: string },
  18341. width: { string: string, number: number },
  18342. zoomable: { 'boolean': bool },
  18343. zoomKey: { string: ['ctrlKey', 'altKey', 'metaKey', ''] },
  18344. zoomMax: { number: number },
  18345. zoomMin: { number: number },
  18346. __type__: { object: object }
  18347. };
  18348. var configureOptions = {
  18349. global: {
  18350. align: ['center', 'left', 'right'],
  18351. direction: false,
  18352. autoResize: true,
  18353. clickToUse: false,
  18354. // dataAttributes: ['all'], // FIXME: can be 'all' or string[]
  18355. editable: {
  18356. add: false,
  18357. remove: false,
  18358. updateGroup: false,
  18359. updateTime: false
  18360. },
  18361. end: '',
  18362. format: {
  18363. minorLabels: {
  18364. millisecond: 'SSS',
  18365. second: 's',
  18366. minute: 'HH:mm',
  18367. hour: 'HH:mm',
  18368. weekday: 'ddd D',
  18369. day: 'D',
  18370. week: 'w',
  18371. month: 'MMM',
  18372. year: 'YYYY'
  18373. },
  18374. majorLabels: {
  18375. millisecond: 'HH:mm:ss',
  18376. second: 'D MMMM HH:mm',
  18377. minute: 'ddd D MMMM',
  18378. hour: 'ddd D MMMM',
  18379. weekday: 'MMMM YYYY',
  18380. day: 'MMMM YYYY',
  18381. week: 'MMMM YYYY',
  18382. month: 'YYYY',
  18383. year: ''
  18384. }
  18385. },
  18386. //groupOrder: {string, 'function': 'function'},
  18387. groupsDraggable: false,
  18388. height: '',
  18389. //hiddenDates: {object, array},
  18390. locale: '',
  18391. margin: {
  18392. axis: [20, 0, 100, 1],
  18393. item: {
  18394. horizontal: [10, 0, 100, 1],
  18395. vertical: [10, 0, 100, 1]
  18396. }
  18397. },
  18398. max: '',
  18399. maxHeight: '',
  18400. maxMinorChars: [7, 0, 20, 1],
  18401. min: '',
  18402. minHeight: '',
  18403. moveable: false,
  18404. multiselect: false,
  18405. multiselectPerGroup: false,
  18406. //onAdd: {'function': 'function'},
  18407. //onUpdate: {'function': 'function'},
  18408. //onMove: {'function': 'function'},
  18409. //onMoving: {'function': 'function'},
  18410. //onRename: {'function': 'function'},
  18411. //order: {'function': 'function'},
  18412. orientation: {
  18413. axis: ['both', 'bottom', 'top'],
  18414. item: ['bottom', 'top']
  18415. },
  18416. selectable: true,
  18417. showCurrentTime: false,
  18418. showMajorLabels: true,
  18419. showMinorLabels: true,
  18420. stack: true,
  18421. stackSubgroups: true,
  18422. //snap: {'function': 'function', nada},
  18423. start: '',
  18424. //template: {'function': 'function'},
  18425. //timeAxis: {
  18426. // scale: ['millisecond', 'second', 'minute', 'hour', 'weekday', 'day', 'week', 'month', 'year'],
  18427. // step: [1, 1, 10, 1]
  18428. //},
  18429. showTooltips: true,
  18430. tooltip: {
  18431. followMouse: false,
  18432. overflowMethod: 'flip'
  18433. },
  18434. tooltipOnItemUpdateTime: false,
  18435. type: ['box', 'point', 'range', 'background'],
  18436. width: '100%',
  18437. zoomable: true,
  18438. zoomKey: ['ctrlKey', 'altKey', 'metaKey', ''],
  18439. zoomMax: [315360000000000, 10, 315360000000000, 1],
  18440. zoomMin: [10, 10, 315360000000000, 1]
  18441. }
  18442. };
  18443. exports.allOptions = allOptions;
  18444. exports.configureOptions = configureOptions;
  18445. /***/ }),
  18446. /* 106 */
  18447. /***/ (function(module, exports, __webpack_require__) {
  18448. "use strict";
  18449. var _typeof2 = __webpack_require__(6);
  18450. var _typeof3 = _interopRequireDefault(_typeof2);
  18451. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  18452. var util = __webpack_require__(2);
  18453. var DOMutil = __webpack_require__(14);
  18454. var DataSet = __webpack_require__(11);
  18455. var DataView = __webpack_require__(12);
  18456. var Component = __webpack_require__(16);
  18457. var DataAxis = __webpack_require__(107);
  18458. var GraphGroup = __webpack_require__(109);
  18459. var Legend = __webpack_require__(112);
  18460. var Bars = __webpack_require__(110);
  18461. var Lines = __webpack_require__(111);
  18462. var Points = __webpack_require__(72);
  18463. var UNGROUPED = '__ungrouped__'; // reserved group id for ungrouped items
  18464. /**
  18465. * This is the constructor of the LineGraph. It requires a Timeline body and options.
  18466. *
  18467. * @param {vis.Timeline.body} body
  18468. * @param {Object} options
  18469. * @constructor LineGraph
  18470. * @extends Component
  18471. */
  18472. function LineGraph(body, options) {
  18473. this.id = util.randomUUID();
  18474. this.body = body;
  18475. this.defaultOptions = {
  18476. yAxisOrientation: 'left',
  18477. defaultGroup: 'default',
  18478. sort: true,
  18479. sampling: true,
  18480. stack: false,
  18481. graphHeight: '400px',
  18482. shaded: {
  18483. enabled: false,
  18484. orientation: 'bottom' // top, bottom, zero
  18485. },
  18486. style: 'line', // line, bar
  18487. barChart: {
  18488. width: 50,
  18489. sideBySide: false,
  18490. align: 'center' // left, center, right
  18491. },
  18492. interpolation: {
  18493. enabled: true,
  18494. parametrization: 'centripetal', // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  18495. alpha: 0.5
  18496. },
  18497. drawPoints: {
  18498. enabled: true,
  18499. size: 6,
  18500. style: 'square' // square, circle
  18501. },
  18502. dataAxis: {}, //Defaults are done on DataAxis level
  18503. legend: {}, //Defaults are done on Legend level
  18504. groups: {
  18505. visibility: {}
  18506. }
  18507. };
  18508. // options is shared by this lineGraph and all its items
  18509. this.options = util.extend({}, this.defaultOptions);
  18510. this.dom = {};
  18511. this.props = {};
  18512. this.hammer = null;
  18513. this.groups = {};
  18514. this.abortedGraphUpdate = false;
  18515. this.updateSVGheight = false;
  18516. this.updateSVGheightOnResize = false;
  18517. this.forceGraphUpdate = true;
  18518. var me = this;
  18519. this.itemsData = null; // DataSet
  18520. this.groupsData = null; // DataSet
  18521. // listeners for the DataSet of the items
  18522. this.itemListeners = {
  18523. 'add': function add(event, params, senderId) {
  18524. // eslint-disable-line no-unused-vars
  18525. me._onAdd(params.items);
  18526. },
  18527. 'update': function update(event, params, senderId) {
  18528. // eslint-disable-line no-unused-vars
  18529. me._onUpdate(params.items);
  18530. },
  18531. 'remove': function remove(event, params, senderId) {
  18532. // eslint-disable-line no-unused-vars
  18533. me._onRemove(params.items);
  18534. }
  18535. };
  18536. // listeners for the DataSet of the groups
  18537. this.groupListeners = {
  18538. 'add': function add(event, params, senderId) {
  18539. // eslint-disable-line no-unused-vars
  18540. me._onAddGroups(params.items);
  18541. },
  18542. 'update': function update(event, params, senderId) {
  18543. // eslint-disable-line no-unused-vars
  18544. me._onUpdateGroups(params.items);
  18545. },
  18546. 'remove': function remove(event, params, senderId) {
  18547. // eslint-disable-line no-unused-vars
  18548. me._onRemoveGroups(params.items);
  18549. }
  18550. };
  18551. this.items = {}; // object with an Item for every data item
  18552. this.selection = []; // list with the ids of all selected nodes
  18553. this.lastStart = this.body.range.start;
  18554. this.touchParams = {}; // stores properties while dragging
  18555. this.svgElements = {};
  18556. this.setOptions(options);
  18557. this.groupsUsingDefaultStyles = [0];
  18558. this.body.emitter.on('rangechanged', function () {
  18559. me.lastStart = me.body.range.start;
  18560. me.svg.style.left = util.option.asSize(-me.props.width);
  18561. me.forceGraphUpdate = true;
  18562. //Is this local redraw necessary? (Core also does a change event!)
  18563. me.redraw.call(me);
  18564. });
  18565. // create the HTML DOM
  18566. this._create();
  18567. this.framework = { svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups };
  18568. }
  18569. LineGraph.prototype = new Component();
  18570. /**
  18571. * Create the HTML DOM for the ItemSet
  18572. */
  18573. LineGraph.prototype._create = function () {
  18574. var frame = document.createElement('div');
  18575. frame.className = 'vis-line-graph';
  18576. this.dom.frame = frame;
  18577. // create svg element for graph drawing.
  18578. this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  18579. this.svg.style.position = 'relative';
  18580. this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px';
  18581. this.svg.style.display = 'block';
  18582. frame.appendChild(this.svg);
  18583. // data axis
  18584. this.options.dataAxis.orientation = 'left';
  18585. this.yAxisLeft = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  18586. this.options.dataAxis.orientation = 'right';
  18587. this.yAxisRight = new DataAxis(this.body, this.options.dataAxis, this.svg, this.options.groups);
  18588. delete this.options.dataAxis.orientation;
  18589. // legends
  18590. this.legendLeft = new Legend(this.body, this.options.legend, 'left', this.options.groups);
  18591. this.legendRight = new Legend(this.body, this.options.legend, 'right', this.options.groups);
  18592. this.show();
  18593. };
  18594. /**
  18595. * set the options of the LineGraph. the mergeOptions is used for subObjects that have an enabled element.
  18596. * @param {object} options
  18597. */
  18598. LineGraph.prototype.setOptions = function (options) {
  18599. if (options) {
  18600. var fields = ['sampling', 'defaultGroup', 'stack', 'height', 'graphHeight', 'yAxisOrientation', 'style', 'barChart', 'dataAxis', 'sort', 'groups'];
  18601. if (options.graphHeight === undefined && options.height !== undefined) {
  18602. this.updateSVGheight = true;
  18603. this.updateSVGheightOnResize = true;
  18604. } else if (this.body.domProps.centerContainer.height !== undefined && options.graphHeight !== undefined) {
  18605. if (parseInt((options.graphHeight + '').replace("px", '')) < this.body.domProps.centerContainer.height) {
  18606. this.updateSVGheight = true;
  18607. }
  18608. }
  18609. util.selectiveDeepExtend(fields, this.options, options);
  18610. util.mergeOptions(this.options, options, 'interpolation');
  18611. util.mergeOptions(this.options, options, 'drawPoints');
  18612. util.mergeOptions(this.options, options, 'shaded');
  18613. util.mergeOptions(this.options, options, 'legend');
  18614. if (options.interpolation) {
  18615. if ((0, _typeof3['default'])(options.interpolation) == 'object') {
  18616. if (options.interpolation.parametrization) {
  18617. if (options.interpolation.parametrization == 'uniform') {
  18618. this.options.interpolation.alpha = 0;
  18619. } else if (options.interpolation.parametrization == 'chordal') {
  18620. this.options.interpolation.alpha = 1.0;
  18621. } else {
  18622. this.options.interpolation.parametrization = 'centripetal';
  18623. this.options.interpolation.alpha = 0.5;
  18624. }
  18625. }
  18626. }
  18627. }
  18628. if (this.yAxisLeft) {
  18629. if (options.dataAxis !== undefined) {
  18630. this.yAxisLeft.setOptions(this.options.dataAxis);
  18631. this.yAxisRight.setOptions(this.options.dataAxis);
  18632. }
  18633. }
  18634. if (this.legendLeft) {
  18635. if (options.legend !== undefined) {
  18636. this.legendLeft.setOptions(this.options.legend);
  18637. this.legendRight.setOptions(this.options.legend);
  18638. }
  18639. }
  18640. if (this.groups.hasOwnProperty(UNGROUPED)) {
  18641. this.groups[UNGROUPED].setOptions(options);
  18642. }
  18643. }
  18644. // this is used to redraw the graph if the visibility of the groups is changed.
  18645. if (this.dom.frame) {
  18646. //not on initial run?
  18647. this.forceGraphUpdate = true;
  18648. this.body.emitter.emit("_change", { queue: true });
  18649. }
  18650. };
  18651. /**
  18652. * Hide the component from the DOM
  18653. */
  18654. LineGraph.prototype.hide = function () {
  18655. // remove the frame containing the items
  18656. if (this.dom.frame.parentNode) {
  18657. this.dom.frame.parentNode.removeChild(this.dom.frame);
  18658. }
  18659. };
  18660. /**
  18661. * Show the component in the DOM (when not already visible).
  18662. */
  18663. LineGraph.prototype.show = function () {
  18664. // show frame containing the items
  18665. if (!this.dom.frame.parentNode) {
  18666. this.body.dom.center.appendChild(this.dom.frame);
  18667. }
  18668. };
  18669. /**
  18670. * Set items
  18671. * @param {vis.DataSet | null} items
  18672. */
  18673. LineGraph.prototype.setItems = function (items) {
  18674. var me = this,
  18675. ids,
  18676. oldItemsData = this.itemsData;
  18677. // replace the dataset
  18678. if (!items) {
  18679. this.itemsData = null;
  18680. } else if (items instanceof DataSet || items instanceof DataView) {
  18681. this.itemsData = items;
  18682. } else {
  18683. throw new TypeError('Data must be an instance of DataSet or DataView');
  18684. }
  18685. if (oldItemsData) {
  18686. // unsubscribe from old dataset
  18687. util.forEach(this.itemListeners, function (callback, event) {
  18688. oldItemsData.off(event, callback);
  18689. });
  18690. // remove all drawn items
  18691. ids = oldItemsData.getIds();
  18692. this._onRemove(ids);
  18693. }
  18694. if (this.itemsData) {
  18695. // subscribe to new dataset
  18696. var id = this.id;
  18697. util.forEach(this.itemListeners, function (callback, event) {
  18698. me.itemsData.on(event, callback, id);
  18699. });
  18700. // add all new items
  18701. ids = this.itemsData.getIds();
  18702. this._onAdd(ids);
  18703. }
  18704. };
  18705. /**
  18706. * Set groups
  18707. * @param {vis.DataSet} groups
  18708. */
  18709. LineGraph.prototype.setGroups = function (groups) {
  18710. var me = this;
  18711. var ids;
  18712. // unsubscribe from current dataset
  18713. if (this.groupsData) {
  18714. util.forEach(this.groupListeners, function (callback, event) {
  18715. me.groupsData.off(event, callback);
  18716. });
  18717. // remove all drawn groups
  18718. ids = this.groupsData.getIds();
  18719. this.groupsData = null;
  18720. for (var i = 0; i < ids.length; i++) {
  18721. this._removeGroup(ids[i]);
  18722. }
  18723. }
  18724. // replace the dataset
  18725. if (!groups) {
  18726. this.groupsData = null;
  18727. } else if (groups instanceof DataSet || groups instanceof DataView) {
  18728. this.groupsData = groups;
  18729. } else {
  18730. throw new TypeError('Data must be an instance of DataSet or DataView');
  18731. }
  18732. if (this.groupsData) {
  18733. // subscribe to new dataset
  18734. var id = this.id;
  18735. util.forEach(this.groupListeners, function (callback, event) {
  18736. me.groupsData.on(event, callback, id);
  18737. });
  18738. // draw all ms
  18739. ids = this.groupsData.getIds();
  18740. this._onAddGroups(ids);
  18741. }
  18742. };
  18743. LineGraph.prototype._onUpdate = function (ids) {
  18744. this._updateAllGroupData(ids);
  18745. };
  18746. LineGraph.prototype._onAdd = function (ids) {
  18747. this._onUpdate(ids);
  18748. };
  18749. LineGraph.prototype._onRemove = function (ids) {
  18750. this._onUpdate(ids);
  18751. };
  18752. LineGraph.prototype._onUpdateGroups = function (groupIds) {
  18753. this._updateAllGroupData(null, groupIds);
  18754. };
  18755. LineGraph.prototype._onAddGroups = function (groupIds) {
  18756. this._onUpdateGroups(groupIds);
  18757. };
  18758. /**
  18759. * this cleans the group out off the legends and the dataaxis, updates the ungrouped and updates the graph
  18760. * @param {Array} groupIds
  18761. * @private
  18762. */
  18763. LineGraph.prototype._onRemoveGroups = function (groupIds) {
  18764. for (var i = 0; i < groupIds.length; i++) {
  18765. this._removeGroup(groupIds[i]);
  18766. }
  18767. this.forceGraphUpdate = true;
  18768. this.body.emitter.emit("_change", { queue: true });
  18769. };
  18770. /**
  18771. * this cleans the group out off the legends and the dataaxis
  18772. * @param {vis.GraphGroup.id} groupId
  18773. * @private
  18774. */
  18775. LineGraph.prototype._removeGroup = function (groupId) {
  18776. if (this.groups.hasOwnProperty(groupId)) {
  18777. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  18778. this.yAxisRight.removeGroup(groupId);
  18779. this.legendRight.removeGroup(groupId);
  18780. this.legendRight.redraw();
  18781. } else {
  18782. this.yAxisLeft.removeGroup(groupId);
  18783. this.legendLeft.removeGroup(groupId);
  18784. this.legendLeft.redraw();
  18785. }
  18786. delete this.groups[groupId];
  18787. }
  18788. };
  18789. /**
  18790. * update a group object with the group dataset entree
  18791. *
  18792. * @param {vis.GraphGroup} group
  18793. * @param {vis.GraphGroup.id} groupId
  18794. * @private
  18795. */
  18796. LineGraph.prototype._updateGroup = function (group, groupId) {
  18797. if (!this.groups.hasOwnProperty(groupId)) {
  18798. this.groups[groupId] = new GraphGroup(group, groupId, this.options, this.groupsUsingDefaultStyles);
  18799. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  18800. this.yAxisRight.addGroup(groupId, this.groups[groupId]);
  18801. this.legendRight.addGroup(groupId, this.groups[groupId]);
  18802. } else {
  18803. this.yAxisLeft.addGroup(groupId, this.groups[groupId]);
  18804. this.legendLeft.addGroup(groupId, this.groups[groupId]);
  18805. }
  18806. } else {
  18807. this.groups[groupId].update(group);
  18808. if (this.groups[groupId].options.yAxisOrientation == 'right') {
  18809. this.yAxisRight.updateGroup(groupId, this.groups[groupId]);
  18810. this.legendRight.updateGroup(groupId, this.groups[groupId]);
  18811. //If yAxisOrientation changed, clean out the group from the other axis.
  18812. this.yAxisLeft.removeGroup(groupId);
  18813. this.legendLeft.removeGroup(groupId);
  18814. } else {
  18815. this.yAxisLeft.updateGroup(groupId, this.groups[groupId]);
  18816. this.legendLeft.updateGroup(groupId, this.groups[groupId]);
  18817. //If yAxisOrientation changed, clean out the group from the other axis.
  18818. this.yAxisRight.removeGroup(groupId);
  18819. this.legendRight.removeGroup(groupId);
  18820. }
  18821. }
  18822. this.legendLeft.redraw();
  18823. this.legendRight.redraw();
  18824. };
  18825. /**
  18826. * this updates all groups, it is used when there is an update the the itemset.
  18827. *
  18828. * @param {Array} ids
  18829. * @param {Array} groupIds
  18830. * @private
  18831. */
  18832. LineGraph.prototype._updateAllGroupData = function (ids, groupIds) {
  18833. if (this.itemsData != null) {
  18834. var groupsContent = {};
  18835. var items = this.itemsData.get();
  18836. var fieldId = this.itemsData._fieldId;
  18837. var idMap = {};
  18838. if (ids) {
  18839. ids.map(function (id) {
  18840. idMap[id] = id;
  18841. });
  18842. }
  18843. //pre-Determine array sizes, for more efficient memory claim
  18844. var groupCounts = {};
  18845. for (var i = 0; i < items.length; i++) {
  18846. var item = items[i];
  18847. var groupId = item.group;
  18848. if (groupId === null || groupId === undefined) {
  18849. groupId = UNGROUPED;
  18850. }
  18851. groupCounts.hasOwnProperty(groupId) ? groupCounts[groupId]++ : groupCounts[groupId] = 1;
  18852. }
  18853. //Pre-load arrays from existing groups if items are not changed (not in ids)
  18854. var existingItemsMap = {};
  18855. if (!groupIds && ids) {
  18856. for (groupId in this.groups) {
  18857. if (this.groups.hasOwnProperty(groupId)) {
  18858. group = this.groups[groupId];
  18859. var existing_items = group.getItems();
  18860. groupsContent[groupId] = existing_items.filter(function (item) {
  18861. existingItemsMap[item[fieldId]] = item[fieldId];
  18862. return item[fieldId] !== idMap[item[fieldId]];
  18863. });
  18864. var newLength = groupCounts[groupId];
  18865. groupCounts[groupId] -= groupsContent[groupId].length;
  18866. if (groupsContent[groupId].length < newLength) {
  18867. groupsContent[groupId][newLength - 1] = {};
  18868. }
  18869. }
  18870. }
  18871. }
  18872. //Now insert data into the arrays.
  18873. for (i = 0; i < items.length; i++) {
  18874. item = items[i];
  18875. groupId = item.group;
  18876. if (groupId === null || groupId === undefined) {
  18877. groupId = UNGROUPED;
  18878. }
  18879. if (!groupIds && ids && item[fieldId] !== idMap[item[fieldId]] && existingItemsMap.hasOwnProperty(item[fieldId])) {
  18880. continue;
  18881. }
  18882. if (!groupsContent.hasOwnProperty(groupId)) {
  18883. groupsContent[groupId] = new Array(groupCounts[groupId]);
  18884. }
  18885. //Copy data (because of unmodifiable DataView input.
  18886. var extended = util.bridgeObject(item);
  18887. extended.x = util.convert(item.x, 'Date');
  18888. extended.end = util.convert(item.end, 'Date');
  18889. extended.orginalY = item.y; //real Y
  18890. extended.y = Number(item.y);
  18891. extended[fieldId] = item[fieldId];
  18892. var index = groupsContent[groupId].length - groupCounts[groupId]--;
  18893. groupsContent[groupId][index] = extended;
  18894. }
  18895. //Make sure all groups are present, to allow removal of old groups
  18896. for (groupId in this.groups) {
  18897. if (this.groups.hasOwnProperty(groupId)) {
  18898. if (!groupsContent.hasOwnProperty(groupId)) {
  18899. groupsContent[groupId] = new Array(0);
  18900. }
  18901. }
  18902. }
  18903. //Update legendas, style and axis
  18904. for (groupId in groupsContent) {
  18905. if (groupsContent.hasOwnProperty(groupId)) {
  18906. if (groupsContent[groupId].length == 0) {
  18907. if (this.groups.hasOwnProperty(groupId)) {
  18908. this._removeGroup(groupId);
  18909. }
  18910. } else {
  18911. var group = undefined;
  18912. if (this.groupsData != undefined) {
  18913. group = this.groupsData.get(groupId);
  18914. }
  18915. if (group == undefined) {
  18916. group = { id: groupId, content: this.options.defaultGroup + groupId };
  18917. }
  18918. this._updateGroup(group, groupId);
  18919. this.groups[groupId].setItems(groupsContent[groupId]);
  18920. }
  18921. }
  18922. }
  18923. this.forceGraphUpdate = true;
  18924. this.body.emitter.emit("_change", { queue: true });
  18925. }
  18926. };
  18927. /**
  18928. * Redraw the component, mandatory function
  18929. * @return {boolean} Returns true if the component is resized
  18930. */
  18931. LineGraph.prototype.redraw = function () {
  18932. var resized = false;
  18933. // calculate actual size and position
  18934. this.props.width = this.dom.frame.offsetWidth;
  18935. this.props.height = this.body.domProps.centerContainer.height - this.body.domProps.border.top - this.body.domProps.border.bottom;
  18936. // check if this component is resized
  18937. resized = this._isResized() || resized;
  18938. // check whether zoomed (in that case we need to re-stack everything)
  18939. var visibleInterval = this.body.range.end - this.body.range.start;
  18940. var zoomed = visibleInterval != this.lastVisibleInterval;
  18941. this.lastVisibleInterval = visibleInterval;
  18942. // the svg element is three times as big as the width, this allows for fully dragging left and right
  18943. // without reloading the graph. the controls for this are bound to events in the constructor
  18944. if (resized == true) {
  18945. this.svg.style.width = util.option.asSize(3 * this.props.width);
  18946. this.svg.style.left = util.option.asSize(-this.props.width);
  18947. // if the height of the graph is set as proportional, change the height of the svg
  18948. if ((this.options.height + '').indexOf("%") != -1 || this.updateSVGheightOnResize == true) {
  18949. this.updateSVGheight = true;
  18950. }
  18951. }
  18952. // update the height of the graph on each redraw of the graph.
  18953. if (this.updateSVGheight == true) {
  18954. if (this.options.graphHeight != this.props.height + 'px') {
  18955. this.options.graphHeight = this.props.height + 'px';
  18956. this.svg.style.height = this.props.height + 'px';
  18957. }
  18958. this.updateSVGheight = false;
  18959. } else {
  18960. this.svg.style.height = ('' + this.options.graphHeight).replace('px', '') + 'px';
  18961. }
  18962. // zoomed is here to ensure that animations are shown correctly.
  18963. if (resized == true || zoomed == true || this.abortedGraphUpdate == true || this.forceGraphUpdate == true) {
  18964. resized = this._updateGraph() || resized;
  18965. this.forceGraphUpdate = false;
  18966. } else {
  18967. // move the whole svg while dragging
  18968. if (this.lastStart != 0) {
  18969. var offset = this.body.range.start - this.lastStart;
  18970. var range = this.body.range.end - this.body.range.start;
  18971. if (this.props.width != 0) {
  18972. var rangePerPixelInv = this.props.width / range;
  18973. var xOffset = offset * rangePerPixelInv;
  18974. this.svg.style.left = -this.props.width - xOffset + 'px';
  18975. }
  18976. }
  18977. }
  18978. this.legendLeft.redraw();
  18979. this.legendRight.redraw();
  18980. return resized;
  18981. };
  18982. LineGraph.prototype._getSortedGroupIds = function () {
  18983. // getting group Ids
  18984. var grouplist = [];
  18985. for (var groupId in this.groups) {
  18986. if (this.groups.hasOwnProperty(groupId)) {
  18987. var group = this.groups[groupId];
  18988. if (group.visible == true && (this.options.groups.visibility[groupId] === undefined || this.options.groups.visibility[groupId] == true)) {
  18989. grouplist.push({ id: groupId, zIndex: group.options.zIndex });
  18990. }
  18991. }
  18992. }
  18993. util.insertSort(grouplist, function (a, b) {
  18994. var az = a.zIndex;
  18995. var bz = b.zIndex;
  18996. if (az === undefined) az = 0;
  18997. if (bz === undefined) bz = 0;
  18998. return az == bz ? 0 : az < bz ? -1 : 1;
  18999. });
  19000. var groupIds = new Array(grouplist.length);
  19001. for (var i = 0; i < grouplist.length; i++) {
  19002. groupIds[i] = grouplist[i].id;
  19003. }
  19004. return groupIds;
  19005. };
  19006. /**
  19007. * Update and redraw the graph.
  19008. *
  19009. * @returns {boolean}
  19010. * @private
  19011. */
  19012. LineGraph.prototype._updateGraph = function () {
  19013. // reset the svg elements
  19014. DOMutil.prepareElements(this.svgElements);
  19015. if (this.props.width != 0 && this.itemsData != null) {
  19016. var group, i;
  19017. var groupRanges = {};
  19018. var changeCalled = false;
  19019. // this is the range of the SVG canvas
  19020. var minDate = this.body.util.toGlobalTime(-this.body.domProps.root.width);
  19021. var maxDate = this.body.util.toGlobalTime(2 * this.body.domProps.root.width);
  19022. // getting group Ids
  19023. var groupIds = this._getSortedGroupIds();
  19024. if (groupIds.length > 0) {
  19025. var groupsData = {};
  19026. // fill groups data, this only loads the data we require based on the timewindow
  19027. this._getRelevantData(groupIds, groupsData, minDate, maxDate);
  19028. // apply sampling, if disabled, it will pass through this function.
  19029. this._applySampling(groupIds, groupsData);
  19030. // we transform the X coordinates to detect collisions
  19031. for (i = 0; i < groupIds.length; i++) {
  19032. this._convertXcoordinates(groupsData[groupIds[i]]);
  19033. }
  19034. // now all needed data has been collected we start the processing.
  19035. this._getYRanges(groupIds, groupsData, groupRanges);
  19036. // update the Y axis first, we use this data to draw at the correct Y points
  19037. changeCalled = this._updateYAxis(groupIds, groupRanges);
  19038. // at changeCalled, abort this update cycle as the graph needs another update with new Width input from the Redraw container.
  19039. // Cleanup SVG elements on abort.
  19040. if (changeCalled == true) {
  19041. DOMutil.cleanupElements(this.svgElements);
  19042. this.abortedGraphUpdate = true;
  19043. return true;
  19044. }
  19045. this.abortedGraphUpdate = false;
  19046. // With the yAxis scaled correctly, use this to get the Y values of the points.
  19047. var below = undefined;
  19048. for (i = 0; i < groupIds.length; i++) {
  19049. group = this.groups[groupIds[i]];
  19050. if (this.options.stack === true && this.options.style === 'line') {
  19051. if (group.options.excludeFromStacking == undefined || !group.options.excludeFromStacking) {
  19052. if (below != undefined) {
  19053. this._stack(groupsData[group.id], groupsData[below.id]);
  19054. if (group.options.shaded.enabled == true && group.options.shaded.orientation !== "group") {
  19055. if (group.options.shaded.orientation == "top" && below.options.shaded.orientation !== "group") {
  19056. below.options.shaded.orientation = "group";
  19057. below.options.shaded.groupId = group.id;
  19058. } else {
  19059. group.options.shaded.orientation = "group";
  19060. group.options.shaded.groupId = below.id;
  19061. }
  19062. }
  19063. }
  19064. below = group;
  19065. }
  19066. }
  19067. this._convertYcoordinates(groupsData[groupIds[i]], group);
  19068. }
  19069. //Precalculate paths and draw shading if appropriate. This will make sure the shading is always behind any lines.
  19070. var paths = {};
  19071. for (i = 0; i < groupIds.length; i++) {
  19072. group = this.groups[groupIds[i]];
  19073. if (group.options.style === 'line' && group.options.shaded.enabled == true) {
  19074. var dataset = groupsData[groupIds[i]];
  19075. if (dataset == null || dataset.length == 0) {
  19076. continue;
  19077. }
  19078. if (!paths.hasOwnProperty(groupIds[i])) {
  19079. paths[groupIds[i]] = Lines.calcPath(dataset, group);
  19080. }
  19081. if (group.options.shaded.orientation === "group") {
  19082. var subGroupId = group.options.shaded.groupId;
  19083. if (groupIds.indexOf(subGroupId) === -1) {
  19084. console.log(group.id + ": Unknown shading group target given:" + subGroupId);
  19085. continue;
  19086. }
  19087. if (!paths.hasOwnProperty(subGroupId)) {
  19088. paths[subGroupId] = Lines.calcPath(groupsData[subGroupId], this.groups[subGroupId]);
  19089. }
  19090. Lines.drawShading(paths[groupIds[i]], group, paths[subGroupId], this.framework);
  19091. } else {
  19092. Lines.drawShading(paths[groupIds[i]], group, undefined, this.framework);
  19093. }
  19094. }
  19095. }
  19096. // draw the groups, calculating paths if still necessary.
  19097. Bars.draw(groupIds, groupsData, this.framework);
  19098. for (i = 0; i < groupIds.length; i++) {
  19099. group = this.groups[groupIds[i]];
  19100. if (groupsData[groupIds[i]].length > 0) {
  19101. switch (group.options.style) {
  19102. case "line":
  19103. if (!paths.hasOwnProperty(groupIds[i])) {
  19104. paths[groupIds[i]] = Lines.calcPath(groupsData[groupIds[i]], group);
  19105. }
  19106. Lines.draw(paths[groupIds[i]], group, this.framework);
  19107. // eslint-disable-line no-fallthrough
  19108. case "point":
  19109. // eslint-disable-line no-fallthrough
  19110. case "points":
  19111. if (group.options.style == "point" || group.options.style == "points" || group.options.drawPoints.enabled == true) {
  19112. Points.draw(groupsData[groupIds[i]], group, this.framework);
  19113. }
  19114. break;
  19115. case "bar":
  19116. // bar needs to be drawn enmasse
  19117. // eslint-disable-line no-fallthrough
  19118. default:
  19119. //do nothing...
  19120. }
  19121. }
  19122. }
  19123. }
  19124. }
  19125. // cleanup unused svg elements
  19126. DOMutil.cleanupElements(this.svgElements);
  19127. return false;
  19128. };
  19129. LineGraph.prototype._stack = function (data, subData) {
  19130. var index, dx, dy, subPrevPoint, subNextPoint;
  19131. index = 0;
  19132. // for each data point we look for a matching on in the set below
  19133. for (var j = 0; j < data.length; j++) {
  19134. subPrevPoint = undefined;
  19135. subNextPoint = undefined;
  19136. // we look for time matches or a before-after point
  19137. for (var k = index; k < subData.length; k++) {
  19138. // if times match exactly
  19139. if (subData[k].x === data[j].x) {
  19140. subPrevPoint = subData[k];
  19141. subNextPoint = subData[k];
  19142. index = k;
  19143. break;
  19144. } else if (subData[k].x > data[j].x) {
  19145. // overshoot
  19146. subNextPoint = subData[k];
  19147. if (k == 0) {
  19148. subPrevPoint = subNextPoint;
  19149. } else {
  19150. subPrevPoint = subData[k - 1];
  19151. }
  19152. index = k;
  19153. break;
  19154. }
  19155. }
  19156. // in case the last data point has been used, we assume it stays like this.
  19157. if (subNextPoint === undefined) {
  19158. subPrevPoint = subData[subData.length - 1];
  19159. subNextPoint = subData[subData.length - 1];
  19160. }
  19161. // linear interpolation
  19162. dx = subNextPoint.x - subPrevPoint.x;
  19163. dy = subNextPoint.y - subPrevPoint.y;
  19164. if (dx == 0) {
  19165. data[j].y = data[j].orginalY + subNextPoint.y;
  19166. } else {
  19167. data[j].y = data[j].orginalY + dy / dx * (data[j].x - subPrevPoint.x) + subPrevPoint.y; // ax + b where b is data[j].y
  19168. }
  19169. }
  19170. };
  19171. /**
  19172. * first select and preprocess the data from the datasets.
  19173. * the groups have their preselection of data, we now loop over this data to see
  19174. * what data we need to draw. Sorted data is much faster.
  19175. * more optimization is possible by doing the sampling before and using the binary search
  19176. * to find the end date to determine the increment.
  19177. *
  19178. * @param {array} groupIds
  19179. * @param {object} groupsData
  19180. * @param {date} minDate
  19181. * @param {date} maxDate
  19182. * @private
  19183. */
  19184. LineGraph.prototype._getRelevantData = function (groupIds, groupsData, minDate, maxDate) {
  19185. var group, i, j, item;
  19186. if (groupIds.length > 0) {
  19187. for (i = 0; i < groupIds.length; i++) {
  19188. group = this.groups[groupIds[i]];
  19189. var itemsData = group.getItems();
  19190. // optimization for sorted data
  19191. if (group.options.sort == true) {
  19192. var dateComparator = function dateComparator(a, b) {
  19193. return a.getTime() == b.getTime() ? 0 : a < b ? -1 : 1;
  19194. };
  19195. var first = Math.max(0, util.binarySearchValue(itemsData, minDate, 'x', 'before', dateComparator));
  19196. var last = Math.min(itemsData.length, util.binarySearchValue(itemsData, maxDate, 'x', 'after', dateComparator) + 1);
  19197. if (last <= 0) {
  19198. last = itemsData.length;
  19199. }
  19200. var dataContainer = new Array(last - first);
  19201. for (j = first; j < last; j++) {
  19202. item = group.itemsData[j];
  19203. dataContainer[j - first] = item;
  19204. }
  19205. groupsData[groupIds[i]] = dataContainer;
  19206. } else {
  19207. // If unsorted data, all data is relevant, just returning entire structure
  19208. groupsData[groupIds[i]] = group.itemsData;
  19209. }
  19210. }
  19211. }
  19212. };
  19213. /**
  19214. *
  19215. * @param {Array.<vis.GraphGroup.id>} groupIds
  19216. * @param {vis.DataSet} groupsData
  19217. * @private
  19218. */
  19219. LineGraph.prototype._applySampling = function (groupIds, groupsData) {
  19220. var group;
  19221. if (groupIds.length > 0) {
  19222. for (var i = 0; i < groupIds.length; i++) {
  19223. group = this.groups[groupIds[i]];
  19224. if (group.options.sampling == true) {
  19225. var dataContainer = groupsData[groupIds[i]];
  19226. if (dataContainer.length > 0) {
  19227. var increment = 1;
  19228. var amountOfPoints = dataContainer.length;
  19229. // the global screen is used because changing the width of the yAxis may affect the increment, resulting in an endless loop
  19230. // of width changing of the yAxis.
  19231. //TODO: This assumes sorted data, but that's not guaranteed!
  19232. var xDistance = this.body.util.toGlobalScreen(dataContainer[dataContainer.length - 1].x) - this.body.util.toGlobalScreen(dataContainer[0].x);
  19233. var pointsPerPixel = amountOfPoints / xDistance;
  19234. increment = Math.min(Math.ceil(0.2 * amountOfPoints), Math.max(1, Math.round(pointsPerPixel)));
  19235. var sampledData = new Array(amountOfPoints);
  19236. for (var j = 0; j < amountOfPoints; j += increment) {
  19237. var idx = Math.round(j / increment);
  19238. sampledData[idx] = dataContainer[j];
  19239. }
  19240. groupsData[groupIds[i]] = sampledData.splice(0, Math.round(amountOfPoints / increment));
  19241. }
  19242. }
  19243. }
  19244. }
  19245. };
  19246. /**
  19247. *
  19248. * @param {Array.<vis.GraphGroup.id>} groupIds
  19249. * @param {vis.DataSet} groupsData
  19250. * @param {object} groupRanges | this is being filled here
  19251. * @private
  19252. */
  19253. LineGraph.prototype._getYRanges = function (groupIds, groupsData, groupRanges) {
  19254. var groupData, group, i;
  19255. var combinedDataLeft = [];
  19256. var combinedDataRight = [];
  19257. var options;
  19258. if (groupIds.length > 0) {
  19259. for (i = 0; i < groupIds.length; i++) {
  19260. groupData = groupsData[groupIds[i]];
  19261. options = this.groups[groupIds[i]].options;
  19262. if (groupData.length > 0) {
  19263. group = this.groups[groupIds[i]];
  19264. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  19265. if (options.stack === true && options.style === 'bar') {
  19266. if (options.yAxisOrientation === 'left') {
  19267. combinedDataLeft = combinedDataLeft.concat(groupData);
  19268. } else {
  19269. combinedDataRight = combinedDataRight.concat(groupData);
  19270. }
  19271. } else {
  19272. groupRanges[groupIds[i]] = group.getYRange(groupData, groupIds[i]);
  19273. }
  19274. }
  19275. }
  19276. // if bar graphs are stacked, their range need to be handled differently and accumulated over all groups.
  19277. Bars.getStackedYRange(combinedDataLeft, groupRanges, groupIds, '__barStackLeft', 'left');
  19278. Bars.getStackedYRange(combinedDataRight, groupRanges, groupIds, '__barStackRight', 'right');
  19279. }
  19280. };
  19281. /**
  19282. * this sets the Y ranges for the Y axis. It also determines which of the axis should be shown or hidden.
  19283. * @param {Array.<vis.GraphGroup.id>} groupIds
  19284. * @param {Object} groupRanges
  19285. * @returns {boolean} resized
  19286. * @private
  19287. */
  19288. LineGraph.prototype._updateYAxis = function (groupIds, groupRanges) {
  19289. var resized = false;
  19290. var yAxisLeftUsed = false;
  19291. var yAxisRightUsed = false;
  19292. var minLeft = 1e9,
  19293. minRight = 1e9,
  19294. maxLeft = -1e9,
  19295. maxRight = -1e9,
  19296. minVal,
  19297. maxVal;
  19298. // if groups are present
  19299. if (groupIds.length > 0) {
  19300. // 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.
  19301. for (var i = 0; i < groupIds.length; i++) {
  19302. var group = this.groups[groupIds[i]];
  19303. if (group && group.options.yAxisOrientation != 'right') {
  19304. yAxisLeftUsed = true;
  19305. minLeft = 1e9;
  19306. maxLeft = -1e9;
  19307. } else if (group && group.options.yAxisOrientation) {
  19308. yAxisRightUsed = true;
  19309. minRight = 1e9;
  19310. maxRight = -1e9;
  19311. }
  19312. }
  19313. // if there are items:
  19314. for (i = 0; i < groupIds.length; i++) {
  19315. if (groupRanges.hasOwnProperty(groupIds[i])) {
  19316. if (groupRanges[groupIds[i]].ignore !== true) {
  19317. minVal = groupRanges[groupIds[i]].min;
  19318. maxVal = groupRanges[groupIds[i]].max;
  19319. if (groupRanges[groupIds[i]].yAxisOrientation != 'right') {
  19320. yAxisLeftUsed = true;
  19321. minLeft = minLeft > minVal ? minVal : minLeft;
  19322. maxLeft = maxLeft < maxVal ? maxVal : maxLeft;
  19323. } else {
  19324. yAxisRightUsed = true;
  19325. minRight = minRight > minVal ? minVal : minRight;
  19326. maxRight = maxRight < maxVal ? maxVal : maxRight;
  19327. }
  19328. }
  19329. }
  19330. }
  19331. if (yAxisLeftUsed == true) {
  19332. this.yAxisLeft.setRange(minLeft, maxLeft);
  19333. }
  19334. if (yAxisRightUsed == true) {
  19335. this.yAxisRight.setRange(minRight, maxRight);
  19336. }
  19337. }
  19338. resized = this._toggleAxisVisiblity(yAxisLeftUsed, this.yAxisLeft) || resized;
  19339. resized = this._toggleAxisVisiblity(yAxisRightUsed, this.yAxisRight) || resized;
  19340. if (yAxisRightUsed == true && yAxisLeftUsed == true) {
  19341. this.yAxisLeft.drawIcons = true;
  19342. this.yAxisRight.drawIcons = true;
  19343. } else {
  19344. this.yAxisLeft.drawIcons = false;
  19345. this.yAxisRight.drawIcons = false;
  19346. }
  19347. this.yAxisRight.master = !yAxisLeftUsed;
  19348. this.yAxisRight.masterAxis = this.yAxisLeft;
  19349. if (this.yAxisRight.master == false) {
  19350. if (yAxisRightUsed == true) {
  19351. this.yAxisLeft.lineOffset = this.yAxisRight.width;
  19352. } else {
  19353. this.yAxisLeft.lineOffset = 0;
  19354. }
  19355. resized = this.yAxisLeft.redraw() || resized;
  19356. resized = this.yAxisRight.redraw() || resized;
  19357. } else {
  19358. resized = this.yAxisRight.redraw() || resized;
  19359. }
  19360. // clean the accumulated lists
  19361. var tempGroups = ['__barStackLeft', '__barStackRight', '__lineStackLeft', '__lineStackRight'];
  19362. for (i = 0; i < tempGroups.length; i++) {
  19363. if (groupIds.indexOf(tempGroups[i]) != -1) {
  19364. groupIds.splice(groupIds.indexOf(tempGroups[i]), 1);
  19365. }
  19366. }
  19367. return resized;
  19368. };
  19369. /**
  19370. * This shows or hides the Y axis if needed. If there is a change, the changed event is emitted by the updateYAxis function
  19371. *
  19372. * @param {boolean} axisUsed
  19373. * @param {vis.DataAxis} axis
  19374. * @returns {boolean}
  19375. * @private
  19376. */
  19377. LineGraph.prototype._toggleAxisVisiblity = function (axisUsed, axis) {
  19378. var changed = false;
  19379. if (axisUsed == false) {
  19380. if (axis.dom.frame.parentNode && axis.hidden == false) {
  19381. axis.hide();
  19382. changed = true;
  19383. }
  19384. } else {
  19385. if (!axis.dom.frame.parentNode && axis.hidden == true) {
  19386. axis.show();
  19387. changed = true;
  19388. }
  19389. }
  19390. return changed;
  19391. };
  19392. /**
  19393. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  19394. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  19395. * the yAxis.
  19396. *
  19397. * @param {Array.<Object>} datapoints
  19398. * @private
  19399. */
  19400. LineGraph.prototype._convertXcoordinates = function (datapoints) {
  19401. var toScreen = this.body.util.toScreen;
  19402. for (var i = 0; i < datapoints.length; i++) {
  19403. datapoints[i].screen_x = toScreen(datapoints[i].x) + this.props.width;
  19404. datapoints[i].screen_y = datapoints[i].y; //starting point for range calculations
  19405. if (datapoints[i].end != undefined) {
  19406. datapoints[i].screen_end = toScreen(datapoints[i].end) + this.props.width;
  19407. } else {
  19408. datapoints[i].screen_end = undefined;
  19409. }
  19410. }
  19411. };
  19412. /**
  19413. * This uses the DataAxis object to generate the correct X coordinate on the SVG window. It uses the
  19414. * util function toScreen to get the x coordinate from the timestamp. It also pre-filters the data and get the minMax ranges for
  19415. * the yAxis.
  19416. *
  19417. * @param {Array.<Object>} datapoints
  19418. * @param {vis.GraphGroup} group
  19419. * @private
  19420. */
  19421. LineGraph.prototype._convertYcoordinates = function (datapoints, group) {
  19422. var axis = this.yAxisLeft;
  19423. var svgHeight = Number(this.svg.style.height.replace('px', ''));
  19424. if (group.options.yAxisOrientation == 'right') {
  19425. axis = this.yAxisRight;
  19426. }
  19427. for (var i = 0; i < datapoints.length; i++) {
  19428. datapoints[i].screen_y = Math.round(axis.convertValue(datapoints[i].y));
  19429. }
  19430. group.setZeroPosition(Math.min(svgHeight, axis.convertValue(0)));
  19431. };
  19432. module.exports = LineGraph;
  19433. /***/ }),
  19434. /* 107 */
  19435. /***/ (function(module, exports, __webpack_require__) {
  19436. "use strict";
  19437. var _keys = __webpack_require__(8);
  19438. var _keys2 = _interopRequireDefault(_keys);
  19439. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  19440. var util = __webpack_require__(2);
  19441. var DOMutil = __webpack_require__(14);
  19442. var Component = __webpack_require__(16);
  19443. var DataScale = __webpack_require__(108);
  19444. /**
  19445. * A horizontal time axis
  19446. * @param {Object} body
  19447. * @param {Object} [options] See DataAxis.setOptions for the available
  19448. * options.
  19449. * @param {SVGElement} svg
  19450. * @param {vis.LineGraph.options} linegraphOptions
  19451. * @constructor DataAxis
  19452. * @extends Component
  19453. */
  19454. function DataAxis(body, options, svg, linegraphOptions) {
  19455. this.id = util.randomUUID();
  19456. this.body = body;
  19457. this.defaultOptions = {
  19458. orientation: 'left', // supported: 'left', 'right'
  19459. showMinorLabels: true,
  19460. showMajorLabels: true,
  19461. icons: false,
  19462. majorLinesOffset: 7,
  19463. minorLinesOffset: 4,
  19464. labelOffsetX: 10,
  19465. labelOffsetY: 2,
  19466. iconWidth: 20,
  19467. width: '40px',
  19468. visible: true,
  19469. alignZeros: true,
  19470. left: {
  19471. range: { min: undefined, max: undefined },
  19472. format: function format(value) {
  19473. return '' + parseFloat(value.toPrecision(3));
  19474. },
  19475. title: { text: undefined, style: undefined }
  19476. },
  19477. right: {
  19478. range: { min: undefined, max: undefined },
  19479. format: function format(value) {
  19480. return '' + parseFloat(value.toPrecision(3));
  19481. },
  19482. title: { text: undefined, style: undefined }
  19483. }
  19484. };
  19485. this.linegraphOptions = linegraphOptions;
  19486. this.linegraphSVG = svg;
  19487. this.props = {};
  19488. this.DOMelements = { // dynamic elements
  19489. lines: {},
  19490. labels: {},
  19491. title: {}
  19492. };
  19493. this.dom = {};
  19494. this.scale = undefined;
  19495. this.range = { start: 0, end: 0 };
  19496. this.options = util.extend({}, this.defaultOptions);
  19497. this.conversionFactor = 1;
  19498. this.setOptions(options);
  19499. this.width = Number(('' + this.options.width).replace("px", ""));
  19500. this.minWidth = this.width;
  19501. this.height = this.linegraphSVG.getBoundingClientRect().height;
  19502. this.hidden = false;
  19503. this.stepPixels = 25;
  19504. this.zeroCrossing = -1;
  19505. this.amountOfSteps = -1;
  19506. this.lineOffset = 0;
  19507. this.master = true;
  19508. this.masterAxis = null;
  19509. this.svgElements = {};
  19510. this.iconsRemoved = false;
  19511. this.groups = {};
  19512. this.amountOfGroups = 0;
  19513. // create the HTML DOM
  19514. this._create();
  19515. this.framework = { svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups };
  19516. var me = this;
  19517. this.body.emitter.on("verticalDrag", function () {
  19518. me.dom.lineContainer.style.top = me.body.domProps.scrollTop + 'px';
  19519. });
  19520. }
  19521. DataAxis.prototype = new Component();
  19522. DataAxis.prototype.addGroup = function (label, graphOptions) {
  19523. if (!this.groups.hasOwnProperty(label)) {
  19524. this.groups[label] = graphOptions;
  19525. }
  19526. this.amountOfGroups += 1;
  19527. };
  19528. DataAxis.prototype.updateGroup = function (label, graphOptions) {
  19529. if (!this.groups.hasOwnProperty(label)) {
  19530. this.amountOfGroups += 1;
  19531. }
  19532. this.groups[label] = graphOptions;
  19533. };
  19534. DataAxis.prototype.removeGroup = function (label) {
  19535. if (this.groups.hasOwnProperty(label)) {
  19536. delete this.groups[label];
  19537. this.amountOfGroups -= 1;
  19538. }
  19539. };
  19540. DataAxis.prototype.setOptions = function (options) {
  19541. if (options) {
  19542. var redraw = false;
  19543. if (this.options.orientation != options.orientation && options.orientation !== undefined) {
  19544. redraw = true;
  19545. }
  19546. var fields = ['orientation', 'showMinorLabels', 'showMajorLabels', 'icons', 'majorLinesOffset', 'minorLinesOffset', 'labelOffsetX', 'labelOffsetY', 'iconWidth', 'width', 'visible', 'left', 'right', 'alignZeros'];
  19547. util.selectiveDeepExtend(fields, this.options, options);
  19548. this.minWidth = Number(('' + this.options.width).replace("px", ""));
  19549. if (redraw === true && this.dom.frame) {
  19550. this.hide();
  19551. this.show();
  19552. }
  19553. }
  19554. };
  19555. /**
  19556. * Create the HTML DOM for the DataAxis
  19557. */
  19558. DataAxis.prototype._create = function () {
  19559. this.dom.frame = document.createElement('div');
  19560. this.dom.frame.style.width = this.options.width;
  19561. this.dom.frame.style.height = this.height;
  19562. this.dom.lineContainer = document.createElement('div');
  19563. this.dom.lineContainer.style.width = '100%';
  19564. this.dom.lineContainer.style.height = this.height;
  19565. this.dom.lineContainer.style.position = 'relative';
  19566. // create svg element for graph drawing.
  19567. this.svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
  19568. this.svg.style.position = "absolute";
  19569. this.svg.style.top = '0px';
  19570. this.svg.style.height = '100%';
  19571. this.svg.style.width = '100%';
  19572. this.svg.style.display = "block";
  19573. this.dom.frame.appendChild(this.svg);
  19574. };
  19575. DataAxis.prototype._redrawGroupIcons = function () {
  19576. DOMutil.prepareElements(this.svgElements);
  19577. var x;
  19578. var iconWidth = this.options.iconWidth;
  19579. var iconHeight = 15;
  19580. var iconOffset = 4;
  19581. var y = iconOffset + 0.5 * iconHeight;
  19582. if (this.options.orientation === 'left') {
  19583. x = iconOffset;
  19584. } else {
  19585. x = this.width - iconWidth - iconOffset;
  19586. }
  19587. var groupArray = (0, _keys2['default'])(this.groups);
  19588. groupArray.sort(function (a, b) {
  19589. return a < b ? -1 : 1;
  19590. });
  19591. for (var i = 0; i < groupArray.length; i++) {
  19592. var groupId = groupArray[i];
  19593. if (this.groups[groupId].visible === true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] === true)) {
  19594. this.groups[groupId].getLegend(iconWidth, iconHeight, this.framework, x, y);
  19595. y += iconHeight + iconOffset;
  19596. }
  19597. }
  19598. DOMutil.cleanupElements(this.svgElements);
  19599. this.iconsRemoved = false;
  19600. };
  19601. DataAxis.prototype._cleanupIcons = function () {
  19602. if (this.iconsRemoved === false) {
  19603. DOMutil.prepareElements(this.svgElements);
  19604. DOMutil.cleanupElements(this.svgElements);
  19605. this.iconsRemoved = true;
  19606. }
  19607. };
  19608. /**
  19609. * Create the HTML DOM for the DataAxis
  19610. */
  19611. DataAxis.prototype.show = function () {
  19612. this.hidden = false;
  19613. if (!this.dom.frame.parentNode) {
  19614. if (this.options.orientation === 'left') {
  19615. this.body.dom.left.appendChild(this.dom.frame);
  19616. } else {
  19617. this.body.dom.right.appendChild(this.dom.frame);
  19618. }
  19619. }
  19620. if (!this.dom.lineContainer.parentNode) {
  19621. this.body.dom.backgroundHorizontal.appendChild(this.dom.lineContainer);
  19622. }
  19623. };
  19624. /**
  19625. * Create the HTML DOM for the DataAxis
  19626. */
  19627. DataAxis.prototype.hide = function () {
  19628. this.hidden = true;
  19629. if (this.dom.frame.parentNode) {
  19630. this.dom.frame.parentNode.removeChild(this.dom.frame);
  19631. }
  19632. if (this.dom.lineContainer.parentNode) {
  19633. this.dom.lineContainer.parentNode.removeChild(this.dom.lineContainer);
  19634. }
  19635. };
  19636. /**
  19637. * Set a range (start and end)
  19638. * @param {number} start
  19639. * @param {number} end
  19640. */
  19641. DataAxis.prototype.setRange = function (start, end) {
  19642. this.range.start = start;
  19643. this.range.end = end;
  19644. };
  19645. /**
  19646. * Repaint the component
  19647. * @return {boolean} Returns true if the component is resized
  19648. */
  19649. DataAxis.prototype.redraw = function () {
  19650. var resized = false;
  19651. var activeGroups = 0;
  19652. // Make sure the line container adheres to the vertical scrolling.
  19653. this.dom.lineContainer.style.top = this.body.domProps.scrollTop + 'px';
  19654. for (var groupId in this.groups) {
  19655. if (this.groups.hasOwnProperty(groupId)) {
  19656. if (this.groups[groupId].visible === true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] === true)) {
  19657. activeGroups++;
  19658. }
  19659. }
  19660. }
  19661. if (this.amountOfGroups === 0 || activeGroups === 0) {
  19662. this.hide();
  19663. } else {
  19664. this.show();
  19665. this.height = Number(this.linegraphSVG.style.height.replace("px", ""));
  19666. // svg offsetheight did not work in firefox and explorer...
  19667. this.dom.lineContainer.style.height = this.height + 'px';
  19668. this.width = this.options.visible === true ? Number(('' + this.options.width).replace("px", "")) : 0;
  19669. var props = this.props;
  19670. var frame = this.dom.frame;
  19671. // update classname
  19672. frame.className = 'vis-data-axis';
  19673. // calculate character width and height
  19674. this._calculateCharSize();
  19675. var orientation = this.options.orientation;
  19676. var showMinorLabels = this.options.showMinorLabels;
  19677. var showMajorLabels = this.options.showMajorLabels;
  19678. // determine the width and height of the elements for the axis
  19679. props.minorLabelHeight = showMinorLabels ? props.minorCharHeight : 0;
  19680. props.majorLabelHeight = showMajorLabels ? props.majorCharHeight : 0;
  19681. props.minorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.minorLinesOffset;
  19682. props.minorLineHeight = 1;
  19683. props.majorLineWidth = this.body.dom.backgroundHorizontal.offsetWidth - this.lineOffset - this.width + 2 * this.options.majorLinesOffset;
  19684. props.majorLineHeight = 1;
  19685. // take frame offline while updating (is almost twice as fast)
  19686. if (orientation === 'left') {
  19687. frame.style.top = '0';
  19688. frame.style.left = '0';
  19689. frame.style.bottom = '';
  19690. frame.style.width = this.width + 'px';
  19691. frame.style.height = this.height + "px";
  19692. this.props.width = this.body.domProps.left.width;
  19693. this.props.height = this.body.domProps.left.height;
  19694. } else {
  19695. // right
  19696. frame.style.top = '';
  19697. frame.style.bottom = '0';
  19698. frame.style.left = '0';
  19699. frame.style.width = this.width + 'px';
  19700. frame.style.height = this.height + "px";
  19701. this.props.width = this.body.domProps.right.width;
  19702. this.props.height = this.body.domProps.right.height;
  19703. }
  19704. resized = this._redrawLabels();
  19705. resized = this._isResized() || resized;
  19706. if (this.options.icons === true) {
  19707. this._redrawGroupIcons();
  19708. } else {
  19709. this._cleanupIcons();
  19710. }
  19711. this._redrawTitle(orientation);
  19712. }
  19713. return resized;
  19714. };
  19715. /**
  19716. * Repaint major and minor text labels and vertical grid lines
  19717. *
  19718. * @returns {boolean}
  19719. * @private
  19720. */
  19721. DataAxis.prototype._redrawLabels = function () {
  19722. var _this = this;
  19723. var resized = false;
  19724. DOMutil.prepareElements(this.DOMelements.lines);
  19725. DOMutil.prepareElements(this.DOMelements.labels);
  19726. var orientation = this.options['orientation'];
  19727. var customRange = this.options[orientation].range != undefined ? this.options[orientation].range : {};
  19728. //Override range with manual options:
  19729. var autoScaleEnd = true;
  19730. if (customRange.max != undefined) {
  19731. this.range.end = customRange.max;
  19732. autoScaleEnd = false;
  19733. }
  19734. var autoScaleStart = true;
  19735. if (customRange.min != undefined) {
  19736. this.range.start = customRange.min;
  19737. autoScaleStart = false;
  19738. }
  19739. 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);
  19740. if (this.master === false && this.masterAxis != undefined) {
  19741. this.scale.followScale(this.masterAxis.scale);
  19742. }
  19743. //Is updated in side-effect of _redrawLabel():
  19744. this.maxLabelSize = 0;
  19745. var lines = this.scale.getLines();
  19746. lines.forEach(function (line) {
  19747. var y = line.y;
  19748. var isMajor = line.major;
  19749. if (_this.options['showMinorLabels'] && isMajor === false) {
  19750. _this._redrawLabel(y - 2, line.val, orientation, 'vis-y-axis vis-minor', _this.props.minorCharHeight);
  19751. }
  19752. if (isMajor) {
  19753. if (y >= 0) {
  19754. _this._redrawLabel(y - 2, line.val, orientation, 'vis-y-axis vis-major', _this.props.majorCharHeight);
  19755. }
  19756. }
  19757. if (_this.master === true) {
  19758. if (isMajor) {
  19759. _this._redrawLine(y, orientation, 'vis-grid vis-horizontal vis-major', _this.options.majorLinesOffset, _this.props.majorLineWidth);
  19760. } else {
  19761. _this._redrawLine(y, orientation, 'vis-grid vis-horizontal vis-minor', _this.options.minorLinesOffset, _this.props.minorLineWidth);
  19762. }
  19763. }
  19764. });
  19765. // Note that title is rotated, so we're using the height, not width!
  19766. var titleWidth = 0;
  19767. if (this.options[orientation].title !== undefined && this.options[orientation].title.text !== undefined) {
  19768. titleWidth = this.props.titleCharHeight;
  19769. }
  19770. var offset = this.options.icons === true ? Math.max(this.options.iconWidth, titleWidth) + this.options.labelOffsetX + 15 : titleWidth + this.options.labelOffsetX + 15;
  19771. // this will resize the yAxis to accommodate the labels.
  19772. if (this.maxLabelSize > this.width - offset && this.options.visible === true) {
  19773. this.width = this.maxLabelSize + offset;
  19774. this.options.width = this.width + "px";
  19775. DOMutil.cleanupElements(this.DOMelements.lines);
  19776. DOMutil.cleanupElements(this.DOMelements.labels);
  19777. this.redraw();
  19778. resized = true;
  19779. }
  19780. // this will resize the yAxis if it is too big for the labels.
  19781. else if (this.maxLabelSize < this.width - offset && this.options.visible === true && this.width > this.minWidth) {
  19782. this.width = Math.max(this.minWidth, this.maxLabelSize + offset);
  19783. this.options.width = this.width + "px";
  19784. DOMutil.cleanupElements(this.DOMelements.lines);
  19785. DOMutil.cleanupElements(this.DOMelements.labels);
  19786. this.redraw();
  19787. resized = true;
  19788. } else {
  19789. DOMutil.cleanupElements(this.DOMelements.lines);
  19790. DOMutil.cleanupElements(this.DOMelements.labels);
  19791. resized = false;
  19792. }
  19793. return resized;
  19794. };
  19795. DataAxis.prototype.convertValue = function (value) {
  19796. return this.scale.convertValue(value);
  19797. };
  19798. DataAxis.prototype.screenToValue = function (x) {
  19799. return this.scale.screenToValue(x);
  19800. };
  19801. /**
  19802. * Create a label for the axis at position x
  19803. *
  19804. * @param {number} y
  19805. * @param {string} text
  19806. * @param {'top'|'right'|'bottom'|'left'} orientation
  19807. * @param {string} className
  19808. * @param {number} characterHeight
  19809. * @private
  19810. */
  19811. DataAxis.prototype._redrawLabel = function (y, text, orientation, className, characterHeight) {
  19812. // reuse redundant label
  19813. var label = DOMutil.getDOMElement('div', this.DOMelements.labels, this.dom.frame); //this.dom.redundant.labels.shift();
  19814. label.className = className;
  19815. label.innerHTML = text;
  19816. if (orientation === 'left') {
  19817. label.style.left = '-' + this.options.labelOffsetX + 'px';
  19818. label.style.textAlign = "right";
  19819. } else {
  19820. label.style.right = '-' + this.options.labelOffsetX + 'px';
  19821. label.style.textAlign = "left";
  19822. }
  19823. label.style.top = y - 0.5 * characterHeight + this.options.labelOffsetY + 'px';
  19824. text += '';
  19825. var largestWidth = Math.max(this.props.majorCharWidth, this.props.minorCharWidth);
  19826. if (this.maxLabelSize < text.length * largestWidth) {
  19827. this.maxLabelSize = text.length * largestWidth;
  19828. }
  19829. };
  19830. /**
  19831. * Create a minor line for the axis at position y
  19832. * @param {number} y
  19833. * @param {'top'|'right'|'bottom'|'left'} orientation
  19834. * @param {string} className
  19835. * @param {number} offset
  19836. * @param {number} width
  19837. */
  19838. DataAxis.prototype._redrawLine = function (y, orientation, className, offset, width) {
  19839. if (this.master === true) {
  19840. var line = DOMutil.getDOMElement('div', this.DOMelements.lines, this.dom.lineContainer); //this.dom.redundant.lines.shift();
  19841. line.className = className;
  19842. line.innerHTML = '';
  19843. if (orientation === 'left') {
  19844. line.style.left = this.width - offset + 'px';
  19845. } else {
  19846. line.style.right = this.width - offset + 'px';
  19847. }
  19848. line.style.width = width + 'px';
  19849. line.style.top = y + 'px';
  19850. }
  19851. };
  19852. /**
  19853. * Create a title for the axis
  19854. * @private
  19855. * @param {'top'|'right'|'bottom'|'left'} orientation
  19856. */
  19857. DataAxis.prototype._redrawTitle = function (orientation) {
  19858. DOMutil.prepareElements(this.DOMelements.title);
  19859. // Check if the title is defined for this axes
  19860. if (this.options[orientation].title !== undefined && this.options[orientation].title.text !== undefined) {
  19861. var title = DOMutil.getDOMElement('div', this.DOMelements.title, this.dom.frame);
  19862. title.className = 'vis-y-axis vis-title vis-' + orientation;
  19863. title.innerHTML = this.options[orientation].title.text;
  19864. // Add style - if provided
  19865. if (this.options[orientation].title.style !== undefined) {
  19866. util.addCssText(title, this.options[orientation].title.style);
  19867. }
  19868. if (orientation === 'left') {
  19869. title.style.left = this.props.titleCharHeight + 'px';
  19870. } else {
  19871. title.style.right = this.props.titleCharHeight + 'px';
  19872. }
  19873. title.style.width = this.height + 'px';
  19874. }
  19875. // we need to clean up in case we did not use all elements.
  19876. DOMutil.cleanupElements(this.DOMelements.title);
  19877. };
  19878. /**
  19879. * Determine the size of text on the axis (both major and minor axis).
  19880. * The size is calculated only once and then cached in this.props.
  19881. * @private
  19882. */
  19883. DataAxis.prototype._calculateCharSize = function () {
  19884. // determine the char width and height on the minor axis
  19885. if (!('minorCharHeight' in this.props)) {
  19886. var textMinor = document.createTextNode('0');
  19887. var measureCharMinor = document.createElement('div');
  19888. measureCharMinor.className = 'vis-y-axis vis-minor vis-measure';
  19889. measureCharMinor.appendChild(textMinor);
  19890. this.dom.frame.appendChild(measureCharMinor);
  19891. this.props.minorCharHeight = measureCharMinor.clientHeight;
  19892. this.props.minorCharWidth = measureCharMinor.clientWidth;
  19893. this.dom.frame.removeChild(measureCharMinor);
  19894. }
  19895. if (!('majorCharHeight' in this.props)) {
  19896. var textMajor = document.createTextNode('0');
  19897. var measureCharMajor = document.createElement('div');
  19898. measureCharMajor.className = 'vis-y-axis vis-major vis-measure';
  19899. measureCharMajor.appendChild(textMajor);
  19900. this.dom.frame.appendChild(measureCharMajor);
  19901. this.props.majorCharHeight = measureCharMajor.clientHeight;
  19902. this.props.majorCharWidth = measureCharMajor.clientWidth;
  19903. this.dom.frame.removeChild(measureCharMajor);
  19904. }
  19905. if (!('titleCharHeight' in this.props)) {
  19906. var textTitle = document.createTextNode('0');
  19907. var measureCharTitle = document.createElement('div');
  19908. measureCharTitle.className = 'vis-y-axis vis-title vis-measure';
  19909. measureCharTitle.appendChild(textTitle);
  19910. this.dom.frame.appendChild(measureCharTitle);
  19911. this.props.titleCharHeight = measureCharTitle.clientHeight;
  19912. this.props.titleCharWidth = measureCharTitle.clientWidth;
  19913. this.dom.frame.removeChild(measureCharTitle);
  19914. }
  19915. };
  19916. module.exports = DataAxis;
  19917. /***/ }),
  19918. /* 108 */
  19919. /***/ (function(module, exports, __webpack_require__) {
  19920. "use strict";
  19921. /**
  19922. *
  19923. * @param {number} start
  19924. * @param {number} end
  19925. * @param {boolean} autoScaleStart
  19926. * @param {boolean} autoScaleEnd
  19927. * @param {number} containerHeight
  19928. * @param {number} majorCharHeight
  19929. * @param {boolean} zeroAlign
  19930. * @param {function} formattingFunction
  19931. * @constructor DataScale
  19932. */
  19933. function DataScale(start, end, autoScaleStart, autoScaleEnd, containerHeight, majorCharHeight) {
  19934. var zeroAlign = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false;
  19935. var formattingFunction = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : false;
  19936. this.majorSteps = [1, 2, 5, 10];
  19937. this.minorSteps = [0.25, 0.5, 1, 2];
  19938. this.customLines = null;
  19939. this.containerHeight = containerHeight;
  19940. this.majorCharHeight = majorCharHeight;
  19941. this._start = start;
  19942. this._end = end;
  19943. this.scale = 1;
  19944. this.minorStepIdx = -1;
  19945. this.magnitudefactor = 1;
  19946. this.determineScale();
  19947. this.zeroAlign = zeroAlign;
  19948. this.autoScaleStart = autoScaleStart;
  19949. this.autoScaleEnd = autoScaleEnd;
  19950. this.formattingFunction = formattingFunction;
  19951. if (autoScaleStart || autoScaleEnd) {
  19952. var me = this;
  19953. var roundToMinor = function roundToMinor(value) {
  19954. var rounded = value - value % (me.magnitudefactor * me.minorSteps[me.minorStepIdx]);
  19955. if (value % (me.magnitudefactor * me.minorSteps[me.minorStepIdx]) > 0.5 * (me.magnitudefactor * me.minorSteps[me.minorStepIdx])) {
  19956. return rounded + me.magnitudefactor * me.minorSteps[me.minorStepIdx];
  19957. } else {
  19958. return rounded;
  19959. }
  19960. };
  19961. if (autoScaleStart) {
  19962. this._start -= this.magnitudefactor * 2 * this.minorSteps[this.minorStepIdx];
  19963. this._start = roundToMinor(this._start);
  19964. }
  19965. if (autoScaleEnd) {
  19966. this._end += this.magnitudefactor * this.minorSteps[this.minorStepIdx];
  19967. this._end = roundToMinor(this._end);
  19968. }
  19969. this.determineScale();
  19970. }
  19971. }
  19972. DataScale.prototype.setCharHeight = function (majorCharHeight) {
  19973. this.majorCharHeight = majorCharHeight;
  19974. };
  19975. DataScale.prototype.setHeight = function (containerHeight) {
  19976. this.containerHeight = containerHeight;
  19977. };
  19978. DataScale.prototype.determineScale = function () {
  19979. var range = this._end - this._start;
  19980. this.scale = this.containerHeight / range;
  19981. var minimumStepValue = this.majorCharHeight / this.scale;
  19982. var orderOfMagnitude = range > 0 ? Math.round(Math.log(range) / Math.LN10) : 0;
  19983. this.minorStepIdx = -1;
  19984. this.magnitudefactor = Math.pow(10, orderOfMagnitude);
  19985. var start = 0;
  19986. if (orderOfMagnitude < 0) {
  19987. start = orderOfMagnitude;
  19988. }
  19989. var solutionFound = false;
  19990. for (var l = start; Math.abs(l) <= Math.abs(orderOfMagnitude); l++) {
  19991. this.magnitudefactor = Math.pow(10, l);
  19992. for (var j = 0; j < this.minorSteps.length; j++) {
  19993. var stepSize = this.magnitudefactor * this.minorSteps[j];
  19994. if (stepSize >= minimumStepValue) {
  19995. solutionFound = true;
  19996. this.minorStepIdx = j;
  19997. break;
  19998. }
  19999. }
  20000. if (solutionFound === true) {
  20001. break;
  20002. }
  20003. }
  20004. };
  20005. DataScale.prototype.is_major = function (value) {
  20006. return value % (this.magnitudefactor * this.majorSteps[this.minorStepIdx]) === 0;
  20007. };
  20008. DataScale.prototype.getStep = function () {
  20009. return this.magnitudefactor * this.minorSteps[this.minorStepIdx];
  20010. };
  20011. DataScale.prototype.getFirstMajor = function () {
  20012. var majorStep = this.magnitudefactor * this.majorSteps[this.minorStepIdx];
  20013. return this.convertValue(this._start + (majorStep - this._start % majorStep) % majorStep);
  20014. };
  20015. DataScale.prototype.formatValue = function (current) {
  20016. var returnValue = current.toPrecision(5);
  20017. if (typeof this.formattingFunction === 'function') {
  20018. returnValue = this.formattingFunction(current);
  20019. }
  20020. if (typeof returnValue === 'number') {
  20021. return '' + returnValue;
  20022. } else if (typeof returnValue === 'string') {
  20023. return returnValue;
  20024. } else {
  20025. return current.toPrecision(5);
  20026. }
  20027. };
  20028. DataScale.prototype.getLines = function () {
  20029. var lines = [];
  20030. var step = this.getStep();
  20031. var bottomOffset = (step - this._start % step) % step;
  20032. for (var i = this._start + bottomOffset; this._end - i > 0.00001; i += step) {
  20033. if (i != this._start) {
  20034. //Skip the bottom line
  20035. lines.push({ major: this.is_major(i), y: this.convertValue(i), val: this.formatValue(i) });
  20036. }
  20037. }
  20038. return lines;
  20039. };
  20040. DataScale.prototype.followScale = function (other) {
  20041. var oldStepIdx = this.minorStepIdx;
  20042. var oldStart = this._start;
  20043. var oldEnd = this._end;
  20044. var me = this;
  20045. var increaseMagnitude = function increaseMagnitude() {
  20046. me.magnitudefactor *= 2;
  20047. };
  20048. var decreaseMagnitude = function decreaseMagnitude() {
  20049. me.magnitudefactor /= 2;
  20050. };
  20051. if (other.minorStepIdx <= 1 && this.minorStepIdx <= 1 || other.minorStepIdx > 1 && this.minorStepIdx > 1) {
  20052. //easy, no need to change stepIdx nor multiplication factor
  20053. } else if (other.minorStepIdx < this.minorStepIdx) {
  20054. //I'm 5, they are 4 per major.
  20055. this.minorStepIdx = 1;
  20056. if (oldStepIdx == 2) {
  20057. increaseMagnitude();
  20058. } else {
  20059. increaseMagnitude();
  20060. increaseMagnitude();
  20061. }
  20062. } else {
  20063. //I'm 4, they are 5 per major
  20064. this.minorStepIdx = 2;
  20065. if (oldStepIdx == 1) {
  20066. decreaseMagnitude();
  20067. } else {
  20068. decreaseMagnitude();
  20069. decreaseMagnitude();
  20070. }
  20071. }
  20072. //Get masters stats:
  20073. var otherZero = other.convertValue(0);
  20074. var otherStep = other.getStep() * other.scale;
  20075. var done = false;
  20076. var count = 0;
  20077. //Loop until magnitude is correct for given constrains.
  20078. while (!done && count++ < 5) {
  20079. //Get my stats:
  20080. this.scale = otherStep / (this.minorSteps[this.minorStepIdx] * this.magnitudefactor);
  20081. var newRange = this.containerHeight / this.scale;
  20082. //For the case the magnitudefactor has changed:
  20083. this._start = oldStart;
  20084. this._end = this._start + newRange;
  20085. var myOriginalZero = this._end * this.scale;
  20086. var majorStep = this.magnitudefactor * this.majorSteps[this.minorStepIdx];
  20087. var majorOffset = this.getFirstMajor() - other.getFirstMajor();
  20088. if (this.zeroAlign) {
  20089. var zeroOffset = otherZero - myOriginalZero;
  20090. this._end += zeroOffset / this.scale;
  20091. this._start = this._end - newRange;
  20092. } else {
  20093. if (!this.autoScaleStart) {
  20094. this._start += majorStep - majorOffset / this.scale;
  20095. this._end = this._start + newRange;
  20096. } else {
  20097. this._start -= majorOffset / this.scale;
  20098. this._end = this._start + newRange;
  20099. }
  20100. }
  20101. if (!this.autoScaleEnd && this._end > oldEnd + 0.00001) {
  20102. //Need to decrease magnitude to prevent scale overshoot! (end)
  20103. decreaseMagnitude();
  20104. done = false;
  20105. continue;
  20106. }
  20107. if (!this.autoScaleStart && this._start < oldStart - 0.00001) {
  20108. if (this.zeroAlign && oldStart >= 0) {
  20109. console.warn("Can't adhere to given 'min' range, due to zeroalign");
  20110. } else {
  20111. //Need to decrease magnitude to prevent scale overshoot! (start)
  20112. decreaseMagnitude();
  20113. done = false;
  20114. continue;
  20115. }
  20116. }
  20117. if (this.autoScaleStart && this.autoScaleEnd && newRange < oldEnd - oldStart) {
  20118. increaseMagnitude();
  20119. done = false;
  20120. continue;
  20121. }
  20122. done = true;
  20123. }
  20124. };
  20125. DataScale.prototype.convertValue = function (value) {
  20126. return this.containerHeight - (value - this._start) * this.scale;
  20127. };
  20128. DataScale.prototype.screenToValue = function (pixels) {
  20129. return (this.containerHeight - pixels) / this.scale + this._start;
  20130. };
  20131. module.exports = DataScale;
  20132. /***/ }),
  20133. /* 109 */
  20134. /***/ (function(module, exports, __webpack_require__) {
  20135. "use strict";
  20136. var _typeof2 = __webpack_require__(6);
  20137. var _typeof3 = _interopRequireDefault(_typeof2);
  20138. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  20139. var util = __webpack_require__(2);
  20140. var Bars = __webpack_require__(110);
  20141. var Lines = __webpack_require__(111);
  20142. var Points = __webpack_require__(72);
  20143. /**
  20144. * /**
  20145. * @param {object} group | the object of the group from the dataset
  20146. * @param {string} groupId | ID of the group
  20147. * @param {object} options | the default options
  20148. * @param {array} groupsUsingDefaultStyles | this array has one entree.
  20149. * It is passed as an array so it is passed by reference.
  20150. * It enumerates through the default styles
  20151. * @constructor GraphGroup
  20152. */
  20153. function GraphGroup(group, groupId, options, groupsUsingDefaultStyles) {
  20154. this.id = groupId;
  20155. var fields = ['sampling', 'style', 'sort', 'yAxisOrientation', 'barChart', 'drawPoints', 'shaded', 'interpolation', 'zIndex', 'excludeFromStacking', 'excludeFromLegend'];
  20156. this.options = util.selectiveBridgeObject(fields, options);
  20157. this.usingDefaultStyle = group.className === undefined;
  20158. this.groupsUsingDefaultStyles = groupsUsingDefaultStyles;
  20159. this.zeroPosition = 0;
  20160. this.update(group);
  20161. if (this.usingDefaultStyle == true) {
  20162. this.groupsUsingDefaultStyles[0] += 1;
  20163. }
  20164. this.itemsData = [];
  20165. this.visible = group.visible === undefined ? true : group.visible;
  20166. }
  20167. /**
  20168. * this loads a reference to all items in this group into this group.
  20169. * @param {array} items
  20170. */
  20171. GraphGroup.prototype.setItems = function (items) {
  20172. if (items != null) {
  20173. this.itemsData = items;
  20174. if (this.options.sort == true) {
  20175. util.insertSort(this.itemsData, function (a, b) {
  20176. return a.x > b.x ? 1 : -1;
  20177. });
  20178. }
  20179. } else {
  20180. this.itemsData = [];
  20181. }
  20182. };
  20183. GraphGroup.prototype.getItems = function () {
  20184. return this.itemsData;
  20185. };
  20186. /**
  20187. * this is used for barcharts and shading, this way, we only have to calculate it once.
  20188. * @param {number} pos
  20189. */
  20190. GraphGroup.prototype.setZeroPosition = function (pos) {
  20191. this.zeroPosition = pos;
  20192. };
  20193. /**
  20194. * set the options of the graph group over the default options.
  20195. * @param {Object} options
  20196. */
  20197. GraphGroup.prototype.setOptions = function (options) {
  20198. if (options !== undefined) {
  20199. var fields = ['sampling', 'style', 'sort', 'yAxisOrientation', 'barChart', 'zIndex', 'excludeFromStacking', 'excludeFromLegend'];
  20200. util.selectiveDeepExtend(fields, this.options, options);
  20201. // if the group's drawPoints is a function delegate the callback to the onRender property
  20202. if (typeof options.drawPoints == 'function') {
  20203. options.drawPoints = {
  20204. onRender: options.drawPoints
  20205. };
  20206. }
  20207. util.mergeOptions(this.options, options, 'interpolation');
  20208. util.mergeOptions(this.options, options, 'drawPoints');
  20209. util.mergeOptions(this.options, options, 'shaded');
  20210. if (options.interpolation) {
  20211. if ((0, _typeof3['default'])(options.interpolation) == 'object') {
  20212. if (options.interpolation.parametrization) {
  20213. if (options.interpolation.parametrization == 'uniform') {
  20214. this.options.interpolation.alpha = 0;
  20215. } else if (options.interpolation.parametrization == 'chordal') {
  20216. this.options.interpolation.alpha = 1.0;
  20217. } else {
  20218. this.options.interpolation.parametrization = 'centripetal';
  20219. this.options.interpolation.alpha = 0.5;
  20220. }
  20221. }
  20222. }
  20223. }
  20224. }
  20225. };
  20226. /**
  20227. * this updates the current group class with the latest group dataset entree, used in _updateGroup in linegraph
  20228. * @param {vis.Group} group
  20229. */
  20230. GraphGroup.prototype.update = function (group) {
  20231. this.group = group;
  20232. this.content = group.content || 'graph';
  20233. this.className = group.className || this.className || 'vis-graph-group' + this.groupsUsingDefaultStyles[0] % 10;
  20234. this.visible = group.visible === undefined ? true : group.visible;
  20235. this.style = group.style;
  20236. this.setOptions(group.options);
  20237. };
  20238. /**
  20239. * return the legend entree for this group.
  20240. *
  20241. * @param {number} iconWidth
  20242. * @param {number} iconHeight
  20243. * @param {{svg: (*|Element), svgElements: Object, options: Object, groups: Array.<Object>}} framework
  20244. * @param {number} x
  20245. * @param {number} y
  20246. * @returns {{icon: (*|Element), label: (*|string), orientation: *}}
  20247. */
  20248. GraphGroup.prototype.getLegend = function (iconWidth, iconHeight, framework, x, y) {
  20249. if (framework == undefined || framework == null) {
  20250. var svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
  20251. framework = { svg: svg, svgElements: {}, options: this.options, groups: [this] };
  20252. }
  20253. if (x == undefined || x == null) {
  20254. x = 0;
  20255. }
  20256. if (y == undefined || y == null) {
  20257. y = 0.5 * iconHeight;
  20258. }
  20259. switch (this.options.style) {
  20260. case "line":
  20261. Lines.drawIcon(this, x, y, iconWidth, iconHeight, framework);
  20262. break;
  20263. case "points": //explicit no break
  20264. case "point":
  20265. Points.drawIcon(this, x, y, iconWidth, iconHeight, framework);
  20266. break;
  20267. case "bar":
  20268. Bars.drawIcon(this, x, y, iconWidth, iconHeight, framework);
  20269. break;
  20270. }
  20271. return { icon: framework.svg, label: this.content, orientation: this.options.yAxisOrientation };
  20272. };
  20273. GraphGroup.prototype.getYRange = function (groupData) {
  20274. var yMin = groupData[0].y;
  20275. var yMax = groupData[0].y;
  20276. for (var j = 0; j < groupData.length; j++) {
  20277. yMin = yMin > groupData[j].y ? groupData[j].y : yMin;
  20278. yMax = yMax < groupData[j].y ? groupData[j].y : yMax;
  20279. }
  20280. return { min: yMin, max: yMax, yAxisOrientation: this.options.yAxisOrientation };
  20281. };
  20282. module.exports = GraphGroup;
  20283. /***/ }),
  20284. /* 110 */
  20285. /***/ (function(module, exports, __webpack_require__) {
  20286. "use strict";
  20287. var DOMutil = __webpack_require__(14);
  20288. var Points = __webpack_require__(72);
  20289. /**
  20290. *
  20291. * @param {vis.GraphGroup.id} groupId
  20292. * @param {Object} options // TODO: Describe options
  20293. * @constructor Bargraph
  20294. */
  20295. function Bargraph(groupId, options) {// eslint-disable-line no-unused-vars
  20296. }
  20297. Bargraph.drawIcon = function (group, x, y, iconWidth, iconHeight, framework) {
  20298. var fillHeight = iconHeight * 0.5;
  20299. var outline = DOMutil.getSVGElement("rect", framework.svgElements, framework.svg);
  20300. outline.setAttributeNS(null, "x", x);
  20301. outline.setAttributeNS(null, "y", y - fillHeight);
  20302. outline.setAttributeNS(null, "width", iconWidth);
  20303. outline.setAttributeNS(null, "height", 2 * fillHeight);
  20304. outline.setAttributeNS(null, "class", "vis-outline");
  20305. var barWidth = Math.round(0.3 * iconWidth);
  20306. var originalWidth = group.options.barChart.width;
  20307. var scale = originalWidth / barWidth;
  20308. var bar1Height = Math.round(0.4 * iconHeight);
  20309. var bar2Height = Math.round(0.75 * iconHeight);
  20310. var offset = Math.round((iconWidth - 2 * barWidth) / 3);
  20311. DOMutil.drawBar(x + 0.5 * barWidth + offset, y + fillHeight - bar1Height - 1, barWidth, bar1Height, group.className + ' vis-bar', framework.svgElements, framework.svg, group.style);
  20312. DOMutil.drawBar(x + 1.5 * barWidth + offset + 2, y + fillHeight - bar2Height - 1, barWidth, bar2Height, group.className + ' vis-bar', framework.svgElements, framework.svg, group.style);
  20313. if (group.options.drawPoints.enabled == true) {
  20314. var groupTemplate = {
  20315. style: group.options.drawPoints.style,
  20316. styles: group.options.drawPoints.styles,
  20317. size: group.options.drawPoints.size / scale,
  20318. className: group.className
  20319. };
  20320. DOMutil.drawPoint(x + 0.5 * barWidth + offset, y + fillHeight - bar1Height - 1, groupTemplate, framework.svgElements, framework.svg);
  20321. DOMutil.drawPoint(x + 1.5 * barWidth + offset + 2, y + fillHeight - bar2Height - 1, groupTemplate, framework.svgElements, framework.svg);
  20322. }
  20323. };
  20324. /**
  20325. * draw a bar graph
  20326. *
  20327. * @param {Array.<vis.GraphGroup.id>} groupIds
  20328. * @param {Object} processedGroupData
  20329. * @param {{svg: Object, svgElements: Array.<Object>, options: Object, groups: Array.<vis.Group>}} framework
  20330. */
  20331. Bargraph.draw = function (groupIds, processedGroupData, framework) {
  20332. var combinedData = [];
  20333. var intersections = {};
  20334. var coreDistance;
  20335. var key, drawData;
  20336. var group;
  20337. var i, j;
  20338. var barPoints = 0;
  20339. // combine all barchart data
  20340. for (i = 0; i < groupIds.length; i++) {
  20341. group = framework.groups[groupIds[i]];
  20342. if (group.options.style === 'bar') {
  20343. if (group.visible === true && (framework.options.groups.visibility[groupIds[i]] === undefined || framework.options.groups.visibility[groupIds[i]] === true)) {
  20344. for (j = 0; j < processedGroupData[groupIds[i]].length; j++) {
  20345. combinedData.push({
  20346. screen_x: processedGroupData[groupIds[i]][j].screen_x,
  20347. screen_end: processedGroupData[groupIds[i]][j].screen_end,
  20348. screen_y: processedGroupData[groupIds[i]][j].screen_y,
  20349. x: processedGroupData[groupIds[i]][j].x,
  20350. end: processedGroupData[groupIds[i]][j].end,
  20351. y: processedGroupData[groupIds[i]][j].y,
  20352. groupId: groupIds[i],
  20353. label: processedGroupData[groupIds[i]][j].label
  20354. });
  20355. barPoints += 1;
  20356. }
  20357. }
  20358. }
  20359. }
  20360. if (barPoints === 0) {
  20361. return;
  20362. }
  20363. // sort by time and by group
  20364. combinedData.sort(function (a, b) {
  20365. if (a.screen_x === b.screen_x) {
  20366. return a.groupId < b.groupId ? -1 : 1;
  20367. } else {
  20368. return a.screen_x - b.screen_x;
  20369. }
  20370. });
  20371. // get intersections
  20372. Bargraph._getDataIntersections(intersections, combinedData);
  20373. // plot barchart
  20374. for (i = 0; i < combinedData.length; i++) {
  20375. group = framework.groups[combinedData[i].groupId];
  20376. var minWidth = group.options.barChart.minWidth != undefined ? group.options.barChart.minWidth : 0.1 * group.options.barChart.width;
  20377. key = combinedData[i].screen_x;
  20378. var heightOffset = 0;
  20379. if (intersections[key] === undefined) {
  20380. if (i + 1 < combinedData.length) {
  20381. coreDistance = Math.abs(combinedData[i + 1].screen_x - key);
  20382. }
  20383. drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth);
  20384. } else {
  20385. var nextKey = i + (intersections[key].amount - intersections[key].resolved);
  20386. if (nextKey < combinedData.length) {
  20387. coreDistance = Math.abs(combinedData[nextKey].screen_x - key);
  20388. }
  20389. drawData = Bargraph._getSafeDrawData(coreDistance, group, minWidth);
  20390. intersections[key].resolved += 1;
  20391. if (group.options.stack === true && group.options.excludeFromStacking !== true) {
  20392. if (combinedData[i].screen_y < group.zeroPosition) {
  20393. heightOffset = intersections[key].accumulatedNegative;
  20394. intersections[key].accumulatedNegative += group.zeroPosition - combinedData[i].screen_y;
  20395. } else {
  20396. heightOffset = intersections[key].accumulatedPositive;
  20397. intersections[key].accumulatedPositive += group.zeroPosition - combinedData[i].screen_y;
  20398. }
  20399. } else if (group.options.barChart.sideBySide === true) {
  20400. drawData.width = drawData.width / intersections[key].amount;
  20401. drawData.offset += intersections[key].resolved * drawData.width - 0.5 * drawData.width * (intersections[key].amount + 1);
  20402. }
  20403. }
  20404. var dataWidth = drawData.width;
  20405. var start = combinedData[i].screen_x;
  20406. // are we drawing explicit boxes? (we supplied an end value)
  20407. if (combinedData[i].screen_end != undefined) {
  20408. dataWidth = combinedData[i].screen_end - combinedData[i].screen_x;
  20409. start += dataWidth * 0.5;
  20410. } else {
  20411. start += drawData.offset;
  20412. }
  20413. DOMutil.drawBar(start, combinedData[i].screen_y - heightOffset, dataWidth, group.zeroPosition - combinedData[i].screen_y, group.className + ' vis-bar', framework.svgElements, framework.svg, group.style);
  20414. // draw points
  20415. if (group.options.drawPoints.enabled === true) {
  20416. var pointData = {
  20417. screen_x: combinedData[i].screen_x,
  20418. screen_y: combinedData[i].screen_y - heightOffset,
  20419. x: combinedData[i].x,
  20420. y: combinedData[i].y,
  20421. groupId: combinedData[i].groupId,
  20422. label: combinedData[i].label
  20423. };
  20424. Points.draw([pointData], group, framework, drawData.offset);
  20425. //DOMutil.drawPoint(combinedData[i].x + drawData.offset, combinedData[i].y, group, framework.svgElements, framework.svg);
  20426. }
  20427. }
  20428. };
  20429. /**
  20430. * Fill the intersections object with counters of how many datapoints share the same x coordinates
  20431. * @param {Object} intersections
  20432. * @param {Array.<Object>} combinedData
  20433. * @private
  20434. */
  20435. Bargraph._getDataIntersections = function (intersections, combinedData) {
  20436. // get intersections
  20437. var coreDistance;
  20438. for (var i = 0; i < combinedData.length; i++) {
  20439. if (i + 1 < combinedData.length) {
  20440. coreDistance = Math.abs(combinedData[i + 1].screen_x - combinedData[i].screen_x);
  20441. }
  20442. if (i > 0) {
  20443. coreDistance = Math.min(coreDistance, Math.abs(combinedData[i - 1].screen_x - combinedData[i].screen_x));
  20444. }
  20445. if (coreDistance === 0) {
  20446. if (intersections[combinedData[i].screen_x] === undefined) {
  20447. intersections[combinedData[i].screen_x] = {
  20448. amount: 0,
  20449. resolved: 0,
  20450. accumulatedPositive: 0,
  20451. accumulatedNegative: 0
  20452. };
  20453. }
  20454. intersections[combinedData[i].screen_x].amount += 1;
  20455. }
  20456. }
  20457. };
  20458. /**
  20459. * Get the width and offset for bargraphs based on the coredistance between datapoints
  20460. *
  20461. * @param {number} coreDistance
  20462. * @param {vis.Group} group
  20463. * @param {number} minWidth
  20464. * @returns {{width: number, offset: number}}
  20465. * @private
  20466. */
  20467. Bargraph._getSafeDrawData = function (coreDistance, group, minWidth) {
  20468. var width, offset;
  20469. if (coreDistance < group.options.barChart.width && coreDistance > 0) {
  20470. width = coreDistance < minWidth ? minWidth : coreDistance;
  20471. offset = 0; // recalculate offset with the new width;
  20472. if (group.options.barChart.align === 'left') {
  20473. offset -= 0.5 * coreDistance;
  20474. } else if (group.options.barChart.align === 'right') {
  20475. offset += 0.5 * coreDistance;
  20476. }
  20477. } else {
  20478. // default settings
  20479. width = group.options.barChart.width;
  20480. offset = 0;
  20481. if (group.options.barChart.align === 'left') {
  20482. offset -= 0.5 * group.options.barChart.width;
  20483. } else if (group.options.barChart.align === 'right') {
  20484. offset += 0.5 * group.options.barChart.width;
  20485. }
  20486. }
  20487. return { width: width, offset: offset };
  20488. };
  20489. Bargraph.getStackedYRange = function (combinedData, groupRanges, groupIds, groupLabel, orientation) {
  20490. if (combinedData.length > 0) {
  20491. // sort by time and by group
  20492. combinedData.sort(function (a, b) {
  20493. if (a.screen_x === b.screen_x) {
  20494. return a.groupId < b.groupId ? -1 : 1;
  20495. } else {
  20496. return a.screen_x - b.screen_x;
  20497. }
  20498. });
  20499. var intersections = {};
  20500. Bargraph._getDataIntersections(intersections, combinedData);
  20501. groupRanges[groupLabel] = Bargraph._getStackedYRange(intersections, combinedData);
  20502. groupRanges[groupLabel].yAxisOrientation = orientation;
  20503. groupIds.push(groupLabel);
  20504. }
  20505. };
  20506. Bargraph._getStackedYRange = function (intersections, combinedData) {
  20507. var key;
  20508. var yMin = combinedData[0].screen_y;
  20509. var yMax = combinedData[0].screen_y;
  20510. for (var i = 0; i < combinedData.length; i++) {
  20511. key = combinedData[i].screen_x;
  20512. if (intersections[key] === undefined) {
  20513. yMin = yMin > combinedData[i].screen_y ? combinedData[i].screen_y : yMin;
  20514. yMax = yMax < combinedData[i].screen_y ? combinedData[i].screen_y : yMax;
  20515. } else {
  20516. if (combinedData[i].screen_y < 0) {
  20517. intersections[key].accumulatedNegative += combinedData[i].screen_y;
  20518. } else {
  20519. intersections[key].accumulatedPositive += combinedData[i].screen_y;
  20520. }
  20521. }
  20522. }
  20523. for (var xpos in intersections) {
  20524. if (intersections.hasOwnProperty(xpos)) {
  20525. yMin = yMin > intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMin;
  20526. yMin = yMin > intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMin;
  20527. yMax = yMax < intersections[xpos].accumulatedNegative ? intersections[xpos].accumulatedNegative : yMax;
  20528. yMax = yMax < intersections[xpos].accumulatedPositive ? intersections[xpos].accumulatedPositive : yMax;
  20529. }
  20530. }
  20531. return { min: yMin, max: yMax };
  20532. };
  20533. module.exports = Bargraph;
  20534. /***/ }),
  20535. /* 111 */
  20536. /***/ (function(module, exports, __webpack_require__) {
  20537. "use strict";
  20538. var DOMutil = __webpack_require__(14);
  20539. /**
  20540. *
  20541. * @param {vis.GraphGroup.id} groupId
  20542. * @param {Object} options // TODO: Describe options
  20543. * @constructor Line
  20544. */
  20545. function Line(groupId, options) {// eslint-disable-line no-unused-vars
  20546. }
  20547. Line.calcPath = function (dataset, group) {
  20548. if (dataset != null) {
  20549. if (dataset.length > 0) {
  20550. var d = [];
  20551. // construct path from dataset
  20552. if (group.options.interpolation.enabled == true) {
  20553. d = Line._catmullRom(dataset, group);
  20554. } else {
  20555. d = Line._linear(dataset);
  20556. }
  20557. return d;
  20558. }
  20559. }
  20560. };
  20561. Line.drawIcon = function (group, x, y, iconWidth, iconHeight, framework) {
  20562. var fillHeight = iconHeight * 0.5;
  20563. var path, fillPath;
  20564. var outline = DOMutil.getSVGElement("rect", framework.svgElements, framework.svg);
  20565. outline.setAttributeNS(null, "x", x);
  20566. outline.setAttributeNS(null, "y", y - fillHeight);
  20567. outline.setAttributeNS(null, "width", iconWidth);
  20568. outline.setAttributeNS(null, "height", 2 * fillHeight);
  20569. outline.setAttributeNS(null, "class", "vis-outline");
  20570. path = DOMutil.getSVGElement("path", framework.svgElements, framework.svg);
  20571. path.setAttributeNS(null, "class", group.className);
  20572. if (group.style !== undefined) {
  20573. path.setAttributeNS(null, "style", group.style);
  20574. }
  20575. path.setAttributeNS(null, "d", "M" + x + "," + y + " L" + (x + iconWidth) + "," + y + "");
  20576. if (group.options.shaded.enabled == true) {
  20577. fillPath = DOMutil.getSVGElement("path", framework.svgElements, framework.svg);
  20578. if (group.options.shaded.orientation == 'top') {
  20579. fillPath.setAttributeNS(null, "d", "M" + x + ", " + (y - fillHeight) + "L" + x + "," + y + " L" + (x + iconWidth) + "," + y + " L" + (x + iconWidth) + "," + (y - fillHeight));
  20580. } else {
  20581. fillPath.setAttributeNS(null, "d", "M" + x + "," + y + " " + "L" + x + "," + (y + fillHeight) + " " + "L" + (x + iconWidth) + "," + (y + fillHeight) + "L" + (x + iconWidth) + "," + y);
  20582. }
  20583. fillPath.setAttributeNS(null, "class", group.className + " vis-icon-fill");
  20584. if (group.options.shaded.style !== undefined && group.options.shaded.style !== "") {
  20585. fillPath.setAttributeNS(null, "style", group.options.shaded.style);
  20586. }
  20587. }
  20588. if (group.options.drawPoints.enabled == true) {
  20589. var groupTemplate = {
  20590. style: group.options.drawPoints.style,
  20591. styles: group.options.drawPoints.styles,
  20592. size: group.options.drawPoints.size,
  20593. className: group.className
  20594. };
  20595. DOMutil.drawPoint(x + 0.5 * iconWidth, y, groupTemplate, framework.svgElements, framework.svg);
  20596. }
  20597. };
  20598. Line.drawShading = function (pathArray, group, subPathArray, framework) {
  20599. // append shading to the path
  20600. if (group.options.shaded.enabled == true) {
  20601. var svgHeight = Number(framework.svg.style.height.replace('px', ''));
  20602. var fillPath = DOMutil.getSVGElement('path', framework.svgElements, framework.svg);
  20603. var type = "L";
  20604. if (group.options.interpolation.enabled == true) {
  20605. type = "C";
  20606. }
  20607. var dFill;
  20608. var zero = 0;
  20609. if (group.options.shaded.orientation == 'top') {
  20610. zero = 0;
  20611. } else if (group.options.shaded.orientation == 'bottom') {
  20612. zero = svgHeight;
  20613. } else {
  20614. zero = Math.min(Math.max(0, group.zeroPosition), svgHeight);
  20615. }
  20616. if (group.options.shaded.orientation == 'group' && subPathArray != null && subPathArray != undefined) {
  20617. 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";
  20618. } else {
  20619. dFill = 'M' + pathArray[0][0] + "," + pathArray[0][1] + " " + this.serializePath(pathArray, type, false) + ' V' + zero + ' H' + pathArray[0][0] + " Z";
  20620. }
  20621. fillPath.setAttributeNS(null, 'class', group.className + ' vis-fill');
  20622. if (group.options.shaded.style !== undefined) {
  20623. fillPath.setAttributeNS(null, 'style', group.options.shaded.style);
  20624. }
  20625. fillPath.setAttributeNS(null, 'd', dFill);
  20626. }
  20627. };
  20628. /**
  20629. * draw a line graph
  20630. *
  20631. * @param {Array.<Object>} pathArray
  20632. * @param {vis.Group} group
  20633. * @param {{svg: Object, svgElements: Array.<Object>, options: Object, groups: Array.<vis.Group>}} framework
  20634. */
  20635. Line.draw = function (pathArray, group, framework) {
  20636. if (pathArray != null && pathArray != undefined) {
  20637. var path = DOMutil.getSVGElement('path', framework.svgElements, framework.svg);
  20638. path.setAttributeNS(null, "class", group.className);
  20639. if (group.style !== undefined) {
  20640. path.setAttributeNS(null, "style", group.style);
  20641. }
  20642. var type = "L";
  20643. if (group.options.interpolation.enabled == true) {
  20644. type = "C";
  20645. }
  20646. // copy properties to path for drawing.
  20647. path.setAttributeNS(null, 'd', 'M' + pathArray[0][0] + "," + pathArray[0][1] + " " + this.serializePath(pathArray, type, false));
  20648. }
  20649. };
  20650. Line.serializePath = function (pathArray, type, inverse) {
  20651. if (pathArray.length < 2) {
  20652. //Too little data to create a path.
  20653. return "";
  20654. }
  20655. var d = type;
  20656. var i;
  20657. if (inverse) {
  20658. for (i = pathArray.length - 2; i > 0; i--) {
  20659. d += pathArray[i][0] + "," + pathArray[i][1] + " ";
  20660. }
  20661. } else {
  20662. for (i = 1; i < pathArray.length; i++) {
  20663. d += pathArray[i][0] + "," + pathArray[i][1] + " ";
  20664. }
  20665. }
  20666. return d;
  20667. };
  20668. /**
  20669. * This uses an uniform parametrization of the interpolation algorithm:
  20670. * 'On the Parameterization of Catmull-Rom Curves' by Cem Yuksel et al.
  20671. * @param {Array.<Object>} data
  20672. * @returns {string}
  20673. * @private
  20674. */
  20675. Line._catmullRomUniform = function (data) {
  20676. // catmull rom
  20677. var p0, p1, p2, p3, bp1, bp2;
  20678. var d = [];
  20679. d.push([Math.round(data[0].screen_x), Math.round(data[0].screen_y)]);
  20680. var normalization = 1 / 6;
  20681. var length = data.length;
  20682. for (var i = 0; i < length - 1; i++) {
  20683. p0 = i == 0 ? data[0] : data[i - 1];
  20684. p1 = data[i];
  20685. p2 = data[i + 1];
  20686. p3 = i + 2 < length ? data[i + 2] : p2;
  20687. // Catmull-Rom to Cubic Bezier conversion matrix
  20688. // 0 1 0 0
  20689. // -1/6 1 1/6 0
  20690. // 0 1/6 1 -1/6
  20691. // 0 0 1 0
  20692. // bp0 = { x: p1.x, y: p1.y };
  20693. bp1 = {
  20694. screen_x: (-p0.screen_x + 6 * p1.screen_x + p2.screen_x) * normalization,
  20695. screen_y: (-p0.screen_y + 6 * p1.screen_y + p2.screen_y) * normalization
  20696. };
  20697. bp2 = {
  20698. screen_x: (p1.screen_x + 6 * p2.screen_x - p3.screen_x) * normalization,
  20699. screen_y: (p1.screen_y + 6 * p2.screen_y - p3.screen_y) * normalization
  20700. };
  20701. // bp0 = { x: p2.x, y: p2.y };
  20702. d.push([bp1.screen_x, bp1.screen_y]);
  20703. d.push([bp2.screen_x, bp2.screen_y]);
  20704. d.push([p2.screen_x, p2.screen_y]);
  20705. }
  20706. return d;
  20707. };
  20708. /**
  20709. * This uses either the chordal or centripetal parameterization of the catmull-rom algorithm.
  20710. * By default, the centripetal parameterization is used because this gives the nicest results.
  20711. * These parameterizations are relatively heavy because the distance between 4 points have to be calculated.
  20712. *
  20713. * One optimization can be used to reuse distances since this is a sliding window approach.
  20714. * @param {Array.<Object>} data
  20715. * @param {vis.GraphGroup} group
  20716. * @returns {string}
  20717. * @private
  20718. */
  20719. Line._catmullRom = function (data, group) {
  20720. var alpha = group.options.interpolation.alpha;
  20721. if (alpha == 0 || alpha === undefined) {
  20722. return this._catmullRomUniform(data);
  20723. } else {
  20724. var p0, p1, p2, p3, bp1, bp2, d1, d2, d3, A, B, N, M;
  20725. var d3powA, d2powA, d3pow2A, d2pow2A, d1pow2A, d1powA;
  20726. var d = [];
  20727. d.push([Math.round(data[0].screen_x), Math.round(data[0].screen_y)]);
  20728. var length = data.length;
  20729. for (var i = 0; i < length - 1; i++) {
  20730. p0 = i == 0 ? data[0] : data[i - 1];
  20731. p1 = data[i];
  20732. p2 = data[i + 1];
  20733. p3 = i + 2 < length ? data[i + 2] : p2;
  20734. d1 = Math.sqrt(Math.pow(p0.screen_x - p1.screen_x, 2) + Math.pow(p0.screen_y - p1.screen_y, 2));
  20735. d2 = Math.sqrt(Math.pow(p1.screen_x - p2.screen_x, 2) + Math.pow(p1.screen_y - p2.screen_y, 2));
  20736. d3 = Math.sqrt(Math.pow(p2.screen_x - p3.screen_x, 2) + Math.pow(p2.screen_y - p3.screen_y, 2));
  20737. // Catmull-Rom to Cubic Bezier conversion matrix
  20738. // A = 2d1^2a + 3d1^a * d2^a + d3^2a
  20739. // B = 2d3^2a + 3d3^a * d2^a + d2^2a
  20740. // [ 0 1 0 0 ]
  20741. // [ -d2^2a /N A/N d1^2a /N 0 ]
  20742. // [ 0 d3^2a /M B/M -d2^2a /M ]
  20743. // [ 0 0 1 0 ]
  20744. d3powA = Math.pow(d3, alpha);
  20745. d3pow2A = Math.pow(d3, 2 * alpha);
  20746. d2powA = Math.pow(d2, alpha);
  20747. d2pow2A = Math.pow(d2, 2 * alpha);
  20748. d1powA = Math.pow(d1, alpha);
  20749. d1pow2A = Math.pow(d1, 2 * alpha);
  20750. A = 2 * d1pow2A + 3 * d1powA * d2powA + d2pow2A;
  20751. B = 2 * d3pow2A + 3 * d3powA * d2powA + d2pow2A;
  20752. N = 3 * d1powA * (d1powA + d2powA);
  20753. if (N > 0) {
  20754. N = 1 / N;
  20755. }
  20756. M = 3 * d3powA * (d3powA + d2powA);
  20757. if (M > 0) {
  20758. M = 1 / M;
  20759. }
  20760. bp1 = {
  20761. screen_x: (-d2pow2A * p0.screen_x + A * p1.screen_x + d1pow2A * p2.screen_x) * N,
  20762. screen_y: (-d2pow2A * p0.screen_y + A * p1.screen_y + d1pow2A * p2.screen_y) * N
  20763. };
  20764. bp2 = {
  20765. screen_x: (d3pow2A * p1.screen_x + B * p2.screen_x - d2pow2A * p3.screen_x) * M,
  20766. screen_y: (d3pow2A * p1.screen_y + B * p2.screen_y - d2pow2A * p3.screen_y) * M
  20767. };
  20768. if (bp1.screen_x == 0 && bp1.screen_y == 0) {
  20769. bp1 = p1;
  20770. }
  20771. if (bp2.screen_x == 0 && bp2.screen_y == 0) {
  20772. bp2 = p2;
  20773. }
  20774. d.push([bp1.screen_x, bp1.screen_y]);
  20775. d.push([bp2.screen_x, bp2.screen_y]);
  20776. d.push([p2.screen_x, p2.screen_y]);
  20777. }
  20778. return d;
  20779. }
  20780. };
  20781. /**
  20782. * this generates the SVG path for a linear drawing between datapoints.
  20783. * @param {Array.<Object>} data
  20784. * @returns {string}
  20785. * @private
  20786. */
  20787. Line._linear = function (data) {
  20788. // linear
  20789. var d = [];
  20790. for (var i = 0; i < data.length; i++) {
  20791. d.push([data[i].screen_x, data[i].screen_y]);
  20792. }
  20793. return d;
  20794. };
  20795. module.exports = Line;
  20796. /***/ }),
  20797. /* 112 */
  20798. /***/ (function(module, exports, __webpack_require__) {
  20799. "use strict";
  20800. var _keys = __webpack_require__(8);
  20801. var _keys2 = _interopRequireDefault(_keys);
  20802. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  20803. var util = __webpack_require__(2);
  20804. var DOMutil = __webpack_require__(14);
  20805. var Component = __webpack_require__(16);
  20806. /**
  20807. * Legend for Graph2d
  20808. *
  20809. * @param {vis.Graph2d.body} body
  20810. * @param {vis.Graph2d.options} options
  20811. * @param {number} side
  20812. * @param {vis.LineGraph.options} linegraphOptions
  20813. * @constructor Legend
  20814. * @extends Component
  20815. */
  20816. function Legend(body, options, side, linegraphOptions) {
  20817. this.body = body;
  20818. this.defaultOptions = {
  20819. enabled: false,
  20820. icons: true,
  20821. iconSize: 20,
  20822. iconSpacing: 6,
  20823. left: {
  20824. visible: true,
  20825. position: 'top-left' // top/bottom - left,center,right
  20826. },
  20827. right: {
  20828. visible: true,
  20829. position: 'top-right' // top/bottom - left,center,right
  20830. }
  20831. };
  20832. this.side = side;
  20833. this.options = util.extend({}, this.defaultOptions);
  20834. this.linegraphOptions = linegraphOptions;
  20835. this.svgElements = {};
  20836. this.dom = {};
  20837. this.groups = {};
  20838. this.amountOfGroups = 0;
  20839. this._create();
  20840. this.framework = { svg: this.svg, svgElements: this.svgElements, options: this.options, groups: this.groups };
  20841. this.setOptions(options);
  20842. }
  20843. Legend.prototype = new Component();
  20844. Legend.prototype.clear = function () {
  20845. this.groups = {};
  20846. this.amountOfGroups = 0;
  20847. };
  20848. Legend.prototype.addGroup = function (label, graphOptions) {
  20849. // Include a group only if the group option 'excludeFromLegend: false' is not set.
  20850. if (graphOptions.options.excludeFromLegend != true) {
  20851. if (!this.groups.hasOwnProperty(label)) {
  20852. this.groups[label] = graphOptions;
  20853. }
  20854. this.amountOfGroups += 1;
  20855. }
  20856. };
  20857. Legend.prototype.updateGroup = function (label, graphOptions) {
  20858. this.groups[label] = graphOptions;
  20859. };
  20860. Legend.prototype.removeGroup = function (label) {
  20861. if (this.groups.hasOwnProperty(label)) {
  20862. delete this.groups[label];
  20863. this.amountOfGroups -= 1;
  20864. }
  20865. };
  20866. Legend.prototype._create = function () {
  20867. this.dom.frame = document.createElement('div');
  20868. this.dom.frame.className = 'vis-legend';
  20869. this.dom.frame.style.position = "absolute";
  20870. this.dom.frame.style.top = "10px";
  20871. this.dom.frame.style.display = "block";
  20872. this.dom.textArea = document.createElement('div');
  20873. this.dom.textArea.className = 'vis-legend-text';
  20874. this.dom.textArea.style.position = "relative";
  20875. this.dom.textArea.style.top = "0px";
  20876. this.svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
  20877. this.svg.style.position = 'absolute';
  20878. this.svg.style.top = 0 + 'px';
  20879. this.svg.style.width = this.options.iconSize + 5 + 'px';
  20880. this.svg.style.height = '100%';
  20881. this.dom.frame.appendChild(this.svg);
  20882. this.dom.frame.appendChild(this.dom.textArea);
  20883. };
  20884. /**
  20885. * Hide the component from the DOM
  20886. */
  20887. Legend.prototype.hide = function () {
  20888. // remove the frame containing the items
  20889. if (this.dom.frame.parentNode) {
  20890. this.dom.frame.parentNode.removeChild(this.dom.frame);
  20891. }
  20892. };
  20893. /**
  20894. * Show the component in the DOM (when not already visible).
  20895. */
  20896. Legend.prototype.show = function () {
  20897. // show frame containing the items
  20898. if (!this.dom.frame.parentNode) {
  20899. this.body.dom.center.appendChild(this.dom.frame);
  20900. }
  20901. };
  20902. Legend.prototype.setOptions = function (options) {
  20903. var fields = ['enabled', 'orientation', 'icons', 'left', 'right'];
  20904. util.selectiveDeepExtend(fields, this.options, options);
  20905. };
  20906. Legend.prototype.redraw = function () {
  20907. var activeGroups = 0;
  20908. var groupArray = (0, _keys2['default'])(this.groups);
  20909. groupArray.sort(function (a, b) {
  20910. return a < b ? -1 : 1;
  20911. });
  20912. for (var i = 0; i < groupArray.length; i++) {
  20913. var groupId = groupArray[i];
  20914. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  20915. activeGroups++;
  20916. }
  20917. }
  20918. if (this.options[this.side].visible == false || this.amountOfGroups == 0 || this.options.enabled == false || activeGroups == 0) {
  20919. this.hide();
  20920. } else {
  20921. this.show();
  20922. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'bottom-left') {
  20923. this.dom.frame.style.left = '4px';
  20924. this.dom.frame.style.textAlign = "left";
  20925. this.dom.textArea.style.textAlign = "left";
  20926. this.dom.textArea.style.left = this.options.iconSize + 15 + 'px';
  20927. this.dom.textArea.style.right = '';
  20928. this.svg.style.left = 0 + 'px';
  20929. this.svg.style.right = '';
  20930. } else {
  20931. this.dom.frame.style.right = '4px';
  20932. this.dom.frame.style.textAlign = "right";
  20933. this.dom.textArea.style.textAlign = "right";
  20934. this.dom.textArea.style.right = this.options.iconSize + 15 + 'px';
  20935. this.dom.textArea.style.left = '';
  20936. this.svg.style.right = 0 + 'px';
  20937. this.svg.style.left = '';
  20938. }
  20939. if (this.options[this.side].position == 'top-left' || this.options[this.side].position == 'top-right') {
  20940. this.dom.frame.style.top = 4 - Number(this.body.dom.center.style.top.replace("px", "")) + 'px';
  20941. this.dom.frame.style.bottom = '';
  20942. } else {
  20943. var scrollableHeight = this.body.domProps.center.height - this.body.domProps.centerContainer.height;
  20944. this.dom.frame.style.bottom = 4 + scrollableHeight + Number(this.body.dom.center.style.top.replace("px", "")) + 'px';
  20945. this.dom.frame.style.top = '';
  20946. }
  20947. if (this.options.icons == false) {
  20948. this.dom.frame.style.width = this.dom.textArea.offsetWidth + 10 + 'px';
  20949. this.dom.textArea.style.right = '';
  20950. this.dom.textArea.style.left = '';
  20951. this.svg.style.width = '0px';
  20952. } else {
  20953. this.dom.frame.style.width = this.options.iconSize + 15 + this.dom.textArea.offsetWidth + 10 + 'px';
  20954. this.drawLegendIcons();
  20955. }
  20956. var content = '';
  20957. for (i = 0; i < groupArray.length; i++) {
  20958. groupId = groupArray[i];
  20959. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  20960. content += this.groups[groupId].content + '<br />';
  20961. }
  20962. }
  20963. this.dom.textArea.innerHTML = content;
  20964. this.dom.textArea.style.lineHeight = 0.75 * this.options.iconSize + this.options.iconSpacing + 'px';
  20965. }
  20966. };
  20967. Legend.prototype.drawLegendIcons = function () {
  20968. if (this.dom.frame.parentNode) {
  20969. var groupArray = (0, _keys2['default'])(this.groups);
  20970. groupArray.sort(function (a, b) {
  20971. return a < b ? -1 : 1;
  20972. });
  20973. // this resets the elements so the order is maintained
  20974. DOMutil.resetElements(this.svgElements);
  20975. var padding = window.getComputedStyle(this.dom.frame).paddingTop;
  20976. var iconOffset = Number(padding.replace('px', ''));
  20977. var x = iconOffset;
  20978. var iconWidth = this.options.iconSize;
  20979. var iconHeight = 0.75 * this.options.iconSize;
  20980. var y = iconOffset + 0.5 * iconHeight + 3;
  20981. this.svg.style.width = iconWidth + 5 + iconOffset + 'px';
  20982. for (var i = 0; i < groupArray.length; i++) {
  20983. var groupId = groupArray[i];
  20984. if (this.groups[groupId].visible == true && (this.linegraphOptions.visibility[groupId] === undefined || this.linegraphOptions.visibility[groupId] == true)) {
  20985. this.groups[groupId].getLegend(iconWidth, iconHeight, this.framework, x, y);
  20986. y += iconHeight + this.options.iconSpacing;
  20987. }
  20988. }
  20989. }
  20990. };
  20991. module.exports = Legend;
  20992. /***/ }),
  20993. /* 113 */
  20994. /***/ (function(module, exports, __webpack_require__) {
  20995. "use strict";
  20996. Object.defineProperty(exports, "__esModule", {
  20997. value: true
  20998. });
  20999. /**
  21000. * This object contains all possible options. It will check if the types are correct, if required if the option is one
  21001. * of the allowed values.
  21002. *
  21003. * __any__ means that the name of the property does not matter.
  21004. * __type__ is a required field for all objects and contains the allowed types of all objects
  21005. */
  21006. var string = 'string';
  21007. var bool = 'boolean';
  21008. var number = 'number';
  21009. var array = 'array';
  21010. var date = 'date';
  21011. var object = 'object'; // should only be in a __type__ property
  21012. var dom = 'dom';
  21013. var moment = 'moment';
  21014. var any = 'any';
  21015. var allOptions = {
  21016. configure: {
  21017. enabled: { 'boolean': bool },
  21018. filter: { 'boolean': bool, 'function': 'function' },
  21019. container: { dom: dom },
  21020. __type__: { object: object, 'boolean': bool, 'function': 'function' }
  21021. },
  21022. //globals :
  21023. yAxisOrientation: { string: ['left', 'right'] },
  21024. defaultGroup: { string: string },
  21025. sort: { 'boolean': bool },
  21026. sampling: { 'boolean': bool },
  21027. stack: { 'boolean': bool },
  21028. graphHeight: { string: string, number: number },
  21029. shaded: {
  21030. enabled: { 'boolean': bool },
  21031. orientation: { string: ['bottom', 'top', 'zero', 'group'] }, // top, bottom, zero, group
  21032. groupId: { object: object },
  21033. __type__: { 'boolean': bool, object: object }
  21034. },
  21035. style: { string: ['line', 'bar', 'points'] }, // line, bar
  21036. barChart: {
  21037. width: { number: number },
  21038. minWidth: { number: number },
  21039. sideBySide: { 'boolean': bool },
  21040. align: { string: ['left', 'center', 'right'] },
  21041. __type__: { object: object }
  21042. },
  21043. interpolation: {
  21044. enabled: { 'boolean': bool },
  21045. parametrization: { string: ['centripetal', 'chordal', 'uniform'] }, // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  21046. alpha: { number: number },
  21047. __type__: { object: object, 'boolean': bool }
  21048. },
  21049. drawPoints: {
  21050. enabled: { 'boolean': bool },
  21051. onRender: { 'function': 'function' },
  21052. size: { number: number },
  21053. style: { string: ['square', 'circle'] }, // square, circle
  21054. __type__: { object: object, 'boolean': bool, 'function': 'function' }
  21055. },
  21056. dataAxis: {
  21057. showMinorLabels: { 'boolean': bool },
  21058. showMajorLabels: { 'boolean': bool },
  21059. icons: { 'boolean': bool },
  21060. width: { string: string, number: number },
  21061. visible: { 'boolean': bool },
  21062. alignZeros: { 'boolean': bool },
  21063. left: {
  21064. range: { min: { number: number, 'undefined': 'undefined' }, max: { number: number, 'undefined': 'undefined' }, __type__: { object: object } },
  21065. format: { 'function': 'function' },
  21066. title: { text: { string: string, number: number, 'undefined': 'undefined' }, style: { string: string, 'undefined': 'undefined' }, __type__: { object: object } },
  21067. __type__: { object: object }
  21068. },
  21069. right: {
  21070. range: { min: { number: number, 'undefined': 'undefined' }, max: { number: number, 'undefined': 'undefined' }, __type__: { object: object } },
  21071. format: { 'function': 'function' },
  21072. title: { text: { string: string, number: number, 'undefined': 'undefined' }, style: { string: string, 'undefined': 'undefined' }, __type__: { object: object } },
  21073. __type__: { object: object }
  21074. },
  21075. __type__: { object: object }
  21076. },
  21077. legend: {
  21078. enabled: { 'boolean': bool },
  21079. icons: { 'boolean': bool },
  21080. left: {
  21081. visible: { 'boolean': bool },
  21082. position: { string: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] },
  21083. __type__: { object: object }
  21084. },
  21085. right: {
  21086. visible: { 'boolean': bool },
  21087. position: { string: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] },
  21088. __type__: { object: object }
  21089. },
  21090. __type__: { object: object, 'boolean': bool }
  21091. },
  21092. groups: {
  21093. visibility: { any: any },
  21094. __type__: { object: object }
  21095. },
  21096. autoResize: { 'boolean': bool },
  21097. throttleRedraw: { number: number }, // TODO: DEPRICATED see https://github.com/almende/vis/issues/2511
  21098. clickToUse: { 'boolean': bool },
  21099. end: { number: number, date: date, string: string, moment: moment },
  21100. format: {
  21101. minorLabels: {
  21102. millisecond: { string: string, 'undefined': 'undefined' },
  21103. second: { string: string, 'undefined': 'undefined' },
  21104. minute: { string: string, 'undefined': 'undefined' },
  21105. hour: { string: string, 'undefined': 'undefined' },
  21106. weekday: { string: string, 'undefined': 'undefined' },
  21107. day: { string: string, 'undefined': 'undefined' },
  21108. month: { string: string, 'undefined': 'undefined' },
  21109. year: { string: string, 'undefined': 'undefined' },
  21110. __type__: { object: object }
  21111. },
  21112. majorLabels: {
  21113. millisecond: { string: string, 'undefined': 'undefined' },
  21114. second: { string: string, 'undefined': 'undefined' },
  21115. minute: { string: string, 'undefined': 'undefined' },
  21116. hour: { string: string, 'undefined': 'undefined' },
  21117. weekday: { string: string, 'undefined': 'undefined' },
  21118. day: { string: string, 'undefined': 'undefined' },
  21119. month: { string: string, 'undefined': 'undefined' },
  21120. year: { string: string, 'undefined': 'undefined' },
  21121. __type__: { object: object }
  21122. },
  21123. __type__: { object: object }
  21124. },
  21125. moment: { 'function': 'function' },
  21126. height: { string: string, number: number },
  21127. hiddenDates: {
  21128. start: { date: date, number: number, string: string, moment: moment },
  21129. end: { date: date, number: number, string: string, moment: moment },
  21130. repeat: { string: string },
  21131. __type__: { object: object, array: array }
  21132. },
  21133. locale: { string: string },
  21134. locales: {
  21135. __any__: { any: any },
  21136. __type__: { object: object }
  21137. },
  21138. max: { date: date, number: number, string: string, moment: moment },
  21139. maxHeight: { number: number, string: string },
  21140. maxMinorChars: { number: number },
  21141. min: { date: date, number: number, string: string, moment: moment },
  21142. minHeight: { number: number, string: string },
  21143. moveable: { 'boolean': bool },
  21144. multiselect: { 'boolean': bool },
  21145. orientation: { string: string },
  21146. showCurrentTime: { 'boolean': bool },
  21147. showMajorLabels: { 'boolean': bool },
  21148. showMinorLabels: { 'boolean': bool },
  21149. start: { date: date, number: number, string: string, moment: moment },
  21150. timeAxis: {
  21151. scale: { string: string, 'undefined': 'undefined' },
  21152. step: { number: number, 'undefined': 'undefined' },
  21153. __type__: { object: object }
  21154. },
  21155. width: { string: string, number: number },
  21156. zoomable: { 'boolean': bool },
  21157. zoomKey: { string: ['ctrlKey', 'altKey', 'metaKey', ''] },
  21158. zoomMax: { number: number },
  21159. zoomMin: { number: number },
  21160. zIndex: { number: number },
  21161. __type__: { object: object }
  21162. };
  21163. var configureOptions = {
  21164. global: {
  21165. //yAxisOrientation: ['left','right'], // TDOO: enable as soon as Grahp2d doesn't crash when changing this on the fly
  21166. sort: true,
  21167. sampling: true,
  21168. stack: false,
  21169. shaded: {
  21170. enabled: false,
  21171. orientation: ['zero', 'top', 'bottom', 'group'] // zero, top, bottom
  21172. },
  21173. style: ['line', 'bar', 'points'], // line, bar
  21174. barChart: {
  21175. width: [50, 5, 100, 5],
  21176. minWidth: [50, 5, 100, 5],
  21177. sideBySide: false,
  21178. align: ['left', 'center', 'right'] // left, center, right
  21179. },
  21180. interpolation: {
  21181. enabled: true,
  21182. parametrization: ['centripetal', 'chordal', 'uniform'] // uniform (alpha = 0.0), chordal (alpha = 1.0), centripetal (alpha = 0.5)
  21183. },
  21184. drawPoints: {
  21185. enabled: true,
  21186. size: [6, 2, 30, 1],
  21187. style: ['square', 'circle'] // square, circle
  21188. },
  21189. dataAxis: {
  21190. showMinorLabels: true,
  21191. showMajorLabels: true,
  21192. icons: false,
  21193. width: [40, 0, 200, 1],
  21194. visible: true,
  21195. alignZeros: true,
  21196. left: {
  21197. //range: {min:'undefined': 'undefined'ined,max:'undefined': 'undefined'ined},
  21198. //format: function (value) {return value;},
  21199. title: { text: '', style: '' }
  21200. },
  21201. right: {
  21202. //range: {min:'undefined': 'undefined'ined,max:'undefined': 'undefined'ined},
  21203. //format: function (value) {return value;},
  21204. title: { text: '', style: '' }
  21205. }
  21206. },
  21207. legend: {
  21208. enabled: false,
  21209. icons: true,
  21210. left: {
  21211. visible: true,
  21212. position: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] // top/bottom - left,right
  21213. },
  21214. right: {
  21215. visible: true,
  21216. position: ['top-right', 'bottom-right', 'top-left', 'bottom-left'] // top/bottom - left,right
  21217. }
  21218. },
  21219. autoResize: true,
  21220. clickToUse: false,
  21221. end: '',
  21222. format: {
  21223. minorLabels: {
  21224. millisecond: 'SSS',
  21225. second: 's',
  21226. minute: 'HH:mm',
  21227. hour: 'HH:mm',
  21228. weekday: 'ddd D',
  21229. day: 'D',
  21230. month: 'MMM',
  21231. year: 'YYYY'
  21232. },
  21233. majorLabels: {
  21234. millisecond: 'HH:mm:ss',
  21235. second: 'D MMMM HH:mm',
  21236. minute: 'ddd D MMMM',
  21237. hour: 'ddd D MMMM',
  21238. weekday: 'MMMM YYYY',
  21239. day: 'MMMM YYYY',
  21240. month: 'YYYY',
  21241. year: ''
  21242. }
  21243. },
  21244. height: '',
  21245. locale: '',
  21246. max: '',
  21247. maxHeight: '',
  21248. maxMinorChars: [7, 0, 20, 1],
  21249. min: '',
  21250. minHeight: '',
  21251. moveable: true,
  21252. orientation: ['both', 'bottom', 'top'],
  21253. showCurrentTime: false,
  21254. showMajorLabels: true,
  21255. showMinorLabels: true,
  21256. start: '',
  21257. width: '100%',
  21258. zoomable: true,
  21259. zoomKey: ['ctrlKey', 'altKey', 'metaKey', ''],
  21260. zoomMax: [315360000000000, 10, 315360000000000, 1],
  21261. zoomMin: [10, 10, 315360000000000, 1],
  21262. zIndex: 0
  21263. }
  21264. };
  21265. exports.allOptions = allOptions;
  21266. exports.configureOptions = configureOptions;
  21267. /***/ }),
  21268. /* 114 */
  21269. /***/ (function(module, exports, __webpack_require__) {
  21270. "use strict";
  21271. var _create = __webpack_require__(29);
  21272. var _create2 = _interopRequireDefault(_create);
  21273. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  21274. /**
  21275. * Parse a text source containing data in DOT language into a JSON object.
  21276. * The object contains two lists: one with nodes and one with edges.
  21277. *
  21278. * DOT language reference: http://www.graphviz.org/doc/info/lang.html
  21279. *
  21280. * DOT language attributes: http://graphviz.org/content/attrs
  21281. *
  21282. * @param {string} data Text containing a graph in DOT-notation
  21283. * @return {Object} graph An object containing two parameters:
  21284. * {Object[]} nodes
  21285. * {Object[]} edges
  21286. *
  21287. * -------------------------------------------
  21288. * TODO
  21289. * ====
  21290. *
  21291. * For label handling, this is an incomplete implementation. From docs (quote #3015):
  21292. *
  21293. * > the escape sequences "\n", "\l" and "\r" divide the label into lines, centered,
  21294. * > left-justified, and right-justified, respectively.
  21295. *
  21296. * Source: http://www.graphviz.org/content/attrs#kescString
  21297. *
  21298. * > As another aid for readability, dot allows double-quoted strings to span multiple physical
  21299. * > lines using the standard C convention of a backslash immediately preceding a newline
  21300. * > character
  21301. * > In addition, double-quoted strings can be concatenated using a '+' operator.
  21302. * > As HTML strings can contain newline characters, which are used solely for formatting,
  21303. * > the language does not allow escaped newlines or concatenation operators to be used
  21304. * > within them.
  21305. *
  21306. * - Currently, only '\\n' is handled
  21307. * - Note that text explicitly says 'labels'; the dot parser currently handles escape
  21308. * sequences in **all** strings.
  21309. */
  21310. function parseDOT(data) {
  21311. dot = data;
  21312. return parseGraph();
  21313. }
  21314. // mapping of attributes from DOT (the keys) to vis.js (the values)
  21315. var NODE_ATTR_MAPPING = {
  21316. 'fontsize': 'font.size',
  21317. 'fontcolor': 'font.color',
  21318. 'labelfontcolor': 'font.color',
  21319. 'fontname': 'font.face',
  21320. 'color': ['color.border', 'color.background'],
  21321. 'fillcolor': 'color.background',
  21322. 'tooltip': 'title',
  21323. 'labeltooltip': 'title'
  21324. };
  21325. var EDGE_ATTR_MAPPING = (0, _create2['default'])(NODE_ATTR_MAPPING);
  21326. EDGE_ATTR_MAPPING.color = 'color.color';
  21327. EDGE_ATTR_MAPPING.style = 'dashes';
  21328. // token types enumeration
  21329. var TOKENTYPE = {
  21330. NULL: 0,
  21331. DELIMITER: 1,
  21332. IDENTIFIER: 2,
  21333. UNKNOWN: 3
  21334. };
  21335. // map with all delimiters
  21336. var DELIMITERS = {
  21337. '{': true,
  21338. '}': true,
  21339. '[': true,
  21340. ']': true,
  21341. ';': true,
  21342. '=': true,
  21343. ',': true,
  21344. '->': true,
  21345. '--': true
  21346. };
  21347. var dot = ''; // current dot file
  21348. var index = 0; // current index in dot file
  21349. var c = ''; // current token character in expr
  21350. var token = ''; // current token
  21351. var tokenType = TOKENTYPE.NULL; // type of the token
  21352. /**
  21353. * Get the first character from the dot file.
  21354. * The character is stored into the char c. If the end of the dot file is
  21355. * reached, the function puts an empty string in c.
  21356. */
  21357. function first() {
  21358. index = 0;
  21359. c = dot.charAt(0);
  21360. }
  21361. /**
  21362. * Get the next character from the dot file.
  21363. * The character is stored into the char c. If the end of the dot file is
  21364. * reached, the function puts an empty string in c.
  21365. */
  21366. function next() {
  21367. index++;
  21368. c = dot.charAt(index);
  21369. }
  21370. /**
  21371. * Preview the next character from the dot file.
  21372. * @return {string} cNext
  21373. */
  21374. function nextPreview() {
  21375. return dot.charAt(index + 1);
  21376. }
  21377. var regexAlphaNumeric = /[a-zA-Z_0-9.:#]/;
  21378. /**
  21379. * Test whether given character is alphabetic or numeric
  21380. * @param {string} c
  21381. * @return {Boolean} isAlphaNumeric
  21382. */
  21383. function isAlphaNumeric(c) {
  21384. return regexAlphaNumeric.test(c);
  21385. }
  21386. /**
  21387. * Merge all options of object b into object b
  21388. * @param {Object} a
  21389. * @param {Object} b
  21390. * @return {Object} a
  21391. */
  21392. function merge(a, b) {
  21393. if (!a) {
  21394. a = {};
  21395. }
  21396. if (b) {
  21397. for (var name in b) {
  21398. if (b.hasOwnProperty(name)) {
  21399. a[name] = b[name];
  21400. }
  21401. }
  21402. }
  21403. return a;
  21404. }
  21405. /**
  21406. * Set a value in an object, where the provided parameter name can be a
  21407. * path with nested parameters. For example:
  21408. *
  21409. * var obj = {a: 2};
  21410. * setValue(obj, 'b.c', 3); // obj = {a: 2, b: {c: 3}}
  21411. *
  21412. * @param {Object} obj
  21413. * @param {string} path A parameter name or dot-separated parameter path,
  21414. * like "color.highlight.border".
  21415. * @param {*} value
  21416. */
  21417. function setValue(obj, path, value) {
  21418. var keys = path.split('.');
  21419. var o = obj;
  21420. while (keys.length) {
  21421. var key = keys.shift();
  21422. if (keys.length) {
  21423. // this isn't the end point
  21424. if (!o[key]) {
  21425. o[key] = {};
  21426. }
  21427. o = o[key];
  21428. } else {
  21429. // this is the end point
  21430. o[key] = value;
  21431. }
  21432. }
  21433. }
  21434. /**
  21435. * Add a node to a graph object. If there is already a node with
  21436. * the same id, their attributes will be merged.
  21437. * @param {Object} graph
  21438. * @param {Object} node
  21439. */
  21440. function addNode(graph, node) {
  21441. var i, len;
  21442. var current = null;
  21443. // find root graph (in case of subgraph)
  21444. var graphs = [graph]; // list with all graphs from current graph to root graph
  21445. var root = graph;
  21446. while (root.parent) {
  21447. graphs.push(root.parent);
  21448. root = root.parent;
  21449. }
  21450. // find existing node (at root level) by its id
  21451. if (root.nodes) {
  21452. for (i = 0, len = root.nodes.length; i < len; i++) {
  21453. if (node.id === root.nodes[i].id) {
  21454. current = root.nodes[i];
  21455. break;
  21456. }
  21457. }
  21458. }
  21459. if (!current) {
  21460. // this is a new node
  21461. current = {
  21462. id: node.id
  21463. };
  21464. if (graph.node) {
  21465. // clone default attributes
  21466. current.attr = merge(current.attr, graph.node);
  21467. }
  21468. }
  21469. // add node to this (sub)graph and all its parent graphs
  21470. for (i = graphs.length - 1; i >= 0; i--) {
  21471. var g = graphs[i];
  21472. if (!g.nodes) {
  21473. g.nodes = [];
  21474. }
  21475. if (g.nodes.indexOf(current) === -1) {
  21476. g.nodes.push(current);
  21477. }
  21478. }
  21479. // merge attributes
  21480. if (node.attr) {
  21481. current.attr = merge(current.attr, node.attr);
  21482. }
  21483. }
  21484. /**
  21485. * Add an edge to a graph object
  21486. * @param {Object} graph
  21487. * @param {Object} edge
  21488. */
  21489. function addEdge(graph, edge) {
  21490. if (!graph.edges) {
  21491. graph.edges = [];
  21492. }
  21493. graph.edges.push(edge);
  21494. if (graph.edge) {
  21495. var attr = merge({}, graph.edge); // clone default attributes
  21496. edge.attr = merge(attr, edge.attr); // merge attributes
  21497. }
  21498. }
  21499. /**
  21500. * Create an edge to a graph object
  21501. * @param {Object} graph
  21502. * @param {string | number | Object} from
  21503. * @param {string | number | Object} to
  21504. * @param {string} type
  21505. * @param {Object | null} attr
  21506. * @return {Object} edge
  21507. */
  21508. function createEdge(graph, from, to, type, attr) {
  21509. var edge = {
  21510. from: from,
  21511. to: to,
  21512. type: type
  21513. };
  21514. if (graph.edge) {
  21515. edge.attr = merge({}, graph.edge); // clone default attributes
  21516. }
  21517. edge.attr = merge(edge.attr || {}, attr); // merge attributes
  21518. return edge;
  21519. }
  21520. /**
  21521. * Get next token in the current dot file.
  21522. * The token and token type are available as token and tokenType
  21523. */
  21524. function getToken() {
  21525. tokenType = TOKENTYPE.NULL;
  21526. token = '';
  21527. // skip over whitespaces
  21528. while (c === ' ' || c === '\t' || c === '\n' || c === '\r') {
  21529. // space, tab, enter
  21530. next();
  21531. }
  21532. do {
  21533. var isComment = false;
  21534. // skip comment
  21535. if (c === '#') {
  21536. // find the previous non-space character
  21537. var i = index - 1;
  21538. while (dot.charAt(i) === ' ' || dot.charAt(i) === '\t') {
  21539. i--;
  21540. }
  21541. if (dot.charAt(i) === '\n' || dot.charAt(i) === '') {
  21542. // the # is at the start of a line, this is indeed a line comment
  21543. while (c != '' && c != '\n') {
  21544. next();
  21545. }
  21546. isComment = true;
  21547. }
  21548. }
  21549. if (c === '/' && nextPreview() === '/') {
  21550. // skip line comment
  21551. while (c != '' && c != '\n') {
  21552. next();
  21553. }
  21554. isComment = true;
  21555. }
  21556. if (c === '/' && nextPreview() === '*') {
  21557. // skip block comment
  21558. while (c != '') {
  21559. if (c === '*' && nextPreview() === '/') {
  21560. // end of block comment found. skip these last two characters
  21561. next();
  21562. next();
  21563. break;
  21564. } else {
  21565. next();
  21566. }
  21567. }
  21568. isComment = true;
  21569. }
  21570. // skip over whitespaces
  21571. while (c === ' ' || c === '\t' || c === '\n' || c === '\r') {
  21572. // space, tab, enter
  21573. next();
  21574. }
  21575. } while (isComment);
  21576. // check for end of dot file
  21577. if (c === '') {
  21578. // token is still empty
  21579. tokenType = TOKENTYPE.DELIMITER;
  21580. return;
  21581. }
  21582. // check for delimiters consisting of 2 characters
  21583. var c2 = c + nextPreview();
  21584. if (DELIMITERS[c2]) {
  21585. tokenType = TOKENTYPE.DELIMITER;
  21586. token = c2;
  21587. next();
  21588. next();
  21589. return;
  21590. }
  21591. // check for delimiters consisting of 1 character
  21592. if (DELIMITERS[c]) {
  21593. tokenType = TOKENTYPE.DELIMITER;
  21594. token = c;
  21595. next();
  21596. return;
  21597. }
  21598. // check for an identifier (number or string)
  21599. // TODO: more precise parsing of numbers/strings (and the port separator ':')
  21600. if (isAlphaNumeric(c) || c === '-') {
  21601. token += c;
  21602. next();
  21603. while (isAlphaNumeric(c)) {
  21604. token += c;
  21605. next();
  21606. }
  21607. if (token === 'false') {
  21608. token = false; // convert to boolean
  21609. } else if (token === 'true') {
  21610. token = true; // convert to boolean
  21611. } else if (!isNaN(Number(token))) {
  21612. token = Number(token); // convert to number
  21613. }
  21614. tokenType = TOKENTYPE.IDENTIFIER;
  21615. return;
  21616. }
  21617. // check for a string enclosed by double quotes
  21618. if (c === '"') {
  21619. next();
  21620. while (c != '' && (c != '"' || c === '"' && nextPreview() === '"')) {
  21621. if (c === '"') {
  21622. // skip the escape character
  21623. token += c;
  21624. next();
  21625. } else if (c === '\\' && nextPreview() === 'n') {
  21626. // Honor a newline escape sequence
  21627. token += '\n';
  21628. next();
  21629. } else {
  21630. token += c;
  21631. }
  21632. next();
  21633. }
  21634. if (c != '"') {
  21635. throw newSyntaxError('End of string " expected');
  21636. }
  21637. next();
  21638. tokenType = TOKENTYPE.IDENTIFIER;
  21639. return;
  21640. }
  21641. // something unknown is found, wrong characters, a syntax error
  21642. tokenType = TOKENTYPE.UNKNOWN;
  21643. while (c != '') {
  21644. token += c;
  21645. next();
  21646. }
  21647. throw new SyntaxError('Syntax error in part "' + chop(token, 30) + '"');
  21648. }
  21649. /**
  21650. * Parse a graph.
  21651. * @returns {Object} graph
  21652. */
  21653. function parseGraph() {
  21654. var graph = {};
  21655. first();
  21656. getToken();
  21657. // optional strict keyword
  21658. if (token === 'strict') {
  21659. graph.strict = true;
  21660. getToken();
  21661. }
  21662. // graph or digraph keyword
  21663. if (token === 'graph' || token === 'digraph') {
  21664. graph.type = token;
  21665. getToken();
  21666. }
  21667. // optional graph id
  21668. if (tokenType === TOKENTYPE.IDENTIFIER) {
  21669. graph.id = token;
  21670. getToken();
  21671. }
  21672. // open angle bracket
  21673. if (token != '{') {
  21674. throw newSyntaxError('Angle bracket { expected');
  21675. }
  21676. getToken();
  21677. // statements
  21678. parseStatements(graph);
  21679. // close angle bracket
  21680. if (token != '}') {
  21681. throw newSyntaxError('Angle bracket } expected');
  21682. }
  21683. getToken();
  21684. // end of file
  21685. if (token !== '') {
  21686. throw newSyntaxError('End of file expected');
  21687. }
  21688. getToken();
  21689. // remove temporary default options
  21690. delete graph.node;
  21691. delete graph.edge;
  21692. delete graph.graph;
  21693. return graph;
  21694. }
  21695. /**
  21696. * Parse a list with statements.
  21697. * @param {Object} graph
  21698. */
  21699. function parseStatements(graph) {
  21700. while (token !== '' && token != '}') {
  21701. parseStatement(graph);
  21702. if (token === ';') {
  21703. getToken();
  21704. }
  21705. }
  21706. }
  21707. /**
  21708. * Parse a single statement. Can be a an attribute statement, node
  21709. * statement, a series of node statements and edge statements, or a
  21710. * parameter.
  21711. * @param {Object} graph
  21712. */
  21713. function parseStatement(graph) {
  21714. // parse subgraph
  21715. var subgraph = parseSubgraph(graph);
  21716. if (subgraph) {
  21717. // edge statements
  21718. parseEdge(graph, subgraph);
  21719. return;
  21720. }
  21721. // parse an attribute statement
  21722. var attr = parseAttributeStatement(graph);
  21723. if (attr) {
  21724. return;
  21725. }
  21726. // parse node
  21727. if (tokenType != TOKENTYPE.IDENTIFIER) {
  21728. throw newSyntaxError('Identifier expected');
  21729. }
  21730. var id = token; // id can be a string or a number
  21731. getToken();
  21732. if (token === '=') {
  21733. // id statement
  21734. getToken();
  21735. if (tokenType != TOKENTYPE.IDENTIFIER) {
  21736. throw newSyntaxError('Identifier expected');
  21737. }
  21738. graph[id] = token;
  21739. getToken();
  21740. // TODO: implement comma separated list with "a_list: ID=ID [','] [a_list] "
  21741. } else {
  21742. parseNodeStatement(graph, id);
  21743. }
  21744. }
  21745. /**
  21746. * Parse a subgraph
  21747. * @param {Object} graph parent graph object
  21748. * @return {Object | null} subgraph
  21749. */
  21750. function parseSubgraph(graph) {
  21751. var subgraph = null;
  21752. // optional subgraph keyword
  21753. if (token === 'subgraph') {
  21754. subgraph = {};
  21755. subgraph.type = 'subgraph';
  21756. getToken();
  21757. // optional graph id
  21758. if (tokenType === TOKENTYPE.IDENTIFIER) {
  21759. subgraph.id = token;
  21760. getToken();
  21761. }
  21762. }
  21763. // open angle bracket
  21764. if (token === '{') {
  21765. getToken();
  21766. if (!subgraph) {
  21767. subgraph = {};
  21768. }
  21769. subgraph.parent = graph;
  21770. subgraph.node = graph.node;
  21771. subgraph.edge = graph.edge;
  21772. subgraph.graph = graph.graph;
  21773. // statements
  21774. parseStatements(subgraph);
  21775. // close angle bracket
  21776. if (token != '}') {
  21777. throw newSyntaxError('Angle bracket } expected');
  21778. }
  21779. getToken();
  21780. // remove temporary default options
  21781. delete subgraph.node;
  21782. delete subgraph.edge;
  21783. delete subgraph.graph;
  21784. delete subgraph.parent;
  21785. // register at the parent graph
  21786. if (!graph.subgraphs) {
  21787. graph.subgraphs = [];
  21788. }
  21789. graph.subgraphs.push(subgraph);
  21790. }
  21791. return subgraph;
  21792. }
  21793. /**
  21794. * parse an attribute statement like "node [shape=circle fontSize=16]".
  21795. * Available keywords are 'node', 'edge', 'graph'.
  21796. * The previous list with default attributes will be replaced
  21797. * @param {Object} graph
  21798. * @returns {String | null} keyword Returns the name of the parsed attribute
  21799. * (node, edge, graph), or null if nothing
  21800. * is parsed.
  21801. */
  21802. function parseAttributeStatement(graph) {
  21803. // attribute statements
  21804. if (token === 'node') {
  21805. getToken();
  21806. // node attributes
  21807. graph.node = parseAttributeList();
  21808. return 'node';
  21809. } else if (token === 'edge') {
  21810. getToken();
  21811. // edge attributes
  21812. graph.edge = parseAttributeList();
  21813. return 'edge';
  21814. } else if (token === 'graph') {
  21815. getToken();
  21816. // graph attributes
  21817. graph.graph = parseAttributeList();
  21818. return 'graph';
  21819. }
  21820. return null;
  21821. }
  21822. /**
  21823. * parse a node statement
  21824. * @param {Object} graph
  21825. * @param {string | number} id
  21826. */
  21827. function parseNodeStatement(graph, id) {
  21828. // node statement
  21829. var node = {
  21830. id: id
  21831. };
  21832. var attr = parseAttributeList();
  21833. if (attr) {
  21834. node.attr = attr;
  21835. }
  21836. addNode(graph, node);
  21837. // edge statements
  21838. parseEdge(graph, id);
  21839. }
  21840. /**
  21841. * Parse an edge or a series of edges
  21842. * @param {Object} graph
  21843. * @param {string | number} from Id of the from node
  21844. */
  21845. function parseEdge(graph, from) {
  21846. while (token === '->' || token === '--') {
  21847. var to;
  21848. var type = token;
  21849. getToken();
  21850. var subgraph = parseSubgraph(graph);
  21851. if (subgraph) {
  21852. to = subgraph;
  21853. } else {
  21854. if (tokenType != TOKENTYPE.IDENTIFIER) {
  21855. throw newSyntaxError('Identifier or subgraph expected');
  21856. }
  21857. to = token;
  21858. addNode(graph, {
  21859. id: to
  21860. });
  21861. getToken();
  21862. }
  21863. // parse edge attributes
  21864. var attr = parseAttributeList();
  21865. // create edge
  21866. var edge = createEdge(graph, from, to, type, attr);
  21867. addEdge(graph, edge);
  21868. from = to;
  21869. }
  21870. }
  21871. /**
  21872. * Parse a set with attributes,
  21873. * for example [label="1.000", shape=solid]
  21874. * @return {Object | null} attr
  21875. */
  21876. function parseAttributeList() {
  21877. var attr = null;
  21878. // edge styles of dot and vis
  21879. var edgeStyles = {
  21880. 'dashed': true,
  21881. 'solid': false,
  21882. 'dotted': [1, 5]
  21883. };
  21884. while (token === '[') {
  21885. getToken();
  21886. attr = {};
  21887. while (token !== '' && token != ']') {
  21888. if (tokenType != TOKENTYPE.IDENTIFIER) {
  21889. throw newSyntaxError('Attribute name expected');
  21890. }
  21891. var name = token;
  21892. getToken();
  21893. if (token != '=') {
  21894. throw newSyntaxError('Equal sign = expected');
  21895. }
  21896. getToken();
  21897. if (tokenType != TOKENTYPE.IDENTIFIER) {
  21898. throw newSyntaxError('Attribute value expected');
  21899. }
  21900. var value = token;
  21901. // convert from dot style to vis
  21902. if (name === 'style') {
  21903. value = edgeStyles[value];
  21904. }
  21905. setValue(attr, name, value); // name can be a path
  21906. getToken();
  21907. if (token == ',') {
  21908. getToken();
  21909. }
  21910. }
  21911. if (token != ']') {
  21912. throw newSyntaxError('Bracket ] expected');
  21913. }
  21914. getToken();
  21915. }
  21916. return attr;
  21917. }
  21918. /**
  21919. * Create a syntax error with extra information on current token and index.
  21920. * @param {string} message
  21921. * @returns {SyntaxError} err
  21922. */
  21923. function newSyntaxError(message) {
  21924. return new SyntaxError(message + ', got "' + chop(token, 30) + '" (char ' + index + ')');
  21925. }
  21926. /**
  21927. * Chop off text after a maximum length
  21928. * @param {string} text
  21929. * @param {number} maxLength
  21930. * @returns {String}
  21931. */
  21932. function chop(text, maxLength) {
  21933. return text.length <= maxLength ? text : text.substr(0, 27) + '...';
  21934. }
  21935. /**
  21936. * Execute a function fn for each pair of elements in two arrays
  21937. * @param {Array | *} array1
  21938. * @param {Array | *} array2
  21939. * @param {function} fn
  21940. */
  21941. function forEach2(array1, array2, fn) {
  21942. if (Array.isArray(array1)) {
  21943. array1.forEach(function (elem1) {
  21944. if (Array.isArray(array2)) {
  21945. array2.forEach(function (elem2) {
  21946. fn(elem1, elem2);
  21947. });
  21948. } else {
  21949. fn(elem1, array2);
  21950. }
  21951. });
  21952. } else {
  21953. if (Array.isArray(array2)) {
  21954. array2.forEach(function (elem2) {
  21955. fn(array1, elem2);
  21956. });
  21957. } else {
  21958. fn(array1, array2);
  21959. }
  21960. }
  21961. }
  21962. /**
  21963. * Set a nested property on an object
  21964. * When nested objects are missing, they will be created.
  21965. * For example setProp({}, 'font.color', 'red') will return {font: {color: 'red'}}
  21966. * @param {Object} object
  21967. * @param {string} path A dot separated string like 'font.color'
  21968. * @param {*} value Value for the property
  21969. * @return {Object} Returns the original object, allows for chaining.
  21970. */
  21971. function setProp(object, path, value) {
  21972. var names = path.split('.');
  21973. var prop = names.pop();
  21974. // traverse over the nested objects
  21975. var obj = object;
  21976. for (var i = 0; i < names.length; i++) {
  21977. var name = names[i];
  21978. if (!(name in obj)) {
  21979. obj[name] = {};
  21980. }
  21981. obj = obj[name];
  21982. }
  21983. // set the property value
  21984. obj[prop] = value;
  21985. return object;
  21986. }
  21987. /**
  21988. * Convert an object with DOT attributes to their vis.js equivalents.
  21989. * @param {Object} attr Object with DOT attributes
  21990. * @param {Object} mapping
  21991. * @return {Object} Returns an object with vis.js attributes
  21992. */
  21993. function convertAttr(attr, mapping) {
  21994. var converted = {};
  21995. for (var prop in attr) {
  21996. if (attr.hasOwnProperty(prop)) {
  21997. var visProp = mapping[prop];
  21998. if (Array.isArray(visProp)) {
  21999. visProp.forEach(function (visPropI) {
  22000. setProp(converted, visPropI, attr[prop]);
  22001. });
  22002. } else if (typeof visProp === 'string') {
  22003. setProp(converted, visProp, attr[prop]);
  22004. } else {
  22005. setProp(converted, prop, attr[prop]);
  22006. }
  22007. }
  22008. }
  22009. return converted;
  22010. }
  22011. /**
  22012. * Convert a string containing a graph in DOT language into a map containing
  22013. * with nodes and edges in the format of graph.
  22014. * @param {string} data Text containing a graph in DOT-notation
  22015. * @return {Object} graphData
  22016. */
  22017. function DOTToGraph(data) {
  22018. // parse the DOT file
  22019. var dotData = parseDOT(data);
  22020. var graphData = {
  22021. nodes: [],
  22022. edges: [],
  22023. options: {}
  22024. };
  22025. // copy the nodes
  22026. if (dotData.nodes) {
  22027. dotData.nodes.forEach(function (dotNode) {
  22028. var graphNode = {
  22029. id: dotNode.id,
  22030. label: String(dotNode.label || dotNode.id)
  22031. };
  22032. merge(graphNode, convertAttr(dotNode.attr, NODE_ATTR_MAPPING));
  22033. if (graphNode.image) {
  22034. graphNode.shape = 'image';
  22035. }
  22036. graphData.nodes.push(graphNode);
  22037. });
  22038. }
  22039. // copy the edges
  22040. if (dotData.edges) {
  22041. /**
  22042. * Convert an edge in DOT format to an edge with VisGraph format
  22043. * @param {Object} dotEdge
  22044. * @returns {Object} graphEdge
  22045. */
  22046. var convertEdge = function convertEdge(dotEdge) {
  22047. var graphEdge = {
  22048. from: dotEdge.from,
  22049. to: dotEdge.to
  22050. };
  22051. merge(graphEdge, convertAttr(dotEdge.attr, EDGE_ATTR_MAPPING));
  22052. graphEdge.arrows = dotEdge.type === '->' ? 'to' : undefined;
  22053. return graphEdge;
  22054. };
  22055. dotData.edges.forEach(function (dotEdge) {
  22056. var from, to;
  22057. if (dotEdge.from instanceof Object) {
  22058. from = dotEdge.from.nodes;
  22059. } else {
  22060. from = {
  22061. id: dotEdge.from
  22062. };
  22063. }
  22064. // TODO: support for attributes 'dir' and 'arrowhead' (edge arrows)
  22065. if (dotEdge.to instanceof Object) {
  22066. to = dotEdge.to.nodes;
  22067. } else {
  22068. to = {
  22069. id: dotEdge.to
  22070. };
  22071. }
  22072. if (dotEdge.from instanceof Object && dotEdge.from.edges) {
  22073. dotEdge.from.edges.forEach(function (subEdge) {
  22074. var graphEdge = convertEdge(subEdge);
  22075. graphData.edges.push(graphEdge);
  22076. });
  22077. }
  22078. forEach2(from, to, function (from, to) {
  22079. var subEdge = createEdge(graphData, from.id, to.id, dotEdge.type, dotEdge.attr);
  22080. var graphEdge = convertEdge(subEdge);
  22081. graphData.edges.push(graphEdge);
  22082. });
  22083. if (dotEdge.to instanceof Object && dotEdge.to.edges) {
  22084. dotEdge.to.edges.forEach(function (subEdge) {
  22085. var graphEdge = convertEdge(subEdge);
  22086. graphData.edges.push(graphEdge);
  22087. });
  22088. }
  22089. });
  22090. }
  22091. // copy the options
  22092. if (dotData.attr) {
  22093. graphData.options = dotData.attr;
  22094. }
  22095. return graphData;
  22096. }
  22097. // exports
  22098. exports.parseDOT = parseDOT;
  22099. exports.DOTToGraph = DOTToGraph;
  22100. /***/ }),
  22101. /* 115 */
  22102. /***/ (function(module, exports, __webpack_require__) {
  22103. "use strict";
  22104. /**
  22105. *
  22106. * @param {json} gephiJSON
  22107. * @param {obj} optionsObj
  22108. * @returns {{nodes: Array, edges: Array}}
  22109. */
  22110. function parseGephi(gephiJSON, optionsObj) {
  22111. var edges = [];
  22112. var nodes = [];
  22113. var options = {
  22114. edges: {
  22115. inheritColor: false
  22116. },
  22117. nodes: {
  22118. fixed: false,
  22119. parseColor: false
  22120. }
  22121. };
  22122. if (optionsObj !== undefined) {
  22123. if (optionsObj.fixed !== undefined) {
  22124. options.nodes.fixed = optionsObj.fixed;
  22125. }
  22126. if (optionsObj.parseColor !== undefined) {
  22127. options.nodes.parseColor = optionsObj.parseColor;
  22128. }
  22129. if (optionsObj.inheritColor !== undefined) {
  22130. options.edges.inheritColor = optionsObj.inheritColor;
  22131. }
  22132. }
  22133. var gEdges = gephiJSON.edges;
  22134. var gNodes = gephiJSON.nodes;
  22135. for (var i = 0; i < gEdges.length; i++) {
  22136. var edge = {};
  22137. var gEdge = gEdges[i];
  22138. edge['id'] = gEdge.id;
  22139. edge['from'] = gEdge.source;
  22140. edge['to'] = gEdge.target;
  22141. edge['attributes'] = gEdge.attributes;
  22142. edge['label'] = gEdge.label;
  22143. edge['title'] = gEdge.attributes !== undefined ? gEdge.attributes.title : undefined;
  22144. if (gEdge['type'] === 'Directed') {
  22145. edge['arrows'] = 'to';
  22146. }
  22147. // edge['value'] = gEdge.attributes !== undefined ? gEdge.attributes.Weight : undefined;
  22148. // edge['width'] = edge['value'] !== undefined ? undefined : edgegEdge.size;
  22149. if (gEdge.color && options.inheritColor === false) {
  22150. edge['color'] = gEdge.color;
  22151. }
  22152. edges.push(edge);
  22153. }
  22154. for (var j = 0; j < gNodes.length; j++) {
  22155. var node = {};
  22156. var gNode = gNodes[j];
  22157. node['id'] = gNode.id;
  22158. node['attributes'] = gNode.attributes;
  22159. node['x'] = gNode.x;
  22160. node['y'] = gNode.y;
  22161. node['label'] = gNode.label;
  22162. node['title'] = gNode.attributes !== undefined ? gNode.attributes.title : gNode.title;
  22163. if (options.nodes.parseColor === true) {
  22164. node['color'] = gNode.color;
  22165. } else {
  22166. 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;
  22167. }
  22168. node['size'] = gNode.size;
  22169. node['fixed'] = options.nodes.fixed && gNode.x !== undefined && gNode.y !== undefined;
  22170. nodes.push(node);
  22171. }
  22172. return { nodes: nodes, edges: edges };
  22173. }
  22174. exports.parseGephi = parseGephi;
  22175. /***/ }),
  22176. /* 116 */
  22177. /***/ (function(module, exports, __webpack_require__) {
  22178. "use strict";
  22179. Object.defineProperty(exports, "__esModule", {
  22180. value: true
  22181. });
  22182. var _classCallCheck2 = __webpack_require__(0);
  22183. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  22184. var _createClass2 = __webpack_require__(1);
  22185. var _createClass3 = _interopRequireDefault(_createClass2);
  22186. var _CachedImage = __webpack_require__(185);
  22187. var _CachedImage2 = _interopRequireDefault(_CachedImage);
  22188. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  22189. /**
  22190. * This callback is a callback that accepts an Image.
  22191. * @callback ImageCallback
  22192. * @param {Image} image
  22193. */
  22194. /**
  22195. * This class loads images and keeps them stored.
  22196. *
  22197. * @param {ImageCallback} callback
  22198. */
  22199. var Images = function () {
  22200. /**
  22201. * @param {ImageCallback} callback
  22202. */
  22203. function Images(callback) {
  22204. (0, _classCallCheck3["default"])(this, Images);
  22205. this.images = {};
  22206. this.imageBroken = {};
  22207. this.callback = callback;
  22208. }
  22209. /**
  22210. * @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
  22211. * @param {string} brokenUrl Url the broken image to try and load
  22212. * @param {Image} imageToLoadBrokenUrlOn The image object
  22213. */
  22214. (0, _createClass3["default"])(Images, [{
  22215. key: "_tryloadBrokenUrl",
  22216. value: function _tryloadBrokenUrl(url, brokenUrl, imageToLoadBrokenUrlOn) {
  22217. //If these parameters aren't specified then exit the function because nothing constructive can be done
  22218. if (url === undefined || imageToLoadBrokenUrlOn === undefined) return;
  22219. if (brokenUrl === undefined) {
  22220. console.warn("No broken url image defined");
  22221. return;
  22222. }
  22223. //Clear the old subscription to the error event and put a new in place that only handle errors in loading the brokenImageUrl
  22224. imageToLoadBrokenUrlOn.onerror = function () {
  22225. console.error("Could not load brokenImage:", brokenUrl);
  22226. // cache item will contain empty image, this should be OK for default
  22227. };
  22228. //Set the source of the image to the brokenUrl, this is actually what kicks off the loading of the broken image
  22229. imageToLoadBrokenUrlOn.image.src = brokenUrl;
  22230. }
  22231. /**
  22232. *
  22233. * @param {vis.Image} imageToRedrawWith
  22234. * @private
  22235. */
  22236. }, {
  22237. key: "_redrawWithImage",
  22238. value: function _redrawWithImage(imageToRedrawWith) {
  22239. if (this.callback) {
  22240. this.callback(imageToRedrawWith);
  22241. }
  22242. }
  22243. /**
  22244. * @param {string} url Url of the image
  22245. * @param {string} brokenUrl Url of an image to use if the url image is not found
  22246. * @return {Image} img The image object
  22247. */
  22248. }, {
  22249. key: "load",
  22250. value: function load(url, brokenUrl) {
  22251. var _this = this;
  22252. //Try and get the image from the cache, if successful then return the cached image
  22253. var cachedImage = this.images[url];
  22254. if (cachedImage) return cachedImage;
  22255. //Create a new image
  22256. var img = new _CachedImage2["default"]();
  22257. // Need to add to cache here, otherwise final return will spawn different copies of the same image,
  22258. // Also, there will be multiple loads of the same image.
  22259. this.images[url] = img;
  22260. //Subscribe to the event that is raised if the image loads successfully
  22261. img.image.onload = function () {
  22262. // Properly init the cached item and then request a redraw
  22263. _this._fixImageCoordinates(img.image);
  22264. img.init();
  22265. _this._redrawWithImage(img);
  22266. };
  22267. //Subscribe to the event that is raised if the image fails to load
  22268. img.image.onerror = function () {
  22269. console.error("Could not load image:", url);
  22270. //Try and load the image specified by the brokenUrl using
  22271. _this._tryloadBrokenUrl(url, brokenUrl, img);
  22272. };
  22273. //Set the source of the image to the url, this is what actually kicks off the loading of the image
  22274. img.image.src = url;
  22275. //Return the new image
  22276. return img;
  22277. }
  22278. /**
  22279. * IE11 fix -- thanks dponch!
  22280. *
  22281. * Local helper function
  22282. * @param {vis.Image} imageToCache
  22283. * @private
  22284. */
  22285. }, {
  22286. key: "_fixImageCoordinates",
  22287. value: function _fixImageCoordinates(imageToCache) {
  22288. if (imageToCache.width === 0) {
  22289. document.body.appendChild(imageToCache);
  22290. imageToCache.width = imageToCache.offsetWidth;
  22291. imageToCache.height = imageToCache.offsetHeight;
  22292. document.body.removeChild(imageToCache);
  22293. }
  22294. }
  22295. }]);
  22296. return Images;
  22297. }();
  22298. exports["default"] = Images;
  22299. /***/ }),
  22300. /* 117 */
  22301. /***/ (function(module, exports, __webpack_require__) {
  22302. "use strict";
  22303. Object.defineProperty(exports, "__esModule", {
  22304. value: true
  22305. });
  22306. var _slicedToArray2 = __webpack_require__(30);
  22307. var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
  22308. var _typeof2 = __webpack_require__(6);
  22309. var _typeof3 = _interopRequireDefault(_typeof2);
  22310. var _classCallCheck2 = __webpack_require__(0);
  22311. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  22312. var _createClass2 = __webpack_require__(1);
  22313. var _createClass3 = _interopRequireDefault(_createClass2);
  22314. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  22315. var util = __webpack_require__(2);
  22316. var ComponentUtil = __webpack_require__(48)['default'];
  22317. var LabelSplitter = __webpack_require__(191)['default'];
  22318. /**
  22319. * @typedef {'bold'|'ital'|'boldital'|'mono'|'normal'} MultiFontStyle
  22320. *
  22321. * The allowed specifiers of multi-fonts.
  22322. */
  22323. /**
  22324. * @typedef {{color:string, size:number, face:string, mod:string, vadjust:number}} MultiFontOptions
  22325. *
  22326. * The full set of options of a given multi-font.
  22327. */
  22328. /**
  22329. * @typedef {Array.<object>} Pile
  22330. *
  22331. * Sequence of option objects, the order is significant.
  22332. * The sequence is used to determine the value of a given option.
  22333. *
  22334. * Usage principles:
  22335. *
  22336. * - All search is done in the sequence of the pile.
  22337. * - As soon as a value is found, the searching stops.
  22338. * - prototypes are totally ignored. The idea is to add option objects used as prototypes
  22339. * to the pile, in the correct order.
  22340. */
  22341. /**
  22342. * List of special styles for multi-fonts
  22343. * @private
  22344. */
  22345. var multiFontStyle = ['bold', 'ital', 'boldital', 'mono'];
  22346. /**
  22347. * A Label to be used for Nodes or Edges.
  22348. */
  22349. var Label = function () {
  22350. /**
  22351. * @param {Object} body
  22352. * @param {Object} options
  22353. * @param {boolean} [edgelabel=false]
  22354. */
  22355. function Label(body, options) {
  22356. var edgelabel = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  22357. (0, _classCallCheck3['default'])(this, Label);
  22358. this.body = body;
  22359. this.pointToSelf = false;
  22360. this.baseSize = undefined;
  22361. this.fontOptions = {}; // instance variable containing the *instance-local* font options
  22362. this.setOptions(options);
  22363. this.size = { top: 0, left: 0, width: 0, height: 0, yLine: 0 };
  22364. this.isEdgeLabel = edgelabel;
  22365. }
  22366. /**
  22367. * @param {Object} options the options of the parent Node-instance
  22368. */
  22369. (0, _createClass3['default'])(Label, [{
  22370. key: 'setOptions',
  22371. value: function setOptions(options) {
  22372. this.elementOptions = options; // Reference to the options of the parent Node-instance
  22373. this.initFontOptions(options.font);
  22374. if (ComponentUtil.isValidLabel(options.label)) {
  22375. this.labelDirty = true;
  22376. } else {
  22377. // Bad label! Change the option value to prevent bad stuff happening
  22378. options.label = '';
  22379. }
  22380. if (options.font !== undefined && options.font !== null) {
  22381. // font options can be deleted at various levels
  22382. if (typeof options.font === 'string') {
  22383. this.baseSize = this.fontOptions.size;
  22384. } else if ((0, _typeof3['default'])(options.font) === 'object') {
  22385. var size = options.font.size;
  22386. if (size !== undefined) {
  22387. this.baseSize = size;
  22388. }
  22389. }
  22390. }
  22391. }
  22392. /**
  22393. * Init the font Options structure.
  22394. *
  22395. * Member fontOptions serves as an accumulator for the current font options.
  22396. * As such, it needs to be completely separated from the node options.
  22397. *
  22398. * @param {Object} newFontOptions the new font options to process
  22399. * @private
  22400. */
  22401. }, {
  22402. key: 'initFontOptions',
  22403. value: function initFontOptions(newFontOptions) {
  22404. var _this = this;
  22405. // Prepare the multi-font option objects.
  22406. // These will be filled in propagateFonts(), if required
  22407. util.forEach(multiFontStyle, function (style) {
  22408. _this.fontOptions[style] = {};
  22409. });
  22410. // Handle shorthand option, if present
  22411. if (Label.parseFontString(this.fontOptions, newFontOptions)) {
  22412. this.fontOptions.vadjust = 0;
  22413. return;
  22414. }
  22415. // Copy over the non-multifont options, if specified
  22416. util.forEach(newFontOptions, function (prop, n) {
  22417. if (prop !== undefined && prop !== null && (typeof prop === 'undefined' ? 'undefined' : (0, _typeof3['default'])(prop)) !== 'object') {
  22418. _this.fontOptions[n] = prop;
  22419. }
  22420. });
  22421. }
  22422. /**
  22423. * If in-variable is a string, parse it as a font specifier.
  22424. *
  22425. * Note that following is not done here and have to be done after the call:
  22426. * - No number conversion (size)
  22427. * - Not all font options are set (vadjust, mod)
  22428. *
  22429. * @param {Object} outOptions out-parameter, object in which to store the parse results (if any)
  22430. * @param {Object} inOptions font options to parse
  22431. * @return {boolean} true if font parsed as string, false otherwise
  22432. * @static
  22433. */
  22434. }, {
  22435. key: 'constrain',
  22436. /**
  22437. * Set the width and height constraints based on 'nearest' value
  22438. *
  22439. * @param {Array} pile array of option objects to consider
  22440. * @returns {object} the actual constraint values to use
  22441. * @private
  22442. */
  22443. value: function constrain(pile) {
  22444. // NOTE: constrainWidth and constrainHeight never set!
  22445. // NOTE: for edge labels, only 'maxWdt' set
  22446. // Node labels can set all the fields
  22447. var fontOptions = {
  22448. constrainWidth: false,
  22449. maxWdt: -1,
  22450. minWdt: -1,
  22451. constrainHeight: false,
  22452. minHgt: -1,
  22453. valign: 'middle'
  22454. };
  22455. var widthConstraint = util.topMost(pile, 'widthConstraint');
  22456. if (typeof widthConstraint === 'number') {
  22457. fontOptions.maxWdt = Number(widthConstraint);
  22458. fontOptions.minWdt = Number(widthConstraint);
  22459. } else if ((typeof widthConstraint === 'undefined' ? 'undefined' : (0, _typeof3['default'])(widthConstraint)) === 'object') {
  22460. var widthConstraintMaximum = util.topMost(pile, ['widthConstraint', 'maximum']);
  22461. if (typeof widthConstraintMaximum === 'number') {
  22462. fontOptions.maxWdt = Number(widthConstraintMaximum);
  22463. }
  22464. var widthConstraintMinimum = util.topMost(pile, ['widthConstraint', 'minimum']);
  22465. if (typeof widthConstraintMinimum === 'number') {
  22466. fontOptions.minWdt = Number(widthConstraintMinimum);
  22467. }
  22468. }
  22469. var heightConstraint = util.topMost(pile, 'heightConstraint');
  22470. if (typeof heightConstraint === 'number') {
  22471. fontOptions.minHgt = Number(heightConstraint);
  22472. } else if ((typeof heightConstraint === 'undefined' ? 'undefined' : (0, _typeof3['default'])(heightConstraint)) === 'object') {
  22473. var heightConstraintMinimum = util.topMost(pile, ['heightConstraint', 'minimum']);
  22474. if (typeof heightConstraintMinimum === 'number') {
  22475. fontOptions.minHgt = Number(heightConstraintMinimum);
  22476. }
  22477. var heightConstraintValign = util.topMost(pile, ['heightConstraint', 'valign']);
  22478. if (typeof heightConstraintValign === 'string') {
  22479. if (heightConstraintValign === 'top' || heightConstraintValign === 'bottom') {
  22480. fontOptions.valign = heightConstraintValign;
  22481. }
  22482. }
  22483. }
  22484. return fontOptions;
  22485. }
  22486. /**
  22487. * Set options and update internal state
  22488. *
  22489. * @param {Object} options options to set
  22490. * @param {Array} pile array of option objects to consider for option 'chosen'
  22491. */
  22492. }, {
  22493. key: 'update',
  22494. value: function update(options, pile) {
  22495. this.setOptions(options, true);
  22496. this.propagateFonts(pile);
  22497. util.deepExtend(this.fontOptions, this.constrain(pile));
  22498. this.fontOptions.chooser = ComponentUtil.choosify('label', pile);
  22499. }
  22500. /**
  22501. * When margins are set in an element, adjust sizes is called to remove them
  22502. * from the width/height constraints. This must be done prior to label sizing.
  22503. *
  22504. * @param {{top: number, right: number, bottom: number, left: number}} margins
  22505. */
  22506. }, {
  22507. key: 'adjustSizes',
  22508. value: function adjustSizes(margins) {
  22509. var widthBias = margins ? margins.right + margins.left : 0;
  22510. if (this.fontOptions.constrainWidth) {
  22511. this.fontOptions.maxWdt -= widthBias;
  22512. this.fontOptions.minWdt -= widthBias;
  22513. }
  22514. var heightBias = margins ? margins.top + margins.bottom : 0;
  22515. if (this.fontOptions.constrainHeight) {
  22516. this.fontOptions.minHgt -= heightBias;
  22517. }
  22518. }
  22519. /////////////////////////////////////////////////////////
  22520. // Methods for handling options piles
  22521. // Eventually, these will be moved to a separate class
  22522. /////////////////////////////////////////////////////////
  22523. /**
  22524. * Add the font members of the passed list of option objects to the pile.
  22525. *
  22526. * @param {Pile} dstPile pile of option objects add to
  22527. * @param {Pile} srcPile pile of option objects to take font options from
  22528. * @private
  22529. */
  22530. }, {
  22531. key: 'addFontOptionsToPile',
  22532. value: function addFontOptionsToPile(dstPile, srcPile) {
  22533. for (var i = 0; i < srcPile.length; ++i) {
  22534. this.addFontToPile(dstPile, srcPile[i]);
  22535. }
  22536. }
  22537. /**
  22538. * Add given font option object to the list of objects (the 'pile') to consider for determining
  22539. * multi-font option values.
  22540. *
  22541. * @param {Pile} pile pile of option objects to use
  22542. * @param {object} options instance to add to pile
  22543. * @private
  22544. */
  22545. }, {
  22546. key: 'addFontToPile',
  22547. value: function addFontToPile(pile, options) {
  22548. if (options === undefined) return;
  22549. if (options.font === undefined || options.font === null) return;
  22550. var item = options.font;
  22551. pile.push(item);
  22552. }
  22553. /**
  22554. * Collect all own-property values from the font pile that aren't multi-font option objectss.
  22555. *
  22556. * @param {Pile} pile pile of option objects to use
  22557. * @returns {object} object with all current own basic font properties
  22558. * @private
  22559. */
  22560. }, {
  22561. key: 'getBasicOptions',
  22562. value: function getBasicOptions(pile) {
  22563. var ret = {};
  22564. // Scans the whole pile to get all options present
  22565. for (var n = 0; n < pile.length; ++n) {
  22566. var fontOptions = pile[n];
  22567. // Convert shorthand if necessary
  22568. var tmpShorthand = {};
  22569. if (Label.parseFontString(tmpShorthand, fontOptions)) {
  22570. fontOptions = tmpShorthand;
  22571. }
  22572. util.forEach(fontOptions, function (opt, name) {
  22573. if (opt === undefined) return; // multi-font option need not be present
  22574. if (ret.hasOwnProperty(name)) return; // Keep first value we encounter
  22575. if (multiFontStyle.indexOf(name) !== -1) {
  22576. // Skip multi-font properties but we do need the structure
  22577. ret[name] = {};
  22578. } else {
  22579. ret[name] = opt;
  22580. }
  22581. });
  22582. }
  22583. return ret;
  22584. }
  22585. /**
  22586. * Return the value for given option for the given multi-font.
  22587. *
  22588. * All available option objects are trawled in the set order to construct the option values.
  22589. *
  22590. * ---------------------------------------------------------------------
  22591. * ## Traversal of pile for multi-fonts
  22592. *
  22593. * The determination of multi-font option values is a special case, because any values not
  22594. * present in the multi-font options should by definition be taken from the main font options,
  22595. * i.e. from the current 'parent' object of the multi-font option.
  22596. *
  22597. * ### Search order for multi-fonts
  22598. *
  22599. * 'bold' used as example:
  22600. *
  22601. * - search in option group 'bold' in local properties
  22602. * - search in main font option group in local properties
  22603. *
  22604. * ---------------------------------------------------------------------
  22605. *
  22606. * @param {Pile} pile pile of option objects to use
  22607. * @param {MultiFontStyle} multiName sub path for the multi-font
  22608. * @param {string} option the option to search for, for the given multi-font
  22609. * @returns {string|number} the value for the given option
  22610. * @private
  22611. */
  22612. }, {
  22613. key: 'getFontOption',
  22614. value: function getFontOption(pile, multiName, option) {
  22615. var multiFont = void 0;
  22616. // Search multi font in local properties
  22617. for (var n = 0; n < pile.length; ++n) {
  22618. var fontOptions = pile[n];
  22619. if (fontOptions.hasOwnProperty(multiName)) {
  22620. multiFont = fontOptions[multiName];
  22621. if (multiFont === undefined || multiFont === null) continue;
  22622. // Convert shorthand if necessary
  22623. // TODO: inefficient to do this conversion every time; find a better way.
  22624. var tmpShorthand = {};
  22625. if (Label.parseFontString(tmpShorthand, multiFont)) {
  22626. multiFont = tmpShorthand;
  22627. }
  22628. if (multiFont.hasOwnProperty(option)) {
  22629. return multiFont[option];
  22630. }
  22631. }
  22632. }
  22633. // Option is not mentioned in the multi font options; take it from the parent font options.
  22634. // These have already been converted with getBasicOptions(), so use the converted values.
  22635. if (this.fontOptions.hasOwnProperty(option)) {
  22636. return this.fontOptions[option];
  22637. }
  22638. // A value **must** be found; you should never get here.
  22639. throw new Error("Did not find value for multi-font for property: '" + option + "'");
  22640. }
  22641. /**
  22642. * Return all options values for the given multi-font.
  22643. *
  22644. * All available option objects are trawled in the set order to construct the option values.
  22645. *
  22646. * @param {Pile} pile pile of option objects to use
  22647. * @param {MultiFontStyle} multiName sub path for the mod-font
  22648. * @returns {MultiFontOptions}
  22649. * @private
  22650. */
  22651. }, {
  22652. key: 'getFontOptions',
  22653. value: function getFontOptions(pile, multiName) {
  22654. var result = {};
  22655. var optionNames = ['color', 'size', 'face', 'mod', 'vadjust']; // List of allowed options per multi-font
  22656. for (var i = 0; i < optionNames.length; ++i) {
  22657. var mod = optionNames[i];
  22658. result[mod] = this.getFontOption(pile, multiName, mod);
  22659. }
  22660. return result;
  22661. }
  22662. /////////////////////////////////////////////////////////
  22663. // End methods for handling options piles
  22664. /////////////////////////////////////////////////////////
  22665. /**
  22666. * Collapse the font options for the multi-font to single objects, from
  22667. * the chain of option objects passed (the 'pile').
  22668. *
  22669. * @param {Pile} pile sequence of option objects to consider.
  22670. * First item in list assumed to be the newly set options.
  22671. */
  22672. }, {
  22673. key: 'propagateFonts',
  22674. value: function propagateFonts(pile) {
  22675. var _this2 = this;
  22676. var fontPile = []; // sequence of font objects to consider, order important
  22677. // Note that this.elementOptions is not used here.
  22678. this.addFontOptionsToPile(fontPile, pile);
  22679. this.fontOptions = this.getBasicOptions(fontPile);
  22680. // We set multifont values even if multi === false, for consistency (things break otherwise)
  22681. var _loop = function _loop(i) {
  22682. var mod = multiFontStyle[i];
  22683. var modOptions = _this2.fontOptions[mod];
  22684. var tmpMultiFontOptions = _this2.getFontOptions(fontPile, mod);
  22685. // Copy over found values
  22686. util.forEach(tmpMultiFontOptions, function (option, n) {
  22687. modOptions[n] = option;
  22688. });
  22689. modOptions.size = Number(modOptions.size);
  22690. modOptions.vadjust = Number(modOptions.vadjust);
  22691. };
  22692. for (var i = 0; i < multiFontStyle.length; ++i) {
  22693. _loop(i);
  22694. }
  22695. }
  22696. /**
  22697. * Main function. This is called from anything that wants to draw a label.
  22698. * @param {CanvasRenderingContext2D} ctx
  22699. * @param {number} x
  22700. * @param {number} y
  22701. * @param {boolean} selected
  22702. * @param {boolean} hover
  22703. * @param {string} [baseline='middle']
  22704. */
  22705. }, {
  22706. key: 'draw',
  22707. value: function draw(ctx, x, y, selected, hover) {
  22708. var baseline = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 'middle';
  22709. // if no label, return
  22710. if (this.elementOptions.label === undefined) return;
  22711. // check if we have to render the label
  22712. var viewFontSize = this.fontOptions.size * this.body.view.scale;
  22713. if (this.elementOptions.label && viewFontSize < this.elementOptions.scaling.label.drawThreshold - 1) return;
  22714. // This ensures that there will not be HUGE letters on screen
  22715. // by setting an upper limit on the visible text size (regardless of zoomLevel)
  22716. if (viewFontSize >= this.elementOptions.scaling.label.maxVisible) {
  22717. viewFontSize = Number(this.elementOptions.scaling.label.maxVisible) / this.body.view.scale;
  22718. }
  22719. // update the size cache if required
  22720. this.calculateLabelSize(ctx, selected, hover, x, y, baseline);
  22721. this._drawBackground(ctx);
  22722. this._drawText(ctx, x, this.size.yLine, baseline, viewFontSize);
  22723. }
  22724. /**
  22725. * Draws the label background
  22726. * @param {CanvasRenderingContext2D} ctx
  22727. * @private
  22728. */
  22729. }, {
  22730. key: '_drawBackground',
  22731. value: function _drawBackground(ctx) {
  22732. if (this.fontOptions.background !== undefined && this.fontOptions.background !== "none") {
  22733. ctx.fillStyle = this.fontOptions.background;
  22734. var size = this.getSize();
  22735. ctx.fillRect(size.left, size.top, size.width, size.height);
  22736. }
  22737. }
  22738. /**
  22739. *
  22740. * @param {CanvasRenderingContext2D} ctx
  22741. * @param {number} x
  22742. * @param {number} y
  22743. * @param {string} [baseline='middle']
  22744. * @param {number} viewFontSize
  22745. * @private
  22746. */
  22747. }, {
  22748. key: '_drawText',
  22749. value: function _drawText(ctx, x, y) {
  22750. var baseline = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'middle';
  22751. var viewFontSize = arguments[4];
  22752. var _setAlignment2 = this._setAlignment(ctx, x, y, baseline);
  22753. var _setAlignment3 = (0, _slicedToArray3['default'])(_setAlignment2, 2);
  22754. x = _setAlignment3[0];
  22755. y = _setAlignment3[1];
  22756. ctx.textAlign = 'left';
  22757. x = x - this.size.width / 2; // Shift label 1/2-distance to the left
  22758. if (this.fontOptions.valign && this.size.height > this.size.labelHeight) {
  22759. if (this.fontOptions.valign === 'top') {
  22760. y -= (this.size.height - this.size.labelHeight) / 2;
  22761. }
  22762. if (this.fontOptions.valign === 'bottom') {
  22763. y += (this.size.height - this.size.labelHeight) / 2;
  22764. }
  22765. }
  22766. // draw the text
  22767. for (var i = 0; i < this.lineCount; i++) {
  22768. var line = this.lines[i];
  22769. if (line && line.blocks) {
  22770. var width = 0;
  22771. if (this.isEdgeLabel || this.fontOptions.align === 'center') {
  22772. width += (this.size.width - line.width) / 2;
  22773. } else if (this.fontOptions.align === 'right') {
  22774. width += this.size.width - line.width;
  22775. }
  22776. for (var j = 0; j < line.blocks.length; j++) {
  22777. var block = line.blocks[j];
  22778. ctx.font = block.font;
  22779. var _getColor2 = this._getColor(block.color, viewFontSize, block.strokeColor),
  22780. _getColor3 = (0, _slicedToArray3['default'])(_getColor2, 2),
  22781. fontColor = _getColor3[0],
  22782. strokeColor = _getColor3[1];
  22783. if (block.strokeWidth > 0) {
  22784. ctx.lineWidth = block.strokeWidth;
  22785. ctx.strokeStyle = strokeColor;
  22786. ctx.lineJoin = 'round';
  22787. }
  22788. ctx.fillStyle = fontColor;
  22789. if (block.strokeWidth > 0) {
  22790. ctx.strokeText(block.text, x + width, y + block.vadjust);
  22791. }
  22792. ctx.fillText(block.text, x + width, y + block.vadjust);
  22793. width += block.width;
  22794. }
  22795. y += line.height;
  22796. }
  22797. }
  22798. }
  22799. /**
  22800. *
  22801. * @param {CanvasRenderingContext2D} ctx
  22802. * @param {number} x
  22803. * @param {number} y
  22804. * @param {string} baseline
  22805. * @returns {Array.<number>}
  22806. * @private
  22807. */
  22808. }, {
  22809. key: '_setAlignment',
  22810. value: function _setAlignment(ctx, x, y, baseline) {
  22811. // check for label alignment (for edges)
  22812. // TODO: make alignment for nodes
  22813. if (this.isEdgeLabel && this.fontOptions.align !== 'horizontal' && this.pointToSelf === false) {
  22814. x = 0;
  22815. y = 0;
  22816. var lineMargin = 2;
  22817. if (this.fontOptions.align === 'top') {
  22818. ctx.textBaseline = 'alphabetic';
  22819. y -= 2 * lineMargin; // distance from edge, required because we use alphabetic. Alphabetic has less difference between browsers
  22820. } else if (this.fontOptions.align === 'bottom') {
  22821. ctx.textBaseline = 'hanging';
  22822. y += 2 * lineMargin; // distance from edge, required because we use hanging. Hanging has less difference between browsers
  22823. } else {
  22824. ctx.textBaseline = 'middle';
  22825. }
  22826. } else {
  22827. ctx.textBaseline = baseline;
  22828. }
  22829. return [x, y];
  22830. }
  22831. /**
  22832. * fade in when relative scale is between threshold and threshold - 1.
  22833. * If the relative scale would be smaller than threshold -1 the draw function would have returned before coming here.
  22834. *
  22835. * @param {string} color The font color to use
  22836. * @param {number} viewFontSize
  22837. * @param {string} initialStrokeColor
  22838. * @returns {Array.<string>} An array containing the font color and stroke color
  22839. * @private
  22840. */
  22841. }, {
  22842. key: '_getColor',
  22843. value: function _getColor(color, viewFontSize, initialStrokeColor) {
  22844. var fontColor = color || '#000000';
  22845. var strokeColor = initialStrokeColor || '#ffffff';
  22846. if (viewFontSize <= this.elementOptions.scaling.label.drawThreshold) {
  22847. var opacity = Math.max(0, Math.min(1, 1 - (this.elementOptions.scaling.label.drawThreshold - viewFontSize)));
  22848. fontColor = util.overrideOpacity(fontColor, opacity);
  22849. strokeColor = util.overrideOpacity(strokeColor, opacity);
  22850. }
  22851. return [fontColor, strokeColor];
  22852. }
  22853. /**
  22854. *
  22855. * @param {CanvasRenderingContext2D} ctx
  22856. * @param {boolean} selected
  22857. * @param {boolean} hover
  22858. * @returns {{width: number, height: number}}
  22859. */
  22860. }, {
  22861. key: 'getTextSize',
  22862. value: function getTextSize(ctx) {
  22863. var selected = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  22864. var hover = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  22865. this._processLabel(ctx, selected, hover);
  22866. return {
  22867. width: this.size.width,
  22868. height: this.size.height,
  22869. lineCount: this.lineCount
  22870. };
  22871. }
  22872. /**
  22873. * Get the current dimensions of the label
  22874. *
  22875. * @return {rect}
  22876. */
  22877. }, {
  22878. key: 'getSize',
  22879. value: function getSize() {
  22880. var lineMargin = 2;
  22881. var x = this.size.left; // default values which might be overridden below
  22882. var y = this.size.top - 0.5 * lineMargin; // idem
  22883. if (this.isEdgeLabel) {
  22884. var x2 = -this.size.width * 0.5;
  22885. switch (this.fontOptions.align) {
  22886. case 'middle':
  22887. x = x2;
  22888. y = -this.size.height * 0.5;
  22889. break;
  22890. case 'top':
  22891. x = x2;
  22892. y = -(this.size.height + lineMargin);
  22893. break;
  22894. case 'bottom':
  22895. x = x2;
  22896. y = lineMargin;
  22897. break;
  22898. }
  22899. }
  22900. var ret = {
  22901. left: x,
  22902. top: y,
  22903. width: this.size.width,
  22904. height: this.size.height
  22905. };
  22906. return ret;
  22907. }
  22908. /**
  22909. *
  22910. * @param {CanvasRenderingContext2D} ctx
  22911. * @param {boolean} selected
  22912. * @param {boolean} hover
  22913. * @param {number} [x=0]
  22914. * @param {number} [y=0]
  22915. * @param {'middle'|'hanging'} [baseline='middle']
  22916. */
  22917. }, {
  22918. key: 'calculateLabelSize',
  22919. value: function calculateLabelSize(ctx, selected, hover) {
  22920. var x = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  22921. var y = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  22922. var baseline = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 'middle';
  22923. this._processLabel(ctx, selected, hover);
  22924. this.size.left = x - this.size.width * 0.5;
  22925. this.size.top = y - this.size.height * 0.5;
  22926. this.size.yLine = y + (1 - this.lineCount) * 0.5 * this.fontOptions.size;
  22927. if (baseline === "hanging") {
  22928. this.size.top += 0.5 * this.fontOptions.size;
  22929. this.size.top += 4; // distance from node, required because we use hanging. Hanging has less difference between browsers
  22930. this.size.yLine += 4; // distance from node
  22931. }
  22932. }
  22933. /**
  22934. *
  22935. * @param {CanvasRenderingContext2D} ctx
  22936. * @param {boolean} selected
  22937. * @param {boolean} hover
  22938. * @param {string} mod
  22939. * @returns {{color, size, face, mod, vadjust, strokeWidth: *, strokeColor: (*|string|allOptions.edges.font.strokeColor|{string}|allOptions.nodes.font.strokeColor|Array)}}
  22940. */
  22941. }, {
  22942. key: 'getFormattingValues',
  22943. value: function getFormattingValues(ctx, selected, hover, mod) {
  22944. var getValue = function getValue(fontOptions, mod, option) {
  22945. if (mod === "normal") {
  22946. if (option === 'mod') return "";
  22947. return fontOptions[option];
  22948. }
  22949. if (fontOptions[mod][option] !== undefined) {
  22950. // Grumbl leaving out test on undefined equals false for ""
  22951. return fontOptions[mod][option];
  22952. } else {
  22953. // Take from parent font option
  22954. return fontOptions[option];
  22955. }
  22956. };
  22957. var values = {
  22958. color: getValue(this.fontOptions, mod, 'color'),
  22959. size: getValue(this.fontOptions, mod, 'size'),
  22960. face: getValue(this.fontOptions, mod, 'face'),
  22961. mod: getValue(this.fontOptions, mod, 'mod'),
  22962. vadjust: getValue(this.fontOptions, mod, 'vadjust'),
  22963. strokeWidth: this.fontOptions.strokeWidth,
  22964. strokeColor: this.fontOptions.strokeColor
  22965. };
  22966. if (selected || hover) {
  22967. if (mod === "normal" && this.fontOptions.chooser === true && this.elementOptions.labelHighlightBold) {
  22968. values.mod = 'bold';
  22969. } else {
  22970. if (typeof this.fontOptions.chooser === 'function') {
  22971. this.fontOptions.chooser(values, this.elementOptions.id, selected, hover);
  22972. }
  22973. }
  22974. }
  22975. var fontString = "";
  22976. if (values.mod !== undefined && values.mod !== "") {
  22977. // safeguard for undefined - this happened
  22978. fontString += values.mod + " ";
  22979. }
  22980. fontString += values.size + "px " + values.face;
  22981. ctx.font = fontString.replace(/"/g, "");
  22982. values.font = ctx.font;
  22983. values.height = values.size;
  22984. return values;
  22985. }
  22986. /**
  22987. *
  22988. * @param {boolean} selected
  22989. * @param {boolean} hover
  22990. * @returns {boolean}
  22991. */
  22992. }, {
  22993. key: 'differentState',
  22994. value: function differentState(selected, hover) {
  22995. return selected !== this.selectedState || hover !== this.hoverState;
  22996. }
  22997. /**
  22998. * This explodes the passed text into lines and determines the width, height and number of lines.
  22999. *
  23000. * @param {CanvasRenderingContext2D} ctx
  23001. * @param {boolean} selected
  23002. * @param {boolean} hover
  23003. * @param {string} inText the text to explode
  23004. * @returns {{width, height, lines}|*}
  23005. * @private
  23006. */
  23007. }, {
  23008. key: '_processLabelText',
  23009. value: function _processLabelText(ctx, selected, hover, inText) {
  23010. var splitter = new LabelSplitter(ctx, this, selected, hover);
  23011. return splitter.process(inText);
  23012. }
  23013. /**
  23014. * This explodes the label string into lines and sets the width, height and number of lines.
  23015. * @param {CanvasRenderingContext2D} ctx
  23016. * @param {boolean} selected
  23017. * @param {boolean} hover
  23018. * @private
  23019. */
  23020. }, {
  23021. key: '_processLabel',
  23022. value: function _processLabel(ctx, selected, hover) {
  23023. if (this.labelDirty === false && !this.differentState(selected, hover)) return;
  23024. var state = this._processLabelText(ctx, selected, hover, this.elementOptions.label);
  23025. if (this.fontOptions.minWdt > 0 && state.width < this.fontOptions.minWdt) {
  23026. state.width = this.fontOptions.minWdt;
  23027. }
  23028. this.size.labelHeight = state.height;
  23029. if (this.fontOptions.minHgt > 0 && state.height < this.fontOptions.minHgt) {
  23030. state.height = this.fontOptions.minHgt;
  23031. }
  23032. this.lines = state.lines;
  23033. this.lineCount = state.lines.length;
  23034. this.size.width = state.width;
  23035. this.size.height = state.height;
  23036. this.selectedState = selected;
  23037. this.hoverState = hover;
  23038. this.labelDirty = false;
  23039. }
  23040. /**
  23041. * Check if this label is visible
  23042. *
  23043. * @return {boolean} true if this label will be show, false otherwise
  23044. */
  23045. }, {
  23046. key: 'visible',
  23047. value: function visible() {
  23048. if (this.size.width === 0 || this.size.height === 0 || this.elementOptions.label === undefined) {
  23049. return false; // nothing to display
  23050. }
  23051. var viewFontSize = this.fontOptions.size * this.body.view.scale;
  23052. if (viewFontSize < this.elementOptions.scaling.label.drawThreshold - 1) {
  23053. return false; // Too small or too far away to show
  23054. }
  23055. return true;
  23056. }
  23057. }], [{
  23058. key: 'parseFontString',
  23059. value: function parseFontString(outOptions, inOptions) {
  23060. if (!inOptions || typeof inOptions !== 'string') return false;
  23061. var newOptionsArray = inOptions.split(" ");
  23062. outOptions.size = newOptionsArray[0].replace("px", '');
  23063. outOptions.face = newOptionsArray[1];
  23064. outOptions.color = newOptionsArray[2];
  23065. return true;
  23066. }
  23067. }]);
  23068. return Label;
  23069. }();
  23070. exports['default'] = Label;
  23071. /***/ }),
  23072. /* 118 */
  23073. /***/ (function(module, exports, __webpack_require__) {
  23074. "use strict";
  23075. Object.defineProperty(exports, "__esModule", {
  23076. value: true
  23077. });
  23078. var _slicedToArray2 = __webpack_require__(30);
  23079. var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
  23080. var _classCallCheck2 = __webpack_require__(0);
  23081. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  23082. var _createClass2 = __webpack_require__(1);
  23083. var _createClass3 = _interopRequireDefault(_createClass2);
  23084. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  23085. var util = __webpack_require__(2);
  23086. var EndPoints = __webpack_require__(119)["default"];
  23087. /**
  23088. * The Base Class for all edges.
  23089. *
  23090. */
  23091. var EdgeBase = function () {
  23092. /**
  23093. * @param {Object} options
  23094. * @param {Object} body
  23095. * @param {Label} labelModule
  23096. */
  23097. function EdgeBase(options, body, labelModule) {
  23098. (0, _classCallCheck3["default"])(this, EdgeBase);
  23099. this.body = body;
  23100. this.labelModule = labelModule;
  23101. this.options = {};
  23102. this.setOptions(options);
  23103. this.colorDirty = true;
  23104. this.color = {};
  23105. this.selectionWidth = 2;
  23106. this.hoverWidth = 1.5;
  23107. this.fromPoint = this.from;
  23108. this.toPoint = this.to;
  23109. }
  23110. /**
  23111. * Connects a node to itself
  23112. */
  23113. (0, _createClass3["default"])(EdgeBase, [{
  23114. key: "connect",
  23115. value: function connect() {
  23116. this.from = this.body.nodes[this.options.from];
  23117. this.to = this.body.nodes[this.options.to];
  23118. }
  23119. /**
  23120. *
  23121. * @returns {boolean} always false
  23122. */
  23123. }, {
  23124. key: "cleanup",
  23125. value: function cleanup() {
  23126. return false;
  23127. }
  23128. /**
  23129. *
  23130. * @param {Object} options
  23131. */
  23132. }, {
  23133. key: "setOptions",
  23134. value: function setOptions(options) {
  23135. this.options = options;
  23136. this.from = this.body.nodes[this.options.from];
  23137. this.to = this.body.nodes[this.options.to];
  23138. this.id = this.options.id;
  23139. }
  23140. /**
  23141. * Redraw a edge as a line
  23142. * Draw this edge in the given canvas
  23143. * The 2d context of a HTML canvas can be retrieved by canvas.getContext("2d");
  23144. *
  23145. * @param {CanvasRenderingContext2D} ctx
  23146. * @param {Array} values
  23147. * @param {boolean} selected
  23148. * @param {boolean} hover
  23149. * @param {Node} viaNode
  23150. * @private
  23151. */
  23152. }, {
  23153. key: "drawLine",
  23154. value: function drawLine(ctx, values, selected, hover, viaNode) {
  23155. // set style
  23156. ctx.strokeStyle = this.getColor(ctx, values, selected, hover);
  23157. ctx.lineWidth = values.width;
  23158. if (values.dashes !== false) {
  23159. this._drawDashedLine(ctx, values, viaNode);
  23160. } else {
  23161. this._drawLine(ctx, values, viaNode);
  23162. }
  23163. }
  23164. /**
  23165. *
  23166. * @param {CanvasRenderingContext2D} ctx
  23167. * @param {Array} values
  23168. * @param {Node} viaNode
  23169. * @param {{x: number, y: number}} [fromPoint]
  23170. * @param {{x: number, y: number}} [toPoint]
  23171. * @private
  23172. */
  23173. }, {
  23174. key: "_drawLine",
  23175. value: function _drawLine(ctx, values, viaNode, fromPoint, toPoint) {
  23176. if (this.from != this.to) {
  23177. // draw line
  23178. this._line(ctx, values, viaNode, fromPoint, toPoint);
  23179. } else {
  23180. var _getCircleData2 = this._getCircleData(ctx),
  23181. _getCircleData3 = (0, _slicedToArray3["default"])(_getCircleData2, 3),
  23182. x = _getCircleData3[0],
  23183. y = _getCircleData3[1],
  23184. radius = _getCircleData3[2];
  23185. this._circle(ctx, values, x, y, radius);
  23186. }
  23187. }
  23188. /**
  23189. *
  23190. * @param {CanvasRenderingContext2D} ctx
  23191. * @param {Array} values
  23192. * @param {Node} viaNode
  23193. * @param {{x: number, y: number}} [fromPoint] TODO: Remove in next major release
  23194. * @param {{x: number, y: number}} [toPoint] TODO: Remove in next major release
  23195. * @private
  23196. */
  23197. }, {
  23198. key: "_drawDashedLine",
  23199. value: function _drawDashedLine(ctx, values, viaNode, fromPoint, toPoint) {
  23200. // eslint-disable-line no-unused-vars
  23201. ctx.lineCap = 'round';
  23202. var pattern = [5, 5];
  23203. if (Array.isArray(values.dashes) === true) {
  23204. pattern = values.dashes;
  23205. }
  23206. // only firefox and chrome support this method, else we use the legacy one.
  23207. if (ctx.setLineDash !== undefined) {
  23208. ctx.save();
  23209. // set dash settings for chrome or firefox
  23210. ctx.setLineDash(pattern);
  23211. ctx.lineDashOffset = 0;
  23212. // draw the line
  23213. if (this.from != this.to) {
  23214. // draw line
  23215. this._line(ctx, values, viaNode);
  23216. } else {
  23217. var _getCircleData4 = this._getCircleData(ctx),
  23218. _getCircleData5 = (0, _slicedToArray3["default"])(_getCircleData4, 3),
  23219. x = _getCircleData5[0],
  23220. y = _getCircleData5[1],
  23221. radius = _getCircleData5[2];
  23222. this._circle(ctx, values, x, y, radius);
  23223. }
  23224. // restore the dash settings.
  23225. ctx.setLineDash([0]);
  23226. ctx.lineDashOffset = 0;
  23227. ctx.restore();
  23228. } else {
  23229. // unsupporting smooth lines
  23230. if (this.from != this.to) {
  23231. // draw line
  23232. ctx.dashedLine(this.from.x, this.from.y, this.to.x, this.to.y, pattern);
  23233. } else {
  23234. var _getCircleData6 = this._getCircleData(ctx),
  23235. _getCircleData7 = (0, _slicedToArray3["default"])(_getCircleData6, 3),
  23236. _x = _getCircleData7[0],
  23237. _y = _getCircleData7[1],
  23238. _radius = _getCircleData7[2];
  23239. this._circle(ctx, values, _x, _y, _radius);
  23240. }
  23241. // draw shadow if enabled
  23242. this.enableShadow(ctx, values);
  23243. ctx.stroke();
  23244. // disable shadows for other elements.
  23245. this.disableShadow(ctx, values);
  23246. }
  23247. }
  23248. /**
  23249. *
  23250. * @param {Node} nearNode
  23251. * @param {CanvasRenderingContext2D} ctx
  23252. * @param {Object} options
  23253. * @returns {{x: number, y: number}}
  23254. */
  23255. }, {
  23256. key: "findBorderPosition",
  23257. value: function findBorderPosition(nearNode, ctx, options) {
  23258. if (this.from != this.to) {
  23259. return this._findBorderPosition(nearNode, ctx, options);
  23260. } else {
  23261. return this._findBorderPositionCircle(nearNode, ctx, options);
  23262. }
  23263. }
  23264. /**
  23265. *
  23266. * @param {CanvasRenderingContext2D} ctx
  23267. * @returns {{from: ({x: number, y: number, t: number}|*), to: ({x: number, y: number, t: number}|*)}}
  23268. */
  23269. }, {
  23270. key: "findBorderPositions",
  23271. value: function findBorderPositions(ctx) {
  23272. var from = {};
  23273. var to = {};
  23274. if (this.from != this.to) {
  23275. from = this._findBorderPosition(this.from, ctx);
  23276. to = this._findBorderPosition(this.to, ctx);
  23277. } else {
  23278. var _getCircleData$slice = this._getCircleData(ctx).slice(0, 2),
  23279. _getCircleData$slice2 = (0, _slicedToArray3["default"])(_getCircleData$slice, 2),
  23280. x = _getCircleData$slice2[0],
  23281. y = _getCircleData$slice2[1];
  23282. from = this._findBorderPositionCircle(this.from, ctx, { x: x, y: y, low: 0.25, high: 0.6, direction: -1 });
  23283. to = this._findBorderPositionCircle(this.from, ctx, { x: x, y: y, low: 0.6, high: 0.8, direction: 1 });
  23284. }
  23285. return { from: from, to: to };
  23286. }
  23287. /**
  23288. *
  23289. * @param {CanvasRenderingContext2D} ctx
  23290. * @returns {Array.<number>} x, y, radius
  23291. * @private
  23292. */
  23293. }, {
  23294. key: "_getCircleData",
  23295. value: function _getCircleData(ctx) {
  23296. var x = void 0,
  23297. y = void 0;
  23298. var node = this.from;
  23299. var radius = this.options.selfReferenceSize;
  23300. if (ctx !== undefined) {
  23301. if (node.shape.width === undefined) {
  23302. node.shape.resize(ctx);
  23303. }
  23304. }
  23305. // get circle coordinates
  23306. if (node.shape.width > node.shape.height) {
  23307. x = node.x + node.shape.width * 0.5;
  23308. y = node.y - radius;
  23309. } else {
  23310. x = node.x + radius;
  23311. y = node.y - node.shape.height * 0.5;
  23312. }
  23313. return [x, y, radius];
  23314. }
  23315. /**
  23316. * Get a point on a circle
  23317. * @param {number} x
  23318. * @param {number} y
  23319. * @param {number} radius
  23320. * @param {number} percentage - Value between 0 (line start) and 1 (line end)
  23321. * @return {Object} point
  23322. * @private
  23323. */
  23324. }, {
  23325. key: "_pointOnCircle",
  23326. value: function _pointOnCircle(x, y, radius, percentage) {
  23327. var angle = percentage * 2 * Math.PI;
  23328. return {
  23329. x: x + radius * Math.cos(angle),
  23330. y: y - radius * Math.sin(angle)
  23331. };
  23332. }
  23333. /**
  23334. * This function uses binary search to look for the point where the circle crosses the border of the node.
  23335. * @param {Node} node
  23336. * @param {CanvasRenderingContext2D} ctx
  23337. * @param {Object} options
  23338. * @returns {*}
  23339. * @private
  23340. */
  23341. }, {
  23342. key: "_findBorderPositionCircle",
  23343. value: function _findBorderPositionCircle(node, ctx, options) {
  23344. var x = options.x;
  23345. var y = options.y;
  23346. var low = options.low;
  23347. var high = options.high;
  23348. var direction = options.direction;
  23349. var maxIterations = 10;
  23350. var iteration = 0;
  23351. var radius = this.options.selfReferenceSize;
  23352. var pos = void 0,
  23353. angle = void 0,
  23354. distanceToBorder = void 0,
  23355. distanceToPoint = void 0,
  23356. difference = void 0;
  23357. var threshold = 0.05;
  23358. var middle = (low + high) * 0.5;
  23359. while (low <= high && iteration < maxIterations) {
  23360. middle = (low + high) * 0.5;
  23361. pos = this._pointOnCircle(x, y, radius, middle);
  23362. angle = Math.atan2(node.y - pos.y, node.x - pos.x);
  23363. distanceToBorder = node.distanceToBorder(ctx, angle);
  23364. distanceToPoint = Math.sqrt(Math.pow(pos.x - node.x, 2) + Math.pow(pos.y - node.y, 2));
  23365. difference = distanceToBorder - distanceToPoint;
  23366. if (Math.abs(difference) < threshold) {
  23367. break; // found
  23368. } else if (difference > 0) {
  23369. // distance to nodes is larger than distance to border --> t needs to be bigger if we're looking at the to node.
  23370. if (direction > 0) {
  23371. low = middle;
  23372. } else {
  23373. high = middle;
  23374. }
  23375. } else {
  23376. if (direction > 0) {
  23377. high = middle;
  23378. } else {
  23379. low = middle;
  23380. }
  23381. }
  23382. iteration++;
  23383. }
  23384. pos.t = middle;
  23385. return pos;
  23386. }
  23387. /**
  23388. * Get the line width of the edge. Depends on width and whether one of the
  23389. * connected nodes is selected.
  23390. * @param {boolean} selected
  23391. * @param {boolean} hover
  23392. * @returns {number} width
  23393. * @private
  23394. */
  23395. }, {
  23396. key: "getLineWidth",
  23397. value: function getLineWidth(selected, hover) {
  23398. if (selected === true) {
  23399. return Math.max(this.selectionWidth, 0.3 / this.body.view.scale);
  23400. } else {
  23401. if (hover === true) {
  23402. return Math.max(this.hoverWidth, 0.3 / this.body.view.scale);
  23403. } else {
  23404. return Math.max(this.options.width, 0.3 / this.body.view.scale);
  23405. }
  23406. }
  23407. }
  23408. /**
  23409. *
  23410. * @param {CanvasRenderingContext2D} ctx
  23411. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  23412. * @param {boolean} selected - Unused
  23413. * @param {boolean} hover - Unused
  23414. * @returns {string}
  23415. */
  23416. }, {
  23417. key: "getColor",
  23418. value: function getColor(ctx, values, selected, hover) {
  23419. // eslint-disable-line no-unused-vars
  23420. if (values.inheritsColor !== false) {
  23421. // when this is a loop edge, just use the 'from' method
  23422. if (values.inheritsColor === 'both' && this.from.id !== this.to.id) {
  23423. var grd = ctx.createLinearGradient(this.from.x, this.from.y, this.to.x, this.to.y);
  23424. var fromColor = void 0,
  23425. toColor = void 0;
  23426. fromColor = this.from.options.color.highlight.border;
  23427. toColor = this.to.options.color.highlight.border;
  23428. if (this.from.selected === false && this.to.selected === false) {
  23429. fromColor = util.overrideOpacity(this.from.options.color.border, values.opacity);
  23430. toColor = util.overrideOpacity(this.to.options.color.border, values.opacity);
  23431. } else if (this.from.selected === true && this.to.selected === false) {
  23432. toColor = this.to.options.color.border;
  23433. } else if (this.from.selected === false && this.to.selected === true) {
  23434. fromColor = this.from.options.color.border;
  23435. }
  23436. grd.addColorStop(0, fromColor);
  23437. grd.addColorStop(1, toColor);
  23438. // -------------------- this returns -------------------- //
  23439. return grd;
  23440. }
  23441. if (values.inheritsColor === "to") {
  23442. return util.overrideOpacity(this.to.options.color.border, values.opacity);
  23443. } else {
  23444. // "from"
  23445. return util.overrideOpacity(this.from.options.color.border, values.opacity);
  23446. }
  23447. } else {
  23448. return util.overrideOpacity(values.color, values.opacity);
  23449. }
  23450. }
  23451. /**
  23452. * Draw a line from a node to itself, a circle
  23453. *
  23454. * @param {CanvasRenderingContext2D} ctx
  23455. * @param {Array} values
  23456. * @param {number} x
  23457. * @param {number} y
  23458. * @param {number} radius
  23459. * @private
  23460. */
  23461. }, {
  23462. key: "_circle",
  23463. value: function _circle(ctx, values, x, y, radius) {
  23464. // draw shadow if enabled
  23465. this.enableShadow(ctx, values);
  23466. // draw a circle
  23467. ctx.beginPath();
  23468. ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  23469. ctx.stroke();
  23470. // disable shadows for other elements.
  23471. this.disableShadow(ctx, values);
  23472. }
  23473. /**
  23474. * Calculate the distance between a point (x3,y3) and a line segment from (x1,y1) to (x2,y2).
  23475. * (x3,y3) is the point.
  23476. *
  23477. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  23478. *
  23479. * @param {number} x1
  23480. * @param {number} y1
  23481. * @param {number} x2
  23482. * @param {number} y2
  23483. * @param {number} x3
  23484. * @param {number} y3
  23485. * @param {Node} via
  23486. * @param {Array} values
  23487. * @returns {number}
  23488. */
  23489. }, {
  23490. key: "getDistanceToEdge",
  23491. value: function getDistanceToEdge(x1, y1, x2, y2, x3, y3, via, values) {
  23492. // eslint-disable-line no-unused-vars
  23493. var returnValue = 0;
  23494. if (this.from != this.to) {
  23495. returnValue = this._getDistanceToEdge(x1, y1, x2, y2, x3, y3, via);
  23496. } else {
  23497. var _getCircleData8 = this._getCircleData(undefined),
  23498. _getCircleData9 = (0, _slicedToArray3["default"])(_getCircleData8, 3),
  23499. x = _getCircleData9[0],
  23500. y = _getCircleData9[1],
  23501. radius = _getCircleData9[2];
  23502. var dx = x - x3;
  23503. var dy = y - y3;
  23504. returnValue = Math.abs(Math.sqrt(dx * dx + dy * dy) - radius);
  23505. }
  23506. return returnValue;
  23507. }
  23508. /**
  23509. *
  23510. * @param {number} x1
  23511. * @param {number} y1
  23512. * @param {number} x2
  23513. * @param {number} y2
  23514. * @param {number} x3
  23515. * @param {number} y3
  23516. * @returns {number}
  23517. * @private
  23518. */
  23519. }, {
  23520. key: "_getDistanceToLine",
  23521. value: function _getDistanceToLine(x1, y1, x2, y2, x3, y3) {
  23522. var px = x2 - x1;
  23523. var py = y2 - y1;
  23524. var something = px * px + py * py;
  23525. var u = ((x3 - x1) * px + (y3 - y1) * py) / something;
  23526. if (u > 1) {
  23527. u = 1;
  23528. } else if (u < 0) {
  23529. u = 0;
  23530. }
  23531. var x = x1 + u * px;
  23532. var y = y1 + u * py;
  23533. var dx = x - x3;
  23534. var dy = y - y3;
  23535. //# Note: If the actual distance does not matter,
  23536. //# if you only want to compare what this function
  23537. //# returns to other results of this function, you
  23538. //# can just return the squared distance instead
  23539. //# (i.e. remove the sqrt) to gain a little performance
  23540. return Math.sqrt(dx * dx + dy * dy);
  23541. }
  23542. /**
  23543. * @param {CanvasRenderingContext2D} ctx
  23544. * @param {string} position
  23545. * @param {Node} viaNode
  23546. * @param {boolean} selected
  23547. * @param {boolean} hover
  23548. * @param {Array} values
  23549. * @returns {{point: *, core: {x: number, y: number}, angle: *, length: number, type: *}}
  23550. */
  23551. }, {
  23552. key: "getArrowData",
  23553. value: function getArrowData(ctx, position, viaNode, selected, hover, values) {
  23554. // set lets
  23555. var angle = void 0;
  23556. var arrowPoint = void 0;
  23557. var node1 = void 0;
  23558. var node2 = void 0;
  23559. var guideOffset = void 0;
  23560. var scaleFactor = void 0;
  23561. var type = void 0;
  23562. var lineWidth = values.width;
  23563. if (position === 'from') {
  23564. node1 = this.from;
  23565. node2 = this.to;
  23566. guideOffset = 0.1;
  23567. scaleFactor = values.fromArrowScale;
  23568. type = values.fromArrowType;
  23569. } else if (position === 'to') {
  23570. node1 = this.to;
  23571. node2 = this.from;
  23572. guideOffset = -0.1;
  23573. scaleFactor = values.toArrowScale;
  23574. type = values.toArrowType;
  23575. } else {
  23576. node1 = this.to;
  23577. node2 = this.from;
  23578. scaleFactor = values.middleArrowScale;
  23579. type = values.middleArrowType;
  23580. }
  23581. // if not connected to itself
  23582. if (node1 != node2) {
  23583. if (position !== 'middle') {
  23584. // draw arrow head
  23585. if (this.options.smooth.enabled === true) {
  23586. arrowPoint = this.findBorderPosition(node1, ctx, { via: viaNode });
  23587. var guidePos = this.getPoint(Math.max(0.0, Math.min(1.0, arrowPoint.t + guideOffset)), viaNode);
  23588. angle = Math.atan2(arrowPoint.y - guidePos.y, arrowPoint.x - guidePos.x);
  23589. } else {
  23590. angle = Math.atan2(node1.y - node2.y, node1.x - node2.x);
  23591. arrowPoint = this.findBorderPosition(node1, ctx);
  23592. }
  23593. } else {
  23594. angle = Math.atan2(node1.y - node2.y, node1.x - node2.x);
  23595. arrowPoint = this.getPoint(0.5, viaNode); // this is 0.6 to account for the size of the arrow.
  23596. }
  23597. } else {
  23598. // draw circle
  23599. var _getCircleData10 = this._getCircleData(ctx),
  23600. _getCircleData11 = (0, _slicedToArray3["default"])(_getCircleData10, 3),
  23601. x = _getCircleData11[0],
  23602. y = _getCircleData11[1],
  23603. radius = _getCircleData11[2];
  23604. if (position === 'from') {
  23605. arrowPoint = this.findBorderPosition(this.from, ctx, { x: x, y: y, low: 0.25, high: 0.6, direction: -1 });
  23606. angle = arrowPoint.t * -2 * Math.PI + 1.5 * Math.PI + 0.1 * Math.PI;
  23607. } else if (position === 'to') {
  23608. arrowPoint = this.findBorderPosition(this.from, ctx, { x: x, y: y, low: 0.6, high: 1.0, direction: 1 });
  23609. angle = arrowPoint.t * -2 * Math.PI + 1.5 * Math.PI - 1.1 * Math.PI;
  23610. } else {
  23611. arrowPoint = this._pointOnCircle(x, y, radius, 0.175);
  23612. angle = 3.9269908169872414; // === 0.175 * -2 * Math.PI + 1.5 * Math.PI + 0.1 * Math.PI;
  23613. }
  23614. }
  23615. if (position === 'middle' && scaleFactor < 0) lineWidth *= -1; // reversed middle arrow
  23616. var length = 15 * scaleFactor + 3 * lineWidth; // 3* lineWidth is the width of the edge.
  23617. var xi = arrowPoint.x - length * 0.9 * Math.cos(angle);
  23618. var yi = arrowPoint.y - length * 0.9 * Math.sin(angle);
  23619. var arrowCore = { x: xi, y: yi };
  23620. return { point: arrowPoint, core: arrowCore, angle: angle, length: length, type: type };
  23621. }
  23622. /**
  23623. *
  23624. * @param {CanvasRenderingContext2D} ctx
  23625. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  23626. * @param {boolean} selected
  23627. * @param {boolean} hover
  23628. * @param {Object} arrowData
  23629. */
  23630. }, {
  23631. key: "drawArrowHead",
  23632. value: function drawArrowHead(ctx, values, selected, hover, arrowData) {
  23633. // set style
  23634. ctx.strokeStyle = this.getColor(ctx, values, selected, hover);
  23635. ctx.fillStyle = ctx.strokeStyle;
  23636. ctx.lineWidth = values.width;
  23637. EndPoints.draw(ctx, arrowData);
  23638. // draw shadow if enabled
  23639. this.enableShadow(ctx, values);
  23640. ctx.fill();
  23641. // disable shadows for other elements.
  23642. this.disableShadow(ctx, values);
  23643. }
  23644. /**
  23645. *
  23646. * @param {CanvasRenderingContext2D} ctx
  23647. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  23648. */
  23649. }, {
  23650. key: "enableShadow",
  23651. value: function enableShadow(ctx, values) {
  23652. if (values.shadow === true) {
  23653. ctx.shadowColor = values.shadowColor;
  23654. ctx.shadowBlur = values.shadowSize;
  23655. ctx.shadowOffsetX = values.shadowX;
  23656. ctx.shadowOffsetY = values.shadowY;
  23657. }
  23658. }
  23659. /**
  23660. *
  23661. * @param {CanvasRenderingContext2D} ctx
  23662. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  23663. */
  23664. }, {
  23665. key: "disableShadow",
  23666. value: function disableShadow(ctx, values) {
  23667. if (values.shadow === true) {
  23668. ctx.shadowColor = 'rgba(0,0,0,0)';
  23669. ctx.shadowBlur = 0;
  23670. ctx.shadowOffsetX = 0;
  23671. ctx.shadowOffsetY = 0;
  23672. }
  23673. }
  23674. }]);
  23675. return EdgeBase;
  23676. }();
  23677. exports["default"] = EdgeBase;
  23678. /***/ }),
  23679. /* 119 */
  23680. /***/ (function(module, exports, __webpack_require__) {
  23681. "use strict";
  23682. Object.defineProperty(exports, "__esModule", {
  23683. value: true
  23684. });
  23685. var _getPrototypeOf = __webpack_require__(3);
  23686. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  23687. var _possibleConstructorReturn2 = __webpack_require__(4);
  23688. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  23689. var _inherits2 = __webpack_require__(5);
  23690. var _inherits3 = _interopRequireDefault(_inherits2);
  23691. var _classCallCheck2 = __webpack_require__(0);
  23692. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  23693. var _createClass2 = __webpack_require__(1);
  23694. var _createClass3 = _interopRequireDefault(_createClass2);
  23695. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  23696. /** ============================================================================
  23697. * Location of all the endpoint drawing routines.
  23698. *
  23699. * Every endpoint has its own drawing routine, which contains an endpoint definition.
  23700. *
  23701. * The endpoint definitions must have the following properies:
  23702. *
  23703. * - (0,0) is the connection point to the node it attaches to
  23704. * - The endpoints are orientated to the positive x-direction
  23705. * - The length of the endpoint is at most 1
  23706. *
  23707. * As long as the endpoint classes remain simple and not too numerous, they will
  23708. * be contained within this module.
  23709. * All classes here except `EndPoints` should be considered as private to this module.
  23710. *
  23711. * -----------------------------------------------------------------------------
  23712. * ### Further Actions
  23713. *
  23714. * After adding a new endpoint here, you also need to do the following things:
  23715. *
  23716. * - Add the new endpoint name to `network/options.js` in array `endPoints`.
  23717. * - Add the new endpoint name to the documentation.
  23718. * Scan for 'arrows.to.type` and add it to the description.
  23719. * - Add the endpoint to the examples. At the very least, add it to example
  23720. * `edgeStyles/arrowTypes`.
  23721. * ============================================================================= */
  23722. // NOTE: When a typedef is isolated in a separate comment block, an actual description is generated for it,
  23723. // using the rest of the commenting in the code block. Usage of typedef in other comments then
  23724. // link to there. TIL.
  23725. //
  23726. // Also noteworthy, all typedef's set up in this manner are collected in a single, global page 'global.html'.
  23727. // In other words, it doesn't matter *where* the typedef's are defined in the code.
  23728. //
  23729. //
  23730. // TODO: add descriptive commenting to given typedef's
  23731. /**
  23732. * @typedef {{type:string, point:Point, angle:number, length:number}} ArrowData
  23733. *
  23734. * Object containing instantiation data for a given endpoint.
  23735. */
  23736. /**
  23737. * @typedef {{x:number, y:number}} Point
  23738. *
  23739. * A point in view-coordinates.
  23740. */
  23741. /**
  23742. * Common methods for endpoints
  23743. *
  23744. * @class
  23745. */
  23746. var EndPoint = function () {
  23747. function EndPoint() {
  23748. (0, _classCallCheck3['default'])(this, EndPoint);
  23749. }
  23750. (0, _createClass3['default'])(EndPoint, null, [{
  23751. key: 'transform',
  23752. /**
  23753. * Apply transformation on points for display.
  23754. *
  23755. * The following is done:
  23756. * - rotate by the specified angle
  23757. * - multiply the (normalized) coordinates by the passed length
  23758. * - offset by the target coordinates
  23759. *
  23760. * @param {Array<Point>} points
  23761. * @param {ArrowData} arrowData
  23762. * @static
  23763. */
  23764. value: function transform(points, arrowData) {
  23765. if (!(points instanceof Array)) {
  23766. points = [points];
  23767. }
  23768. var x = arrowData.point.x;
  23769. var y = arrowData.point.y;
  23770. var angle = arrowData.angle;
  23771. var length = arrowData.length;
  23772. for (var i = 0; i < points.length; ++i) {
  23773. var p = points[i];
  23774. var xt = p.x * Math.cos(angle) - p.y * Math.sin(angle);
  23775. var yt = p.x * Math.sin(angle) + p.y * Math.cos(angle);
  23776. p.x = x + length * xt;
  23777. p.y = y + length * yt;
  23778. }
  23779. }
  23780. /**
  23781. * Draw a closed path using the given real coordinates.
  23782. *
  23783. * @param {CanvasRenderingContext2D} ctx
  23784. * @param {Array.<Point>} points
  23785. * @static
  23786. */
  23787. }, {
  23788. key: 'drawPath',
  23789. value: function drawPath(ctx, points) {
  23790. ctx.beginPath();
  23791. ctx.moveTo(points[0].x, points[0].y);
  23792. for (var i = 1; i < points.length; ++i) {
  23793. ctx.lineTo(points[i].x, points[i].y);
  23794. }
  23795. ctx.closePath();
  23796. }
  23797. }]);
  23798. return EndPoint;
  23799. }();
  23800. /**
  23801. * Drawing methods for the arrow endpoint.
  23802. * @extends EndPoint
  23803. */
  23804. var Arrow = function (_EndPoint) {
  23805. (0, _inherits3['default'])(Arrow, _EndPoint);
  23806. function Arrow() {
  23807. (0, _classCallCheck3['default'])(this, Arrow);
  23808. return (0, _possibleConstructorReturn3['default'])(this, (Arrow.__proto__ || (0, _getPrototypeOf2['default'])(Arrow)).apply(this, arguments));
  23809. }
  23810. (0, _createClass3['default'])(Arrow, null, [{
  23811. key: 'draw',
  23812. /**
  23813. * Draw this shape at the end of a line.
  23814. *
  23815. * @param {CanvasRenderingContext2D} ctx
  23816. * @param {ArrowData} arrowData
  23817. * @static
  23818. */
  23819. value: function draw(ctx, arrowData) {
  23820. // Normalized points of closed path, in the order that they should be drawn.
  23821. // (0, 0) is the attachment point, and the point around which should be rotated
  23822. var points = [{ x: 0, y: 0 }, { x: -1, y: 0.3 }, { x: -0.9, y: 0 }, { x: -1, y: -0.3 }];
  23823. EndPoint.transform(points, arrowData);
  23824. EndPoint.drawPath(ctx, points);
  23825. }
  23826. }]);
  23827. return Arrow;
  23828. }(EndPoint);
  23829. /**
  23830. * Drawing methods for the circle endpoint.
  23831. */
  23832. var Circle = function () {
  23833. function Circle() {
  23834. (0, _classCallCheck3['default'])(this, Circle);
  23835. }
  23836. (0, _createClass3['default'])(Circle, null, [{
  23837. key: 'draw',
  23838. /**
  23839. * Draw this shape at the end of a line.
  23840. *
  23841. * @param {CanvasRenderingContext2D} ctx
  23842. * @param {ArrowData} arrowData
  23843. * @static
  23844. */
  23845. value: function draw(ctx, arrowData) {
  23846. var point = { x: -0.4, y: 0 };
  23847. EndPoint.transform(point, arrowData);
  23848. ctx.circle(point.x, point.y, arrowData.length * 0.4);
  23849. }
  23850. }]);
  23851. return Circle;
  23852. }();
  23853. /**
  23854. * Drawing methods for the bar endpoint.
  23855. */
  23856. var Bar = function () {
  23857. function Bar() {
  23858. (0, _classCallCheck3['default'])(this, Bar);
  23859. }
  23860. (0, _createClass3['default'])(Bar, null, [{
  23861. key: 'draw',
  23862. /**
  23863. * Draw this shape at the end of a line.
  23864. *
  23865. * @param {CanvasRenderingContext2D} ctx
  23866. * @param {ArrowData} arrowData
  23867. * @static
  23868. */
  23869. value: function draw(ctx, arrowData) {
  23870. /*
  23871. var points = [
  23872. {x:0, y:0.5},
  23873. {x:0, y:-0.5}
  23874. ];
  23875. EndPoint.transform(points, arrowData);
  23876. ctx.beginPath();
  23877. ctx.moveTo(points[0].x, points[0].y);
  23878. ctx.lineTo(points[1].x, points[1].y);
  23879. ctx.stroke();
  23880. */
  23881. var points = [{ x: 0, y: 0.5 }, { x: 0, y: -0.5 }, { x: -0.15, y: -0.5 }, { x: -0.15, y: 0.5 }];
  23882. EndPoint.transform(points, arrowData);
  23883. EndPoint.drawPath(ctx, points);
  23884. }
  23885. }]);
  23886. return Bar;
  23887. }();
  23888. /**
  23889. * Drawing methods for the endpoints.
  23890. */
  23891. var EndPoints = function () {
  23892. function EndPoints() {
  23893. (0, _classCallCheck3['default'])(this, EndPoints);
  23894. }
  23895. (0, _createClass3['default'])(EndPoints, null, [{
  23896. key: 'draw',
  23897. /**
  23898. * Draw an endpoint
  23899. *
  23900. * @param {CanvasRenderingContext2D} ctx
  23901. * @param {ArrowData} arrowData
  23902. * @static
  23903. */
  23904. value: function draw(ctx, arrowData) {
  23905. var type;
  23906. if (arrowData.type) {
  23907. type = arrowData.type.toLowerCase();
  23908. }
  23909. switch (type) {
  23910. case 'circle':
  23911. Circle.draw(ctx, arrowData);
  23912. break;
  23913. case 'bar':
  23914. Bar.draw(ctx, arrowData);
  23915. break;
  23916. case 'arrow': // fall-through
  23917. default:
  23918. Arrow.draw(ctx, arrowData);
  23919. }
  23920. }
  23921. }]);
  23922. return EndPoints;
  23923. }();
  23924. exports['default'] = EndPoints;
  23925. /***/ }),
  23926. /* 120 */
  23927. /***/ (function(module, exports, __webpack_require__) {
  23928. "use strict";
  23929. Object.defineProperty(exports, "__esModule", {
  23930. value: true
  23931. });
  23932. var _classCallCheck2 = __webpack_require__(0);
  23933. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  23934. var _createClass2 = __webpack_require__(1);
  23935. var _createClass3 = _interopRequireDefault(_createClass2);
  23936. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  23937. /**
  23938. * Barnes Hut Solver
  23939. */
  23940. var BarnesHutSolver = function () {
  23941. /**
  23942. * @param {Object} body
  23943. * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
  23944. * @param {Object} options
  23945. */
  23946. function BarnesHutSolver(body, physicsBody, options) {
  23947. (0, _classCallCheck3["default"])(this, BarnesHutSolver);
  23948. this.body = body;
  23949. this.physicsBody = physicsBody;
  23950. this.barnesHutTree;
  23951. this.setOptions(options);
  23952. this.randomSeed = 5;
  23953. // debug: show grid
  23954. // this.body.emitter.on("afterDrawing", (ctx) => {this._debug(ctx,'#ff0000')})
  23955. }
  23956. /**
  23957. *
  23958. * @param {Object} options
  23959. */
  23960. (0, _createClass3["default"])(BarnesHutSolver, [{
  23961. key: "setOptions",
  23962. value: function setOptions(options) {
  23963. this.options = options;
  23964. this.thetaInversed = 1 / this.options.theta;
  23965. // if 1 then min distance = 0.5, if 0.5 then min distance = 0.5 + 0.5*node.shape.radius
  23966. this.overlapAvoidanceFactor = 1 - Math.max(0, Math.min(1, this.options.avoidOverlap));
  23967. }
  23968. /**
  23969. *
  23970. * @returns {number} random integer
  23971. */
  23972. }, {
  23973. key: "seededRandom",
  23974. value: function seededRandom() {
  23975. var x = Math.sin(this.randomSeed++) * 10000;
  23976. return x - Math.floor(x);
  23977. }
  23978. /**
  23979. * This function calculates the forces the nodes apply on each other based on a gravitational model.
  23980. * The Barnes Hut method is used to speed up this N-body simulation.
  23981. *
  23982. * @private
  23983. */
  23984. }, {
  23985. key: "solve",
  23986. value: function solve() {
  23987. if (this.options.gravitationalConstant !== 0 && this.physicsBody.physicsNodeIndices.length > 0) {
  23988. var node = void 0;
  23989. var nodes = this.body.nodes;
  23990. var nodeIndices = this.physicsBody.physicsNodeIndices;
  23991. var nodeCount = nodeIndices.length;
  23992. // create the tree
  23993. var barnesHutTree = this._formBarnesHutTree(nodes, nodeIndices);
  23994. // for debugging
  23995. this.barnesHutTree = barnesHutTree;
  23996. // place the nodes one by one recursively
  23997. for (var i = 0; i < nodeCount; i++) {
  23998. node = nodes[nodeIndices[i]];
  23999. if (node.options.mass > 0) {
  24000. // starting with root is irrelevant, it never passes the BarnesHutSolver condition
  24001. this._getForceContributions(barnesHutTree.root, node);
  24002. }
  24003. }
  24004. }
  24005. }
  24006. /**
  24007. * @param {Object} parentBranch
  24008. * @param {Node} node
  24009. * @private
  24010. */
  24011. }, {
  24012. key: "_getForceContributions",
  24013. value: function _getForceContributions(parentBranch, node) {
  24014. this._getForceContribution(parentBranch.children.NW, node);
  24015. this._getForceContribution(parentBranch.children.NE, node);
  24016. this._getForceContribution(parentBranch.children.SW, node);
  24017. this._getForceContribution(parentBranch.children.SE, node);
  24018. }
  24019. /**
  24020. * This function traverses the barnesHutTree. It checks when it can approximate distant nodes with their center of mass.
  24021. * If a region contains a single node, we check if it is not itself, then we apply the force.
  24022. *
  24023. * @param {Object} parentBranch
  24024. * @param {Node} node
  24025. * @private
  24026. */
  24027. }, {
  24028. key: "_getForceContribution",
  24029. value: function _getForceContribution(parentBranch, node) {
  24030. // we get no force contribution from an empty region
  24031. if (parentBranch.childrenCount > 0) {
  24032. var dx = void 0,
  24033. dy = void 0,
  24034. distance = void 0;
  24035. // get the distance from the center of mass to the node.
  24036. dx = parentBranch.centerOfMass.x - node.x;
  24037. dy = parentBranch.centerOfMass.y - node.y;
  24038. distance = Math.sqrt(dx * dx + dy * dy);
  24039. // BarnesHutSolver condition
  24040. // original condition : s/d < theta = passed === d/s > 1/theta = passed
  24041. // calcSize = 1/s --> d * 1/s > 1/theta = passed
  24042. if (distance * parentBranch.calcSize > this.thetaInversed) {
  24043. this._calculateForces(distance, dx, dy, node, parentBranch);
  24044. } else {
  24045. // Did not pass the condition, go into children if available
  24046. if (parentBranch.childrenCount === 4) {
  24047. this._getForceContributions(parentBranch, node);
  24048. } else {
  24049. // parentBranch must have only one node, if it was empty we wouldnt be here
  24050. if (parentBranch.children.data.id != node.id) {
  24051. // if it is not self
  24052. this._calculateForces(distance, dx, dy, node, parentBranch);
  24053. }
  24054. }
  24055. }
  24056. }
  24057. }
  24058. /**
  24059. * Calculate the forces based on the distance.
  24060. *
  24061. * @param {number} distance
  24062. * @param {number} dx
  24063. * @param {number} dy
  24064. * @param {Node} node
  24065. * @param {Object} parentBranch
  24066. * @private
  24067. */
  24068. }, {
  24069. key: "_calculateForces",
  24070. value: function _calculateForces(distance, dx, dy, node, parentBranch) {
  24071. if (distance === 0) {
  24072. distance = 0.1;
  24073. dx = distance;
  24074. }
  24075. if (this.overlapAvoidanceFactor < 1 && node.shape.radius) {
  24076. distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius);
  24077. }
  24078. // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines
  24079. // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce
  24080. var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass / Math.pow(distance, 3);
  24081. var fx = dx * gravityForce;
  24082. var fy = dy * gravityForce;
  24083. this.physicsBody.forces[node.id].x += fx;
  24084. this.physicsBody.forces[node.id].y += fy;
  24085. }
  24086. /**
  24087. * This function constructs the barnesHut tree recursively. It creates the root, splits it and starts placing the nodes.
  24088. *
  24089. * @param {Array.<Node>} nodes
  24090. * @param {Array.<number>} nodeIndices
  24091. * @returns {{root: {centerOfMass: {x: number, y: number}, mass: number, range: {minX: number, maxX: number, minY: number, maxY: number}, size: number, calcSize: number, children: {data: null}, maxWidth: number, level: number, childrenCount: number}}} BarnesHutTree
  24092. * @private
  24093. */
  24094. }, {
  24095. key: "_formBarnesHutTree",
  24096. value: function _formBarnesHutTree(nodes, nodeIndices) {
  24097. var node = void 0;
  24098. var nodeCount = nodeIndices.length;
  24099. var minX = nodes[nodeIndices[0]].x;
  24100. var minY = nodes[nodeIndices[0]].y;
  24101. var maxX = nodes[nodeIndices[0]].x;
  24102. var maxY = nodes[nodeIndices[0]].y;
  24103. // get the range of the nodes
  24104. for (var i = 1; i < nodeCount; i++) {
  24105. var _node = nodes[nodeIndices[i]];
  24106. var x = _node.x;
  24107. var y = _node.y;
  24108. if (_node.options.mass > 0) {
  24109. if (x < minX) {
  24110. minX = x;
  24111. }
  24112. if (x > maxX) {
  24113. maxX = x;
  24114. }
  24115. if (y < minY) {
  24116. minY = y;
  24117. }
  24118. if (y > maxY) {
  24119. maxY = y;
  24120. }
  24121. }
  24122. }
  24123. // make the range a square
  24124. var sizeDiff = Math.abs(maxX - minX) - Math.abs(maxY - minY); // difference between X and Y
  24125. if (sizeDiff > 0) {
  24126. minY -= 0.5 * sizeDiff;
  24127. maxY += 0.5 * sizeDiff;
  24128. } // xSize > ySize
  24129. else {
  24130. minX += 0.5 * sizeDiff;
  24131. maxX -= 0.5 * sizeDiff;
  24132. } // xSize < ySize
  24133. var minimumTreeSize = 1e-5;
  24134. var rootSize = Math.max(minimumTreeSize, Math.abs(maxX - minX));
  24135. var halfRootSize = 0.5 * rootSize;
  24136. var centerX = 0.5 * (minX + maxX),
  24137. centerY = 0.5 * (minY + maxY);
  24138. // construct the barnesHutTree
  24139. var barnesHutTree = {
  24140. root: {
  24141. centerOfMass: { x: 0, y: 0 },
  24142. mass: 0,
  24143. range: {
  24144. minX: centerX - halfRootSize, maxX: centerX + halfRootSize,
  24145. minY: centerY - halfRootSize, maxY: centerY + halfRootSize
  24146. },
  24147. size: rootSize,
  24148. calcSize: 1 / rootSize,
  24149. children: { data: null },
  24150. maxWidth: 0,
  24151. level: 0,
  24152. childrenCount: 4
  24153. }
  24154. };
  24155. this._splitBranch(barnesHutTree.root);
  24156. // place the nodes one by one recursively
  24157. for (var _i = 0; _i < nodeCount; _i++) {
  24158. node = nodes[nodeIndices[_i]];
  24159. if (node.options.mass > 0) {
  24160. this._placeInTree(barnesHutTree.root, node);
  24161. }
  24162. }
  24163. // make global
  24164. return barnesHutTree;
  24165. }
  24166. /**
  24167. * this updates the mass of a branch. this is increased by adding a node.
  24168. *
  24169. * @param {Object} parentBranch
  24170. * @param {Node} node
  24171. * @private
  24172. */
  24173. }, {
  24174. key: "_updateBranchMass",
  24175. value: function _updateBranchMass(parentBranch, node) {
  24176. var centerOfMass = parentBranch.centerOfMass;
  24177. var totalMass = parentBranch.mass + node.options.mass;
  24178. var totalMassInv = 1 / totalMass;
  24179. centerOfMass.x = centerOfMass.x * parentBranch.mass + node.x * node.options.mass;
  24180. centerOfMass.x *= totalMassInv;
  24181. centerOfMass.y = centerOfMass.y * parentBranch.mass + node.y * node.options.mass;
  24182. centerOfMass.y *= totalMassInv;
  24183. parentBranch.mass = totalMass;
  24184. var biggestSize = Math.max(Math.max(node.height, node.radius), node.width);
  24185. parentBranch.maxWidth = parentBranch.maxWidth < biggestSize ? biggestSize : parentBranch.maxWidth;
  24186. }
  24187. /**
  24188. * determine in which branch the node will be placed.
  24189. *
  24190. * @param {Object} parentBranch
  24191. * @param {Node} node
  24192. * @param {boolean} skipMassUpdate
  24193. * @private
  24194. */
  24195. }, {
  24196. key: "_placeInTree",
  24197. value: function _placeInTree(parentBranch, node, skipMassUpdate) {
  24198. if (skipMassUpdate != true || skipMassUpdate === undefined) {
  24199. // update the mass of the branch.
  24200. this._updateBranchMass(parentBranch, node);
  24201. }
  24202. var range = parentBranch.children.NW.range;
  24203. var region = void 0;
  24204. if (range.maxX > node.x) {
  24205. // in NW or SW
  24206. if (range.maxY > node.y) {
  24207. region = "NW";
  24208. } else {
  24209. region = "SW";
  24210. }
  24211. } else {
  24212. // in NE or SE
  24213. if (range.maxY > node.y) {
  24214. region = "NE";
  24215. } else {
  24216. region = "SE";
  24217. }
  24218. }
  24219. this._placeInRegion(parentBranch, node, region);
  24220. }
  24221. /**
  24222. * actually place the node in a region (or branch)
  24223. *
  24224. * @param {Object} parentBranch
  24225. * @param {Node} node
  24226. * @param {'NW'| 'NE' | 'SW' | 'SE'} region
  24227. * @private
  24228. */
  24229. }, {
  24230. key: "_placeInRegion",
  24231. value: function _placeInRegion(parentBranch, node, region) {
  24232. var children = parentBranch.children[region];
  24233. switch (children.childrenCount) {
  24234. case 0:
  24235. // place node here
  24236. children.children.data = node;
  24237. children.childrenCount = 1;
  24238. this._updateBranchMass(children, node);
  24239. break;
  24240. case 1:
  24241. // convert into children
  24242. // if there are two nodes exactly overlapping (on init, on opening of cluster etc.)
  24243. // we move one node a little bit and we do not put it in the tree.
  24244. if (children.children.data.x === node.x && children.children.data.y === node.y) {
  24245. node.x += this.seededRandom();
  24246. node.y += this.seededRandom();
  24247. } else {
  24248. this._splitBranch(children);
  24249. this._placeInTree(children, node);
  24250. }
  24251. break;
  24252. case 4:
  24253. // place in branch
  24254. this._placeInTree(children, node);
  24255. break;
  24256. }
  24257. }
  24258. /**
  24259. * this function splits a branch into 4 sub branches. If the branch contained a node, we place it in the subbranch
  24260. * after the split is complete.
  24261. *
  24262. * @param {Object} parentBranch
  24263. * @private
  24264. */
  24265. }, {
  24266. key: "_splitBranch",
  24267. value: function _splitBranch(parentBranch) {
  24268. // if the branch is shaded with a node, replace the node in the new subset.
  24269. var containedNode = null;
  24270. if (parentBranch.childrenCount === 1) {
  24271. containedNode = parentBranch.children.data;
  24272. parentBranch.mass = 0;
  24273. parentBranch.centerOfMass.x = 0;
  24274. parentBranch.centerOfMass.y = 0;
  24275. }
  24276. parentBranch.childrenCount = 4;
  24277. parentBranch.children.data = null;
  24278. this._insertRegion(parentBranch, "NW");
  24279. this._insertRegion(parentBranch, "NE");
  24280. this._insertRegion(parentBranch, "SW");
  24281. this._insertRegion(parentBranch, "SE");
  24282. if (containedNode != null) {
  24283. this._placeInTree(parentBranch, containedNode);
  24284. }
  24285. }
  24286. /**
  24287. * This function subdivides the region into four new segments.
  24288. * Specifically, this inserts a single new segment.
  24289. * It fills the children section of the parentBranch
  24290. *
  24291. * @param {Object} parentBranch
  24292. * @param {'NW'| 'NE' | 'SW' | 'SE'} region
  24293. * @private
  24294. */
  24295. }, {
  24296. key: "_insertRegion",
  24297. value: function _insertRegion(parentBranch, region) {
  24298. var minX = void 0,
  24299. maxX = void 0,
  24300. minY = void 0,
  24301. maxY = void 0;
  24302. var childSize = 0.5 * parentBranch.size;
  24303. switch (region) {
  24304. case "NW":
  24305. minX = parentBranch.range.minX;
  24306. maxX = parentBranch.range.minX + childSize;
  24307. minY = parentBranch.range.minY;
  24308. maxY = parentBranch.range.minY + childSize;
  24309. break;
  24310. case "NE":
  24311. minX = parentBranch.range.minX + childSize;
  24312. maxX = parentBranch.range.maxX;
  24313. minY = parentBranch.range.minY;
  24314. maxY = parentBranch.range.minY + childSize;
  24315. break;
  24316. case "SW":
  24317. minX = parentBranch.range.minX;
  24318. maxX = parentBranch.range.minX + childSize;
  24319. minY = parentBranch.range.minY + childSize;
  24320. maxY = parentBranch.range.maxY;
  24321. break;
  24322. case "SE":
  24323. minX = parentBranch.range.minX + childSize;
  24324. maxX = parentBranch.range.maxX;
  24325. minY = parentBranch.range.minY + childSize;
  24326. maxY = parentBranch.range.maxY;
  24327. break;
  24328. }
  24329. parentBranch.children[region] = {
  24330. centerOfMass: { x: 0, y: 0 },
  24331. mass: 0,
  24332. range: { minX: minX, maxX: maxX, minY: minY, maxY: maxY },
  24333. size: 0.5 * parentBranch.size,
  24334. calcSize: 2 * parentBranch.calcSize,
  24335. children: { data: null },
  24336. maxWidth: 0,
  24337. level: parentBranch.level + 1,
  24338. childrenCount: 0
  24339. };
  24340. }
  24341. //--------------------------- DEBUGGING BELOW ---------------------------//
  24342. /**
  24343. * This function is for debugging purposed, it draws the tree.
  24344. *
  24345. * @param {CanvasRenderingContext2D} ctx
  24346. * @param {string} color
  24347. * @private
  24348. */
  24349. }, {
  24350. key: "_debug",
  24351. value: function _debug(ctx, color) {
  24352. if (this.barnesHutTree !== undefined) {
  24353. ctx.lineWidth = 1;
  24354. this._drawBranch(this.barnesHutTree.root, ctx, color);
  24355. }
  24356. }
  24357. /**
  24358. * This function is for debugging purposes. It draws the branches recursively.
  24359. *
  24360. * @param {Object} branch
  24361. * @param {CanvasRenderingContext2D} ctx
  24362. * @param {string} color
  24363. * @private
  24364. */
  24365. }, {
  24366. key: "_drawBranch",
  24367. value: function _drawBranch(branch, ctx, color) {
  24368. if (color === undefined) {
  24369. color = "#FF0000";
  24370. }
  24371. if (branch.childrenCount === 4) {
  24372. this._drawBranch(branch.children.NW, ctx);
  24373. this._drawBranch(branch.children.NE, ctx);
  24374. this._drawBranch(branch.children.SE, ctx);
  24375. this._drawBranch(branch.children.SW, ctx);
  24376. }
  24377. ctx.strokeStyle = color;
  24378. ctx.beginPath();
  24379. ctx.moveTo(branch.range.minX, branch.range.minY);
  24380. ctx.lineTo(branch.range.maxX, branch.range.minY);
  24381. ctx.stroke();
  24382. ctx.beginPath();
  24383. ctx.moveTo(branch.range.maxX, branch.range.minY);
  24384. ctx.lineTo(branch.range.maxX, branch.range.maxY);
  24385. ctx.stroke();
  24386. ctx.beginPath();
  24387. ctx.moveTo(branch.range.maxX, branch.range.maxY);
  24388. ctx.lineTo(branch.range.minX, branch.range.maxY);
  24389. ctx.stroke();
  24390. ctx.beginPath();
  24391. ctx.moveTo(branch.range.minX, branch.range.maxY);
  24392. ctx.lineTo(branch.range.minX, branch.range.minY);
  24393. ctx.stroke();
  24394. /*
  24395. if (branch.mass > 0) {
  24396. ctx.circle(branch.centerOfMass.x, branch.centerOfMass.y, 3*branch.mass);
  24397. ctx.stroke();
  24398. }
  24399. */
  24400. }
  24401. }]);
  24402. return BarnesHutSolver;
  24403. }();
  24404. exports["default"] = BarnesHutSolver;
  24405. /***/ }),
  24406. /* 121 */
  24407. /***/ (function(module, exports, __webpack_require__) {
  24408. "use strict";
  24409. Object.defineProperty(exports, "__esModule", {
  24410. value: true
  24411. });
  24412. var _classCallCheck2 = __webpack_require__(0);
  24413. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  24414. var _createClass2 = __webpack_require__(1);
  24415. var _createClass3 = _interopRequireDefault(_createClass2);
  24416. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  24417. /**
  24418. * Central Gravity Solver
  24419. */
  24420. var CentralGravitySolver = function () {
  24421. /**
  24422. * @param {Object} body
  24423. * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
  24424. * @param {Object} options
  24425. */
  24426. function CentralGravitySolver(body, physicsBody, options) {
  24427. (0, _classCallCheck3["default"])(this, CentralGravitySolver);
  24428. this.body = body;
  24429. this.physicsBody = physicsBody;
  24430. this.setOptions(options);
  24431. }
  24432. /**
  24433. *
  24434. * @param {Object} options
  24435. */
  24436. (0, _createClass3["default"])(CentralGravitySolver, [{
  24437. key: "setOptions",
  24438. value: function setOptions(options) {
  24439. this.options = options;
  24440. }
  24441. /**
  24442. * Calculates forces for each node
  24443. */
  24444. }, {
  24445. key: "solve",
  24446. value: function solve() {
  24447. var dx = void 0,
  24448. dy = void 0,
  24449. distance = void 0,
  24450. node = void 0;
  24451. var nodes = this.body.nodes;
  24452. var nodeIndices = this.physicsBody.physicsNodeIndices;
  24453. var forces = this.physicsBody.forces;
  24454. for (var i = 0; i < nodeIndices.length; i++) {
  24455. var nodeId = nodeIndices[i];
  24456. node = nodes[nodeId];
  24457. dx = -node.x;
  24458. dy = -node.y;
  24459. distance = Math.sqrt(dx * dx + dy * dy);
  24460. this._calculateForces(distance, dx, dy, forces, node);
  24461. }
  24462. }
  24463. /**
  24464. * Calculate the forces based on the distance.
  24465. * @param {number} distance
  24466. * @param {number} dx
  24467. * @param {number} dy
  24468. * @param {Object<Node.id, vis.Node>} forces
  24469. * @param {Node} node
  24470. * @private
  24471. */
  24472. }, {
  24473. key: "_calculateForces",
  24474. value: function _calculateForces(distance, dx, dy, forces, node) {
  24475. var gravityForce = distance === 0 ? 0 : this.options.centralGravity / distance;
  24476. forces[node.id].x = dx * gravityForce;
  24477. forces[node.id].y = dy * gravityForce;
  24478. }
  24479. }]);
  24480. return CentralGravitySolver;
  24481. }();
  24482. exports["default"] = CentralGravitySolver;
  24483. /***/ }),
  24484. /* 122 */
  24485. /***/ (function(module, exports, __webpack_require__) {
  24486. "use strict";
  24487. Object.defineProperty(exports, "__esModule", {
  24488. value: true
  24489. });
  24490. /**
  24491. * This object contains all possible options. It will check if the types are correct, if required if the option is one
  24492. * of the allowed values.
  24493. *
  24494. * __any__ means that the name of the property does not matter.
  24495. * __type__ is a required field for all objects and contains the allowed types of all objects
  24496. */
  24497. var string = 'string';
  24498. var bool = 'boolean';
  24499. var number = 'number';
  24500. var array = 'array';
  24501. var object = 'object'; // should only be in a __type__ property
  24502. var dom = 'dom';
  24503. var any = 'any';
  24504. // List of endpoints
  24505. var endPoints = ['arrow', 'circle', 'bar'];
  24506. var allOptions = {
  24507. configure: {
  24508. enabled: { boolean: bool },
  24509. filter: { boolean: bool, string: string, array: array, 'function': 'function' },
  24510. container: { dom: dom },
  24511. showButton: { boolean: bool },
  24512. __type__: { object: object, boolean: bool, string: string, array: array, 'function': 'function' }
  24513. },
  24514. edges: {
  24515. arrows: {
  24516. to: { enabled: { boolean: bool }, scaleFactor: { number: number }, type: { string: endPoints }, __type__: { object: object, boolean: bool } },
  24517. middle: { enabled: { boolean: bool }, scaleFactor: { number: number }, type: { string: endPoints }, __type__: { object: object, boolean: bool } },
  24518. from: { enabled: { boolean: bool }, scaleFactor: { number: number }, type: { string: endPoints }, __type__: { object: object, boolean: bool } },
  24519. __type__: { string: ['from', 'to', 'middle'], object: object }
  24520. },
  24521. arrowStrikethrough: { boolean: bool },
  24522. chosen: {
  24523. label: { boolean: bool, 'function': 'function' },
  24524. edge: { boolean: bool, 'function': 'function' },
  24525. __type__: { object: object, boolean: bool }
  24526. },
  24527. color: {
  24528. color: { string: string },
  24529. highlight: { string: string },
  24530. hover: { string: string },
  24531. inherit: { string: ['from', 'to', 'both'], boolean: bool },
  24532. opacity: { number: number },
  24533. __type__: { object: object, string: string }
  24534. },
  24535. dashes: { boolean: bool, array: array },
  24536. font: {
  24537. color: { string: string },
  24538. size: { number: number }, // px
  24539. face: { string: string },
  24540. background: { string: string },
  24541. strokeWidth: { number: number }, // px
  24542. strokeColor: { string: string },
  24543. align: { string: ['horizontal', 'top', 'middle', 'bottom'] },
  24544. vadjust: { number: number },
  24545. multi: { boolean: bool, string: string },
  24546. bold: {
  24547. color: { string: string },
  24548. size: { number: number }, // px
  24549. face: { string: string },
  24550. mod: { string: string },
  24551. vadjust: { number: number },
  24552. __type__: { object: object, string: string }
  24553. },
  24554. boldital: {
  24555. color: { string: string },
  24556. size: { number: number }, // px
  24557. face: { string: string },
  24558. mod: { string: string },
  24559. vadjust: { number: number },
  24560. __type__: { object: object, string: string }
  24561. },
  24562. ital: {
  24563. color: { string: string },
  24564. size: { number: number }, // px
  24565. face: { string: string },
  24566. mod: { string: string },
  24567. vadjust: { number: number },
  24568. __type__: { object: object, string: string }
  24569. },
  24570. mono: {
  24571. color: { string: string },
  24572. size: { number: number }, // px
  24573. face: { string: string },
  24574. mod: { string: string },
  24575. vadjust: { number: number },
  24576. __type__: { object: object, string: string }
  24577. },
  24578. __type__: { object: object, string: string }
  24579. },
  24580. hidden: { boolean: bool },
  24581. hoverWidth: { 'function': 'function', number: number },
  24582. label: { string: string, 'undefined': 'undefined' },
  24583. labelHighlightBold: { boolean: bool },
  24584. length: { number: number, 'undefined': 'undefined' },
  24585. physics: { boolean: bool },
  24586. scaling: {
  24587. min: { number: number },
  24588. max: { number: number },
  24589. label: {
  24590. enabled: { boolean: bool },
  24591. min: { number: number },
  24592. max: { number: number },
  24593. maxVisible: { number: number },
  24594. drawThreshold: { number: number },
  24595. __type__: { object: object, boolean: bool }
  24596. },
  24597. customScalingFunction: { 'function': 'function' },
  24598. __type__: { object: object }
  24599. },
  24600. selectionWidth: { 'function': 'function', number: number },
  24601. selfReferenceSize: { number: number },
  24602. shadow: {
  24603. enabled: { boolean: bool },
  24604. color: { string: string },
  24605. size: { number: number },
  24606. x: { number: number },
  24607. y: { number: number },
  24608. __type__: { object: object, boolean: bool }
  24609. },
  24610. smooth: {
  24611. enabled: { boolean: bool },
  24612. type: { string: ['dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW', 'cubicBezier'] },
  24613. roundness: { number: number },
  24614. forceDirection: { string: ['horizontal', 'vertical', 'none'], boolean: bool },
  24615. __type__: { object: object, boolean: bool }
  24616. },
  24617. title: { string: string, 'undefined': 'undefined' },
  24618. width: { number: number },
  24619. widthConstraint: {
  24620. maximum: { number: number },
  24621. __type__: { object: object, boolean: bool, number: number }
  24622. },
  24623. value: { number: number, 'undefined': 'undefined' },
  24624. __type__: { object: object }
  24625. },
  24626. groups: {
  24627. useDefaultGroups: { boolean: bool },
  24628. __any__: 'get from nodes, will be overwritten below',
  24629. __type__: { object: object }
  24630. },
  24631. interaction: {
  24632. dragNodes: { boolean: bool },
  24633. dragView: { boolean: bool },
  24634. hideEdgesOnDrag: { boolean: bool },
  24635. hideNodesOnDrag: { boolean: bool },
  24636. hover: { boolean: bool },
  24637. keyboard: {
  24638. enabled: { boolean: bool },
  24639. speed: { x: { number: number }, y: { number: number }, zoom: { number: number }, __type__: { object: object } },
  24640. bindToWindow: { boolean: bool },
  24641. __type__: { object: object, boolean: bool }
  24642. },
  24643. multiselect: { boolean: bool },
  24644. navigationButtons: { boolean: bool },
  24645. selectable: { boolean: bool },
  24646. selectConnectedEdges: { boolean: bool },
  24647. hoverConnectedEdges: { boolean: bool },
  24648. tooltipDelay: { number: number },
  24649. zoomView: { boolean: bool },
  24650. __type__: { object: object }
  24651. },
  24652. layout: {
  24653. randomSeed: { 'undefined': 'undefined', number: number },
  24654. improvedLayout: { boolean: bool },
  24655. hierarchical: {
  24656. enabled: { boolean: bool },
  24657. levelSeparation: { number: number },
  24658. nodeSpacing: { number: number },
  24659. treeSpacing: { number: number },
  24660. blockShifting: { boolean: bool },
  24661. edgeMinimization: { boolean: bool },
  24662. parentCentralization: { boolean: bool },
  24663. direction: { string: ['UD', 'DU', 'LR', 'RL'] }, // UD, DU, LR, RL
  24664. sortMethod: { string: ['hubsize', 'directed'] }, // hubsize, directed
  24665. __type__: { object: object, boolean: bool }
  24666. },
  24667. __type__: { object: object }
  24668. },
  24669. manipulation: {
  24670. enabled: { boolean: bool },
  24671. initiallyActive: { boolean: bool },
  24672. addNode: { boolean: bool, 'function': 'function' },
  24673. addEdge: { boolean: bool, 'function': 'function' },
  24674. editNode: { 'function': 'function' },
  24675. editEdge: {
  24676. editWithoutDrag: { 'function': 'function' },
  24677. __type__: { object: object, boolean: bool, 'function': 'function' }
  24678. },
  24679. deleteNode: { boolean: bool, 'function': 'function' },
  24680. deleteEdge: { boolean: bool, 'function': 'function' },
  24681. controlNodeStyle: 'get from nodes, will be overwritten below',
  24682. __type__: { object: object, boolean: bool }
  24683. },
  24684. nodes: {
  24685. borderWidth: { number: number },
  24686. borderWidthSelected: { number: number, 'undefined': 'undefined' },
  24687. brokenImage: { string: string, 'undefined': 'undefined' },
  24688. chosen: {
  24689. label: { boolean: bool, 'function': 'function' },
  24690. node: { boolean: bool, 'function': 'function' },
  24691. __type__: { object: object, boolean: bool }
  24692. },
  24693. color: {
  24694. border: { string: string },
  24695. background: { string: string },
  24696. highlight: {
  24697. border: { string: string },
  24698. background: { string: string },
  24699. __type__: { object: object, string: string }
  24700. },
  24701. hover: {
  24702. border: { string: string },
  24703. background: { string: string },
  24704. __type__: { object: object, string: string }
  24705. },
  24706. __type__: { object: object, string: string }
  24707. },
  24708. fixed: {
  24709. x: { boolean: bool },
  24710. y: { boolean: bool },
  24711. __type__: { object: object, boolean: bool }
  24712. },
  24713. font: {
  24714. align: { string: string },
  24715. color: { string: string },
  24716. size: { number: number }, // px
  24717. face: { string: string },
  24718. background: { string: string },
  24719. strokeWidth: { number: number }, // px
  24720. strokeColor: { string: string },
  24721. vadjust: { number: number },
  24722. multi: { boolean: bool, string: string },
  24723. bold: {
  24724. color: { string: string },
  24725. size: { number: number }, // px
  24726. face: { string: string },
  24727. mod: { string: string },
  24728. vadjust: { number: number },
  24729. __type__: { object: object, string: string }
  24730. },
  24731. boldital: {
  24732. color: { string: string },
  24733. size: { number: number }, // px
  24734. face: { string: string },
  24735. mod: { string: string },
  24736. vadjust: { number: number },
  24737. __type__: { object: object, string: string }
  24738. },
  24739. ital: {
  24740. color: { string: string },
  24741. size: { number: number }, // px
  24742. face: { string: string },
  24743. mod: { string: string },
  24744. vadjust: { number: number },
  24745. __type__: { object: object, string: string }
  24746. },
  24747. mono: {
  24748. color: { string: string },
  24749. size: { number: number }, // px
  24750. face: { string: string },
  24751. mod: { string: string },
  24752. vadjust: { number: number },
  24753. __type__: { object: object, string: string }
  24754. },
  24755. __type__: { object: object, string: string }
  24756. },
  24757. group: { string: string, number: number, 'undefined': 'undefined' },
  24758. heightConstraint: {
  24759. minimum: { number: number },
  24760. valign: { string: string },
  24761. __type__: { object: object, boolean: bool, number: number }
  24762. },
  24763. hidden: { boolean: bool },
  24764. icon: {
  24765. face: { string: string },
  24766. code: { string: string }, //'\uf007',
  24767. size: { number: number }, //50,
  24768. color: { string: string },
  24769. __type__: { object: object }
  24770. },
  24771. id: { string: string, number: number },
  24772. image: {
  24773. selected: { string: string, 'undefined': 'undefined' }, // --> URL
  24774. unselected: { string: string, 'undefined': 'undefined' }, // --> URL
  24775. __type__: { object: object, string: string }
  24776. },
  24777. label: { string: string, 'undefined': 'undefined' },
  24778. labelHighlightBold: { boolean: bool },
  24779. level: { number: number, 'undefined': 'undefined' },
  24780. margin: {
  24781. top: { number: number },
  24782. right: { number: number },
  24783. bottom: { number: number },
  24784. left: { number: number },
  24785. __type__: { object: object, number: number }
  24786. },
  24787. mass: { number: number },
  24788. physics: { boolean: bool },
  24789. scaling: {
  24790. min: { number: number },
  24791. max: { number: number },
  24792. label: {
  24793. enabled: { boolean: bool },
  24794. min: { number: number },
  24795. max: { number: number },
  24796. maxVisible: { number: number },
  24797. drawThreshold: { number: number },
  24798. __type__: { object: object, boolean: bool }
  24799. },
  24800. customScalingFunction: { 'function': 'function' },
  24801. __type__: { object: object }
  24802. },
  24803. shadow: {
  24804. enabled: { boolean: bool },
  24805. color: { string: string },
  24806. size: { number: number },
  24807. x: { number: number },
  24808. y: { number: number },
  24809. __type__: { object: object, boolean: bool }
  24810. },
  24811. shape: { string: ['ellipse', 'circle', 'database', 'box', 'text', 'image', 'circularImage', 'diamond', 'dot', 'star', 'triangle', 'triangleDown', 'square', 'icon', 'hexagon'] },
  24812. shapeProperties: {
  24813. borderDashes: { boolean: bool, array: array },
  24814. borderRadius: { number: number },
  24815. interpolation: { boolean: bool },
  24816. useImageSize: { boolean: bool },
  24817. useBorderWithImage: { boolean: bool },
  24818. __type__: { object: object }
  24819. },
  24820. size: { number: number },
  24821. title: { string: string, dom: dom, 'undefined': 'undefined' },
  24822. value: { number: number, 'undefined': 'undefined' },
  24823. widthConstraint: {
  24824. minimum: { number: number },
  24825. maximum: { number: number },
  24826. __type__: { object: object, boolean: bool, number: number }
  24827. },
  24828. x: { number: number },
  24829. y: { number: number },
  24830. __type__: { object: object }
  24831. },
  24832. physics: {
  24833. enabled: { boolean: bool },
  24834. barnesHut: {
  24835. gravitationalConstant: { number: number },
  24836. centralGravity: { number: number },
  24837. springLength: { number: number },
  24838. springConstant: { number: number },
  24839. damping: { number: number },
  24840. avoidOverlap: { number: number },
  24841. __type__: { object: object }
  24842. },
  24843. forceAtlas2Based: {
  24844. gravitationalConstant: { number: number },
  24845. centralGravity: { number: number },
  24846. springLength: { number: number },
  24847. springConstant: { number: number },
  24848. damping: { number: number },
  24849. avoidOverlap: { number: number },
  24850. __type__: { object: object }
  24851. },
  24852. repulsion: {
  24853. centralGravity: { number: number },
  24854. springLength: { number: number },
  24855. springConstant: { number: number },
  24856. nodeDistance: { number: number },
  24857. damping: { number: number },
  24858. __type__: { object: object }
  24859. },
  24860. hierarchicalRepulsion: {
  24861. centralGravity: { number: number },
  24862. springLength: { number: number },
  24863. springConstant: { number: number },
  24864. nodeDistance: { number: number },
  24865. damping: { number: number },
  24866. __type__: { object: object }
  24867. },
  24868. maxVelocity: { number: number },
  24869. minVelocity: { number: number }, // px/s
  24870. solver: { string: ['barnesHut', 'repulsion', 'hierarchicalRepulsion', 'forceAtlas2Based'] },
  24871. stabilization: {
  24872. enabled: { boolean: bool },
  24873. iterations: { number: number }, // maximum number of iteration to stabilize
  24874. updateInterval: { number: number },
  24875. onlyDynamicEdges: { boolean: bool },
  24876. fit: { boolean: bool },
  24877. __type__: { object: object, boolean: bool }
  24878. },
  24879. timestep: { number: number },
  24880. adaptiveTimestep: { boolean: bool },
  24881. __type__: { object: object, boolean: bool }
  24882. },
  24883. //globals :
  24884. autoResize: { boolean: bool },
  24885. clickToUse: { boolean: bool },
  24886. locale: { string: string },
  24887. locales: {
  24888. __any__: { any: any },
  24889. __type__: { object: object }
  24890. },
  24891. height: { string: string },
  24892. width: { string: string },
  24893. __type__: { object: object }
  24894. };
  24895. allOptions.groups.__any__ = allOptions.nodes;
  24896. allOptions.manipulation.controlNodeStyle = allOptions.nodes;
  24897. var configureOptions = {
  24898. nodes: {
  24899. borderWidth: [1, 0, 10, 1],
  24900. borderWidthSelected: [2, 0, 10, 1],
  24901. color: {
  24902. border: ['color', '#2B7CE9'],
  24903. background: ['color', '#97C2FC'],
  24904. highlight: {
  24905. border: ['color', '#2B7CE9'],
  24906. background: ['color', '#D2E5FF']
  24907. },
  24908. hover: {
  24909. border: ['color', '#2B7CE9'],
  24910. background: ['color', '#D2E5FF']
  24911. }
  24912. },
  24913. fixed: {
  24914. x: false,
  24915. y: false
  24916. },
  24917. font: {
  24918. color: ['color', '#343434'],
  24919. size: [14, 0, 100, 1], // px
  24920. face: ['arial', 'verdana', 'tahoma'],
  24921. background: ['color', 'none'],
  24922. strokeWidth: [0, 0, 50, 1], // px
  24923. strokeColor: ['color', '#ffffff']
  24924. },
  24925. //group: 'string',
  24926. hidden: false,
  24927. labelHighlightBold: true,
  24928. //icon: {
  24929. // face: 'string', //'FontAwesome',
  24930. // code: 'string', //'\uf007',
  24931. // size: [50, 0, 200, 1], //50,
  24932. // color: ['color','#2B7CE9'] //'#aa00ff'
  24933. //},
  24934. //image: 'string', // --> URL
  24935. physics: true,
  24936. scaling: {
  24937. min: [10, 0, 200, 1],
  24938. max: [30, 0, 200, 1],
  24939. label: {
  24940. enabled: false,
  24941. min: [14, 0, 200, 1],
  24942. max: [30, 0, 200, 1],
  24943. maxVisible: [30, 0, 200, 1],
  24944. drawThreshold: [5, 0, 20, 1]
  24945. }
  24946. },
  24947. shadow: {
  24948. enabled: false,
  24949. color: 'rgba(0,0,0,0.5)',
  24950. size: [10, 0, 20, 1],
  24951. x: [5, -30, 30, 1],
  24952. y: [5, -30, 30, 1]
  24953. },
  24954. shape: ['ellipse', 'box', 'circle', 'database', 'diamond', 'dot', 'square', 'star', 'text', 'triangle', 'triangleDown', 'hexagon'],
  24955. shapeProperties: {
  24956. borderDashes: false,
  24957. borderRadius: [6, 0, 20, 1],
  24958. interpolation: true,
  24959. useImageSize: false
  24960. },
  24961. size: [25, 0, 200, 1]
  24962. },
  24963. edges: {
  24964. arrows: {
  24965. to: { enabled: false, scaleFactor: [1, 0, 3, 0.05], type: 'arrow' },
  24966. middle: { enabled: false, scaleFactor: [1, 0, 3, 0.05], type: 'arrow' },
  24967. from: { enabled: false, scaleFactor: [1, 0, 3, 0.05], type: 'arrow' }
  24968. },
  24969. arrowStrikethrough: true,
  24970. color: {
  24971. color: ['color', '#848484'],
  24972. highlight: ['color', '#848484'],
  24973. hover: ['color', '#848484'],
  24974. inherit: ['from', 'to', 'both', true, false],
  24975. opacity: [1, 0, 1, 0.05]
  24976. },
  24977. dashes: false,
  24978. font: {
  24979. color: ['color', '#343434'],
  24980. size: [14, 0, 100, 1], // px
  24981. face: ['arial', 'verdana', 'tahoma'],
  24982. background: ['color', 'none'],
  24983. strokeWidth: [2, 0, 50, 1], // px
  24984. strokeColor: ['color', '#ffffff'],
  24985. align: ['horizontal', 'top', 'middle', 'bottom']
  24986. },
  24987. hidden: false,
  24988. hoverWidth: [1.5, 0, 5, 0.1],
  24989. labelHighlightBold: true,
  24990. physics: true,
  24991. scaling: {
  24992. min: [1, 0, 100, 1],
  24993. max: [15, 0, 100, 1],
  24994. label: {
  24995. enabled: true,
  24996. min: [14, 0, 200, 1],
  24997. max: [30, 0, 200, 1],
  24998. maxVisible: [30, 0, 200, 1],
  24999. drawThreshold: [5, 0, 20, 1]
  25000. }
  25001. },
  25002. selectionWidth: [1.5, 0, 5, 0.1],
  25003. selfReferenceSize: [20, 0, 200, 1],
  25004. shadow: {
  25005. enabled: false,
  25006. color: 'rgba(0,0,0,0.5)',
  25007. size: [10, 0, 20, 1],
  25008. x: [5, -30, 30, 1],
  25009. y: [5, -30, 30, 1]
  25010. },
  25011. smooth: {
  25012. enabled: true,
  25013. type: ['dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW', 'cubicBezier'],
  25014. forceDirection: ['horizontal', 'vertical', 'none'],
  25015. roundness: [0.5, 0, 1, 0.05]
  25016. },
  25017. width: [1, 0, 30, 1]
  25018. },
  25019. layout: {
  25020. //randomSeed: [0, 0, 500, 1],
  25021. //improvedLayout: true,
  25022. hierarchical: {
  25023. enabled: false,
  25024. levelSeparation: [150, 20, 500, 5],
  25025. nodeSpacing: [100, 20, 500, 5],
  25026. treeSpacing: [200, 20, 500, 5],
  25027. blockShifting: true,
  25028. edgeMinimization: true,
  25029. parentCentralization: true,
  25030. direction: ['UD', 'DU', 'LR', 'RL'], // UD, DU, LR, RL
  25031. sortMethod: ['hubsize', 'directed'] // hubsize, directed
  25032. }
  25033. },
  25034. interaction: {
  25035. dragNodes: true,
  25036. dragView: true,
  25037. hideEdgesOnDrag: false,
  25038. hideNodesOnDrag: false,
  25039. hover: false,
  25040. keyboard: {
  25041. enabled: false,
  25042. speed: { x: [10, 0, 40, 1], y: [10, 0, 40, 1], zoom: [0.02, 0, 0.1, 0.005] },
  25043. bindToWindow: true
  25044. },
  25045. multiselect: false,
  25046. navigationButtons: false,
  25047. selectable: true,
  25048. selectConnectedEdges: true,
  25049. hoverConnectedEdges: true,
  25050. tooltipDelay: [300, 0, 1000, 25],
  25051. zoomView: true
  25052. },
  25053. manipulation: {
  25054. enabled: false,
  25055. initiallyActive: false
  25056. },
  25057. physics: {
  25058. enabled: true,
  25059. barnesHut: {
  25060. //theta: [0.5, 0.1, 1, 0.05],
  25061. gravitationalConstant: [-2000, -30000, 0, 50],
  25062. centralGravity: [0.3, 0, 10, 0.05],
  25063. springLength: [95, 0, 500, 5],
  25064. springConstant: [0.04, 0, 1.2, 0.005],
  25065. damping: [0.09, 0, 1, 0.01],
  25066. avoidOverlap: [0, 0, 1, 0.01]
  25067. },
  25068. forceAtlas2Based: {
  25069. //theta: [0.5, 0.1, 1, 0.05],
  25070. gravitationalConstant: [-50, -500, 0, 1],
  25071. centralGravity: [0.01, 0, 1, 0.005],
  25072. springLength: [95, 0, 500, 5],
  25073. springConstant: [0.08, 0, 1.2, 0.005],
  25074. damping: [0.4, 0, 1, 0.01],
  25075. avoidOverlap: [0, 0, 1, 0.01]
  25076. },
  25077. repulsion: {
  25078. centralGravity: [0.2, 0, 10, 0.05],
  25079. springLength: [200, 0, 500, 5],
  25080. springConstant: [0.05, 0, 1.2, 0.005],
  25081. nodeDistance: [100, 0, 500, 5],
  25082. damping: [0.09, 0, 1, 0.01]
  25083. },
  25084. hierarchicalRepulsion: {
  25085. centralGravity: [0.2, 0, 10, 0.05],
  25086. springLength: [100, 0, 500, 5],
  25087. springConstant: [0.01, 0, 1.2, 0.005],
  25088. nodeDistance: [120, 0, 500, 5],
  25089. damping: [0.09, 0, 1, 0.01]
  25090. },
  25091. maxVelocity: [50, 0, 150, 1],
  25092. minVelocity: [0.1, 0.01, 0.5, 0.01],
  25093. solver: ['barnesHut', 'forceAtlas2Based', 'repulsion', 'hierarchicalRepulsion'],
  25094. timestep: [0.5, 0.01, 1, 0.01]
  25095. //adaptiveTimestep: true
  25096. }
  25097. };
  25098. exports.allOptions = allOptions;
  25099. exports.configureOptions = configureOptions;
  25100. /***/ }),
  25101. /* 123 */
  25102. /***/ (function(module, exports, __webpack_require__) {
  25103. "use strict";
  25104. var util = __webpack_require__(2);
  25105. // Graph3d
  25106. util.extend(exports, __webpack_require__(159));
  25107. // Timeline & Graph2d
  25108. util.extend(exports, __webpack_require__(177));
  25109. // Network
  25110. util.extend(exports, __webpack_require__(181));
  25111. /***/ }),
  25112. /* 124 */
  25113. /***/ (function(module, exports, __webpack_require__) {
  25114. __webpack_require__(49);
  25115. __webpack_require__(60);
  25116. module.exports = __webpack_require__(136);
  25117. /***/ }),
  25118. /* 125 */
  25119. /***/ (function(module, exports, __webpack_require__) {
  25120. "use strict";
  25121. var addToUnscopables = __webpack_require__(126);
  25122. var step = __webpack_require__(127);
  25123. var Iterators = __webpack_require__(31);
  25124. var toIObject = __webpack_require__(25);
  25125. // 22.1.3.4 Array.prototype.entries()
  25126. // 22.1.3.13 Array.prototype.keys()
  25127. // 22.1.3.29 Array.prototype.values()
  25128. // 22.1.3.30 Array.prototype[@@iterator]()
  25129. module.exports = __webpack_require__(79)(Array, 'Array', function (iterated, kind) {
  25130. this._t = toIObject(iterated); // target
  25131. this._i = 0; // next index
  25132. this._k = kind; // kind
  25133. // 22.1.5.2.1 %ArrayIteratorPrototype%.next()
  25134. }, function () {
  25135. var O = this._t;
  25136. var kind = this._k;
  25137. var index = this._i++;
  25138. if (!O || index >= O.length) {
  25139. this._t = undefined;
  25140. return step(1);
  25141. }
  25142. if (kind == 'keys') return step(0, index);
  25143. if (kind == 'values') return step(0, O[index]);
  25144. return step(0, [index, O[index]]);
  25145. }, 'values');
  25146. // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
  25147. Iterators.Arguments = Iterators.Array;
  25148. addToUnscopables('keys');
  25149. addToUnscopables('values');
  25150. addToUnscopables('entries');
  25151. /***/ }),
  25152. /* 126 */
  25153. /***/ (function(module, exports) {
  25154. module.exports = function () { /* empty */ };
  25155. /***/ }),
  25156. /* 127 */
  25157. /***/ (function(module, exports) {
  25158. module.exports = function (done, value) {
  25159. return { value: value, done: !!done };
  25160. };
  25161. /***/ }),
  25162. /* 128 */
  25163. /***/ (function(module, exports) {
  25164. module.exports = function (it) {
  25165. if (typeof it != 'function') throw TypeError(it + ' is not a function!');
  25166. return it;
  25167. };
  25168. /***/ }),
  25169. /* 129 */
  25170. /***/ (function(module, exports, __webpack_require__) {
  25171. "use strict";
  25172. var create = __webpack_require__(54);
  25173. var descriptor = __webpack_require__(39);
  25174. var setToStringTag = __webpack_require__(59);
  25175. var IteratorPrototype = {};
  25176. // 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
  25177. __webpack_require__(26)(IteratorPrototype, __webpack_require__(13)('iterator'), function () { return this; });
  25178. module.exports = function (Constructor, NAME, next) {
  25179. Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) });
  25180. setToStringTag(Constructor, NAME + ' Iterator');
  25181. };
  25182. /***/ }),
  25183. /* 130 */
  25184. /***/ (function(module, exports, __webpack_require__) {
  25185. var dP = __webpack_require__(20);
  25186. var anObject = __webpack_require__(27);
  25187. var getKeys = __webpack_require__(33);
  25188. module.exports = __webpack_require__(21) ? Object.defineProperties : function defineProperties(O, Properties) {
  25189. anObject(O);
  25190. var keys = getKeys(Properties);
  25191. var length = keys.length;
  25192. var i = 0;
  25193. var P;
  25194. while (length > i) dP.f(O, P = keys[i++], Properties[P]);
  25195. return O;
  25196. };
  25197. /***/ }),
  25198. /* 131 */
  25199. /***/ (function(module, exports, __webpack_require__) {
  25200. // false -> Array#indexOf
  25201. // true -> Array#includes
  25202. var toIObject = __webpack_require__(25);
  25203. var toLength = __webpack_require__(132);
  25204. var toAbsoluteIndex = __webpack_require__(133);
  25205. module.exports = function (IS_INCLUDES) {
  25206. return function ($this, el, fromIndex) {
  25207. var O = toIObject($this);
  25208. var length = toLength(O.length);
  25209. var index = toAbsoluteIndex(fromIndex, length);
  25210. var value;
  25211. // Array#includes uses SameValueZero equality algorithm
  25212. // eslint-disable-next-line no-self-compare
  25213. if (IS_INCLUDES && el != el) while (length > index) {
  25214. value = O[index++];
  25215. // eslint-disable-next-line no-self-compare
  25216. if (value != value) return true;
  25217. // Array#indexOf ignores holes, Array#includes - not
  25218. } else for (;length > index; index++) if (IS_INCLUDES || index in O) {
  25219. if (O[index] === el) return IS_INCLUDES || index || 0;
  25220. } return !IS_INCLUDES && -1;
  25221. };
  25222. };
  25223. /***/ }),
  25224. /* 132 */
  25225. /***/ (function(module, exports, __webpack_require__) {
  25226. // 7.1.15 ToLength
  25227. var toInteger = __webpack_require__(55);
  25228. var min = Math.min;
  25229. module.exports = function (it) {
  25230. return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
  25231. };
  25232. /***/ }),
  25233. /* 133 */
  25234. /***/ (function(module, exports, __webpack_require__) {
  25235. var toInteger = __webpack_require__(55);
  25236. var max = Math.max;
  25237. var min = Math.min;
  25238. module.exports = function (index, length) {
  25239. index = toInteger(index);
  25240. return index < 0 ? max(index + length, 0) : min(index, length);
  25241. };
  25242. /***/ }),
  25243. /* 134 */
  25244. /***/ (function(module, exports, __webpack_require__) {
  25245. var document = __webpack_require__(18).document;
  25246. module.exports = document && document.documentElement;
  25247. /***/ }),
  25248. /* 135 */
  25249. /***/ (function(module, exports, __webpack_require__) {
  25250. var toInteger = __webpack_require__(55);
  25251. var defined = __webpack_require__(51);
  25252. // true -> String#at
  25253. // false -> String#codePointAt
  25254. module.exports = function (TO_STRING) {
  25255. return function (that, pos) {
  25256. var s = String(defined(that));
  25257. var i = toInteger(pos);
  25258. var l = s.length;
  25259. var a, b;
  25260. if (i < 0 || i >= l) return TO_STRING ? '' : undefined;
  25261. a = s.charCodeAt(i);
  25262. return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
  25263. ? TO_STRING ? s.charAt(i) : a
  25264. : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
  25265. };
  25266. };
  25267. /***/ }),
  25268. /* 136 */
  25269. /***/ (function(module, exports, __webpack_require__) {
  25270. var anObject = __webpack_require__(27);
  25271. var get = __webpack_require__(137);
  25272. module.exports = __webpack_require__(7).getIterator = function (it) {
  25273. var iterFn = get(it);
  25274. if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!');
  25275. return anObject(iterFn.call(it));
  25276. };
  25277. /***/ }),
  25278. /* 137 */
  25279. /***/ (function(module, exports, __webpack_require__) {
  25280. var classof = __webpack_require__(86);
  25281. var ITERATOR = __webpack_require__(13)('iterator');
  25282. var Iterators = __webpack_require__(31);
  25283. module.exports = __webpack_require__(7).getIteratorMethod = function (it) {
  25284. if (it != undefined) return it[ITERATOR]
  25285. || it['@@iterator']
  25286. || Iterators[classof(it)];
  25287. };
  25288. /***/ }),
  25289. /* 138 */
  25290. /***/ (function(module, exports, __webpack_require__) {
  25291. __webpack_require__(139);
  25292. var $Object = __webpack_require__(7).Object;
  25293. module.exports = function create(P, D) {
  25294. return $Object.create(P, D);
  25295. };
  25296. /***/ }),
  25297. /* 139 */
  25298. /***/ (function(module, exports, __webpack_require__) {
  25299. var $export = __webpack_require__(17);
  25300. // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
  25301. $export($export.S, 'Object', { create: __webpack_require__(54) });
  25302. /***/ }),
  25303. /* 140 */
  25304. /***/ (function(module, exports, __webpack_require__) {
  25305. __webpack_require__(141);
  25306. module.exports = __webpack_require__(7).Object.keys;
  25307. /***/ }),
  25308. /* 141 */
  25309. /***/ (function(module, exports, __webpack_require__) {
  25310. // 19.1.2.14 Object.keys(O)
  25311. var toObject = __webpack_require__(41);
  25312. var $keys = __webpack_require__(33);
  25313. __webpack_require__(87)('keys', function () {
  25314. return function keys(it) {
  25315. return $keys(toObject(it));
  25316. };
  25317. });
  25318. /***/ }),
  25319. /* 142 */
  25320. /***/ (function(module, exports, __webpack_require__) {
  25321. module.exports = { "default": __webpack_require__(143), __esModule: true };
  25322. /***/ }),
  25323. /* 143 */
  25324. /***/ (function(module, exports, __webpack_require__) {
  25325. __webpack_require__(60);
  25326. __webpack_require__(49);
  25327. module.exports = __webpack_require__(61).f('iterator');
  25328. /***/ }),
  25329. /* 144 */
  25330. /***/ (function(module, exports, __webpack_require__) {
  25331. module.exports = { "default": __webpack_require__(145), __esModule: true };
  25332. /***/ }),
  25333. /* 145 */
  25334. /***/ (function(module, exports, __webpack_require__) {
  25335. __webpack_require__(146);
  25336. __webpack_require__(151);
  25337. __webpack_require__(152);
  25338. __webpack_require__(153);
  25339. module.exports = __webpack_require__(7).Symbol;
  25340. /***/ }),
  25341. /* 146 */
  25342. /***/ (function(module, exports, __webpack_require__) {
  25343. "use strict";
  25344. // ECMAScript 6 symbols shim
  25345. var global = __webpack_require__(18);
  25346. var has = __webpack_require__(22);
  25347. var DESCRIPTORS = __webpack_require__(21);
  25348. var $export = __webpack_require__(17);
  25349. var redefine = __webpack_require__(83);
  25350. var META = __webpack_require__(147).KEY;
  25351. var $fails = __webpack_require__(28);
  25352. var shared = __webpack_require__(57);
  25353. var setToStringTag = __webpack_require__(59);
  25354. var uid = __webpack_require__(40);
  25355. var wks = __webpack_require__(13);
  25356. var wksExt = __webpack_require__(61);
  25357. var wksDefine = __webpack_require__(62);
  25358. var enumKeys = __webpack_require__(148);
  25359. var isArray = __webpack_require__(149);
  25360. var anObject = __webpack_require__(27);
  25361. var toIObject = __webpack_require__(25);
  25362. var toPrimitive = __webpack_require__(53);
  25363. var createDesc = __webpack_require__(39);
  25364. var _create = __webpack_require__(54);
  25365. var gOPNExt = __webpack_require__(150);
  25366. var $GOPD = __webpack_require__(89);
  25367. var $DP = __webpack_require__(20);
  25368. var $keys = __webpack_require__(33);
  25369. var gOPD = $GOPD.f;
  25370. var dP = $DP.f;
  25371. var gOPN = gOPNExt.f;
  25372. var $Symbol = global.Symbol;
  25373. var $JSON = global.JSON;
  25374. var _stringify = $JSON && $JSON.stringify;
  25375. var PROTOTYPE = 'prototype';
  25376. var HIDDEN = wks('_hidden');
  25377. var TO_PRIMITIVE = wks('toPrimitive');
  25378. var isEnum = {}.propertyIsEnumerable;
  25379. var SymbolRegistry = shared('symbol-registry');
  25380. var AllSymbols = shared('symbols');
  25381. var OPSymbols = shared('op-symbols');
  25382. var ObjectProto = Object[PROTOTYPE];
  25383. var USE_NATIVE = typeof $Symbol == 'function';
  25384. var QObject = global.QObject;
  25385. // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
  25386. var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
  25387. // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
  25388. var setSymbolDesc = DESCRIPTORS && $fails(function () {
  25389. return _create(dP({}, 'a', {
  25390. get: function () { return dP(this, 'a', { value: 7 }).a; }
  25391. })).a != 7;
  25392. }) ? function (it, key, D) {
  25393. var protoDesc = gOPD(ObjectProto, key);
  25394. if (protoDesc) delete ObjectProto[key];
  25395. dP(it, key, D);
  25396. if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc);
  25397. } : dP;
  25398. var wrap = function (tag) {
  25399. var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
  25400. sym._k = tag;
  25401. return sym;
  25402. };
  25403. var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) {
  25404. return typeof it == 'symbol';
  25405. } : function (it) {
  25406. return it instanceof $Symbol;
  25407. };
  25408. var $defineProperty = function defineProperty(it, key, D) {
  25409. if (it === ObjectProto) $defineProperty(OPSymbols, key, D);
  25410. anObject(it);
  25411. key = toPrimitive(key, true);
  25412. anObject(D);
  25413. if (has(AllSymbols, key)) {
  25414. if (!D.enumerable) {
  25415. if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {}));
  25416. it[HIDDEN][key] = true;
  25417. } else {
  25418. if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false;
  25419. D = _create(D, { enumerable: createDesc(0, false) });
  25420. } return setSymbolDesc(it, key, D);
  25421. } return dP(it, key, D);
  25422. };
  25423. var $defineProperties = function defineProperties(it, P) {
  25424. anObject(it);
  25425. var keys = enumKeys(P = toIObject(P));
  25426. var i = 0;
  25427. var l = keys.length;
  25428. var key;
  25429. while (l > i) $defineProperty(it, key = keys[i++], P[key]);
  25430. return it;
  25431. };
  25432. var $create = function create(it, P) {
  25433. return P === undefined ? _create(it) : $defineProperties(_create(it), P);
  25434. };
  25435. var $propertyIsEnumerable = function propertyIsEnumerable(key) {
  25436. var E = isEnum.call(this, key = toPrimitive(key, true));
  25437. if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false;
  25438. return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
  25439. };
  25440. var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) {
  25441. it = toIObject(it);
  25442. key = toPrimitive(key, true);
  25443. if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return;
  25444. var D = gOPD(it, key);
  25445. if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true;
  25446. return D;
  25447. };
  25448. var $getOwnPropertyNames = function getOwnPropertyNames(it) {
  25449. var names = gOPN(toIObject(it));
  25450. var result = [];
  25451. var i = 0;
  25452. var key;
  25453. while (names.length > i) {
  25454. if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key);
  25455. } return result;
  25456. };
  25457. var $getOwnPropertySymbols = function getOwnPropertySymbols(it) {
  25458. var IS_OP = it === ObjectProto;
  25459. var names = gOPN(IS_OP ? OPSymbols : toIObject(it));
  25460. var result = [];
  25461. var i = 0;
  25462. var key;
  25463. while (names.length > i) {
  25464. if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]);
  25465. } return result;
  25466. };
  25467. // 19.4.1.1 Symbol([description])
  25468. if (!USE_NATIVE) {
  25469. $Symbol = function Symbol() {
  25470. if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!');
  25471. var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
  25472. var $set = function (value) {
  25473. if (this === ObjectProto) $set.call(OPSymbols, value);
  25474. if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
  25475. setSymbolDesc(this, tag, createDesc(1, value));
  25476. };
  25477. if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set });
  25478. return wrap(tag);
  25479. };
  25480. redefine($Symbol[PROTOTYPE], 'toString', function toString() {
  25481. return this._k;
  25482. });
  25483. $GOPD.f = $getOwnPropertyDescriptor;
  25484. $DP.f = $defineProperty;
  25485. __webpack_require__(88).f = gOPNExt.f = $getOwnPropertyNames;
  25486. __webpack_require__(42).f = $propertyIsEnumerable;
  25487. __webpack_require__(63).f = $getOwnPropertySymbols;
  25488. if (DESCRIPTORS && !__webpack_require__(52)) {
  25489. redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
  25490. }
  25491. wksExt.f = function (name) {
  25492. return wrap(wks(name));
  25493. };
  25494. }
  25495. $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol });
  25496. for (var es6Symbols = (
  25497. // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
  25498. 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
  25499. ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]);
  25500. for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]);
  25501. $export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
  25502. // 19.4.2.1 Symbol.for(key)
  25503. 'for': function (key) {
  25504. return has(SymbolRegistry, key += '')
  25505. ? SymbolRegistry[key]
  25506. : SymbolRegistry[key] = $Symbol(key);
  25507. },
  25508. // 19.4.2.5 Symbol.keyFor(sym)
  25509. keyFor: function keyFor(sym) {
  25510. if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!');
  25511. for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key;
  25512. },
  25513. useSetter: function () { setter = true; },
  25514. useSimple: function () { setter = false; }
  25515. });
  25516. $export($export.S + $export.F * !USE_NATIVE, 'Object', {
  25517. // 19.1.2.2 Object.create(O [, Properties])
  25518. create: $create,
  25519. // 19.1.2.4 Object.defineProperty(O, P, Attributes)
  25520. defineProperty: $defineProperty,
  25521. // 19.1.2.3 Object.defineProperties(O, Properties)
  25522. defineProperties: $defineProperties,
  25523. // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
  25524. getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
  25525. // 19.1.2.7 Object.getOwnPropertyNames(O)
  25526. getOwnPropertyNames: $getOwnPropertyNames,
  25527. // 19.1.2.8 Object.getOwnPropertySymbols(O)
  25528. getOwnPropertySymbols: $getOwnPropertySymbols
  25529. });
  25530. // 24.3.2 JSON.stringify(value [, replacer [, space]])
  25531. $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () {
  25532. var S = $Symbol();
  25533. // MS Edge converts symbol values to JSON as {}
  25534. // WebKit converts symbol values to JSON as null
  25535. // V8 throws on boxed symbols
  25536. return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}';
  25537. })), 'JSON', {
  25538. stringify: function stringify(it) {
  25539. if (it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
  25540. var args = [it];
  25541. var i = 1;
  25542. var replacer, $replacer;
  25543. while (arguments.length > i) args.push(arguments[i++]);
  25544. replacer = args[1];
  25545. if (typeof replacer == 'function') $replacer = replacer;
  25546. if ($replacer || !isArray(replacer)) replacer = function (key, value) {
  25547. if ($replacer) value = $replacer.call(this, key, value);
  25548. if (!isSymbol(value)) return value;
  25549. };
  25550. args[1] = replacer;
  25551. return _stringify.apply($JSON, args);
  25552. }
  25553. });
  25554. // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
  25555. $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(26)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
  25556. // 19.4.3.5 Symbol.prototype[@@toStringTag]
  25557. setToStringTag($Symbol, 'Symbol');
  25558. // 20.2.1.9 Math[@@toStringTag]
  25559. setToStringTag(Math, 'Math', true);
  25560. // 24.3.3 JSON[@@toStringTag]
  25561. setToStringTag(global.JSON, 'JSON', true);
  25562. /***/ }),
  25563. /* 147 */
  25564. /***/ (function(module, exports, __webpack_require__) {
  25565. var META = __webpack_require__(40)('meta');
  25566. var isObject = __webpack_require__(32);
  25567. var has = __webpack_require__(22);
  25568. var setDesc = __webpack_require__(20).f;
  25569. var id = 0;
  25570. var isExtensible = Object.isExtensible || function () {
  25571. return true;
  25572. };
  25573. var FREEZE = !__webpack_require__(28)(function () {
  25574. return isExtensible(Object.preventExtensions({}));
  25575. });
  25576. var setMeta = function (it) {
  25577. setDesc(it, META, { value: {
  25578. i: 'O' + ++id, // object ID
  25579. w: {} // weak collections IDs
  25580. } });
  25581. };
  25582. var fastKey = function (it, create) {
  25583. // return primitive with prefix
  25584. if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
  25585. if (!has(it, META)) {
  25586. // can't set metadata to uncaught frozen object
  25587. if (!isExtensible(it)) return 'F';
  25588. // not necessary to add metadata
  25589. if (!create) return 'E';
  25590. // add missing metadata
  25591. setMeta(it);
  25592. // return object ID
  25593. } return it[META].i;
  25594. };
  25595. var getWeak = function (it, create) {
  25596. if (!has(it, META)) {
  25597. // can't set metadata to uncaught frozen object
  25598. if (!isExtensible(it)) return true;
  25599. // not necessary to add metadata
  25600. if (!create) return false;
  25601. // add missing metadata
  25602. setMeta(it);
  25603. // return hash weak collections IDs
  25604. } return it[META].w;
  25605. };
  25606. // add metadata on freeze-family methods calling
  25607. var onFreeze = function (it) {
  25608. if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it);
  25609. return it;
  25610. };
  25611. var meta = module.exports = {
  25612. KEY: META,
  25613. NEED: false,
  25614. fastKey: fastKey,
  25615. getWeak: getWeak,
  25616. onFreeze: onFreeze
  25617. };
  25618. /***/ }),
  25619. /* 148 */
  25620. /***/ (function(module, exports, __webpack_require__) {
  25621. // all enumerable object keys, includes symbols
  25622. var getKeys = __webpack_require__(33);
  25623. var gOPS = __webpack_require__(63);
  25624. var pIE = __webpack_require__(42);
  25625. module.exports = function (it) {
  25626. var result = getKeys(it);
  25627. var getSymbols = gOPS.f;
  25628. if (getSymbols) {
  25629. var symbols = getSymbols(it);
  25630. var isEnum = pIE.f;
  25631. var i = 0;
  25632. var key;
  25633. while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key);
  25634. } return result;
  25635. };
  25636. /***/ }),
  25637. /* 149 */
  25638. /***/ (function(module, exports, __webpack_require__) {
  25639. // 7.2.2 IsArray(argument)
  25640. var cof = __webpack_require__(50);
  25641. module.exports = Array.isArray || function isArray(arg) {
  25642. return cof(arg) == 'Array';
  25643. };
  25644. /***/ }),
  25645. /* 150 */
  25646. /***/ (function(module, exports, __webpack_require__) {
  25647. // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
  25648. var toIObject = __webpack_require__(25);
  25649. var gOPN = __webpack_require__(88).f;
  25650. var toString = {}.toString;
  25651. var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
  25652. ? Object.getOwnPropertyNames(window) : [];
  25653. var getWindowNames = function (it) {
  25654. try {
  25655. return gOPN(it);
  25656. } catch (e) {
  25657. return windowNames.slice();
  25658. }
  25659. };
  25660. module.exports.f = function getOwnPropertyNames(it) {
  25661. return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
  25662. };
  25663. /***/ }),
  25664. /* 151 */
  25665. /***/ (function(module, exports) {
  25666. /***/ }),
  25667. /* 152 */
  25668. /***/ (function(module, exports, __webpack_require__) {
  25669. __webpack_require__(62)('asyncIterator');
  25670. /***/ }),
  25671. /* 153 */
  25672. /***/ (function(module, exports, __webpack_require__) {
  25673. __webpack_require__(62)('observable');
  25674. /***/ }),
  25675. /* 154 */
  25676. /***/ (function(module, exports, __webpack_require__) {
  25677. /* WEBPACK VAR INJECTION */(function(module) {var require;//! moment.js
  25678. //! version : 2.19.1
  25679. //! authors : Tim Wood, Iskren Chernev, Moment.js contributors
  25680. //! license : MIT
  25681. //! momentjs.com
  25682. ;(function (global, factory) {
  25683. true ? module.exports = factory() :
  25684. typeof define === 'function' && define.amd ? define(factory) :
  25685. global.moment = factory()
  25686. }(this, (function () { 'use strict';
  25687. var hookCallback;
  25688. function hooks () {
  25689. return hookCallback.apply(null, arguments);
  25690. }
  25691. // This is done to register the method called with moment()
  25692. // without creating circular dependencies.
  25693. function setHookCallback (callback) {
  25694. hookCallback = callback;
  25695. }
  25696. function isArray(input) {
  25697. return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
  25698. }
  25699. function isObject(input) {
  25700. // IE8 will treat undefined and null as object if it wasn't for
  25701. // input != null
  25702. return input != null && Object.prototype.toString.call(input) === '[object Object]';
  25703. }
  25704. function isObjectEmpty(obj) {
  25705. if (Object.getOwnPropertyNames) {
  25706. return (Object.getOwnPropertyNames(obj).length === 0);
  25707. } else {
  25708. var k;
  25709. for (k in obj) {
  25710. if (obj.hasOwnProperty(k)) {
  25711. return false;
  25712. }
  25713. }
  25714. return true;
  25715. }
  25716. }
  25717. function isUndefined(input) {
  25718. return input === void 0;
  25719. }
  25720. function isNumber(input) {
  25721. return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
  25722. }
  25723. function isDate(input) {
  25724. return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
  25725. }
  25726. function map(arr, fn) {
  25727. var res = [], i;
  25728. for (i = 0; i < arr.length; ++i) {
  25729. res.push(fn(arr[i], i));
  25730. }
  25731. return res;
  25732. }
  25733. function hasOwnProp(a, b) {
  25734. return Object.prototype.hasOwnProperty.call(a, b);
  25735. }
  25736. function extend(a, b) {
  25737. for (var i in b) {
  25738. if (hasOwnProp(b, i)) {
  25739. a[i] = b[i];
  25740. }
  25741. }
  25742. if (hasOwnProp(b, 'toString')) {
  25743. a.toString = b.toString;
  25744. }
  25745. if (hasOwnProp(b, 'valueOf')) {
  25746. a.valueOf = b.valueOf;
  25747. }
  25748. return a;
  25749. }
  25750. function createUTC (input, format, locale, strict) {
  25751. return createLocalOrUTC(input, format, locale, strict, true).utc();
  25752. }
  25753. function defaultParsingFlags() {
  25754. // We need to deep clone this object.
  25755. return {
  25756. empty : false,
  25757. unusedTokens : [],
  25758. unusedInput : [],
  25759. overflow : -2,
  25760. charsLeftOver : 0,
  25761. nullInput : false,
  25762. invalidMonth : null,
  25763. invalidFormat : false,
  25764. userInvalidated : false,
  25765. iso : false,
  25766. parsedDateParts : [],
  25767. meridiem : null,
  25768. rfc2822 : false,
  25769. weekdayMismatch : false
  25770. };
  25771. }
  25772. function getParsingFlags(m) {
  25773. if (m._pf == null) {
  25774. m._pf = defaultParsingFlags();
  25775. }
  25776. return m._pf;
  25777. }
  25778. var some;
  25779. if (Array.prototype.some) {
  25780. some = Array.prototype.some;
  25781. } else {
  25782. some = function (fun) {
  25783. var t = Object(this);
  25784. var len = t.length >>> 0;
  25785. for (var i = 0; i < len; i++) {
  25786. if (i in t && fun.call(this, t[i], i, t)) {
  25787. return true;
  25788. }
  25789. }
  25790. return false;
  25791. };
  25792. }
  25793. function isValid(m) {
  25794. if (m._isValid == null) {
  25795. var flags = getParsingFlags(m);
  25796. var parsedParts = some.call(flags.parsedDateParts, function (i) {
  25797. return i != null;
  25798. });
  25799. var isNowValid = !isNaN(m._d.getTime()) &&
  25800. flags.overflow < 0 &&
  25801. !flags.empty &&
  25802. !flags.invalidMonth &&
  25803. !flags.invalidWeekday &&
  25804. !flags.weekdayMismatch &&
  25805. !flags.nullInput &&
  25806. !flags.invalidFormat &&
  25807. !flags.userInvalidated &&
  25808. (!flags.meridiem || (flags.meridiem && parsedParts));
  25809. if (m._strict) {
  25810. isNowValid = isNowValid &&
  25811. flags.charsLeftOver === 0 &&
  25812. flags.unusedTokens.length === 0 &&
  25813. flags.bigHour === undefined;
  25814. }
  25815. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  25816. m._isValid = isNowValid;
  25817. }
  25818. else {
  25819. return isNowValid;
  25820. }
  25821. }
  25822. return m._isValid;
  25823. }
  25824. function createInvalid (flags) {
  25825. var m = createUTC(NaN);
  25826. if (flags != null) {
  25827. extend(getParsingFlags(m), flags);
  25828. }
  25829. else {
  25830. getParsingFlags(m).userInvalidated = true;
  25831. }
  25832. return m;
  25833. }
  25834. // Plugins that add properties should also add the key here (null value),
  25835. // so we can properly clone ourselves.
  25836. var momentProperties = hooks.momentProperties = [];
  25837. function copyConfig(to, from) {
  25838. var i, prop, val;
  25839. if (!isUndefined(from._isAMomentObject)) {
  25840. to._isAMomentObject = from._isAMomentObject;
  25841. }
  25842. if (!isUndefined(from._i)) {
  25843. to._i = from._i;
  25844. }
  25845. if (!isUndefined(from._f)) {
  25846. to._f = from._f;
  25847. }
  25848. if (!isUndefined(from._l)) {
  25849. to._l = from._l;
  25850. }
  25851. if (!isUndefined(from._strict)) {
  25852. to._strict = from._strict;
  25853. }
  25854. if (!isUndefined(from._tzm)) {
  25855. to._tzm = from._tzm;
  25856. }
  25857. if (!isUndefined(from._isUTC)) {
  25858. to._isUTC = from._isUTC;
  25859. }
  25860. if (!isUndefined(from._offset)) {
  25861. to._offset = from._offset;
  25862. }
  25863. if (!isUndefined(from._pf)) {
  25864. to._pf = getParsingFlags(from);
  25865. }
  25866. if (!isUndefined(from._locale)) {
  25867. to._locale = from._locale;
  25868. }
  25869. if (momentProperties.length > 0) {
  25870. for (i = 0; i < momentProperties.length; i++) {
  25871. prop = momentProperties[i];
  25872. val = from[prop];
  25873. if (!isUndefined(val)) {
  25874. to[prop] = val;
  25875. }
  25876. }
  25877. }
  25878. return to;
  25879. }
  25880. var updateInProgress = false;
  25881. // Moment prototype object
  25882. function Moment(config) {
  25883. copyConfig(this, config);
  25884. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  25885. if (!this.isValid()) {
  25886. this._d = new Date(NaN);
  25887. }
  25888. // Prevent infinite loop in case updateOffset creates new moment
  25889. // objects.
  25890. if (updateInProgress === false) {
  25891. updateInProgress = true;
  25892. hooks.updateOffset(this);
  25893. updateInProgress = false;
  25894. }
  25895. }
  25896. function isMoment (obj) {
  25897. return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
  25898. }
  25899. function absFloor (number) {
  25900. if (number < 0) {
  25901. // -0 -> 0
  25902. return Math.ceil(number) || 0;
  25903. } else {
  25904. return Math.floor(number);
  25905. }
  25906. }
  25907. function toInt(argumentForCoercion) {
  25908. var coercedNumber = +argumentForCoercion,
  25909. value = 0;
  25910. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  25911. value = absFloor(coercedNumber);
  25912. }
  25913. return value;
  25914. }
  25915. // compare two arrays, return the number of differences
  25916. function compareArrays(array1, array2, dontConvert) {
  25917. var len = Math.min(array1.length, array2.length),
  25918. lengthDiff = Math.abs(array1.length - array2.length),
  25919. diffs = 0,
  25920. i;
  25921. for (i = 0; i < len; i++) {
  25922. if ((dontConvert && array1[i] !== array2[i]) ||
  25923. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  25924. diffs++;
  25925. }
  25926. }
  25927. return diffs + lengthDiff;
  25928. }
  25929. function warn(msg) {
  25930. if (hooks.suppressDeprecationWarnings === false &&
  25931. (typeof console !== 'undefined') && console.warn) {
  25932. console.warn('Deprecation warning: ' + msg);
  25933. }
  25934. }
  25935. function deprecate(msg, fn) {
  25936. var firstTime = true;
  25937. return extend(function () {
  25938. if (hooks.deprecationHandler != null) {
  25939. hooks.deprecationHandler(null, msg);
  25940. }
  25941. if (firstTime) {
  25942. var args = [];
  25943. var arg;
  25944. for (var i = 0; i < arguments.length; i++) {
  25945. arg = '';
  25946. if (typeof arguments[i] === 'object') {
  25947. arg += '\n[' + i + '] ';
  25948. for (var key in arguments[0]) {
  25949. arg += key + ': ' + arguments[0][key] + ', ';
  25950. }
  25951. arg = arg.slice(0, -2); // Remove trailing comma and space
  25952. } else {
  25953. arg = arguments[i];
  25954. }
  25955. args.push(arg);
  25956. }
  25957. warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
  25958. firstTime = false;
  25959. }
  25960. return fn.apply(this, arguments);
  25961. }, fn);
  25962. }
  25963. var deprecations = {};
  25964. function deprecateSimple(name, msg) {
  25965. if (hooks.deprecationHandler != null) {
  25966. hooks.deprecationHandler(name, msg);
  25967. }
  25968. if (!deprecations[name]) {
  25969. warn(msg);
  25970. deprecations[name] = true;
  25971. }
  25972. }
  25973. hooks.suppressDeprecationWarnings = false;
  25974. hooks.deprecationHandler = null;
  25975. function isFunction(input) {
  25976. return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
  25977. }
  25978. function set (config) {
  25979. var prop, i;
  25980. for (i in config) {
  25981. prop = config[i];
  25982. if (isFunction(prop)) {
  25983. this[i] = prop;
  25984. } else {
  25985. this['_' + i] = prop;
  25986. }
  25987. }
  25988. this._config = config;
  25989. // Lenient ordinal parsing accepts just a number in addition to
  25990. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  25991. // TODO: Remove "ordinalParse" fallback in next major release.
  25992. this._dayOfMonthOrdinalParseLenient = new RegExp(
  25993. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  25994. '|' + (/\d{1,2}/).source);
  25995. }
  25996. function mergeConfigs(parentConfig, childConfig) {
  25997. var res = extend({}, parentConfig), prop;
  25998. for (prop in childConfig) {
  25999. if (hasOwnProp(childConfig, prop)) {
  26000. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  26001. res[prop] = {};
  26002. extend(res[prop], parentConfig[prop]);
  26003. extend(res[prop], childConfig[prop]);
  26004. } else if (childConfig[prop] != null) {
  26005. res[prop] = childConfig[prop];
  26006. } else {
  26007. delete res[prop];
  26008. }
  26009. }
  26010. }
  26011. for (prop in parentConfig) {
  26012. if (hasOwnProp(parentConfig, prop) &&
  26013. !hasOwnProp(childConfig, prop) &&
  26014. isObject(parentConfig[prop])) {
  26015. // make sure changes to properties don't modify parent config
  26016. res[prop] = extend({}, res[prop]);
  26017. }
  26018. }
  26019. return res;
  26020. }
  26021. function Locale(config) {
  26022. if (config != null) {
  26023. this.set(config);
  26024. }
  26025. }
  26026. var keys;
  26027. if (Object.keys) {
  26028. keys = Object.keys;
  26029. } else {
  26030. keys = function (obj) {
  26031. var i, res = [];
  26032. for (i in obj) {
  26033. if (hasOwnProp(obj, i)) {
  26034. res.push(i);
  26035. }
  26036. }
  26037. return res;
  26038. };
  26039. }
  26040. var defaultCalendar = {
  26041. sameDay : '[Today at] LT',
  26042. nextDay : '[Tomorrow at] LT',
  26043. nextWeek : 'dddd [at] LT',
  26044. lastDay : '[Yesterday at] LT',
  26045. lastWeek : '[Last] dddd [at] LT',
  26046. sameElse : 'L'
  26047. };
  26048. function calendar (key, mom, now) {
  26049. var output = this._calendar[key] || this._calendar['sameElse'];
  26050. return isFunction(output) ? output.call(mom, now) : output;
  26051. }
  26052. var defaultLongDateFormat = {
  26053. LTS : 'h:mm:ss A',
  26054. LT : 'h:mm A',
  26055. L : 'MM/DD/YYYY',
  26056. LL : 'MMMM D, YYYY',
  26057. LLL : 'MMMM D, YYYY h:mm A',
  26058. LLLL : 'dddd, MMMM D, YYYY h:mm A'
  26059. };
  26060. function longDateFormat (key) {
  26061. var format = this._longDateFormat[key],
  26062. formatUpper = this._longDateFormat[key.toUpperCase()];
  26063. if (format || !formatUpper) {
  26064. return format;
  26065. }
  26066. this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
  26067. return val.slice(1);
  26068. });
  26069. return this._longDateFormat[key];
  26070. }
  26071. var defaultInvalidDate = 'Invalid date';
  26072. function invalidDate () {
  26073. return this._invalidDate;
  26074. }
  26075. var defaultOrdinal = '%d';
  26076. var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  26077. function ordinal (number) {
  26078. return this._ordinal.replace('%d', number);
  26079. }
  26080. var defaultRelativeTime = {
  26081. future : 'in %s',
  26082. past : '%s ago',
  26083. s : 'a few seconds',
  26084. ss : '%d seconds',
  26085. m : 'a minute',
  26086. mm : '%d minutes',
  26087. h : 'an hour',
  26088. hh : '%d hours',
  26089. d : 'a day',
  26090. dd : '%d days',
  26091. M : 'a month',
  26092. MM : '%d months',
  26093. y : 'a year',
  26094. yy : '%d years'
  26095. };
  26096. function relativeTime (number, withoutSuffix, string, isFuture) {
  26097. var output = this._relativeTime[string];
  26098. return (isFunction(output)) ?
  26099. output(number, withoutSuffix, string, isFuture) :
  26100. output.replace(/%d/i, number);
  26101. }
  26102. function pastFuture (diff, output) {
  26103. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  26104. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  26105. }
  26106. var aliases = {};
  26107. function addUnitAlias (unit, shorthand) {
  26108. var lowerCase = unit.toLowerCase();
  26109. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  26110. }
  26111. function normalizeUnits(units) {
  26112. return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
  26113. }
  26114. function normalizeObjectUnits(inputObject) {
  26115. var normalizedInput = {},
  26116. normalizedProp,
  26117. prop;
  26118. for (prop in inputObject) {
  26119. if (hasOwnProp(inputObject, prop)) {
  26120. normalizedProp = normalizeUnits(prop);
  26121. if (normalizedProp) {
  26122. normalizedInput[normalizedProp] = inputObject[prop];
  26123. }
  26124. }
  26125. }
  26126. return normalizedInput;
  26127. }
  26128. var priorities = {};
  26129. function addUnitPriority(unit, priority) {
  26130. priorities[unit] = priority;
  26131. }
  26132. function getPrioritizedUnits(unitsObj) {
  26133. var units = [];
  26134. for (var u in unitsObj) {
  26135. units.push({unit: u, priority: priorities[u]});
  26136. }
  26137. units.sort(function (a, b) {
  26138. return a.priority - b.priority;
  26139. });
  26140. return units;
  26141. }
  26142. function zeroFill(number, targetLength, forceSign) {
  26143. var absNumber = '' + Math.abs(number),
  26144. zerosToFill = targetLength - absNumber.length,
  26145. sign = number >= 0;
  26146. return (sign ? (forceSign ? '+' : '') : '-') +
  26147. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
  26148. }
  26149. 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;
  26150. var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
  26151. var formatFunctions = {};
  26152. var formatTokenFunctions = {};
  26153. // token: 'M'
  26154. // padded: ['MM', 2]
  26155. // ordinal: 'Mo'
  26156. // callback: function () { this.month() + 1 }
  26157. function addFormatToken (token, padded, ordinal, callback) {
  26158. var func = callback;
  26159. if (typeof callback === 'string') {
  26160. func = function () {
  26161. return this[callback]();
  26162. };
  26163. }
  26164. if (token) {
  26165. formatTokenFunctions[token] = func;
  26166. }
  26167. if (padded) {
  26168. formatTokenFunctions[padded[0]] = function () {
  26169. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  26170. };
  26171. }
  26172. if (ordinal) {
  26173. formatTokenFunctions[ordinal] = function () {
  26174. return this.localeData().ordinal(func.apply(this, arguments), token);
  26175. };
  26176. }
  26177. }
  26178. function removeFormattingTokens(input) {
  26179. if (input.match(/\[[\s\S]/)) {
  26180. return input.replace(/^\[|\]$/g, '');
  26181. }
  26182. return input.replace(/\\/g, '');
  26183. }
  26184. function makeFormatFunction(format) {
  26185. var array = format.match(formattingTokens), i, length;
  26186. for (i = 0, length = array.length; i < length; i++) {
  26187. if (formatTokenFunctions[array[i]]) {
  26188. array[i] = formatTokenFunctions[array[i]];
  26189. } else {
  26190. array[i] = removeFormattingTokens(array[i]);
  26191. }
  26192. }
  26193. return function (mom) {
  26194. var output = '', i;
  26195. for (i = 0; i < length; i++) {
  26196. output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
  26197. }
  26198. return output;
  26199. };
  26200. }
  26201. // format date using native date object
  26202. function formatMoment(m, format) {
  26203. if (!m.isValid()) {
  26204. return m.localeData().invalidDate();
  26205. }
  26206. format = expandFormat(format, m.localeData());
  26207. formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
  26208. return formatFunctions[format](m);
  26209. }
  26210. function expandFormat(format, locale) {
  26211. var i = 5;
  26212. function replaceLongDateFormatTokens(input) {
  26213. return locale.longDateFormat(input) || input;
  26214. }
  26215. localFormattingTokens.lastIndex = 0;
  26216. while (i >= 0 && localFormattingTokens.test(format)) {
  26217. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  26218. localFormattingTokens.lastIndex = 0;
  26219. i -= 1;
  26220. }
  26221. return format;
  26222. }
  26223. var match1 = /\d/; // 0 - 9
  26224. var match2 = /\d\d/; // 00 - 99
  26225. var match3 = /\d{3}/; // 000 - 999
  26226. var match4 = /\d{4}/; // 0000 - 9999
  26227. var match6 = /[+-]?\d{6}/; // -999999 - 999999
  26228. var match1to2 = /\d\d?/; // 0 - 99
  26229. var match3to4 = /\d\d\d\d?/; // 999 - 9999
  26230. var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
  26231. var match1to3 = /\d{1,3}/; // 0 - 999
  26232. var match1to4 = /\d{1,4}/; // 0 - 9999
  26233. var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
  26234. var matchUnsigned = /\d+/; // 0 - inf
  26235. var matchSigned = /[+-]?\d+/; // -inf - inf
  26236. var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
  26237. var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  26238. var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
  26239. // any word (or two) characters or numbers including two/three word month in arabic.
  26240. // includes scottish gaelic two word and hyphenated months
  26241. var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;
  26242. var regexes = {};
  26243. function addRegexToken (token, regex, strictRegex) {
  26244. regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
  26245. return (isStrict && strictRegex) ? strictRegex : regex;
  26246. };
  26247. }
  26248. function getParseRegexForToken (token, config) {
  26249. if (!hasOwnProp(regexes, token)) {
  26250. return new RegExp(unescapeFormat(token));
  26251. }
  26252. return regexes[token](config._strict, config._locale);
  26253. }
  26254. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  26255. function unescapeFormat(s) {
  26256. return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  26257. return p1 || p2 || p3 || p4;
  26258. }));
  26259. }
  26260. function regexEscape(s) {
  26261. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  26262. }
  26263. var tokens = {};
  26264. function addParseToken (token, callback) {
  26265. var i, func = callback;
  26266. if (typeof token === 'string') {
  26267. token = [token];
  26268. }
  26269. if (isNumber(callback)) {
  26270. func = function (input, array) {
  26271. array[callback] = toInt(input);
  26272. };
  26273. }
  26274. for (i = 0; i < token.length; i++) {
  26275. tokens[token[i]] = func;
  26276. }
  26277. }
  26278. function addWeekParseToken (token, callback) {
  26279. addParseToken(token, function (input, array, config, token) {
  26280. config._w = config._w || {};
  26281. callback(input, config._w, config, token);
  26282. });
  26283. }
  26284. function addTimeToArrayFromToken(token, input, config) {
  26285. if (input != null && hasOwnProp(tokens, token)) {
  26286. tokens[token](input, config._a, config, token);
  26287. }
  26288. }
  26289. var YEAR = 0;
  26290. var MONTH = 1;
  26291. var DATE = 2;
  26292. var HOUR = 3;
  26293. var MINUTE = 4;
  26294. var SECOND = 5;
  26295. var MILLISECOND = 6;
  26296. var WEEK = 7;
  26297. var WEEKDAY = 8;
  26298. // FORMATTING
  26299. addFormatToken('Y', 0, 0, function () {
  26300. var y = this.year();
  26301. return y <= 9999 ? '' + y : '+' + y;
  26302. });
  26303. addFormatToken(0, ['YY', 2], 0, function () {
  26304. return this.year() % 100;
  26305. });
  26306. addFormatToken(0, ['YYYY', 4], 0, 'year');
  26307. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  26308. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  26309. // ALIASES
  26310. addUnitAlias('year', 'y');
  26311. // PRIORITIES
  26312. addUnitPriority('year', 1);
  26313. // PARSING
  26314. addRegexToken('Y', matchSigned);
  26315. addRegexToken('YY', match1to2, match2);
  26316. addRegexToken('YYYY', match1to4, match4);
  26317. addRegexToken('YYYYY', match1to6, match6);
  26318. addRegexToken('YYYYYY', match1to6, match6);
  26319. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  26320. addParseToken('YYYY', function (input, array) {
  26321. array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  26322. });
  26323. addParseToken('YY', function (input, array) {
  26324. array[YEAR] = hooks.parseTwoDigitYear(input);
  26325. });
  26326. addParseToken('Y', function (input, array) {
  26327. array[YEAR] = parseInt(input, 10);
  26328. });
  26329. // HELPERS
  26330. function daysInYear(year) {
  26331. return isLeapYear(year) ? 366 : 365;
  26332. }
  26333. function isLeapYear(year) {
  26334. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  26335. }
  26336. // HOOKS
  26337. hooks.parseTwoDigitYear = function (input) {
  26338. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  26339. };
  26340. // MOMENTS
  26341. var getSetYear = makeGetSet('FullYear', true);
  26342. function getIsLeapYear () {
  26343. return isLeapYear(this.year());
  26344. }
  26345. function makeGetSet (unit, keepTime) {
  26346. return function (value) {
  26347. if (value != null) {
  26348. set$1(this, unit, value);
  26349. hooks.updateOffset(this, keepTime);
  26350. return this;
  26351. } else {
  26352. return get(this, unit);
  26353. }
  26354. };
  26355. }
  26356. function get (mom, unit) {
  26357. return mom.isValid() ?
  26358. mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
  26359. }
  26360. function set$1 (mom, unit, value) {
  26361. if (mom.isValid() && !isNaN(value)) {
  26362. if (unit === 'FullYear' && isLeapYear(mom.year())) {
  26363. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
  26364. }
  26365. else {
  26366. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  26367. }
  26368. }
  26369. }
  26370. // MOMENTS
  26371. function stringGet (units) {
  26372. units = normalizeUnits(units);
  26373. if (isFunction(this[units])) {
  26374. return this[units]();
  26375. }
  26376. return this;
  26377. }
  26378. function stringSet (units, value) {
  26379. if (typeof units === 'object') {
  26380. units = normalizeObjectUnits(units);
  26381. var prioritized = getPrioritizedUnits(units);
  26382. for (var i = 0; i < prioritized.length; i++) {
  26383. this[prioritized[i].unit](units[prioritized[i].unit]);
  26384. }
  26385. } else {
  26386. units = normalizeUnits(units);
  26387. if (isFunction(this[units])) {
  26388. return this[units](value);
  26389. }
  26390. }
  26391. return this;
  26392. }
  26393. function mod(n, x) {
  26394. return ((n % x) + x) % x;
  26395. }
  26396. var indexOf;
  26397. if (Array.prototype.indexOf) {
  26398. indexOf = Array.prototype.indexOf;
  26399. } else {
  26400. indexOf = function (o) {
  26401. // I know
  26402. var i;
  26403. for (i = 0; i < this.length; ++i) {
  26404. if (this[i] === o) {
  26405. return i;
  26406. }
  26407. }
  26408. return -1;
  26409. };
  26410. }
  26411. function daysInMonth(year, month) {
  26412. if (isNaN(year) || isNaN(month)) {
  26413. return NaN;
  26414. }
  26415. var modMonth = mod(month, 12);
  26416. year += (month - modMonth) / 12;
  26417. return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2);
  26418. }
  26419. // FORMATTING
  26420. addFormatToken('M', ['MM', 2], 'Mo', function () {
  26421. return this.month() + 1;
  26422. });
  26423. addFormatToken('MMM', 0, 0, function (format) {
  26424. return this.localeData().monthsShort(this, format);
  26425. });
  26426. addFormatToken('MMMM', 0, 0, function (format) {
  26427. return this.localeData().months(this, format);
  26428. });
  26429. // ALIASES
  26430. addUnitAlias('month', 'M');
  26431. // PRIORITY
  26432. addUnitPriority('month', 8);
  26433. // PARSING
  26434. addRegexToken('M', match1to2);
  26435. addRegexToken('MM', match1to2, match2);
  26436. addRegexToken('MMM', function (isStrict, locale) {
  26437. return locale.monthsShortRegex(isStrict);
  26438. });
  26439. addRegexToken('MMMM', function (isStrict, locale) {
  26440. return locale.monthsRegex(isStrict);
  26441. });
  26442. addParseToken(['M', 'MM'], function (input, array) {
  26443. array[MONTH] = toInt(input) - 1;
  26444. });
  26445. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  26446. var month = config._locale.monthsParse(input, token, config._strict);
  26447. // if we didn't find a month name, mark the date as invalid.
  26448. if (month != null) {
  26449. array[MONTH] = month;
  26450. } else {
  26451. getParsingFlags(config).invalidMonth = input;
  26452. }
  26453. });
  26454. // LOCALES
  26455. var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
  26456. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
  26457. function localeMonths (m, format) {
  26458. if (!m) {
  26459. return isArray(this._months) ? this._months :
  26460. this._months['standalone'];
  26461. }
  26462. return isArray(this._months) ? this._months[m.month()] :
  26463. this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
  26464. }
  26465. var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
  26466. function localeMonthsShort (m, format) {
  26467. if (!m) {
  26468. return isArray(this._monthsShort) ? this._monthsShort :
  26469. this._monthsShort['standalone'];
  26470. }
  26471. return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
  26472. this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
  26473. }
  26474. function handleStrictParse(monthName, format, strict) {
  26475. var i, ii, mom, llc = monthName.toLocaleLowerCase();
  26476. if (!this._monthsParse) {
  26477. // this is not used
  26478. this._monthsParse = [];
  26479. this._longMonthsParse = [];
  26480. this._shortMonthsParse = [];
  26481. for (i = 0; i < 12; ++i) {
  26482. mom = createUTC([2000, i]);
  26483. this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
  26484. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  26485. }
  26486. }
  26487. if (strict) {
  26488. if (format === 'MMM') {
  26489. ii = indexOf.call(this._shortMonthsParse, llc);
  26490. return ii !== -1 ? ii : null;
  26491. } else {
  26492. ii = indexOf.call(this._longMonthsParse, llc);
  26493. return ii !== -1 ? ii : null;
  26494. }
  26495. } else {
  26496. if (format === 'MMM') {
  26497. ii = indexOf.call(this._shortMonthsParse, llc);
  26498. if (ii !== -1) {
  26499. return ii;
  26500. }
  26501. ii = indexOf.call(this._longMonthsParse, llc);
  26502. return ii !== -1 ? ii : null;
  26503. } else {
  26504. ii = indexOf.call(this._longMonthsParse, llc);
  26505. if (ii !== -1) {
  26506. return ii;
  26507. }
  26508. ii = indexOf.call(this._shortMonthsParse, llc);
  26509. return ii !== -1 ? ii : null;
  26510. }
  26511. }
  26512. }
  26513. function localeMonthsParse (monthName, format, strict) {
  26514. var i, mom, regex;
  26515. if (this._monthsParseExact) {
  26516. return handleStrictParse.call(this, monthName, format, strict);
  26517. }
  26518. if (!this._monthsParse) {
  26519. this._monthsParse = [];
  26520. this._longMonthsParse = [];
  26521. this._shortMonthsParse = [];
  26522. }
  26523. // TODO: add sorting
  26524. // Sorting makes sure if one month (or abbr) is a prefix of another
  26525. // see sorting in computeMonthsParse
  26526. for (i = 0; i < 12; i++) {
  26527. // make the regex if we don't have it already
  26528. mom = createUTC([2000, i]);
  26529. if (strict && !this._longMonthsParse[i]) {
  26530. this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
  26531. this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
  26532. }
  26533. if (!strict && !this._monthsParse[i]) {
  26534. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  26535. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  26536. }
  26537. // test the regex
  26538. if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
  26539. return i;
  26540. } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
  26541. return i;
  26542. } else if (!strict && this._monthsParse[i].test(monthName)) {
  26543. return i;
  26544. }
  26545. }
  26546. }
  26547. // MOMENTS
  26548. function setMonth (mom, value) {
  26549. var dayOfMonth;
  26550. if (!mom.isValid()) {
  26551. // No op
  26552. return mom;
  26553. }
  26554. if (typeof value === 'string') {
  26555. if (/^\d+$/.test(value)) {
  26556. value = toInt(value);
  26557. } else {
  26558. value = mom.localeData().monthsParse(value);
  26559. // TODO: Another silent failure?
  26560. if (!isNumber(value)) {
  26561. return mom;
  26562. }
  26563. }
  26564. }
  26565. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  26566. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  26567. return mom;
  26568. }
  26569. function getSetMonth (value) {
  26570. if (value != null) {
  26571. setMonth(this, value);
  26572. hooks.updateOffset(this, true);
  26573. return this;
  26574. } else {
  26575. return get(this, 'Month');
  26576. }
  26577. }
  26578. function getDaysInMonth () {
  26579. return daysInMonth(this.year(), this.month());
  26580. }
  26581. var defaultMonthsShortRegex = matchWord;
  26582. function monthsShortRegex (isStrict) {
  26583. if (this._monthsParseExact) {
  26584. if (!hasOwnProp(this, '_monthsRegex')) {
  26585. computeMonthsParse.call(this);
  26586. }
  26587. if (isStrict) {
  26588. return this._monthsShortStrictRegex;
  26589. } else {
  26590. return this._monthsShortRegex;
  26591. }
  26592. } else {
  26593. if (!hasOwnProp(this, '_monthsShortRegex')) {
  26594. this._monthsShortRegex = defaultMonthsShortRegex;
  26595. }
  26596. return this._monthsShortStrictRegex && isStrict ?
  26597. this._monthsShortStrictRegex : this._monthsShortRegex;
  26598. }
  26599. }
  26600. var defaultMonthsRegex = matchWord;
  26601. function monthsRegex (isStrict) {
  26602. if (this._monthsParseExact) {
  26603. if (!hasOwnProp(this, '_monthsRegex')) {
  26604. computeMonthsParse.call(this);
  26605. }
  26606. if (isStrict) {
  26607. return this._monthsStrictRegex;
  26608. } else {
  26609. return this._monthsRegex;
  26610. }
  26611. } else {
  26612. if (!hasOwnProp(this, '_monthsRegex')) {
  26613. this._monthsRegex = defaultMonthsRegex;
  26614. }
  26615. return this._monthsStrictRegex && isStrict ?
  26616. this._monthsStrictRegex : this._monthsRegex;
  26617. }
  26618. }
  26619. function computeMonthsParse () {
  26620. function cmpLenRev(a, b) {
  26621. return b.length - a.length;
  26622. }
  26623. var shortPieces = [], longPieces = [], mixedPieces = [],
  26624. i, mom;
  26625. for (i = 0; i < 12; i++) {
  26626. // make the regex if we don't have it already
  26627. mom = createUTC([2000, i]);
  26628. shortPieces.push(this.monthsShort(mom, ''));
  26629. longPieces.push(this.months(mom, ''));
  26630. mixedPieces.push(this.months(mom, ''));
  26631. mixedPieces.push(this.monthsShort(mom, ''));
  26632. }
  26633. // Sorting makes sure if one month (or abbr) is a prefix of another it
  26634. // will match the longer piece.
  26635. shortPieces.sort(cmpLenRev);
  26636. longPieces.sort(cmpLenRev);
  26637. mixedPieces.sort(cmpLenRev);
  26638. for (i = 0; i < 12; i++) {
  26639. shortPieces[i] = regexEscape(shortPieces[i]);
  26640. longPieces[i] = regexEscape(longPieces[i]);
  26641. }
  26642. for (i = 0; i < 24; i++) {
  26643. mixedPieces[i] = regexEscape(mixedPieces[i]);
  26644. }
  26645. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  26646. this._monthsShortRegex = this._monthsRegex;
  26647. this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  26648. this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  26649. }
  26650. function createDate (y, m, d, h, M, s, ms) {
  26651. // can't just apply() to create a date:
  26652. // https://stackoverflow.com/q/181348
  26653. var date = new Date(y, m, d, h, M, s, ms);
  26654. // the date constructor remaps years 0-99 to 1900-1999
  26655. if (y < 100 && y >= 0 && isFinite(date.getFullYear())) {
  26656. date.setFullYear(y);
  26657. }
  26658. return date;
  26659. }
  26660. function createUTCDate (y) {
  26661. var date = new Date(Date.UTC.apply(null, arguments));
  26662. // the Date.UTC function remaps years 0-99 to 1900-1999
  26663. if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) {
  26664. date.setUTCFullYear(y);
  26665. }
  26666. return date;
  26667. }
  26668. // start-of-first-week - start-of-year
  26669. function firstWeekOffset(year, dow, doy) {
  26670. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  26671. fwd = 7 + dow - doy,
  26672. // first-week day local weekday -- which local weekday is fwd
  26673. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  26674. return -fwdlw + fwd - 1;
  26675. }
  26676. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  26677. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  26678. var localWeekday = (7 + weekday - dow) % 7,
  26679. weekOffset = firstWeekOffset(year, dow, doy),
  26680. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  26681. resYear, resDayOfYear;
  26682. if (dayOfYear <= 0) {
  26683. resYear = year - 1;
  26684. resDayOfYear = daysInYear(resYear) + dayOfYear;
  26685. } else if (dayOfYear > daysInYear(year)) {
  26686. resYear = year + 1;
  26687. resDayOfYear = dayOfYear - daysInYear(year);
  26688. } else {
  26689. resYear = year;
  26690. resDayOfYear = dayOfYear;
  26691. }
  26692. return {
  26693. year: resYear,
  26694. dayOfYear: resDayOfYear
  26695. };
  26696. }
  26697. function weekOfYear(mom, dow, doy) {
  26698. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  26699. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  26700. resWeek, resYear;
  26701. if (week < 1) {
  26702. resYear = mom.year() - 1;
  26703. resWeek = week + weeksInYear(resYear, dow, doy);
  26704. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  26705. resWeek = week - weeksInYear(mom.year(), dow, doy);
  26706. resYear = mom.year() + 1;
  26707. } else {
  26708. resYear = mom.year();
  26709. resWeek = week;
  26710. }
  26711. return {
  26712. week: resWeek,
  26713. year: resYear
  26714. };
  26715. }
  26716. function weeksInYear(year, dow, doy) {
  26717. var weekOffset = firstWeekOffset(year, dow, doy),
  26718. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  26719. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  26720. }
  26721. // FORMATTING
  26722. addFormatToken('w', ['ww', 2], 'wo', 'week');
  26723. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  26724. // ALIASES
  26725. addUnitAlias('week', 'w');
  26726. addUnitAlias('isoWeek', 'W');
  26727. // PRIORITIES
  26728. addUnitPriority('week', 5);
  26729. addUnitPriority('isoWeek', 5);
  26730. // PARSING
  26731. addRegexToken('w', match1to2);
  26732. addRegexToken('ww', match1to2, match2);
  26733. addRegexToken('W', match1to2);
  26734. addRegexToken('WW', match1to2, match2);
  26735. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
  26736. week[token.substr(0, 1)] = toInt(input);
  26737. });
  26738. // HELPERS
  26739. // LOCALES
  26740. function localeWeek (mom) {
  26741. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  26742. }
  26743. var defaultLocaleWeek = {
  26744. dow : 0, // Sunday is the first day of the week.
  26745. doy : 6 // The week that contains Jan 1st is the first week of the year.
  26746. };
  26747. function localeFirstDayOfWeek () {
  26748. return this._week.dow;
  26749. }
  26750. function localeFirstDayOfYear () {
  26751. return this._week.doy;
  26752. }
  26753. // MOMENTS
  26754. function getSetWeek (input) {
  26755. var week = this.localeData().week(this);
  26756. return input == null ? week : this.add((input - week) * 7, 'd');
  26757. }
  26758. function getSetISOWeek (input) {
  26759. var week = weekOfYear(this, 1, 4).week;
  26760. return input == null ? week : this.add((input - week) * 7, 'd');
  26761. }
  26762. // FORMATTING
  26763. addFormatToken('d', 0, 'do', 'day');
  26764. addFormatToken('dd', 0, 0, function (format) {
  26765. return this.localeData().weekdaysMin(this, format);
  26766. });
  26767. addFormatToken('ddd', 0, 0, function (format) {
  26768. return this.localeData().weekdaysShort(this, format);
  26769. });
  26770. addFormatToken('dddd', 0, 0, function (format) {
  26771. return this.localeData().weekdays(this, format);
  26772. });
  26773. addFormatToken('e', 0, 0, 'weekday');
  26774. addFormatToken('E', 0, 0, 'isoWeekday');
  26775. // ALIASES
  26776. addUnitAlias('day', 'd');
  26777. addUnitAlias('weekday', 'e');
  26778. addUnitAlias('isoWeekday', 'E');
  26779. // PRIORITY
  26780. addUnitPriority('day', 11);
  26781. addUnitPriority('weekday', 11);
  26782. addUnitPriority('isoWeekday', 11);
  26783. // PARSING
  26784. addRegexToken('d', match1to2);
  26785. addRegexToken('e', match1to2);
  26786. addRegexToken('E', match1to2);
  26787. addRegexToken('dd', function (isStrict, locale) {
  26788. return locale.weekdaysMinRegex(isStrict);
  26789. });
  26790. addRegexToken('ddd', function (isStrict, locale) {
  26791. return locale.weekdaysShortRegex(isStrict);
  26792. });
  26793. addRegexToken('dddd', function (isStrict, locale) {
  26794. return locale.weekdaysRegex(isStrict);
  26795. });
  26796. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  26797. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  26798. // if we didn't get a weekday name, mark the date as invalid
  26799. if (weekday != null) {
  26800. week.d = weekday;
  26801. } else {
  26802. getParsingFlags(config).invalidWeekday = input;
  26803. }
  26804. });
  26805. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  26806. week[token] = toInt(input);
  26807. });
  26808. // HELPERS
  26809. function parseWeekday(input, locale) {
  26810. if (typeof input !== 'string') {
  26811. return input;
  26812. }
  26813. if (!isNaN(input)) {
  26814. return parseInt(input, 10);
  26815. }
  26816. input = locale.weekdaysParse(input);
  26817. if (typeof input === 'number') {
  26818. return input;
  26819. }
  26820. return null;
  26821. }
  26822. function parseIsoWeekday(input, locale) {
  26823. if (typeof input === 'string') {
  26824. return locale.weekdaysParse(input) % 7 || 7;
  26825. }
  26826. return isNaN(input) ? null : input;
  26827. }
  26828. // LOCALES
  26829. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
  26830. function localeWeekdays (m, format) {
  26831. if (!m) {
  26832. return isArray(this._weekdays) ? this._weekdays :
  26833. this._weekdays['standalone'];
  26834. }
  26835. return isArray(this._weekdays) ? this._weekdays[m.day()] :
  26836. this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()];
  26837. }
  26838. var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
  26839. function localeWeekdaysShort (m) {
  26840. return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
  26841. }
  26842. var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
  26843. function localeWeekdaysMin (m) {
  26844. return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
  26845. }
  26846. function handleStrictParse$1(weekdayName, format, strict) {
  26847. var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
  26848. if (!this._weekdaysParse) {
  26849. this._weekdaysParse = [];
  26850. this._shortWeekdaysParse = [];
  26851. this._minWeekdaysParse = [];
  26852. for (i = 0; i < 7; ++i) {
  26853. mom = createUTC([2000, 1]).day(i);
  26854. this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
  26855. this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
  26856. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  26857. }
  26858. }
  26859. if (strict) {
  26860. if (format === 'dddd') {
  26861. ii = indexOf.call(this._weekdaysParse, llc);
  26862. return ii !== -1 ? ii : null;
  26863. } else if (format === 'ddd') {
  26864. ii = indexOf.call(this._shortWeekdaysParse, llc);
  26865. return ii !== -1 ? ii : null;
  26866. } else {
  26867. ii = indexOf.call(this._minWeekdaysParse, llc);
  26868. return ii !== -1 ? ii : null;
  26869. }
  26870. } else {
  26871. if (format === 'dddd') {
  26872. ii = indexOf.call(this._weekdaysParse, llc);
  26873. if (ii !== -1) {
  26874. return ii;
  26875. }
  26876. ii = indexOf.call(this._shortWeekdaysParse, llc);
  26877. if (ii !== -1) {
  26878. return ii;
  26879. }
  26880. ii = indexOf.call(this._minWeekdaysParse, llc);
  26881. return ii !== -1 ? ii : null;
  26882. } else if (format === 'ddd') {
  26883. ii = indexOf.call(this._shortWeekdaysParse, llc);
  26884. if (ii !== -1) {
  26885. return ii;
  26886. }
  26887. ii = indexOf.call(this._weekdaysParse, llc);
  26888. if (ii !== -1) {
  26889. return ii;
  26890. }
  26891. ii = indexOf.call(this._minWeekdaysParse, llc);
  26892. return ii !== -1 ? ii : null;
  26893. } else {
  26894. ii = indexOf.call(this._minWeekdaysParse, llc);
  26895. if (ii !== -1) {
  26896. return ii;
  26897. }
  26898. ii = indexOf.call(this._weekdaysParse, llc);
  26899. if (ii !== -1) {
  26900. return ii;
  26901. }
  26902. ii = indexOf.call(this._shortWeekdaysParse, llc);
  26903. return ii !== -1 ? ii : null;
  26904. }
  26905. }
  26906. }
  26907. function localeWeekdaysParse (weekdayName, format, strict) {
  26908. var i, mom, regex;
  26909. if (this._weekdaysParseExact) {
  26910. return handleStrictParse$1.call(this, weekdayName, format, strict);
  26911. }
  26912. if (!this._weekdaysParse) {
  26913. this._weekdaysParse = [];
  26914. this._minWeekdaysParse = [];
  26915. this._shortWeekdaysParse = [];
  26916. this._fullWeekdaysParse = [];
  26917. }
  26918. for (i = 0; i < 7; i++) {
  26919. // make the regex if we don't have it already
  26920. mom = createUTC([2000, 1]).day(i);
  26921. if (strict && !this._fullWeekdaysParse[i]) {
  26922. this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i');
  26923. this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i');
  26924. this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i');
  26925. }
  26926. if (!this._weekdaysParse[i]) {
  26927. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  26928. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  26929. }
  26930. // test the regex
  26931. if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
  26932. return i;
  26933. } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
  26934. return i;
  26935. } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
  26936. return i;
  26937. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  26938. return i;
  26939. }
  26940. }
  26941. }
  26942. // MOMENTS
  26943. function getSetDayOfWeek (input) {
  26944. if (!this.isValid()) {
  26945. return input != null ? this : NaN;
  26946. }
  26947. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  26948. if (input != null) {
  26949. input = parseWeekday(input, this.localeData());
  26950. return this.add(input - day, 'd');
  26951. } else {
  26952. return day;
  26953. }
  26954. }
  26955. function getSetLocaleDayOfWeek (input) {
  26956. if (!this.isValid()) {
  26957. return input != null ? this : NaN;
  26958. }
  26959. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  26960. return input == null ? weekday : this.add(input - weekday, 'd');
  26961. }
  26962. function getSetISODayOfWeek (input) {
  26963. if (!this.isValid()) {
  26964. return input != null ? this : NaN;
  26965. }
  26966. // behaves the same as moment#day except
  26967. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  26968. // as a setter, sunday should belong to the previous week.
  26969. if (input != null) {
  26970. var weekday = parseIsoWeekday(input, this.localeData());
  26971. return this.day(this.day() % 7 ? weekday : weekday - 7);
  26972. } else {
  26973. return this.day() || 7;
  26974. }
  26975. }
  26976. var defaultWeekdaysRegex = matchWord;
  26977. function weekdaysRegex (isStrict) {
  26978. if (this._weekdaysParseExact) {
  26979. if (!hasOwnProp(this, '_weekdaysRegex')) {
  26980. computeWeekdaysParse.call(this);
  26981. }
  26982. if (isStrict) {
  26983. return this._weekdaysStrictRegex;
  26984. } else {
  26985. return this._weekdaysRegex;
  26986. }
  26987. } else {
  26988. if (!hasOwnProp(this, '_weekdaysRegex')) {
  26989. this._weekdaysRegex = defaultWeekdaysRegex;
  26990. }
  26991. return this._weekdaysStrictRegex && isStrict ?
  26992. this._weekdaysStrictRegex : this._weekdaysRegex;
  26993. }
  26994. }
  26995. var defaultWeekdaysShortRegex = matchWord;
  26996. function weekdaysShortRegex (isStrict) {
  26997. if (this._weekdaysParseExact) {
  26998. if (!hasOwnProp(this, '_weekdaysRegex')) {
  26999. computeWeekdaysParse.call(this);
  27000. }
  27001. if (isStrict) {
  27002. return this._weekdaysShortStrictRegex;
  27003. } else {
  27004. return this._weekdaysShortRegex;
  27005. }
  27006. } else {
  27007. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  27008. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  27009. }
  27010. return this._weekdaysShortStrictRegex && isStrict ?
  27011. this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
  27012. }
  27013. }
  27014. var defaultWeekdaysMinRegex = matchWord;
  27015. function weekdaysMinRegex (isStrict) {
  27016. if (this._weekdaysParseExact) {
  27017. if (!hasOwnProp(this, '_weekdaysRegex')) {
  27018. computeWeekdaysParse.call(this);
  27019. }
  27020. if (isStrict) {
  27021. return this._weekdaysMinStrictRegex;
  27022. } else {
  27023. return this._weekdaysMinRegex;
  27024. }
  27025. } else {
  27026. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  27027. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  27028. }
  27029. return this._weekdaysMinStrictRegex && isStrict ?
  27030. this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
  27031. }
  27032. }
  27033. function computeWeekdaysParse () {
  27034. function cmpLenRev(a, b) {
  27035. return b.length - a.length;
  27036. }
  27037. var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
  27038. i, mom, minp, shortp, longp;
  27039. for (i = 0; i < 7; i++) {
  27040. // make the regex if we don't have it already
  27041. mom = createUTC([2000, 1]).day(i);
  27042. minp = this.weekdaysMin(mom, '');
  27043. shortp = this.weekdaysShort(mom, '');
  27044. longp = this.weekdays(mom, '');
  27045. minPieces.push(minp);
  27046. shortPieces.push(shortp);
  27047. longPieces.push(longp);
  27048. mixedPieces.push(minp);
  27049. mixedPieces.push(shortp);
  27050. mixedPieces.push(longp);
  27051. }
  27052. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  27053. // will match the longer piece.
  27054. minPieces.sort(cmpLenRev);
  27055. shortPieces.sort(cmpLenRev);
  27056. longPieces.sort(cmpLenRev);
  27057. mixedPieces.sort(cmpLenRev);
  27058. for (i = 0; i < 7; i++) {
  27059. shortPieces[i] = regexEscape(shortPieces[i]);
  27060. longPieces[i] = regexEscape(longPieces[i]);
  27061. mixedPieces[i] = regexEscape(mixedPieces[i]);
  27062. }
  27063. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  27064. this._weekdaysShortRegex = this._weekdaysRegex;
  27065. this._weekdaysMinRegex = this._weekdaysRegex;
  27066. this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  27067. this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  27068. this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
  27069. }
  27070. // FORMATTING
  27071. function hFormat() {
  27072. return this.hours() % 12 || 12;
  27073. }
  27074. function kFormat() {
  27075. return this.hours() || 24;
  27076. }
  27077. addFormatToken('H', ['HH', 2], 0, 'hour');
  27078. addFormatToken('h', ['hh', 2], 0, hFormat);
  27079. addFormatToken('k', ['kk', 2], 0, kFormat);
  27080. addFormatToken('hmm', 0, 0, function () {
  27081. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  27082. });
  27083. addFormatToken('hmmss', 0, 0, function () {
  27084. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
  27085. zeroFill(this.seconds(), 2);
  27086. });
  27087. addFormatToken('Hmm', 0, 0, function () {
  27088. return '' + this.hours() + zeroFill(this.minutes(), 2);
  27089. });
  27090. addFormatToken('Hmmss', 0, 0, function () {
  27091. return '' + this.hours() + zeroFill(this.minutes(), 2) +
  27092. zeroFill(this.seconds(), 2);
  27093. });
  27094. function meridiem (token, lowercase) {
  27095. addFormatToken(token, 0, 0, function () {
  27096. return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
  27097. });
  27098. }
  27099. meridiem('a', true);
  27100. meridiem('A', false);
  27101. // ALIASES
  27102. addUnitAlias('hour', 'h');
  27103. // PRIORITY
  27104. addUnitPriority('hour', 13);
  27105. // PARSING
  27106. function matchMeridiem (isStrict, locale) {
  27107. return locale._meridiemParse;
  27108. }
  27109. addRegexToken('a', matchMeridiem);
  27110. addRegexToken('A', matchMeridiem);
  27111. addRegexToken('H', match1to2);
  27112. addRegexToken('h', match1to2);
  27113. addRegexToken('k', match1to2);
  27114. addRegexToken('HH', match1to2, match2);
  27115. addRegexToken('hh', match1to2, match2);
  27116. addRegexToken('kk', match1to2, match2);
  27117. addRegexToken('hmm', match3to4);
  27118. addRegexToken('hmmss', match5to6);
  27119. addRegexToken('Hmm', match3to4);
  27120. addRegexToken('Hmmss', match5to6);
  27121. addParseToken(['H', 'HH'], HOUR);
  27122. addParseToken(['k', 'kk'], function (input, array, config) {
  27123. var kInput = toInt(input);
  27124. array[HOUR] = kInput === 24 ? 0 : kInput;
  27125. });
  27126. addParseToken(['a', 'A'], function (input, array, config) {
  27127. config._isPm = config._locale.isPM(input);
  27128. config._meridiem = input;
  27129. });
  27130. addParseToken(['h', 'hh'], function (input, array, config) {
  27131. array[HOUR] = toInt(input);
  27132. getParsingFlags(config).bigHour = true;
  27133. });
  27134. addParseToken('hmm', function (input, array, config) {
  27135. var pos = input.length - 2;
  27136. array[HOUR] = toInt(input.substr(0, pos));
  27137. array[MINUTE] = toInt(input.substr(pos));
  27138. getParsingFlags(config).bigHour = true;
  27139. });
  27140. addParseToken('hmmss', function (input, array, config) {
  27141. var pos1 = input.length - 4;
  27142. var pos2 = input.length - 2;
  27143. array[HOUR] = toInt(input.substr(0, pos1));
  27144. array[MINUTE] = toInt(input.substr(pos1, 2));
  27145. array[SECOND] = toInt(input.substr(pos2));
  27146. getParsingFlags(config).bigHour = true;
  27147. });
  27148. addParseToken('Hmm', function (input, array, config) {
  27149. var pos = input.length - 2;
  27150. array[HOUR] = toInt(input.substr(0, pos));
  27151. array[MINUTE] = toInt(input.substr(pos));
  27152. });
  27153. addParseToken('Hmmss', function (input, array, config) {
  27154. var pos1 = input.length - 4;
  27155. var pos2 = input.length - 2;
  27156. array[HOUR] = toInt(input.substr(0, pos1));
  27157. array[MINUTE] = toInt(input.substr(pos1, 2));
  27158. array[SECOND] = toInt(input.substr(pos2));
  27159. });
  27160. // LOCALES
  27161. function localeIsPM (input) {
  27162. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  27163. // Using charAt should be more compatible.
  27164. return ((input + '').toLowerCase().charAt(0) === 'p');
  27165. }
  27166. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
  27167. function localeMeridiem (hours, minutes, isLower) {
  27168. if (hours > 11) {
  27169. return isLower ? 'pm' : 'PM';
  27170. } else {
  27171. return isLower ? 'am' : 'AM';
  27172. }
  27173. }
  27174. // MOMENTS
  27175. // Setting the hour should keep the time, because the user explicitly
  27176. // specified which hour he wants. So trying to maintain the same hour (in
  27177. // a new timezone) makes sense. Adding/subtracting hours does not follow
  27178. // this rule.
  27179. var getSetHour = makeGetSet('Hours', true);
  27180. // months
  27181. // week
  27182. // weekdays
  27183. // meridiem
  27184. var baseConfig = {
  27185. calendar: defaultCalendar,
  27186. longDateFormat: defaultLongDateFormat,
  27187. invalidDate: defaultInvalidDate,
  27188. ordinal: defaultOrdinal,
  27189. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  27190. relativeTime: defaultRelativeTime,
  27191. months: defaultLocaleMonths,
  27192. monthsShort: defaultLocaleMonthsShort,
  27193. week: defaultLocaleWeek,
  27194. weekdays: defaultLocaleWeekdays,
  27195. weekdaysMin: defaultLocaleWeekdaysMin,
  27196. weekdaysShort: defaultLocaleWeekdaysShort,
  27197. meridiemParse: defaultLocaleMeridiemParse
  27198. };
  27199. // internal storage for locale config files
  27200. var locales = {};
  27201. var localeFamilies = {};
  27202. var globalLocale;
  27203. function normalizeLocale(key) {
  27204. return key ? key.toLowerCase().replace('_', '-') : key;
  27205. }
  27206. // pick the locale from the array
  27207. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  27208. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  27209. function chooseLocale(names) {
  27210. var i = 0, j, next, locale, split;
  27211. while (i < names.length) {
  27212. split = normalizeLocale(names[i]).split('-');
  27213. j = split.length;
  27214. next = normalizeLocale(names[i + 1]);
  27215. next = next ? next.split('-') : null;
  27216. while (j > 0) {
  27217. locale = loadLocale(split.slice(0, j).join('-'));
  27218. if (locale) {
  27219. return locale;
  27220. }
  27221. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  27222. //the next array item is better than a shallower substring of this one
  27223. break;
  27224. }
  27225. j--;
  27226. }
  27227. i++;
  27228. }
  27229. return null;
  27230. }
  27231. function loadLocale(name) {
  27232. var oldLocale = null;
  27233. // TODO: Find a better way to register and load all the locales in Node
  27234. if (!locales[name] && (typeof module !== 'undefined') &&
  27235. module && module.exports) {
  27236. try {
  27237. oldLocale = globalLocale._abbr;
  27238. var aliasedRequire = require;
  27239. !(function webpackMissingModule() { var e = new Error("Cannot find module \"./locale\""); e.code = 'MODULE_NOT_FOUND'; throw e; }());
  27240. getSetGlobalLocale(oldLocale);
  27241. } catch (e) {}
  27242. }
  27243. return locales[name];
  27244. }
  27245. // This function will load locale and then set the global locale. If
  27246. // no arguments are passed in, it will simply return the current global
  27247. // locale key.
  27248. function getSetGlobalLocale (key, values) {
  27249. var data;
  27250. if (key) {
  27251. if (isUndefined(values)) {
  27252. data = getLocale(key);
  27253. }
  27254. else {
  27255. data = defineLocale(key, values);
  27256. }
  27257. if (data) {
  27258. // moment.duration._locale = moment._locale = data;
  27259. globalLocale = data;
  27260. }
  27261. }
  27262. return globalLocale._abbr;
  27263. }
  27264. function defineLocale (name, config) {
  27265. if (config !== null) {
  27266. var parentConfig = baseConfig;
  27267. config.abbr = name;
  27268. if (locales[name] != null) {
  27269. deprecateSimple('defineLocaleOverride',
  27270. 'use moment.updateLocale(localeName, config) to change ' +
  27271. 'an existing locale. moment.defineLocale(localeName, ' +
  27272. 'config) should only be used for creating a new locale ' +
  27273. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
  27274. parentConfig = locales[name]._config;
  27275. } else if (config.parentLocale != null) {
  27276. if (locales[config.parentLocale] != null) {
  27277. parentConfig = locales[config.parentLocale]._config;
  27278. } else {
  27279. if (!localeFamilies[config.parentLocale]) {
  27280. localeFamilies[config.parentLocale] = [];
  27281. }
  27282. localeFamilies[config.parentLocale].push({
  27283. name: name,
  27284. config: config
  27285. });
  27286. return null;
  27287. }
  27288. }
  27289. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  27290. if (localeFamilies[name]) {
  27291. localeFamilies[name].forEach(function (x) {
  27292. defineLocale(x.name, x.config);
  27293. });
  27294. }
  27295. // backwards compat for now: also set the locale
  27296. // make sure we set the locale AFTER all child locales have been
  27297. // created, so we won't end up with the child locale set.
  27298. getSetGlobalLocale(name);
  27299. return locales[name];
  27300. } else {
  27301. // useful for testing
  27302. delete locales[name];
  27303. return null;
  27304. }
  27305. }
  27306. function updateLocale(name, config) {
  27307. if (config != null) {
  27308. var locale, parentConfig = baseConfig;
  27309. // MERGE
  27310. if (locales[name] != null) {
  27311. parentConfig = locales[name]._config;
  27312. }
  27313. config = mergeConfigs(parentConfig, config);
  27314. locale = new Locale(config);
  27315. locale.parentLocale = locales[name];
  27316. locales[name] = locale;
  27317. // backwards compat for now: also set the locale
  27318. getSetGlobalLocale(name);
  27319. } else {
  27320. // pass null for config to unupdate, useful for tests
  27321. if (locales[name] != null) {
  27322. if (locales[name].parentLocale != null) {
  27323. locales[name] = locales[name].parentLocale;
  27324. } else if (locales[name] != null) {
  27325. delete locales[name];
  27326. }
  27327. }
  27328. }
  27329. return locales[name];
  27330. }
  27331. // returns locale data
  27332. function getLocale (key) {
  27333. var locale;
  27334. if (key && key._locale && key._locale._abbr) {
  27335. key = key._locale._abbr;
  27336. }
  27337. if (!key) {
  27338. return globalLocale;
  27339. }
  27340. if (!isArray(key)) {
  27341. //short-circuit everything else
  27342. locale = loadLocale(key);
  27343. if (locale) {
  27344. return locale;
  27345. }
  27346. key = [key];
  27347. }
  27348. return chooseLocale(key);
  27349. }
  27350. function listLocales() {
  27351. return keys(locales);
  27352. }
  27353. function checkOverflow (m) {
  27354. var overflow;
  27355. var a = m._a;
  27356. if (a && getParsingFlags(m).overflow === -2) {
  27357. overflow =
  27358. a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
  27359. a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
  27360. a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
  27361. a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
  27362. a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
  27363. a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
  27364. -1;
  27365. if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  27366. overflow = DATE;
  27367. }
  27368. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  27369. overflow = WEEK;
  27370. }
  27371. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  27372. overflow = WEEKDAY;
  27373. }
  27374. getParsingFlags(m).overflow = overflow;
  27375. }
  27376. return m;
  27377. }
  27378. // Pick the first defined of two or three arguments.
  27379. function defaults(a, b, c) {
  27380. if (a != null) {
  27381. return a;
  27382. }
  27383. if (b != null) {
  27384. return b;
  27385. }
  27386. return c;
  27387. }
  27388. function currentDateArray(config) {
  27389. // hooks is actually the exported moment object
  27390. var nowValue = new Date(hooks.now());
  27391. if (config._useUTC) {
  27392. return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
  27393. }
  27394. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  27395. }
  27396. // convert an array to a date.
  27397. // the array should mirror the parameters below
  27398. // note: all values past the year are optional and will default to the lowest possible value.
  27399. // [year, month, day , hour, minute, second, millisecond]
  27400. function configFromArray (config) {
  27401. var i, date, input = [], currentDate, yearToUse;
  27402. if (config._d) {
  27403. return;
  27404. }
  27405. currentDate = currentDateArray(config);
  27406. //compute day of the year from weeks and weekdays
  27407. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  27408. dayOfYearFromWeekInfo(config);
  27409. }
  27410. //if the day of the year is set, figure out what it is
  27411. if (config._dayOfYear != null) {
  27412. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  27413. if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
  27414. getParsingFlags(config)._overflowDayOfYear = true;
  27415. }
  27416. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  27417. config._a[MONTH] = date.getUTCMonth();
  27418. config._a[DATE] = date.getUTCDate();
  27419. }
  27420. // Default to current date.
  27421. // * if no year, month, day of month are given, default to today
  27422. // * if day of month is given, default month and year
  27423. // * if month is given, default only year
  27424. // * if year is given, don't default anything
  27425. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  27426. config._a[i] = input[i] = currentDate[i];
  27427. }
  27428. // Zero out whatever was not defaulted, including time
  27429. for (; i < 7; i++) {
  27430. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  27431. }
  27432. // Check for 24:00:00.000
  27433. if (config._a[HOUR] === 24 &&
  27434. config._a[MINUTE] === 0 &&
  27435. config._a[SECOND] === 0 &&
  27436. config._a[MILLISECOND] === 0) {
  27437. config._nextDay = true;
  27438. config._a[HOUR] = 0;
  27439. }
  27440. config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
  27441. // Apply timezone offset from input. The actual utcOffset can be changed
  27442. // with parseZone.
  27443. if (config._tzm != null) {
  27444. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  27445. }
  27446. if (config._nextDay) {
  27447. config._a[HOUR] = 24;
  27448. }
  27449. // check for mismatching day of week
  27450. if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== config._d.getDay()) {
  27451. getParsingFlags(config).weekdayMismatch = true;
  27452. }
  27453. }
  27454. function dayOfYearFromWeekInfo(config) {
  27455. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
  27456. w = config._w;
  27457. if (w.GG != null || w.W != null || w.E != null) {
  27458. dow = 1;
  27459. doy = 4;
  27460. // TODO: We need to take the current isoWeekYear, but that depends on
  27461. // how we interpret now (local, utc, fixed offset). So create
  27462. // a now version of current config (take local/utc/offset flags, and
  27463. // create now).
  27464. weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
  27465. week = defaults(w.W, 1);
  27466. weekday = defaults(w.E, 1);
  27467. if (weekday < 1 || weekday > 7) {
  27468. weekdayOverflow = true;
  27469. }
  27470. } else {
  27471. dow = config._locale._week.dow;
  27472. doy = config._locale._week.doy;
  27473. var curWeek = weekOfYear(createLocal(), dow, doy);
  27474. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  27475. // Default to current week.
  27476. week = defaults(w.w, curWeek.week);
  27477. if (w.d != null) {
  27478. // weekday -- low day numbers are considered next week
  27479. weekday = w.d;
  27480. if (weekday < 0 || weekday > 6) {
  27481. weekdayOverflow = true;
  27482. }
  27483. } else if (w.e != null) {
  27484. // local weekday -- counting starts from begining of week
  27485. weekday = w.e + dow;
  27486. if (w.e < 0 || w.e > 6) {
  27487. weekdayOverflow = true;
  27488. }
  27489. } else {
  27490. // default to begining of week
  27491. weekday = dow;
  27492. }
  27493. }
  27494. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  27495. getParsingFlags(config)._overflowWeeks = true;
  27496. } else if (weekdayOverflow != null) {
  27497. getParsingFlags(config)._overflowWeekday = true;
  27498. } else {
  27499. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  27500. config._a[YEAR] = temp.year;
  27501. config._dayOfYear = temp.dayOfYear;
  27502. }
  27503. }
  27504. // iso 8601 regex
  27505. // 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)
  27506. 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)?)?$/;
  27507. 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)?)?$/;
  27508. var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
  27509. var isoDates = [
  27510. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  27511. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  27512. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  27513. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  27514. ['YYYY-DDD', /\d{4}-\d{3}/],
  27515. ['YYYY-MM', /\d{4}-\d\d/, false],
  27516. ['YYYYYYMMDD', /[+-]\d{10}/],
  27517. ['YYYYMMDD', /\d{8}/],
  27518. // YYYYMM is NOT allowed by the standard
  27519. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  27520. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  27521. ['YYYYDDD', /\d{7}/]
  27522. ];
  27523. // iso time formats and regexes
  27524. var isoTimes = [
  27525. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  27526. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  27527. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  27528. ['HH:mm', /\d\d:\d\d/],
  27529. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  27530. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  27531. ['HHmmss', /\d\d\d\d\d\d/],
  27532. ['HHmm', /\d\d\d\d/],
  27533. ['HH', /\d\d/]
  27534. ];
  27535. var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
  27536. // date from iso format
  27537. function configFromISO(config) {
  27538. var i, l,
  27539. string = config._i,
  27540. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  27541. allowTime, dateFormat, timeFormat, tzFormat;
  27542. if (match) {
  27543. getParsingFlags(config).iso = true;
  27544. for (i = 0, l = isoDates.length; i < l; i++) {
  27545. if (isoDates[i][1].exec(match[1])) {
  27546. dateFormat = isoDates[i][0];
  27547. allowTime = isoDates[i][2] !== false;
  27548. break;
  27549. }
  27550. }
  27551. if (dateFormat == null) {
  27552. config._isValid = false;
  27553. return;
  27554. }
  27555. if (match[3]) {
  27556. for (i = 0, l = isoTimes.length; i < l; i++) {
  27557. if (isoTimes[i][1].exec(match[3])) {
  27558. // match[2] should be 'T' or space
  27559. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  27560. break;
  27561. }
  27562. }
  27563. if (timeFormat == null) {
  27564. config._isValid = false;
  27565. return;
  27566. }
  27567. }
  27568. if (!allowTime && timeFormat != null) {
  27569. config._isValid = false;
  27570. return;
  27571. }
  27572. if (match[4]) {
  27573. if (tzRegex.exec(match[4])) {
  27574. tzFormat = 'Z';
  27575. } else {
  27576. config._isValid = false;
  27577. return;
  27578. }
  27579. }
  27580. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  27581. configFromStringAndFormat(config);
  27582. } else {
  27583. config._isValid = false;
  27584. }
  27585. }
  27586. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  27587. var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;
  27588. function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
  27589. var result = [
  27590. untruncateYear(yearStr),
  27591. defaultLocaleMonthsShort.indexOf(monthStr),
  27592. parseInt(dayStr, 10),
  27593. parseInt(hourStr, 10),
  27594. parseInt(minuteStr, 10)
  27595. ];
  27596. if (secondStr) {
  27597. result.push(parseInt(secondStr, 10));
  27598. }
  27599. return result;
  27600. }
  27601. function untruncateYear(yearStr) {
  27602. var year = parseInt(yearStr, 10);
  27603. if (year <= 49) {
  27604. return 2000 + year;
  27605. } else if (year <= 999) {
  27606. return 1900 + year;
  27607. }
  27608. return year;
  27609. }
  27610. function preprocessRFC2822(s) {
  27611. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  27612. return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').trim();
  27613. }
  27614. function checkWeekday(weekdayStr, parsedInput, config) {
  27615. if (weekdayStr) {
  27616. // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
  27617. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  27618. weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
  27619. if (weekdayProvided !== weekdayActual) {
  27620. getParsingFlags(config).weekdayMismatch = true;
  27621. config._isValid = false;
  27622. return false;
  27623. }
  27624. }
  27625. return true;
  27626. }
  27627. var obsOffsets = {
  27628. UT: 0,
  27629. GMT: 0,
  27630. EDT: -4 * 60,
  27631. EST: -5 * 60,
  27632. CDT: -5 * 60,
  27633. CST: -6 * 60,
  27634. MDT: -6 * 60,
  27635. MST: -7 * 60,
  27636. PDT: -7 * 60,
  27637. PST: -8 * 60
  27638. };
  27639. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  27640. if (obsOffset) {
  27641. return obsOffsets[obsOffset];
  27642. } else if (militaryOffset) {
  27643. // the only allowed military tz is Z
  27644. return 0;
  27645. } else {
  27646. var hm = parseInt(numOffset, 10);
  27647. var m = hm % 100, h = (hm - m) / 100;
  27648. return h * 60 + m;
  27649. }
  27650. }
  27651. // date and time from ref 2822 format
  27652. function configFromRFC2822(config) {
  27653. var match = rfc2822.exec(preprocessRFC2822(config._i));
  27654. if (match) {
  27655. var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
  27656. if (!checkWeekday(match[1], parsedArray, config)) {
  27657. return;
  27658. }
  27659. config._a = parsedArray;
  27660. config._tzm = calculateOffset(match[8], match[9], match[10]);
  27661. config._d = createUTCDate.apply(null, config._a);
  27662. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  27663. getParsingFlags(config).rfc2822 = true;
  27664. } else {
  27665. config._isValid = false;
  27666. }
  27667. }
  27668. // date from iso format or fallback
  27669. function configFromString(config) {
  27670. var matched = aspNetJsonRegex.exec(config._i);
  27671. if (matched !== null) {
  27672. config._d = new Date(+matched[1]);
  27673. return;
  27674. }
  27675. configFromISO(config);
  27676. if (config._isValid === false) {
  27677. delete config._isValid;
  27678. } else {
  27679. return;
  27680. }
  27681. configFromRFC2822(config);
  27682. if (config._isValid === false) {
  27683. delete config._isValid;
  27684. } else {
  27685. return;
  27686. }
  27687. // Final attempt, use Input Fallback
  27688. hooks.createFromInputFallback(config);
  27689. }
  27690. hooks.createFromInputFallback = deprecate(
  27691. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  27692. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  27693. 'discouraged and will be removed in an upcoming major release. Please refer to ' +
  27694. 'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  27695. function (config) {
  27696. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  27697. }
  27698. );
  27699. // constant that refers to the ISO standard
  27700. hooks.ISO_8601 = function () {};
  27701. // constant that refers to the RFC 2822 form
  27702. hooks.RFC_2822 = function () {};
  27703. // date from string and format string
  27704. function configFromStringAndFormat(config) {
  27705. // TODO: Move this to another part of the creation flow to prevent circular deps
  27706. if (config._f === hooks.ISO_8601) {
  27707. configFromISO(config);
  27708. return;
  27709. }
  27710. if (config._f === hooks.RFC_2822) {
  27711. configFromRFC2822(config);
  27712. return;
  27713. }
  27714. config._a = [];
  27715. getParsingFlags(config).empty = true;
  27716. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  27717. var string = '' + config._i,
  27718. i, parsedInput, tokens, token, skipped,
  27719. stringLength = string.length,
  27720. totalParsedInputLength = 0;
  27721. tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
  27722. for (i = 0; i < tokens.length; i++) {
  27723. token = tokens[i];
  27724. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  27725. // console.log('token', token, 'parsedInput', parsedInput,
  27726. // 'regex', getParseRegexForToken(token, config));
  27727. if (parsedInput) {
  27728. skipped = string.substr(0, string.indexOf(parsedInput));
  27729. if (skipped.length > 0) {
  27730. getParsingFlags(config).unusedInput.push(skipped);
  27731. }
  27732. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  27733. totalParsedInputLength += parsedInput.length;
  27734. }
  27735. // don't parse if it's not a known token
  27736. if (formatTokenFunctions[token]) {
  27737. if (parsedInput) {
  27738. getParsingFlags(config).empty = false;
  27739. }
  27740. else {
  27741. getParsingFlags(config).unusedTokens.push(token);
  27742. }
  27743. addTimeToArrayFromToken(token, parsedInput, config);
  27744. }
  27745. else if (config._strict && !parsedInput) {
  27746. getParsingFlags(config).unusedTokens.push(token);
  27747. }
  27748. }
  27749. // add remaining unparsed input length to the string
  27750. getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
  27751. if (string.length > 0) {
  27752. getParsingFlags(config).unusedInput.push(string);
  27753. }
  27754. // clear _12h flag if hour is <= 12
  27755. if (config._a[HOUR] <= 12 &&
  27756. getParsingFlags(config).bigHour === true &&
  27757. config._a[HOUR] > 0) {
  27758. getParsingFlags(config).bigHour = undefined;
  27759. }
  27760. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  27761. getParsingFlags(config).meridiem = config._meridiem;
  27762. // handle meridiem
  27763. config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
  27764. configFromArray(config);
  27765. checkOverflow(config);
  27766. }
  27767. function meridiemFixWrap (locale, hour, meridiem) {
  27768. var isPm;
  27769. if (meridiem == null) {
  27770. // nothing to do
  27771. return hour;
  27772. }
  27773. if (locale.meridiemHour != null) {
  27774. return locale.meridiemHour(hour, meridiem);
  27775. } else if (locale.isPM != null) {
  27776. // Fallback
  27777. isPm = locale.isPM(meridiem);
  27778. if (isPm && hour < 12) {
  27779. hour += 12;
  27780. }
  27781. if (!isPm && hour === 12) {
  27782. hour = 0;
  27783. }
  27784. return hour;
  27785. } else {
  27786. // this is not supposed to happen
  27787. return hour;
  27788. }
  27789. }
  27790. // date from string and array of format strings
  27791. function configFromStringAndArray(config) {
  27792. var tempConfig,
  27793. bestMoment,
  27794. scoreToBeat,
  27795. i,
  27796. currentScore;
  27797. if (config._f.length === 0) {
  27798. getParsingFlags(config).invalidFormat = true;
  27799. config._d = new Date(NaN);
  27800. return;
  27801. }
  27802. for (i = 0; i < config._f.length; i++) {
  27803. currentScore = 0;
  27804. tempConfig = copyConfig({}, config);
  27805. if (config._useUTC != null) {
  27806. tempConfig._useUTC = config._useUTC;
  27807. }
  27808. tempConfig._f = config._f[i];
  27809. configFromStringAndFormat(tempConfig);
  27810. if (!isValid(tempConfig)) {
  27811. continue;
  27812. }
  27813. // if there is any input that was not parsed add a penalty for that format
  27814. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  27815. //or tokens
  27816. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  27817. getParsingFlags(tempConfig).score = currentScore;
  27818. if (scoreToBeat == null || currentScore < scoreToBeat) {
  27819. scoreToBeat = currentScore;
  27820. bestMoment = tempConfig;
  27821. }
  27822. }
  27823. extend(config, bestMoment || tempConfig);
  27824. }
  27825. function configFromObject(config) {
  27826. if (config._d) {
  27827. return;
  27828. }
  27829. var i = normalizeObjectUnits(config._i);
  27830. config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
  27831. return obj && parseInt(obj, 10);
  27832. });
  27833. configFromArray(config);
  27834. }
  27835. function createFromConfig (config) {
  27836. var res = new Moment(checkOverflow(prepareConfig(config)));
  27837. if (res._nextDay) {
  27838. // Adding is smart enough around DST
  27839. res.add(1, 'd');
  27840. res._nextDay = undefined;
  27841. }
  27842. return res;
  27843. }
  27844. function prepareConfig (config) {
  27845. var input = config._i,
  27846. format = config._f;
  27847. config._locale = config._locale || getLocale(config._l);
  27848. if (input === null || (format === undefined && input === '')) {
  27849. return createInvalid({nullInput: true});
  27850. }
  27851. if (typeof input === 'string') {
  27852. config._i = input = config._locale.preparse(input);
  27853. }
  27854. if (isMoment(input)) {
  27855. return new Moment(checkOverflow(input));
  27856. } else if (isDate(input)) {
  27857. config._d = input;
  27858. } else if (isArray(format)) {
  27859. configFromStringAndArray(config);
  27860. } else if (format) {
  27861. configFromStringAndFormat(config);
  27862. } else {
  27863. configFromInput(config);
  27864. }
  27865. if (!isValid(config)) {
  27866. config._d = null;
  27867. }
  27868. return config;
  27869. }
  27870. function configFromInput(config) {
  27871. var input = config._i;
  27872. if (isUndefined(input)) {
  27873. config._d = new Date(hooks.now());
  27874. } else if (isDate(input)) {
  27875. config._d = new Date(input.valueOf());
  27876. } else if (typeof input === 'string') {
  27877. configFromString(config);
  27878. } else if (isArray(input)) {
  27879. config._a = map(input.slice(0), function (obj) {
  27880. return parseInt(obj, 10);
  27881. });
  27882. configFromArray(config);
  27883. } else if (isObject(input)) {
  27884. configFromObject(config);
  27885. } else if (isNumber(input)) {
  27886. // from milliseconds
  27887. config._d = new Date(input);
  27888. } else {
  27889. hooks.createFromInputFallback(config);
  27890. }
  27891. }
  27892. function createLocalOrUTC (input, format, locale, strict, isUTC) {
  27893. var c = {};
  27894. if (locale === true || locale === false) {
  27895. strict = locale;
  27896. locale = undefined;
  27897. }
  27898. if ((isObject(input) && isObjectEmpty(input)) ||
  27899. (isArray(input) && input.length === 0)) {
  27900. input = undefined;
  27901. }
  27902. // object construction must be done this way.
  27903. // https://github.com/moment/moment/issues/1423
  27904. c._isAMomentObject = true;
  27905. c._useUTC = c._isUTC = isUTC;
  27906. c._l = locale;
  27907. c._i = input;
  27908. c._f = format;
  27909. c._strict = strict;
  27910. return createFromConfig(c);
  27911. }
  27912. function createLocal (input, format, locale, strict) {
  27913. return createLocalOrUTC(input, format, locale, strict, false);
  27914. }
  27915. var prototypeMin = deprecate(
  27916. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  27917. function () {
  27918. var other = createLocal.apply(null, arguments);
  27919. if (this.isValid() && other.isValid()) {
  27920. return other < this ? this : other;
  27921. } else {
  27922. return createInvalid();
  27923. }
  27924. }
  27925. );
  27926. var prototypeMax = deprecate(
  27927. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  27928. function () {
  27929. var other = createLocal.apply(null, arguments);
  27930. if (this.isValid() && other.isValid()) {
  27931. return other > this ? this : other;
  27932. } else {
  27933. return createInvalid();
  27934. }
  27935. }
  27936. );
  27937. // Pick a moment m from moments so that m[fn](other) is true for all
  27938. // other. This relies on the function fn to be transitive.
  27939. //
  27940. // moments should either be an array of moment objects or an array, whose
  27941. // first element is an array of moment objects.
  27942. function pickBy(fn, moments) {
  27943. var res, i;
  27944. if (moments.length === 1 && isArray(moments[0])) {
  27945. moments = moments[0];
  27946. }
  27947. if (!moments.length) {
  27948. return createLocal();
  27949. }
  27950. res = moments[0];
  27951. for (i = 1; i < moments.length; ++i) {
  27952. if (!moments[i].isValid() || moments[i][fn](res)) {
  27953. res = moments[i];
  27954. }
  27955. }
  27956. return res;
  27957. }
  27958. // TODO: Use [].sort instead?
  27959. function min () {
  27960. var args = [].slice.call(arguments, 0);
  27961. return pickBy('isBefore', args);
  27962. }
  27963. function max () {
  27964. var args = [].slice.call(arguments, 0);
  27965. return pickBy('isAfter', args);
  27966. }
  27967. var now = function () {
  27968. return Date.now ? Date.now() : +(new Date());
  27969. };
  27970. var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
  27971. function isDurationValid(m) {
  27972. for (var key in m) {
  27973. if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
  27974. return false;
  27975. }
  27976. }
  27977. var unitHasDecimal = false;
  27978. for (var i = 0; i < ordering.length; ++i) {
  27979. if (m[ordering[i]]) {
  27980. if (unitHasDecimal) {
  27981. return false; // only allow non-integers for smallest unit
  27982. }
  27983. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  27984. unitHasDecimal = true;
  27985. }
  27986. }
  27987. }
  27988. return true;
  27989. }
  27990. function isValid$1() {
  27991. return this._isValid;
  27992. }
  27993. function createInvalid$1() {
  27994. return createDuration(NaN);
  27995. }
  27996. function Duration (duration) {
  27997. var normalizedInput = normalizeObjectUnits(duration),
  27998. years = normalizedInput.year || 0,
  27999. quarters = normalizedInput.quarter || 0,
  28000. months = normalizedInput.month || 0,
  28001. weeks = normalizedInput.week || 0,
  28002. days = normalizedInput.day || 0,
  28003. hours = normalizedInput.hour || 0,
  28004. minutes = normalizedInput.minute || 0,
  28005. seconds = normalizedInput.second || 0,
  28006. milliseconds = normalizedInput.millisecond || 0;
  28007. this._isValid = isDurationValid(normalizedInput);
  28008. // representation for dateAddRemove
  28009. this._milliseconds = +milliseconds +
  28010. seconds * 1e3 + // 1000
  28011. minutes * 6e4 + // 1000 * 60
  28012. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  28013. // Because of dateAddRemove treats 24 hours as different from a
  28014. // day when working around DST, we need to store them separately
  28015. this._days = +days +
  28016. weeks * 7;
  28017. // It is impossible to translate months into days without knowing
  28018. // which months you are are talking about, so we have to store
  28019. // it separately.
  28020. this._months = +months +
  28021. quarters * 3 +
  28022. years * 12;
  28023. this._data = {};
  28024. this._locale = getLocale();
  28025. this._bubble();
  28026. }
  28027. function isDuration (obj) {
  28028. return obj instanceof Duration;
  28029. }
  28030. function absRound (number) {
  28031. if (number < 0) {
  28032. return Math.round(-1 * number) * -1;
  28033. } else {
  28034. return Math.round(number);
  28035. }
  28036. }
  28037. // FORMATTING
  28038. function offset (token, separator) {
  28039. addFormatToken(token, 0, 0, function () {
  28040. var offset = this.utcOffset();
  28041. var sign = '+';
  28042. if (offset < 0) {
  28043. offset = -offset;
  28044. sign = '-';
  28045. }
  28046. return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
  28047. });
  28048. }
  28049. offset('Z', ':');
  28050. offset('ZZ', '');
  28051. // PARSING
  28052. addRegexToken('Z', matchShortOffset);
  28053. addRegexToken('ZZ', matchShortOffset);
  28054. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  28055. config._useUTC = true;
  28056. config._tzm = offsetFromString(matchShortOffset, input);
  28057. });
  28058. // HELPERS
  28059. // timezone chunker
  28060. // '+10:00' > ['10', '00']
  28061. // '-1530' > ['-15', '30']
  28062. var chunkOffset = /([\+\-]|\d\d)/gi;
  28063. function offsetFromString(matcher, string) {
  28064. var matches = (string || '').match(matcher);
  28065. if (matches === null) {
  28066. return null;
  28067. }
  28068. var chunk = matches[matches.length - 1] || [];
  28069. var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  28070. var minutes = +(parts[1] * 60) + toInt(parts[2]);
  28071. return minutes === 0 ?
  28072. 0 :
  28073. parts[0] === '+' ? minutes : -minutes;
  28074. }
  28075. // Return a moment from input, that is local/utc/zone equivalent to model.
  28076. function cloneWithOffset(input, model) {
  28077. var res, diff;
  28078. if (model._isUTC) {
  28079. res = model.clone();
  28080. diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
  28081. // Use low-level api, because this fn is low-level api.
  28082. res._d.setTime(res._d.valueOf() + diff);
  28083. hooks.updateOffset(res, false);
  28084. return res;
  28085. } else {
  28086. return createLocal(input).local();
  28087. }
  28088. }
  28089. function getDateOffset (m) {
  28090. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  28091. // https://github.com/moment/moment/pull/1871
  28092. return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
  28093. }
  28094. // HOOKS
  28095. // This function will be called whenever a moment is mutated.
  28096. // It is intended to keep the offset in sync with the timezone.
  28097. hooks.updateOffset = function () {};
  28098. // MOMENTS
  28099. // keepLocalTime = true means only change the timezone, without
  28100. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  28101. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  28102. // +0200, so we adjust the time as needed, to be valid.
  28103. //
  28104. // Keeping the time actually adds/subtracts (one hour)
  28105. // from the actual represented time. That is why we call updateOffset
  28106. // a second time. In case it wants us to change the offset again
  28107. // _changeInProgress == true case, then we have to adjust, because
  28108. // there is no such time in the given timezone.
  28109. function getSetOffset (input, keepLocalTime, keepMinutes) {
  28110. var offset = this._offset || 0,
  28111. localAdjust;
  28112. if (!this.isValid()) {
  28113. return input != null ? this : NaN;
  28114. }
  28115. if (input != null) {
  28116. if (typeof input === 'string') {
  28117. input = offsetFromString(matchShortOffset, input);
  28118. if (input === null) {
  28119. return this;
  28120. }
  28121. } else if (Math.abs(input) < 16 && !keepMinutes) {
  28122. input = input * 60;
  28123. }
  28124. if (!this._isUTC && keepLocalTime) {
  28125. localAdjust = getDateOffset(this);
  28126. }
  28127. this._offset = input;
  28128. this._isUTC = true;
  28129. if (localAdjust != null) {
  28130. this.add(localAdjust, 'm');
  28131. }
  28132. if (offset !== input) {
  28133. if (!keepLocalTime || this._changeInProgress) {
  28134. addSubtract(this, createDuration(input - offset, 'm'), 1, false);
  28135. } else if (!this._changeInProgress) {
  28136. this._changeInProgress = true;
  28137. hooks.updateOffset(this, true);
  28138. this._changeInProgress = null;
  28139. }
  28140. }
  28141. return this;
  28142. } else {
  28143. return this._isUTC ? offset : getDateOffset(this);
  28144. }
  28145. }
  28146. function getSetZone (input, keepLocalTime) {
  28147. if (input != null) {
  28148. if (typeof input !== 'string') {
  28149. input = -input;
  28150. }
  28151. this.utcOffset(input, keepLocalTime);
  28152. return this;
  28153. } else {
  28154. return -this.utcOffset();
  28155. }
  28156. }
  28157. function setOffsetToUTC (keepLocalTime) {
  28158. return this.utcOffset(0, keepLocalTime);
  28159. }
  28160. function setOffsetToLocal (keepLocalTime) {
  28161. if (this._isUTC) {
  28162. this.utcOffset(0, keepLocalTime);
  28163. this._isUTC = false;
  28164. if (keepLocalTime) {
  28165. this.subtract(getDateOffset(this), 'm');
  28166. }
  28167. }
  28168. return this;
  28169. }
  28170. function setOffsetToParsedOffset () {
  28171. if (this._tzm != null) {
  28172. this.utcOffset(this._tzm, false, true);
  28173. } else if (typeof this._i === 'string') {
  28174. var tZone = offsetFromString(matchOffset, this._i);
  28175. if (tZone != null) {
  28176. this.utcOffset(tZone);
  28177. }
  28178. else {
  28179. this.utcOffset(0, true);
  28180. }
  28181. }
  28182. return this;
  28183. }
  28184. function hasAlignedHourOffset (input) {
  28185. if (!this.isValid()) {
  28186. return false;
  28187. }
  28188. input = input ? createLocal(input).utcOffset() : 0;
  28189. return (this.utcOffset() - input) % 60 === 0;
  28190. }
  28191. function isDaylightSavingTime () {
  28192. return (
  28193. this.utcOffset() > this.clone().month(0).utcOffset() ||
  28194. this.utcOffset() > this.clone().month(5).utcOffset()
  28195. );
  28196. }
  28197. function isDaylightSavingTimeShifted () {
  28198. if (!isUndefined(this._isDSTShifted)) {
  28199. return this._isDSTShifted;
  28200. }
  28201. var c = {};
  28202. copyConfig(c, this);
  28203. c = prepareConfig(c);
  28204. if (c._a) {
  28205. var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  28206. this._isDSTShifted = this.isValid() &&
  28207. compareArrays(c._a, other.toArray()) > 0;
  28208. } else {
  28209. this._isDSTShifted = false;
  28210. }
  28211. return this._isDSTShifted;
  28212. }
  28213. function isLocal () {
  28214. return this.isValid() ? !this._isUTC : false;
  28215. }
  28216. function isUtcOffset () {
  28217. return this.isValid() ? this._isUTC : false;
  28218. }
  28219. function isUtc () {
  28220. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  28221. }
  28222. // ASP.NET json date format regex
  28223. var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;
  28224. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  28225. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  28226. // and further modified to allow for strings containing both week and day
  28227. 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)?)?$/;
  28228. function createDuration (input, key) {
  28229. var duration = input,
  28230. // matching against regexp is expensive, do it on demand
  28231. match = null,
  28232. sign,
  28233. ret,
  28234. diffRes;
  28235. if (isDuration(input)) {
  28236. duration = {
  28237. ms : input._milliseconds,
  28238. d : input._days,
  28239. M : input._months
  28240. };
  28241. } else if (isNumber(input)) {
  28242. duration = {};
  28243. if (key) {
  28244. duration[key] = input;
  28245. } else {
  28246. duration.milliseconds = input;
  28247. }
  28248. } else if (!!(match = aspNetRegex.exec(input))) {
  28249. sign = (match[1] === '-') ? -1 : 1;
  28250. duration = {
  28251. y : 0,
  28252. d : toInt(match[DATE]) * sign,
  28253. h : toInt(match[HOUR]) * sign,
  28254. m : toInt(match[MINUTE]) * sign,
  28255. s : toInt(match[SECOND]) * sign,
  28256. ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
  28257. };
  28258. } else if (!!(match = isoRegex.exec(input))) {
  28259. sign = (match[1] === '-') ? -1 : (match[1] === '+') ? 1 : 1;
  28260. duration = {
  28261. y : parseIso(match[2], sign),
  28262. M : parseIso(match[3], sign),
  28263. w : parseIso(match[4], sign),
  28264. d : parseIso(match[5], sign),
  28265. h : parseIso(match[6], sign),
  28266. m : parseIso(match[7], sign),
  28267. s : parseIso(match[8], sign)
  28268. };
  28269. } else if (duration == null) {// checks for null or undefined
  28270. duration = {};
  28271. } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
  28272. diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
  28273. duration = {};
  28274. duration.ms = diffRes.milliseconds;
  28275. duration.M = diffRes.months;
  28276. }
  28277. ret = new Duration(duration);
  28278. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  28279. ret._locale = input._locale;
  28280. }
  28281. return ret;
  28282. }
  28283. createDuration.fn = Duration.prototype;
  28284. createDuration.invalid = createInvalid$1;
  28285. function parseIso (inp, sign) {
  28286. // We'd normally use ~~inp for this, but unfortunately it also
  28287. // converts floats to ints.
  28288. // inp may be undefined, so careful calling replace on it.
  28289. var res = inp && parseFloat(inp.replace(',', '.'));
  28290. // apply sign while we're at it
  28291. return (isNaN(res) ? 0 : res) * sign;
  28292. }
  28293. function positiveMomentsDifference(base, other) {
  28294. var res = {milliseconds: 0, months: 0};
  28295. res.months = other.month() - base.month() +
  28296. (other.year() - base.year()) * 12;
  28297. if (base.clone().add(res.months, 'M').isAfter(other)) {
  28298. --res.months;
  28299. }
  28300. res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
  28301. return res;
  28302. }
  28303. function momentsDifference(base, other) {
  28304. var res;
  28305. if (!(base.isValid() && other.isValid())) {
  28306. return {milliseconds: 0, months: 0};
  28307. }
  28308. other = cloneWithOffset(other, base);
  28309. if (base.isBefore(other)) {
  28310. res = positiveMomentsDifference(base, other);
  28311. } else {
  28312. res = positiveMomentsDifference(other, base);
  28313. res.milliseconds = -res.milliseconds;
  28314. res.months = -res.months;
  28315. }
  28316. return res;
  28317. }
  28318. // TODO: remove 'name' arg after deprecation is removed
  28319. function createAdder(direction, name) {
  28320. return function (val, period) {
  28321. var dur, tmp;
  28322. //invert the arguments, but complain about it
  28323. if (period !== null && !isNaN(+period)) {
  28324. deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
  28325. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
  28326. tmp = val; val = period; period = tmp;
  28327. }
  28328. val = typeof val === 'string' ? +val : val;
  28329. dur = createDuration(val, period);
  28330. addSubtract(this, dur, direction);
  28331. return this;
  28332. };
  28333. }
  28334. function addSubtract (mom, duration, isAdding, updateOffset) {
  28335. var milliseconds = duration._milliseconds,
  28336. days = absRound(duration._days),
  28337. months = absRound(duration._months);
  28338. if (!mom.isValid()) {
  28339. // No op
  28340. return;
  28341. }
  28342. updateOffset = updateOffset == null ? true : updateOffset;
  28343. if (months) {
  28344. setMonth(mom, get(mom, 'Month') + months * isAdding);
  28345. }
  28346. if (days) {
  28347. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  28348. }
  28349. if (milliseconds) {
  28350. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  28351. }
  28352. if (updateOffset) {
  28353. hooks.updateOffset(mom, days || months);
  28354. }
  28355. }
  28356. var add = createAdder(1, 'add');
  28357. var subtract = createAdder(-1, 'subtract');
  28358. function getCalendarFormat(myMoment, now) {
  28359. var diff = myMoment.diff(now, 'days', true);
  28360. return diff < -6 ? 'sameElse' :
  28361. diff < -1 ? 'lastWeek' :
  28362. diff < 0 ? 'lastDay' :
  28363. diff < 1 ? 'sameDay' :
  28364. diff < 2 ? 'nextDay' :
  28365. diff < 7 ? 'nextWeek' : 'sameElse';
  28366. }
  28367. function calendar$1 (time, formats) {
  28368. // We want to compare the start of today, vs this.
  28369. // Getting start-of-today depends on whether we're local/utc/offset or not.
  28370. var now = time || createLocal(),
  28371. sod = cloneWithOffset(now, this).startOf('day'),
  28372. format = hooks.calendarFormat(this, sod) || 'sameElse';
  28373. var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
  28374. return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
  28375. }
  28376. function clone () {
  28377. return new Moment(this);
  28378. }
  28379. function isAfter (input, units) {
  28380. var localInput = isMoment(input) ? input : createLocal(input);
  28381. if (!(this.isValid() && localInput.isValid())) {
  28382. return false;
  28383. }
  28384. units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
  28385. if (units === 'millisecond') {
  28386. return this.valueOf() > localInput.valueOf();
  28387. } else {
  28388. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  28389. }
  28390. }
  28391. function isBefore (input, units) {
  28392. var localInput = isMoment(input) ? input : createLocal(input);
  28393. if (!(this.isValid() && localInput.isValid())) {
  28394. return false;
  28395. }
  28396. units = normalizeUnits(!isUndefined(units) ? units : 'millisecond');
  28397. if (units === 'millisecond') {
  28398. return this.valueOf() < localInput.valueOf();
  28399. } else {
  28400. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  28401. }
  28402. }
  28403. function isBetween (from, to, units, inclusivity) {
  28404. inclusivity = inclusivity || '()';
  28405. return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) &&
  28406. (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units));
  28407. }
  28408. function isSame (input, units) {
  28409. var localInput = isMoment(input) ? input : createLocal(input),
  28410. inputMs;
  28411. if (!(this.isValid() && localInput.isValid())) {
  28412. return false;
  28413. }
  28414. units = normalizeUnits(units || 'millisecond');
  28415. if (units === 'millisecond') {
  28416. return this.valueOf() === localInput.valueOf();
  28417. } else {
  28418. inputMs = localInput.valueOf();
  28419. return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
  28420. }
  28421. }
  28422. function isSameOrAfter (input, units) {
  28423. return this.isSame(input, units) || this.isAfter(input,units);
  28424. }
  28425. function isSameOrBefore (input, units) {
  28426. return this.isSame(input, units) || this.isBefore(input,units);
  28427. }
  28428. function diff (input, units, asFloat) {
  28429. var that,
  28430. zoneDelta,
  28431. delta, output;
  28432. if (!this.isValid()) {
  28433. return NaN;
  28434. }
  28435. that = cloneWithOffset(input, this);
  28436. if (!that.isValid()) {
  28437. return NaN;
  28438. }
  28439. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  28440. units = normalizeUnits(units);
  28441. switch (units) {
  28442. case 'year': output = monthDiff(this, that) / 12; break;
  28443. case 'month': output = monthDiff(this, that); break;
  28444. case 'quarter': output = monthDiff(this, that) / 3; break;
  28445. case 'second': output = (this - that) / 1e3; break; // 1000
  28446. case 'minute': output = (this - that) / 6e4; break; // 1000 * 60
  28447. case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60
  28448. case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst
  28449. case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst
  28450. default: output = this - that;
  28451. }
  28452. return asFloat ? output : absFloor(output);
  28453. }
  28454. function monthDiff (a, b) {
  28455. // difference in months
  28456. var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
  28457. // b is in (anchor - 1 month, anchor + 1 month)
  28458. anchor = a.clone().add(wholeMonthDiff, 'months'),
  28459. anchor2, adjust;
  28460. if (b - anchor < 0) {
  28461. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  28462. // linear across the month
  28463. adjust = (b - anchor) / (anchor - anchor2);
  28464. } else {
  28465. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  28466. // linear across the month
  28467. adjust = (b - anchor) / (anchor2 - anchor);
  28468. }
  28469. //check for negative zero, return zero if negative zero
  28470. return -(wholeMonthDiff + adjust) || 0;
  28471. }
  28472. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  28473. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  28474. function toString () {
  28475. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  28476. }
  28477. function toISOString() {
  28478. if (!this.isValid()) {
  28479. return null;
  28480. }
  28481. var m = this.clone().utc();
  28482. if (m.year() < 0 || m.year() > 9999) {
  28483. return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  28484. }
  28485. if (isFunction(Date.prototype.toISOString)) {
  28486. // native implementation is ~50x faster, use it when we can
  28487. return this.toDate().toISOString();
  28488. }
  28489. return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
  28490. }
  28491. /**
  28492. * Return a human readable representation of a moment that can
  28493. * also be evaluated to get a new moment which is the same
  28494. *
  28495. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  28496. */
  28497. function inspect () {
  28498. if (!this.isValid()) {
  28499. return 'moment.invalid(/* ' + this._i + ' */)';
  28500. }
  28501. var func = 'moment';
  28502. var zone = '';
  28503. if (!this.isLocal()) {
  28504. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  28505. zone = 'Z';
  28506. }
  28507. var prefix = '[' + func + '("]';
  28508. var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
  28509. var datetime = '-MM-DD[T]HH:mm:ss.SSS';
  28510. var suffix = zone + '[")]';
  28511. return this.format(prefix + year + datetime + suffix);
  28512. }
  28513. function format (inputString) {
  28514. if (!inputString) {
  28515. inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
  28516. }
  28517. var output = formatMoment(this, inputString);
  28518. return this.localeData().postformat(output);
  28519. }
  28520. function from (time, withoutSuffix) {
  28521. if (this.isValid() &&
  28522. ((isMoment(time) && time.isValid()) ||
  28523. createLocal(time).isValid())) {
  28524. return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
  28525. } else {
  28526. return this.localeData().invalidDate();
  28527. }
  28528. }
  28529. function fromNow (withoutSuffix) {
  28530. return this.from(createLocal(), withoutSuffix);
  28531. }
  28532. function to (time, withoutSuffix) {
  28533. if (this.isValid() &&
  28534. ((isMoment(time) && time.isValid()) ||
  28535. createLocal(time).isValid())) {
  28536. return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
  28537. } else {
  28538. return this.localeData().invalidDate();
  28539. }
  28540. }
  28541. function toNow (withoutSuffix) {
  28542. return this.to(createLocal(), withoutSuffix);
  28543. }
  28544. // If passed a locale key, it will set the locale for this
  28545. // instance. Otherwise, it will return the locale configuration
  28546. // variables for this instance.
  28547. function locale (key) {
  28548. var newLocaleData;
  28549. if (key === undefined) {
  28550. return this._locale._abbr;
  28551. } else {
  28552. newLocaleData = getLocale(key);
  28553. if (newLocaleData != null) {
  28554. this._locale = newLocaleData;
  28555. }
  28556. return this;
  28557. }
  28558. }
  28559. var lang = deprecate(
  28560. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  28561. function (key) {
  28562. if (key === undefined) {
  28563. return this.localeData();
  28564. } else {
  28565. return this.locale(key);
  28566. }
  28567. }
  28568. );
  28569. function localeData () {
  28570. return this._locale;
  28571. }
  28572. function startOf (units) {
  28573. units = normalizeUnits(units);
  28574. // the following switch intentionally omits break keywords
  28575. // to utilize falling through the cases.
  28576. switch (units) {
  28577. case 'year':
  28578. this.month(0);
  28579. /* falls through */
  28580. case 'quarter':
  28581. case 'month':
  28582. this.date(1);
  28583. /* falls through */
  28584. case 'week':
  28585. case 'isoWeek':
  28586. case 'day':
  28587. case 'date':
  28588. this.hours(0);
  28589. /* falls through */
  28590. case 'hour':
  28591. this.minutes(0);
  28592. /* falls through */
  28593. case 'minute':
  28594. this.seconds(0);
  28595. /* falls through */
  28596. case 'second':
  28597. this.milliseconds(0);
  28598. }
  28599. // weeks are a special case
  28600. if (units === 'week') {
  28601. this.weekday(0);
  28602. }
  28603. if (units === 'isoWeek') {
  28604. this.isoWeekday(1);
  28605. }
  28606. // quarters are also special
  28607. if (units === 'quarter') {
  28608. this.month(Math.floor(this.month() / 3) * 3);
  28609. }
  28610. return this;
  28611. }
  28612. function endOf (units) {
  28613. units = normalizeUnits(units);
  28614. if (units === undefined || units === 'millisecond') {
  28615. return this;
  28616. }
  28617. // 'date' is an alias for 'day', so it should be considered as such.
  28618. if (units === 'date') {
  28619. units = 'day';
  28620. }
  28621. return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms');
  28622. }
  28623. function valueOf () {
  28624. return this._d.valueOf() - ((this._offset || 0) * 60000);
  28625. }
  28626. function unix () {
  28627. return Math.floor(this.valueOf() / 1000);
  28628. }
  28629. function toDate () {
  28630. return new Date(this.valueOf());
  28631. }
  28632. function toArray () {
  28633. var m = this;
  28634. return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
  28635. }
  28636. function toObject () {
  28637. var m = this;
  28638. return {
  28639. years: m.year(),
  28640. months: m.month(),
  28641. date: m.date(),
  28642. hours: m.hours(),
  28643. minutes: m.minutes(),
  28644. seconds: m.seconds(),
  28645. milliseconds: m.milliseconds()
  28646. };
  28647. }
  28648. function toJSON () {
  28649. // new Date(NaN).toJSON() === null
  28650. return this.isValid() ? this.toISOString() : null;
  28651. }
  28652. function isValid$2 () {
  28653. return isValid(this);
  28654. }
  28655. function parsingFlags () {
  28656. return extend({}, getParsingFlags(this));
  28657. }
  28658. function invalidAt () {
  28659. return getParsingFlags(this).overflow;
  28660. }
  28661. function creationData() {
  28662. return {
  28663. input: this._i,
  28664. format: this._f,
  28665. locale: this._locale,
  28666. isUTC: this._isUTC,
  28667. strict: this._strict
  28668. };
  28669. }
  28670. // FORMATTING
  28671. addFormatToken(0, ['gg', 2], 0, function () {
  28672. return this.weekYear() % 100;
  28673. });
  28674. addFormatToken(0, ['GG', 2], 0, function () {
  28675. return this.isoWeekYear() % 100;
  28676. });
  28677. function addWeekYearFormatToken (token, getter) {
  28678. addFormatToken(0, [token, token.length], 0, getter);
  28679. }
  28680. addWeekYearFormatToken('gggg', 'weekYear');
  28681. addWeekYearFormatToken('ggggg', 'weekYear');
  28682. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  28683. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  28684. // ALIASES
  28685. addUnitAlias('weekYear', 'gg');
  28686. addUnitAlias('isoWeekYear', 'GG');
  28687. // PRIORITY
  28688. addUnitPriority('weekYear', 1);
  28689. addUnitPriority('isoWeekYear', 1);
  28690. // PARSING
  28691. addRegexToken('G', matchSigned);
  28692. addRegexToken('g', matchSigned);
  28693. addRegexToken('GG', match1to2, match2);
  28694. addRegexToken('gg', match1to2, match2);
  28695. addRegexToken('GGGG', match1to4, match4);
  28696. addRegexToken('gggg', match1to4, match4);
  28697. addRegexToken('GGGGG', match1to6, match6);
  28698. addRegexToken('ggggg', match1to6, match6);
  28699. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
  28700. week[token.substr(0, 2)] = toInt(input);
  28701. });
  28702. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  28703. week[token] = hooks.parseTwoDigitYear(input);
  28704. });
  28705. // MOMENTS
  28706. function getSetWeekYear (input) {
  28707. return getSetWeekYearHelper.call(this,
  28708. input,
  28709. this.week(),
  28710. this.weekday(),
  28711. this.localeData()._week.dow,
  28712. this.localeData()._week.doy);
  28713. }
  28714. function getSetISOWeekYear (input) {
  28715. return getSetWeekYearHelper.call(this,
  28716. input, this.isoWeek(), this.isoWeekday(), 1, 4);
  28717. }
  28718. function getISOWeeksInYear () {
  28719. return weeksInYear(this.year(), 1, 4);
  28720. }
  28721. function getWeeksInYear () {
  28722. var weekInfo = this.localeData()._week;
  28723. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  28724. }
  28725. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  28726. var weeksTarget;
  28727. if (input == null) {
  28728. return weekOfYear(this, dow, doy).year;
  28729. } else {
  28730. weeksTarget = weeksInYear(input, dow, doy);
  28731. if (week > weeksTarget) {
  28732. week = weeksTarget;
  28733. }
  28734. return setWeekAll.call(this, input, week, weekday, dow, doy);
  28735. }
  28736. }
  28737. function setWeekAll(weekYear, week, weekday, dow, doy) {
  28738. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  28739. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  28740. this.year(date.getUTCFullYear());
  28741. this.month(date.getUTCMonth());
  28742. this.date(date.getUTCDate());
  28743. return this;
  28744. }
  28745. // FORMATTING
  28746. addFormatToken('Q', 0, 'Qo', 'quarter');
  28747. // ALIASES
  28748. addUnitAlias('quarter', 'Q');
  28749. // PRIORITY
  28750. addUnitPriority('quarter', 7);
  28751. // PARSING
  28752. addRegexToken('Q', match1);
  28753. addParseToken('Q', function (input, array) {
  28754. array[MONTH] = (toInt(input) - 1) * 3;
  28755. });
  28756. // MOMENTS
  28757. function getSetQuarter (input) {
  28758. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  28759. }
  28760. // FORMATTING
  28761. addFormatToken('D', ['DD', 2], 'Do', 'date');
  28762. // ALIASES
  28763. addUnitAlias('date', 'D');
  28764. // PRIOROITY
  28765. addUnitPriority('date', 9);
  28766. // PARSING
  28767. addRegexToken('D', match1to2);
  28768. addRegexToken('DD', match1to2, match2);
  28769. addRegexToken('Do', function (isStrict, locale) {
  28770. // TODO: Remove "ordinalParse" fallback in next major release.
  28771. return isStrict ?
  28772. (locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
  28773. locale._dayOfMonthOrdinalParseLenient;
  28774. });
  28775. addParseToken(['D', 'DD'], DATE);
  28776. addParseToken('Do', function (input, array) {
  28777. array[DATE] = toInt(input.match(match1to2)[0], 10);
  28778. });
  28779. // MOMENTS
  28780. var getSetDayOfMonth = makeGetSet('Date', true);
  28781. // FORMATTING
  28782. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  28783. // ALIASES
  28784. addUnitAlias('dayOfYear', 'DDD');
  28785. // PRIORITY
  28786. addUnitPriority('dayOfYear', 4);
  28787. // PARSING
  28788. addRegexToken('DDD', match1to3);
  28789. addRegexToken('DDDD', match3);
  28790. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  28791. config._dayOfYear = toInt(input);
  28792. });
  28793. // HELPERS
  28794. // MOMENTS
  28795. function getSetDayOfYear (input) {
  28796. var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
  28797. return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
  28798. }
  28799. // FORMATTING
  28800. addFormatToken('m', ['mm', 2], 0, 'minute');
  28801. // ALIASES
  28802. addUnitAlias('minute', 'm');
  28803. // PRIORITY
  28804. addUnitPriority('minute', 14);
  28805. // PARSING
  28806. addRegexToken('m', match1to2);
  28807. addRegexToken('mm', match1to2, match2);
  28808. addParseToken(['m', 'mm'], MINUTE);
  28809. // MOMENTS
  28810. var getSetMinute = makeGetSet('Minutes', false);
  28811. // FORMATTING
  28812. addFormatToken('s', ['ss', 2], 0, 'second');
  28813. // ALIASES
  28814. addUnitAlias('second', 's');
  28815. // PRIORITY
  28816. addUnitPriority('second', 15);
  28817. // PARSING
  28818. addRegexToken('s', match1to2);
  28819. addRegexToken('ss', match1to2, match2);
  28820. addParseToken(['s', 'ss'], SECOND);
  28821. // MOMENTS
  28822. var getSetSecond = makeGetSet('Seconds', false);
  28823. // FORMATTING
  28824. addFormatToken('S', 0, 0, function () {
  28825. return ~~(this.millisecond() / 100);
  28826. });
  28827. addFormatToken(0, ['SS', 2], 0, function () {
  28828. return ~~(this.millisecond() / 10);
  28829. });
  28830. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  28831. addFormatToken(0, ['SSSS', 4], 0, function () {
  28832. return this.millisecond() * 10;
  28833. });
  28834. addFormatToken(0, ['SSSSS', 5], 0, function () {
  28835. return this.millisecond() * 100;
  28836. });
  28837. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  28838. return this.millisecond() * 1000;
  28839. });
  28840. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  28841. return this.millisecond() * 10000;
  28842. });
  28843. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  28844. return this.millisecond() * 100000;
  28845. });
  28846. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  28847. return this.millisecond() * 1000000;
  28848. });
  28849. // ALIASES
  28850. addUnitAlias('millisecond', 'ms');
  28851. // PRIORITY
  28852. addUnitPriority('millisecond', 16);
  28853. // PARSING
  28854. addRegexToken('S', match1to3, match1);
  28855. addRegexToken('SS', match1to3, match2);
  28856. addRegexToken('SSS', match1to3, match3);
  28857. var token;
  28858. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  28859. addRegexToken(token, matchUnsigned);
  28860. }
  28861. function parseMs(input, array) {
  28862. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  28863. }
  28864. for (token = 'S'; token.length <= 9; token += 'S') {
  28865. addParseToken(token, parseMs);
  28866. }
  28867. // MOMENTS
  28868. var getSetMillisecond = makeGetSet('Milliseconds', false);
  28869. // FORMATTING
  28870. addFormatToken('z', 0, 0, 'zoneAbbr');
  28871. addFormatToken('zz', 0, 0, 'zoneName');
  28872. // MOMENTS
  28873. function getZoneAbbr () {
  28874. return this._isUTC ? 'UTC' : '';
  28875. }
  28876. function getZoneName () {
  28877. return this._isUTC ? 'Coordinated Universal Time' : '';
  28878. }
  28879. var proto = Moment.prototype;
  28880. proto.add = add;
  28881. proto.calendar = calendar$1;
  28882. proto.clone = clone;
  28883. proto.diff = diff;
  28884. proto.endOf = endOf;
  28885. proto.format = format;
  28886. proto.from = from;
  28887. proto.fromNow = fromNow;
  28888. proto.to = to;
  28889. proto.toNow = toNow;
  28890. proto.get = stringGet;
  28891. proto.invalidAt = invalidAt;
  28892. proto.isAfter = isAfter;
  28893. proto.isBefore = isBefore;
  28894. proto.isBetween = isBetween;
  28895. proto.isSame = isSame;
  28896. proto.isSameOrAfter = isSameOrAfter;
  28897. proto.isSameOrBefore = isSameOrBefore;
  28898. proto.isValid = isValid$2;
  28899. proto.lang = lang;
  28900. proto.locale = locale;
  28901. proto.localeData = localeData;
  28902. proto.max = prototypeMax;
  28903. proto.min = prototypeMin;
  28904. proto.parsingFlags = parsingFlags;
  28905. proto.set = stringSet;
  28906. proto.startOf = startOf;
  28907. proto.subtract = subtract;
  28908. proto.toArray = toArray;
  28909. proto.toObject = toObject;
  28910. proto.toDate = toDate;
  28911. proto.toISOString = toISOString;
  28912. proto.inspect = inspect;
  28913. proto.toJSON = toJSON;
  28914. proto.toString = toString;
  28915. proto.unix = unix;
  28916. proto.valueOf = valueOf;
  28917. proto.creationData = creationData;
  28918. // Year
  28919. proto.year = getSetYear;
  28920. proto.isLeapYear = getIsLeapYear;
  28921. // Week Year
  28922. proto.weekYear = getSetWeekYear;
  28923. proto.isoWeekYear = getSetISOWeekYear;
  28924. // Quarter
  28925. proto.quarter = proto.quarters = getSetQuarter;
  28926. // Month
  28927. proto.month = getSetMonth;
  28928. proto.daysInMonth = getDaysInMonth;
  28929. // Week
  28930. proto.week = proto.weeks = getSetWeek;
  28931. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  28932. proto.weeksInYear = getWeeksInYear;
  28933. proto.isoWeeksInYear = getISOWeeksInYear;
  28934. // Day
  28935. proto.date = getSetDayOfMonth;
  28936. proto.day = proto.days = getSetDayOfWeek;
  28937. proto.weekday = getSetLocaleDayOfWeek;
  28938. proto.isoWeekday = getSetISODayOfWeek;
  28939. proto.dayOfYear = getSetDayOfYear;
  28940. // Hour
  28941. proto.hour = proto.hours = getSetHour;
  28942. // Minute
  28943. proto.minute = proto.minutes = getSetMinute;
  28944. // Second
  28945. proto.second = proto.seconds = getSetSecond;
  28946. // Millisecond
  28947. proto.millisecond = proto.milliseconds = getSetMillisecond;
  28948. // Offset
  28949. proto.utcOffset = getSetOffset;
  28950. proto.utc = setOffsetToUTC;
  28951. proto.local = setOffsetToLocal;
  28952. proto.parseZone = setOffsetToParsedOffset;
  28953. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  28954. proto.isDST = isDaylightSavingTime;
  28955. proto.isLocal = isLocal;
  28956. proto.isUtcOffset = isUtcOffset;
  28957. proto.isUtc = isUtc;
  28958. proto.isUTC = isUtc;
  28959. // Timezone
  28960. proto.zoneAbbr = getZoneAbbr;
  28961. proto.zoneName = getZoneName;
  28962. // Deprecations
  28963. proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
  28964. proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
  28965. proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
  28966. proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
  28967. proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
  28968. function createUnix (input) {
  28969. return createLocal(input * 1000);
  28970. }
  28971. function createInZone () {
  28972. return createLocal.apply(null, arguments).parseZone();
  28973. }
  28974. function preParsePostFormat (string) {
  28975. return string;
  28976. }
  28977. var proto$1 = Locale.prototype;
  28978. proto$1.calendar = calendar;
  28979. proto$1.longDateFormat = longDateFormat;
  28980. proto$1.invalidDate = invalidDate;
  28981. proto$1.ordinal = ordinal;
  28982. proto$1.preparse = preParsePostFormat;
  28983. proto$1.postformat = preParsePostFormat;
  28984. proto$1.relativeTime = relativeTime;
  28985. proto$1.pastFuture = pastFuture;
  28986. proto$1.set = set;
  28987. // Month
  28988. proto$1.months = localeMonths;
  28989. proto$1.monthsShort = localeMonthsShort;
  28990. proto$1.monthsParse = localeMonthsParse;
  28991. proto$1.monthsRegex = monthsRegex;
  28992. proto$1.monthsShortRegex = monthsShortRegex;
  28993. // Week
  28994. proto$1.week = localeWeek;
  28995. proto$1.firstDayOfYear = localeFirstDayOfYear;
  28996. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  28997. // Day of Week
  28998. proto$1.weekdays = localeWeekdays;
  28999. proto$1.weekdaysMin = localeWeekdaysMin;
  29000. proto$1.weekdaysShort = localeWeekdaysShort;
  29001. proto$1.weekdaysParse = localeWeekdaysParse;
  29002. proto$1.weekdaysRegex = weekdaysRegex;
  29003. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  29004. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  29005. // Hours
  29006. proto$1.isPM = localeIsPM;
  29007. proto$1.meridiem = localeMeridiem;
  29008. function get$1 (format, index, field, setter) {
  29009. var locale = getLocale();
  29010. var utc = createUTC().set(setter, index);
  29011. return locale[field](utc, format);
  29012. }
  29013. function listMonthsImpl (format, index, field) {
  29014. if (isNumber(format)) {
  29015. index = format;
  29016. format = undefined;
  29017. }
  29018. format = format || '';
  29019. if (index != null) {
  29020. return get$1(format, index, field, 'month');
  29021. }
  29022. var i;
  29023. var out = [];
  29024. for (i = 0; i < 12; i++) {
  29025. out[i] = get$1(format, i, field, 'month');
  29026. }
  29027. return out;
  29028. }
  29029. // ()
  29030. // (5)
  29031. // (fmt, 5)
  29032. // (fmt)
  29033. // (true)
  29034. // (true, 5)
  29035. // (true, fmt, 5)
  29036. // (true, fmt)
  29037. function listWeekdaysImpl (localeSorted, format, index, field) {
  29038. if (typeof localeSorted === 'boolean') {
  29039. if (isNumber(format)) {
  29040. index = format;
  29041. format = undefined;
  29042. }
  29043. format = format || '';
  29044. } else {
  29045. format = localeSorted;
  29046. index = format;
  29047. localeSorted = false;
  29048. if (isNumber(format)) {
  29049. index = format;
  29050. format = undefined;
  29051. }
  29052. format = format || '';
  29053. }
  29054. var locale = getLocale(),
  29055. shift = localeSorted ? locale._week.dow : 0;
  29056. if (index != null) {
  29057. return get$1(format, (index + shift) % 7, field, 'day');
  29058. }
  29059. var i;
  29060. var out = [];
  29061. for (i = 0; i < 7; i++) {
  29062. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  29063. }
  29064. return out;
  29065. }
  29066. function listMonths (format, index) {
  29067. return listMonthsImpl(format, index, 'months');
  29068. }
  29069. function listMonthsShort (format, index) {
  29070. return listMonthsImpl(format, index, 'monthsShort');
  29071. }
  29072. function listWeekdays (localeSorted, format, index) {
  29073. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  29074. }
  29075. function listWeekdaysShort (localeSorted, format, index) {
  29076. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  29077. }
  29078. function listWeekdaysMin (localeSorted, format, index) {
  29079. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  29080. }
  29081. getSetGlobalLocale('en', {
  29082. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  29083. ordinal : function (number) {
  29084. var b = number % 10,
  29085. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  29086. (b === 1) ? 'st' :
  29087. (b === 2) ? 'nd' :
  29088. (b === 3) ? 'rd' : 'th';
  29089. return number + output;
  29090. }
  29091. });
  29092. // Side effect imports
  29093. hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
  29094. hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
  29095. var mathAbs = Math.abs;
  29096. function abs () {
  29097. var data = this._data;
  29098. this._milliseconds = mathAbs(this._milliseconds);
  29099. this._days = mathAbs(this._days);
  29100. this._months = mathAbs(this._months);
  29101. data.milliseconds = mathAbs(data.milliseconds);
  29102. data.seconds = mathAbs(data.seconds);
  29103. data.minutes = mathAbs(data.minutes);
  29104. data.hours = mathAbs(data.hours);
  29105. data.months = mathAbs(data.months);
  29106. data.years = mathAbs(data.years);
  29107. return this;
  29108. }
  29109. function addSubtract$1 (duration, input, value, direction) {
  29110. var other = createDuration(input, value);
  29111. duration._milliseconds += direction * other._milliseconds;
  29112. duration._days += direction * other._days;
  29113. duration._months += direction * other._months;
  29114. return duration._bubble();
  29115. }
  29116. // supports only 2.0-style add(1, 's') or add(duration)
  29117. function add$1 (input, value) {
  29118. return addSubtract$1(this, input, value, 1);
  29119. }
  29120. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  29121. function subtract$1 (input, value) {
  29122. return addSubtract$1(this, input, value, -1);
  29123. }
  29124. function absCeil (number) {
  29125. if (number < 0) {
  29126. return Math.floor(number);
  29127. } else {
  29128. return Math.ceil(number);
  29129. }
  29130. }
  29131. function bubble () {
  29132. var milliseconds = this._milliseconds;
  29133. var days = this._days;
  29134. var months = this._months;
  29135. var data = this._data;
  29136. var seconds, minutes, hours, years, monthsFromDays;
  29137. // if we have a mix of positive and negative values, bubble down first
  29138. // check: https://github.com/moment/moment/issues/2166
  29139. if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
  29140. (milliseconds <= 0 && days <= 0 && months <= 0))) {
  29141. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  29142. days = 0;
  29143. months = 0;
  29144. }
  29145. // The following code bubbles up values, see the tests for
  29146. // examples of what that means.
  29147. data.milliseconds = milliseconds % 1000;
  29148. seconds = absFloor(milliseconds / 1000);
  29149. data.seconds = seconds % 60;
  29150. minutes = absFloor(seconds / 60);
  29151. data.minutes = minutes % 60;
  29152. hours = absFloor(minutes / 60);
  29153. data.hours = hours % 24;
  29154. days += absFloor(hours / 24);
  29155. // convert days to months
  29156. monthsFromDays = absFloor(daysToMonths(days));
  29157. months += monthsFromDays;
  29158. days -= absCeil(monthsToDays(monthsFromDays));
  29159. // 12 months -> 1 year
  29160. years = absFloor(months / 12);
  29161. months %= 12;
  29162. data.days = days;
  29163. data.months = months;
  29164. data.years = years;
  29165. return this;
  29166. }
  29167. function daysToMonths (days) {
  29168. // 400 years have 146097 days (taking into account leap year rules)
  29169. // 400 years have 12 months === 4800
  29170. return days * 4800 / 146097;
  29171. }
  29172. function monthsToDays (months) {
  29173. // the reverse of daysToMonths
  29174. return months * 146097 / 4800;
  29175. }
  29176. function as (units) {
  29177. if (!this.isValid()) {
  29178. return NaN;
  29179. }
  29180. var days;
  29181. var months;
  29182. var milliseconds = this._milliseconds;
  29183. units = normalizeUnits(units);
  29184. if (units === 'month' || units === 'year') {
  29185. days = this._days + milliseconds / 864e5;
  29186. months = this._months + daysToMonths(days);
  29187. return units === 'month' ? months : months / 12;
  29188. } else {
  29189. // handle milliseconds separately because of floating point math errors (issue #1867)
  29190. days = this._days + Math.round(monthsToDays(this._months));
  29191. switch (units) {
  29192. case 'week' : return days / 7 + milliseconds / 6048e5;
  29193. case 'day' : return days + milliseconds / 864e5;
  29194. case 'hour' : return days * 24 + milliseconds / 36e5;
  29195. case 'minute' : return days * 1440 + milliseconds / 6e4;
  29196. case 'second' : return days * 86400 + milliseconds / 1000;
  29197. // Math.floor prevents floating point math errors here
  29198. case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
  29199. default: throw new Error('Unknown unit ' + units);
  29200. }
  29201. }
  29202. }
  29203. // TODO: Use this.as('ms')?
  29204. function valueOf$1 () {
  29205. if (!this.isValid()) {
  29206. return NaN;
  29207. }
  29208. return (
  29209. this._milliseconds +
  29210. this._days * 864e5 +
  29211. (this._months % 12) * 2592e6 +
  29212. toInt(this._months / 12) * 31536e6
  29213. );
  29214. }
  29215. function makeAs (alias) {
  29216. return function () {
  29217. return this.as(alias);
  29218. };
  29219. }
  29220. var asMilliseconds = makeAs('ms');
  29221. var asSeconds = makeAs('s');
  29222. var asMinutes = makeAs('m');
  29223. var asHours = makeAs('h');
  29224. var asDays = makeAs('d');
  29225. var asWeeks = makeAs('w');
  29226. var asMonths = makeAs('M');
  29227. var asYears = makeAs('y');
  29228. function clone$1 () {
  29229. return createDuration(this);
  29230. }
  29231. function get$2 (units) {
  29232. units = normalizeUnits(units);
  29233. return this.isValid() ? this[units + 's']() : NaN;
  29234. }
  29235. function makeGetter(name) {
  29236. return function () {
  29237. return this.isValid() ? this._data[name] : NaN;
  29238. };
  29239. }
  29240. var milliseconds = makeGetter('milliseconds');
  29241. var seconds = makeGetter('seconds');
  29242. var minutes = makeGetter('minutes');
  29243. var hours = makeGetter('hours');
  29244. var days = makeGetter('days');
  29245. var months = makeGetter('months');
  29246. var years = makeGetter('years');
  29247. function weeks () {
  29248. return absFloor(this.days() / 7);
  29249. }
  29250. var round = Math.round;
  29251. var thresholds = {
  29252. ss: 44, // a few seconds to seconds
  29253. s : 45, // seconds to minute
  29254. m : 45, // minutes to hour
  29255. h : 22, // hours to day
  29256. d : 26, // days to month
  29257. M : 11 // months to year
  29258. };
  29259. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  29260. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  29261. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  29262. }
  29263. function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
  29264. var duration = createDuration(posNegDuration).abs();
  29265. var seconds = round(duration.as('s'));
  29266. var minutes = round(duration.as('m'));
  29267. var hours = round(duration.as('h'));
  29268. var days = round(duration.as('d'));
  29269. var months = round(duration.as('M'));
  29270. var years = round(duration.as('y'));
  29271. var a = seconds <= thresholds.ss && ['s', seconds] ||
  29272. seconds < thresholds.s && ['ss', seconds] ||
  29273. minutes <= 1 && ['m'] ||
  29274. minutes < thresholds.m && ['mm', minutes] ||
  29275. hours <= 1 && ['h'] ||
  29276. hours < thresholds.h && ['hh', hours] ||
  29277. days <= 1 && ['d'] ||
  29278. days < thresholds.d && ['dd', days] ||
  29279. months <= 1 && ['M'] ||
  29280. months < thresholds.M && ['MM', months] ||
  29281. years <= 1 && ['y'] || ['yy', years];
  29282. a[2] = withoutSuffix;
  29283. a[3] = +posNegDuration > 0;
  29284. a[4] = locale;
  29285. return substituteTimeAgo.apply(null, a);
  29286. }
  29287. // This function allows you to set the rounding function for relative time strings
  29288. function getSetRelativeTimeRounding (roundingFunction) {
  29289. if (roundingFunction === undefined) {
  29290. return round;
  29291. }
  29292. if (typeof(roundingFunction) === 'function') {
  29293. round = roundingFunction;
  29294. return true;
  29295. }
  29296. return false;
  29297. }
  29298. // This function allows you to set a threshold for relative time strings
  29299. function getSetRelativeTimeThreshold (threshold, limit) {
  29300. if (thresholds[threshold] === undefined) {
  29301. return false;
  29302. }
  29303. if (limit === undefined) {
  29304. return thresholds[threshold];
  29305. }
  29306. thresholds[threshold] = limit;
  29307. if (threshold === 's') {
  29308. thresholds.ss = limit - 1;
  29309. }
  29310. return true;
  29311. }
  29312. function humanize (withSuffix) {
  29313. if (!this.isValid()) {
  29314. return this.localeData().invalidDate();
  29315. }
  29316. var locale = this.localeData();
  29317. var output = relativeTime$1(this, !withSuffix, locale);
  29318. if (withSuffix) {
  29319. output = locale.pastFuture(+this, output);
  29320. }
  29321. return locale.postformat(output);
  29322. }
  29323. var abs$1 = Math.abs;
  29324. function sign(x) {
  29325. return ((x > 0) - (x < 0)) || +x;
  29326. }
  29327. function toISOString$1() {
  29328. // for ISO strings we do not use the normal bubbling rules:
  29329. // * milliseconds bubble up until they become hours
  29330. // * days do not bubble at all
  29331. // * months bubble up until they become years
  29332. // This is because there is no context-free conversion between hours and days
  29333. // (think of clock changes)
  29334. // and also not between days and months (28-31 days per month)
  29335. if (!this.isValid()) {
  29336. return this.localeData().invalidDate();
  29337. }
  29338. var seconds = abs$1(this._milliseconds) / 1000;
  29339. var days = abs$1(this._days);
  29340. var months = abs$1(this._months);
  29341. var minutes, hours, years;
  29342. // 3600 seconds -> 60 minutes -> 1 hour
  29343. minutes = absFloor(seconds / 60);
  29344. hours = absFloor(minutes / 60);
  29345. seconds %= 60;
  29346. minutes %= 60;
  29347. // 12 months -> 1 year
  29348. years = absFloor(months / 12);
  29349. months %= 12;
  29350. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  29351. var Y = years;
  29352. var M = months;
  29353. var D = days;
  29354. var h = hours;
  29355. var m = minutes;
  29356. var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  29357. var total = this.asSeconds();
  29358. if (!total) {
  29359. // this is the same as C#'s (Noda) and python (isodate)...
  29360. // but not other JS (goog.date)
  29361. return 'P0D';
  29362. }
  29363. var totalSign = total < 0 ? '-' : '';
  29364. var ymSign = sign(this._months) !== sign(total) ? '-' : '';
  29365. var daysSign = sign(this._days) !== sign(total) ? '-' : '';
  29366. var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  29367. return totalSign + 'P' +
  29368. (Y ? ymSign + Y + 'Y' : '') +
  29369. (M ? ymSign + M + 'M' : '') +
  29370. (D ? daysSign + D + 'D' : '') +
  29371. ((h || m || s) ? 'T' : '') +
  29372. (h ? hmsSign + h + 'H' : '') +
  29373. (m ? hmsSign + m + 'M' : '') +
  29374. (s ? hmsSign + s + 'S' : '');
  29375. }
  29376. var proto$2 = Duration.prototype;
  29377. proto$2.isValid = isValid$1;
  29378. proto$2.abs = abs;
  29379. proto$2.add = add$1;
  29380. proto$2.subtract = subtract$1;
  29381. proto$2.as = as;
  29382. proto$2.asMilliseconds = asMilliseconds;
  29383. proto$2.asSeconds = asSeconds;
  29384. proto$2.asMinutes = asMinutes;
  29385. proto$2.asHours = asHours;
  29386. proto$2.asDays = asDays;
  29387. proto$2.asWeeks = asWeeks;
  29388. proto$2.asMonths = asMonths;
  29389. proto$2.asYears = asYears;
  29390. proto$2.valueOf = valueOf$1;
  29391. proto$2._bubble = bubble;
  29392. proto$2.clone = clone$1;
  29393. proto$2.get = get$2;
  29394. proto$2.milliseconds = milliseconds;
  29395. proto$2.seconds = seconds;
  29396. proto$2.minutes = minutes;
  29397. proto$2.hours = hours;
  29398. proto$2.days = days;
  29399. proto$2.weeks = weeks;
  29400. proto$2.months = months;
  29401. proto$2.years = years;
  29402. proto$2.humanize = humanize;
  29403. proto$2.toISOString = toISOString$1;
  29404. proto$2.toString = toISOString$1;
  29405. proto$2.toJSON = toISOString$1;
  29406. proto$2.locale = locale;
  29407. proto$2.localeData = localeData;
  29408. // Deprecations
  29409. proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
  29410. proto$2.lang = lang;
  29411. // Side effect imports
  29412. // FORMATTING
  29413. addFormatToken('X', 0, 0, 'unix');
  29414. addFormatToken('x', 0, 0, 'valueOf');
  29415. // PARSING
  29416. addRegexToken('x', matchSigned);
  29417. addRegexToken('X', matchTimestamp);
  29418. addParseToken('X', function (input, array, config) {
  29419. config._d = new Date(parseFloat(input, 10) * 1000);
  29420. });
  29421. addParseToken('x', function (input, array, config) {
  29422. config._d = new Date(toInt(input));
  29423. });
  29424. // Side effect imports
  29425. hooks.version = '2.19.1';
  29426. setHookCallback(createLocal);
  29427. hooks.fn = proto;
  29428. hooks.min = min;
  29429. hooks.max = max;
  29430. hooks.now = now;
  29431. hooks.utc = createUTC;
  29432. hooks.unix = createUnix;
  29433. hooks.months = listMonths;
  29434. hooks.isDate = isDate;
  29435. hooks.locale = getSetGlobalLocale;
  29436. hooks.invalid = createInvalid;
  29437. hooks.duration = createDuration;
  29438. hooks.isMoment = isMoment;
  29439. hooks.weekdays = listWeekdays;
  29440. hooks.parseZone = createInZone;
  29441. hooks.localeData = getLocale;
  29442. hooks.isDuration = isDuration;
  29443. hooks.monthsShort = listMonthsShort;
  29444. hooks.weekdaysMin = listWeekdaysMin;
  29445. hooks.defineLocale = defineLocale;
  29446. hooks.updateLocale = updateLocale;
  29447. hooks.locales = listLocales;
  29448. hooks.weekdaysShort = listWeekdaysShort;
  29449. hooks.normalizeUnits = normalizeUnits;
  29450. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  29451. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  29452. hooks.calendarFormat = getCalendarFormat;
  29453. hooks.prototype = proto;
  29454. return hooks;
  29455. })));
  29456. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(155)(module)))
  29457. /***/ }),
  29458. /* 155 */
  29459. /***/ (function(module, exports) {
  29460. module.exports = function(module) {
  29461. if(!module.webpackPolyfill) {
  29462. module.deprecate = function() {};
  29463. module.paths = [];
  29464. // module.parent = undefined by default
  29465. if(!module.children) module.children = [];
  29466. Object.defineProperty(module, "loaded", {
  29467. enumerable: true,
  29468. get: function() {
  29469. return module.l;
  29470. }
  29471. });
  29472. Object.defineProperty(module, "id", {
  29473. enumerable: true,
  29474. get: function() {
  29475. return module.i;
  29476. }
  29477. });
  29478. module.webpackPolyfill = 1;
  29479. }
  29480. return module;
  29481. };
  29482. /***/ }),
  29483. /* 156 */
  29484. /***/ (function(module, exports) {
  29485. function webpackEmptyContext(req) {
  29486. throw new Error("Cannot find module '" + req + "'.");
  29487. }
  29488. webpackEmptyContext.keys = function() { return []; };
  29489. webpackEmptyContext.resolve = webpackEmptyContext;
  29490. module.exports = webpackEmptyContext;
  29491. webpackEmptyContext.id = 156;
  29492. /***/ }),
  29493. /* 157 */
  29494. /***/ (function(module, exports, __webpack_require__) {
  29495. "use strict";
  29496. /* WEBPACK VAR INJECTION */(function(global) {
  29497. /* eslint-disable require-jsdoc */
  29498. var _rng;
  29499. var globalVar = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : null;
  29500. if (globalVar && globalVar.crypto && crypto.getRandomValues) {
  29501. // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
  29502. // Moderately fast, high quality
  29503. var _rnds8 = new Uint8Array(16);
  29504. _rng = function whatwgRNG() {
  29505. crypto.getRandomValues(_rnds8);
  29506. return _rnds8;
  29507. };
  29508. }
  29509. if (!_rng) {
  29510. // Math.random()-based (RNG)
  29511. //
  29512. // If all else fails, use Math.random(). It's fast, but is of unspecified
  29513. // quality.
  29514. var _rnds = new Array(16);
  29515. _rng = function _rng() {
  29516. for (var i = 0, r; i < 16; i++) {
  29517. if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
  29518. _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
  29519. }
  29520. return _rnds;
  29521. };
  29522. }
  29523. // uuid.js
  29524. //
  29525. // Copyright (c) 2010-2012 Robert Kieffer
  29526. // MIT License - http://opensource.org/licenses/mit-license.php
  29527. // Unique ID creation requires a high quality random # generator. We feature
  29528. // detect to determine the best RNG source, normalizing to a function that
  29529. // returns 128-bits of randomness, since that's what's usually required
  29530. //var _rng = require('./rng');
  29531. // Maps for number <-> hex string conversion
  29532. var _byteToHex = [];
  29533. var _hexToByte = {};
  29534. for (var i = 0; i < 256; i++) {
  29535. _byteToHex[i] = (i + 0x100).toString(16).substr(1);
  29536. _hexToByte[_byteToHex[i]] = i;
  29537. }
  29538. // **`parse()` - Parse a UUID into it's component bytes**
  29539. function parse(s, buf, offset) {
  29540. var i = buf && offset || 0,
  29541. ii = 0;
  29542. buf = buf || [];
  29543. s.toLowerCase().replace(/[0-9a-f]{2}/g, function (oct) {
  29544. if (ii < 16) {
  29545. // Don't overflow!
  29546. buf[i + ii++] = _hexToByte[oct];
  29547. }
  29548. });
  29549. // Zero out remaining bytes if string was short
  29550. while (ii < 16) {
  29551. buf[i + ii++] = 0;
  29552. }
  29553. return buf;
  29554. }
  29555. // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
  29556. function unparse(buf, offset) {
  29557. var i = offset || 0,
  29558. bth = _byteToHex;
  29559. 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++]];
  29560. }
  29561. // **`v1()` - Generate time-based UUID**
  29562. //
  29563. // Inspired by https://github.com/LiosK/UUID.js
  29564. // and http://docs.python.org/library/uuid.html
  29565. // random #'s we need to init node and clockseq
  29566. var _seedBytes = _rng();
  29567. // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
  29568. var _nodeId = [_seedBytes[0] | 0x01, _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]];
  29569. // Per 4.2.2, randomize (14 bit) clockseq
  29570. var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
  29571. // Previous uuid creation time
  29572. var _lastMSecs = 0,
  29573. _lastNSecs = 0;
  29574. // See https://github.com/broofa/node-uuid for API details
  29575. function v1(options, buf, offset) {
  29576. var i = buf && offset || 0;
  29577. var b = buf || [];
  29578. options = options || {};
  29579. var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
  29580. // UUID timestamps are 100 nano-second units since the Gregorian epoch,
  29581. // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
  29582. // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
  29583. // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
  29584. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
  29585. // Per 4.2.1.2, use count of uuid's generated during the current clock
  29586. // cycle to simulate higher resolution clock
  29587. var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
  29588. // Time since last uuid creation (in msecs)
  29589. var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000;
  29590. // Per 4.2.1.2, Bump clockseq on clock regression
  29591. if (dt < 0 && options.clockseq === undefined) {
  29592. clockseq = clockseq + 1 & 0x3fff;
  29593. }
  29594. // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
  29595. // time interval
  29596. if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
  29597. nsecs = 0;
  29598. }
  29599. // Per 4.2.1.2 Throw error if too many uuids are requested
  29600. if (nsecs >= 10000) {
  29601. throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
  29602. }
  29603. _lastMSecs = msecs;
  29604. _lastNSecs = nsecs;
  29605. _clockseq = clockseq;
  29606. // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
  29607. msecs += 12219292800000;
  29608. // `time_low`
  29609. var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
  29610. b[i++] = tl >>> 24 & 0xff;
  29611. b[i++] = tl >>> 16 & 0xff;
  29612. b[i++] = tl >>> 8 & 0xff;
  29613. b[i++] = tl & 0xff;
  29614. // `time_mid`
  29615. var tmh = msecs / 0x100000000 * 10000 & 0xfffffff;
  29616. b[i++] = tmh >>> 8 & 0xff;
  29617. b[i++] = tmh & 0xff;
  29618. // `time_high_and_version`
  29619. b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
  29620. b[i++] = tmh >>> 16 & 0xff;
  29621. // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
  29622. b[i++] = clockseq >>> 8 | 0x80;
  29623. // `clock_seq_low`
  29624. b[i++] = clockseq & 0xff;
  29625. // `node`
  29626. var node = options.node || _nodeId;
  29627. for (var n = 0; n < 6; n++) {
  29628. b[i + n] = node[n];
  29629. }
  29630. return buf ? buf : unparse(b);
  29631. }
  29632. // **`v4()` - Generate random UUID**
  29633. // See https://github.com/broofa/node-uuid for API details
  29634. function v4(options, buf, offset) {
  29635. // Deprecated - 'format' argument, as supported in v1.2
  29636. var i = buf && offset || 0;
  29637. if (typeof options == 'string') {
  29638. buf = options == 'binary' ? new Array(16) : null;
  29639. options = null;
  29640. }
  29641. options = options || {};
  29642. var rnds = options.random || (options.rng || _rng)();
  29643. // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
  29644. rnds[6] = rnds[6] & 0x0f | 0x40;
  29645. rnds[8] = rnds[8] & 0x3f | 0x80;
  29646. // Copy bytes to buffer, if provided
  29647. if (buf) {
  29648. for (var ii = 0; ii < 16; ii++) {
  29649. buf[i + ii] = rnds[ii];
  29650. }
  29651. }
  29652. return buf || unparse(rnds);
  29653. }
  29654. // Export public API
  29655. var uuid = v4;
  29656. uuid.v1 = v1;
  29657. uuid.v4 = v4;
  29658. uuid.parse = parse;
  29659. uuid.unparse = unparse;
  29660. module.exports = uuid;
  29661. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(158)))
  29662. /***/ }),
  29663. /* 158 */
  29664. /***/ (function(module, exports) {
  29665. var g;
  29666. // This works in non-strict mode
  29667. g = (function() {
  29668. return this;
  29669. })();
  29670. try {
  29671. // This works if eval is allowed (see CSP)
  29672. g = g || Function("return this")() || (1,eval)("this");
  29673. } catch(e) {
  29674. // This works if the window reference is available
  29675. if(typeof window === "object")
  29676. g = window;
  29677. }
  29678. // g can still be undefined, but nothing to do about it...
  29679. // We return undefined, instead of nothing here, so it's
  29680. // easier to handle this case. if(!global) { ...}
  29681. module.exports = g;
  29682. /***/ }),
  29683. /* 159 */
  29684. /***/ (function(module, exports, __webpack_require__) {
  29685. "use strict";
  29686. // utils
  29687. exports.util = __webpack_require__(2);
  29688. exports.DOMutil = __webpack_require__(14);
  29689. // data
  29690. exports.DataSet = __webpack_require__(11);
  29691. exports.DataView = __webpack_require__(12);
  29692. exports.Queue = __webpack_require__(43);
  29693. // Graph3d
  29694. exports.Graph3d = __webpack_require__(161);
  29695. exports.graph3d = {
  29696. Camera: __webpack_require__(95),
  29697. Filter: __webpack_require__(96),
  29698. Point2d: __webpack_require__(91),
  29699. Point3d: __webpack_require__(34),
  29700. Slider: __webpack_require__(92),
  29701. StepNumber: __webpack_require__(93)
  29702. };
  29703. // bundled external libraries
  29704. exports.moment = __webpack_require__(9);
  29705. exports.Hammer = __webpack_require__(10);
  29706. exports.keycharm = __webpack_require__(35);
  29707. /***/ }),
  29708. /* 160 */
  29709. /***/ (function(module, exports, __webpack_require__) {
  29710. var core = __webpack_require__(7);
  29711. var $JSON = core.JSON || (core.JSON = { stringify: JSON.stringify });
  29712. module.exports = function stringify(it) { // eslint-disable-line no-unused-vars
  29713. return $JSON.stringify.apply($JSON, arguments);
  29714. };
  29715. /***/ }),
  29716. /* 161 */
  29717. /***/ (function(module, exports, __webpack_require__) {
  29718. "use strict";
  29719. var _assign = __webpack_require__(90);
  29720. var _assign2 = _interopRequireDefault(_assign);
  29721. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  29722. var Emitter = __webpack_require__(44);
  29723. var util = __webpack_require__(2);
  29724. var Point3d = __webpack_require__(34);
  29725. var Point2d = __webpack_require__(91);
  29726. var Slider = __webpack_require__(92);
  29727. var StepNumber = __webpack_require__(93);
  29728. var Settings = __webpack_require__(94);
  29729. var Validator = __webpack_require__(15)['default'];
  29730. var _require = __webpack_require__(15),
  29731. printStyle = _require.printStyle;
  29732. var _require2 = __webpack_require__(172),
  29733. allOptions = _require2.allOptions;
  29734. var DataGroup = __webpack_require__(173);
  29735. /// enumerate the available styles
  29736. Graph3d.STYLE = Settings.STYLE;
  29737. /**
  29738. * Following label is used in the settings to describe values which should be
  29739. * determined by the code while running, from the current data and graph style.
  29740. *
  29741. * Using 'undefined' directly achieves the same thing, but this is more
  29742. * descriptive by describing the intent.
  29743. */
  29744. var autoByDefault = undefined;
  29745. /**
  29746. * Default values for option settings.
  29747. *
  29748. * These are the values used when a Graph3d instance is initialized without
  29749. * custom settings.
  29750. *
  29751. * If a field is not in this list, a default value of 'autoByDefault' is assumed,
  29752. * which is just an alias for 'undefined'.
  29753. */
  29754. Graph3d.DEFAULTS = {
  29755. width: '400px',
  29756. height: '400px',
  29757. filterLabel: 'time',
  29758. legendLabel: 'value',
  29759. xLabel: 'x',
  29760. yLabel: 'y',
  29761. zLabel: 'z',
  29762. xValueLabel: function xValueLabel(v) {
  29763. return v;
  29764. },
  29765. yValueLabel: function yValueLabel(v) {
  29766. return v;
  29767. },
  29768. zValueLabel: function zValueLabel(v) {
  29769. return v;
  29770. },
  29771. showXAxis: true,
  29772. showYAxis: true,
  29773. showZAxis: true,
  29774. showGrid: true,
  29775. showPerspective: true,
  29776. showShadow: false,
  29777. keepAspectRatio: true,
  29778. verticalRatio: 0.5, // 0.1 to 1.0, where 1.0 results in a 'cube'
  29779. dotSizeRatio: 0.02, // size of the dots as a fraction of the graph width
  29780. dotSizeMinFraction: 0.5, // size of min-value dot as a fraction of dotSizeRatio
  29781. dotSizeMaxFraction: 2.5, // size of max-value dot as a fraction of dotSizeRatio
  29782. showAnimationControls: autoByDefault,
  29783. animationInterval: 1000, // milliseconds
  29784. animationPreload: false,
  29785. animationAutoStart: autoByDefault,
  29786. axisColor: '#4D4D4D',
  29787. gridColor: '#D3D3D3',
  29788. xCenter: '55%',
  29789. yCenter: '50%',
  29790. style: Graph3d.STYLE.DOT,
  29791. tooltip: false,
  29792. tooltipStyle: {
  29793. content: {
  29794. padding: '10px',
  29795. border: '1px solid #4d4d4d',
  29796. color: '#1a1a1a',
  29797. background: 'rgba(255,255,255,0.7)',
  29798. borderRadius: '2px',
  29799. boxShadow: '5px 5px 10px rgba(128,128,128,0.5)'
  29800. },
  29801. line: {
  29802. height: '40px',
  29803. width: '0',
  29804. borderLeft: '1px solid #4d4d4d'
  29805. },
  29806. dot: {
  29807. height: '0',
  29808. width: '0',
  29809. border: '5px solid #4d4d4d',
  29810. borderRadius: '5px'
  29811. }
  29812. },
  29813. dataColor: {
  29814. fill: '#7DC1FF',
  29815. stroke: '#3267D2',
  29816. strokeWidth: 1 // px
  29817. },
  29818. cameraPosition: {
  29819. horizontal: 1.0,
  29820. vertical: 0.5,
  29821. distance: 1.7
  29822. },
  29823. /*
  29824. The following fields are 'auto by default', see above.
  29825. */
  29826. showLegend: autoByDefault, // determined by graph style
  29827. backgroundColor: autoByDefault,
  29828. xBarWidth: autoByDefault,
  29829. yBarWidth: autoByDefault,
  29830. valueMin: autoByDefault,
  29831. valueMax: autoByDefault,
  29832. xMin: autoByDefault,
  29833. xMax: autoByDefault,
  29834. xStep: autoByDefault,
  29835. yMin: autoByDefault,
  29836. yMax: autoByDefault,
  29837. yStep: autoByDefault,
  29838. zMin: autoByDefault,
  29839. zMax: autoByDefault,
  29840. zStep: autoByDefault
  29841. };
  29842. // -----------------------------------------------------------------------------
  29843. // Class Graph3d
  29844. // -----------------------------------------------------------------------------
  29845. /**
  29846. * Graph3d displays data in 3d.
  29847. *
  29848. * Graph3d is developed in javascript as a Google Visualization Chart.
  29849. *
  29850. * @constructor Graph3d
  29851. * @param {Element} container The DOM element in which the Graph3d will
  29852. * be created. Normally a div element.
  29853. * @param {DataSet | DataView | Array} [data]
  29854. * @param {Object} [options]
  29855. */
  29856. function Graph3d(container, data, options) {
  29857. if (!(this instanceof Graph3d)) {
  29858. throw new SyntaxError('Constructor must be called with the new operator');
  29859. }
  29860. // create variables and set default values
  29861. this.containerElement = container;
  29862. this.dataGroup = new DataGroup();
  29863. this.dataPoints = null; // The table with point objects
  29864. // create a frame and canvas
  29865. this.create();
  29866. Settings.setDefaults(Graph3d.DEFAULTS, this);
  29867. // the column indexes
  29868. this.colX = undefined;
  29869. this.colY = undefined;
  29870. this.colZ = undefined;
  29871. this.colValue = undefined;
  29872. // TODO: customize axis range
  29873. // apply options (also when undefined)
  29874. this.setOptions(options);
  29875. // apply data
  29876. this.setData(data);
  29877. }
  29878. // Extend Graph3d with an Emitter mixin
  29879. Emitter(Graph3d.prototype);
  29880. /**
  29881. * Calculate the scaling values, dependent on the range in x, y, and z direction
  29882. */
  29883. Graph3d.prototype._setScale = function () {
  29884. this.scale = new Point3d(1 / this.xRange.range(), 1 / this.yRange.range(), 1 / this.zRange.range());
  29885. // keep aspect ration between x and y scale if desired
  29886. if (this.keepAspectRatio) {
  29887. if (this.scale.x < this.scale.y) {
  29888. //noinspection JSSuspiciousNameCombination
  29889. this.scale.y = this.scale.x;
  29890. } else {
  29891. //noinspection JSSuspiciousNameCombination
  29892. this.scale.x = this.scale.y;
  29893. }
  29894. }
  29895. // scale the vertical axis
  29896. this.scale.z *= this.verticalRatio;
  29897. // TODO: can this be automated? verticalRatio?
  29898. // determine scale for (optional) value
  29899. if (this.valueRange !== undefined) {
  29900. this.scale.value = 1 / this.valueRange.range();
  29901. }
  29902. // position the camera arm
  29903. var xCenter = this.xRange.center() * this.scale.x;
  29904. var yCenter = this.yRange.center() * this.scale.y;
  29905. var zCenter = this.zRange.center() * this.scale.z;
  29906. this.camera.setArmLocation(xCenter, yCenter, zCenter);
  29907. };
  29908. /**
  29909. * Convert a 3D location to a 2D location on screen
  29910. * Source: ttp://en.wikipedia.org/wiki/3D_projection
  29911. *
  29912. * @param {Point3d} point3d A 3D point with parameters x, y, z
  29913. * @returns {Point2d} point2d A 2D point with parameters x, y
  29914. */
  29915. Graph3d.prototype._convert3Dto2D = function (point3d) {
  29916. var translation = this._convertPointToTranslation(point3d);
  29917. return this._convertTranslationToScreen(translation);
  29918. };
  29919. /**
  29920. * Convert a 3D location its translation seen from the camera
  29921. * Source: http://en.wikipedia.org/wiki/3D_projection
  29922. *
  29923. * @param {Point3d} point3d A 3D point with parameters x, y, z
  29924. * @returns {Point3d} translation A 3D point with parameters x, y, z This is
  29925. * the translation of the point, seen from the
  29926. * camera.
  29927. */
  29928. Graph3d.prototype._convertPointToTranslation = function (point3d) {
  29929. var cameraLocation = this.camera.getCameraLocation(),
  29930. cameraRotation = this.camera.getCameraRotation(),
  29931. ax = point3d.x * this.scale.x,
  29932. ay = point3d.y * this.scale.y,
  29933. az = point3d.z * this.scale.z,
  29934. cx = cameraLocation.x,
  29935. cy = cameraLocation.y,
  29936. cz = cameraLocation.z,
  29937. // calculate angles
  29938. sinTx = Math.sin(cameraRotation.x),
  29939. cosTx = Math.cos(cameraRotation.x),
  29940. sinTy = Math.sin(cameraRotation.y),
  29941. cosTy = Math.cos(cameraRotation.y),
  29942. sinTz = Math.sin(cameraRotation.z),
  29943. cosTz = Math.cos(cameraRotation.z),
  29944. // calculate translation
  29945. dx = cosTy * (sinTz * (ay - cy) + cosTz * (ax - cx)) - sinTy * (az - cz),
  29946. dy = sinTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) + cosTx * (cosTz * (ay - cy) - sinTz * (ax - cx)),
  29947. dz = cosTx * (cosTy * (az - cz) + sinTy * (sinTz * (ay - cy) + cosTz * (ax - cx))) - sinTx * (cosTz * (ay - cy) - sinTz * (ax - cx));
  29948. return new Point3d(dx, dy, dz);
  29949. };
  29950. /**
  29951. * Convert a translation point to a point on the screen
  29952. *
  29953. * @param {Point3d} translation A 3D point with parameters x, y, z This is
  29954. * the translation of the point, seen from the
  29955. * camera.
  29956. * @returns {Point2d} point2d A 2D point with parameters x, y
  29957. */
  29958. Graph3d.prototype._convertTranslationToScreen = function (translation) {
  29959. var ex = this.eye.x,
  29960. ey = this.eye.y,
  29961. ez = this.eye.z,
  29962. dx = translation.x,
  29963. dy = translation.y,
  29964. dz = translation.z;
  29965. // calculate position on screen from translation
  29966. var bx;
  29967. var by;
  29968. if (this.showPerspective) {
  29969. bx = (dx - ex) * (ez / dz);
  29970. by = (dy - ey) * (ez / dz);
  29971. } else {
  29972. bx = dx * -(ez / this.camera.getArmLength());
  29973. by = dy * -(ez / this.camera.getArmLength());
  29974. }
  29975. // shift and scale the point to the center of the screen
  29976. // use the width of the graph to scale both horizontally and vertically.
  29977. return new Point2d(this.currentXCenter + bx * this.frame.canvas.clientWidth, this.currentYCenter - by * this.frame.canvas.clientWidth);
  29978. };
  29979. /**
  29980. * Calculate the translations and screen positions of all points
  29981. *
  29982. * @param {Array.<Point3d>} points
  29983. * @private
  29984. */
  29985. Graph3d.prototype._calcTranslations = function (points) {
  29986. for (var i = 0; i < points.length; i++) {
  29987. var point = points[i];
  29988. point.trans = this._convertPointToTranslation(point.point);
  29989. point.screen = this._convertTranslationToScreen(point.trans);
  29990. // calculate the translation of the point at the bottom (needed for sorting)
  29991. var transBottom = this._convertPointToTranslation(point.bottom);
  29992. point.dist = this.showPerspective ? transBottom.length() : -transBottom.z;
  29993. }
  29994. // sort the points on depth of their (x,y) position (not on z)
  29995. var sortDepth = function sortDepth(a, b) {
  29996. return b.dist - a.dist;
  29997. };
  29998. points.sort(sortDepth);
  29999. };
  30000. /**
  30001. * Transfer min/max values to the Graph3d instance.
  30002. */
  30003. Graph3d.prototype._initializeRanges = function () {
  30004. // TODO: later on, all min/maxes of all datagroups will be combined here
  30005. var dg = this.dataGroup;
  30006. this.xRange = dg.xRange;
  30007. this.yRange = dg.yRange;
  30008. this.zRange = dg.zRange;
  30009. this.valueRange = dg.valueRange;
  30010. // Values currently needed but which need to be sorted out for
  30011. // the multiple graph case.
  30012. this.xStep = dg.xStep;
  30013. this.yStep = dg.yStep;
  30014. this.zStep = dg.zStep;
  30015. this.xBarWidth = dg.xBarWidth;
  30016. this.yBarWidth = dg.yBarWidth;
  30017. this.colX = dg.colX;
  30018. this.colY = dg.colY;
  30019. this.colZ = dg.colZ;
  30020. this.colValue = dg.colValue;
  30021. // set the scale dependent on the ranges.
  30022. this._setScale();
  30023. };
  30024. /**
  30025. * Return all data values as a list of Point3d objects
  30026. *
  30027. * @param {vis.DataSet} data
  30028. * @returns {Array.<Object>}
  30029. */
  30030. Graph3d.prototype.getDataPoints = function (data) {
  30031. var dataPoints = [];
  30032. for (var i = 0; i < data.length; i++) {
  30033. var point = new Point3d();
  30034. point.x = data[i][this.colX] || 0;
  30035. point.y = data[i][this.colY] || 0;
  30036. point.z = data[i][this.colZ] || 0;
  30037. point.data = data[i];
  30038. if (this.colValue !== undefined) {
  30039. point.value = data[i][this.colValue] || 0;
  30040. }
  30041. var obj = {};
  30042. obj.point = point;
  30043. obj.bottom = new Point3d(point.x, point.y, this.zRange.min);
  30044. obj.trans = undefined;
  30045. obj.screen = undefined;
  30046. dataPoints.push(obj);
  30047. }
  30048. return dataPoints;
  30049. };
  30050. /**
  30051. * Filter the data based on the current filter
  30052. *
  30053. * @param {Array} data
  30054. * @returns {Array} dataPoints Array with point objects which can be drawn on
  30055. * screen
  30056. */
  30057. Graph3d.prototype._getDataPoints = function (data) {
  30058. // TODO: store the created matrix dataPoints in the filters instead of
  30059. // reloading each time.
  30060. var x, y, i, obj;
  30061. var dataPoints = [];
  30062. if (this.style === Graph3d.STYLE.GRID || this.style === Graph3d.STYLE.SURFACE) {
  30063. // copy all values from the data table to a matrix
  30064. // the provided values are supposed to form a grid of (x,y) positions
  30065. // create two lists with all present x and y values
  30066. var dataX = this.dataGroup.getDistinctValues(this.colX, data);
  30067. var dataY = this.dataGroup.getDistinctValues(this.colY, data);
  30068. dataPoints = this.getDataPoints(data);
  30069. // create a grid, a 2d matrix, with all values.
  30070. var dataMatrix = []; // temporary data matrix
  30071. for (i = 0; i < dataPoints.length; i++) {
  30072. obj = dataPoints[i];
  30073. // TODO: implement Array().indexOf() for Internet Explorer
  30074. var xIndex = dataX.indexOf(obj.point.x);
  30075. var yIndex = dataY.indexOf(obj.point.y);
  30076. if (dataMatrix[xIndex] === undefined) {
  30077. dataMatrix[xIndex] = [];
  30078. }
  30079. dataMatrix[xIndex][yIndex] = obj;
  30080. }
  30081. // fill in the pointers to the neighbors.
  30082. for (x = 0; x < dataMatrix.length; x++) {
  30083. for (y = 0; y < dataMatrix[x].length; y++) {
  30084. if (dataMatrix[x][y]) {
  30085. dataMatrix[x][y].pointRight = x < dataMatrix.length - 1 ? dataMatrix[x + 1][y] : undefined;
  30086. dataMatrix[x][y].pointTop = y < dataMatrix[x].length - 1 ? dataMatrix[x][y + 1] : undefined;
  30087. dataMatrix[x][y].pointCross = x < dataMatrix.length - 1 && y < dataMatrix[x].length - 1 ? dataMatrix[x + 1][y + 1] : undefined;
  30088. }
  30089. }
  30090. }
  30091. } else {
  30092. // 'dot', 'dot-line', etc.
  30093. this._checkValueField(data);
  30094. dataPoints = this.getDataPoints(data);
  30095. if (this.style === Graph3d.STYLE.LINE) {
  30096. // Add next member points for line drawing
  30097. for (i = 0; i < dataPoints.length; i++) {
  30098. if (i > 0) {
  30099. dataPoints[i - 1].pointNext = dataPoints[i];
  30100. }
  30101. }
  30102. }
  30103. }
  30104. return dataPoints;
  30105. };
  30106. /**
  30107. * Create the main frame for the Graph3d.
  30108. *
  30109. * This function is executed once when a Graph3d object is created. The frame
  30110. * contains a canvas, and this canvas contains all objects like the axis and
  30111. * nodes.
  30112. */
  30113. Graph3d.prototype.create = function () {
  30114. // remove all elements from the container element.
  30115. while (this.containerElement.hasChildNodes()) {
  30116. this.containerElement.removeChild(this.containerElement.firstChild);
  30117. }
  30118. this.frame = document.createElement('div');
  30119. this.frame.style.position = 'relative';
  30120. this.frame.style.overflow = 'hidden';
  30121. // create the graph canvas (HTML canvas element)
  30122. this.frame.canvas = document.createElement('canvas');
  30123. this.frame.canvas.style.position = 'relative';
  30124. this.frame.appendChild(this.frame.canvas);
  30125. //if (!this.frame.canvas.getContext) {
  30126. {
  30127. var noCanvas = document.createElement('DIV');
  30128. noCanvas.style.color = 'red';
  30129. noCanvas.style.fontWeight = 'bold';
  30130. noCanvas.style.padding = '10px';
  30131. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  30132. this.frame.canvas.appendChild(noCanvas);
  30133. }
  30134. this.frame.filter = document.createElement('div');
  30135. this.frame.filter.style.position = 'absolute';
  30136. this.frame.filter.style.bottom = '0px';
  30137. this.frame.filter.style.left = '0px';
  30138. this.frame.filter.style.width = '100%';
  30139. this.frame.appendChild(this.frame.filter);
  30140. // add event listeners to handle moving and zooming the contents
  30141. var me = this;
  30142. var onmousedown = function onmousedown(event) {
  30143. me._onMouseDown(event);
  30144. };
  30145. var ontouchstart = function ontouchstart(event) {
  30146. me._onTouchStart(event);
  30147. };
  30148. var onmousewheel = function onmousewheel(event) {
  30149. me._onWheel(event);
  30150. };
  30151. var ontooltip = function ontooltip(event) {
  30152. me._onTooltip(event);
  30153. };
  30154. var onclick = function onclick(event) {
  30155. me._onClick(event);
  30156. };
  30157. // TODO: these events are never cleaned up... can give a 'memory leakage'
  30158. util.addEventListener(this.frame.canvas, 'mousedown', onmousedown);
  30159. util.addEventListener(this.frame.canvas, 'touchstart', ontouchstart);
  30160. util.addEventListener(this.frame.canvas, 'mousewheel', onmousewheel);
  30161. util.addEventListener(this.frame.canvas, 'mousemove', ontooltip);
  30162. util.addEventListener(this.frame.canvas, 'click', onclick);
  30163. // add the new graph to the container element
  30164. this.containerElement.appendChild(this.frame);
  30165. };
  30166. /**
  30167. * Set a new size for the graph
  30168. *
  30169. * @param {number} width
  30170. * @param {number} height
  30171. * @private
  30172. */
  30173. Graph3d.prototype._setSize = function (width, height) {
  30174. this.frame.style.width = width;
  30175. this.frame.style.height = height;
  30176. this._resizeCanvas();
  30177. };
  30178. /**
  30179. * Resize the canvas to the current size of the frame
  30180. */
  30181. Graph3d.prototype._resizeCanvas = function () {
  30182. this.frame.canvas.style.width = '100%';
  30183. this.frame.canvas.style.height = '100%';
  30184. this.frame.canvas.width = this.frame.canvas.clientWidth;
  30185. this.frame.canvas.height = this.frame.canvas.clientHeight;
  30186. // adjust with for margin
  30187. this.frame.filter.style.width = this.frame.canvas.clientWidth - 2 * 10 + 'px';
  30188. };
  30189. /**
  30190. * Start playing the animation, if requested and filter present. Only applicable
  30191. * when animation data is available.
  30192. */
  30193. Graph3d.prototype.animationStart = function () {
  30194. // start animation when option is true
  30195. if (!this.animationAutoStart || !this.dataGroup.dataFilter) return;
  30196. if (!this.frame.filter || !this.frame.filter.slider) throw new Error('No animation available');
  30197. this.frame.filter.slider.play();
  30198. };
  30199. /**
  30200. * Stop animation
  30201. */
  30202. Graph3d.prototype.animationStop = function () {
  30203. if (!this.frame.filter || !this.frame.filter.slider) return;
  30204. this.frame.filter.slider.stop();
  30205. };
  30206. /**
  30207. * Resize the center position based on the current values in this.xCenter
  30208. * and this.yCenter (which are strings with a percentage or a value
  30209. * in pixels). The center positions are the variables this.currentXCenter
  30210. * and this.currentYCenter
  30211. */
  30212. Graph3d.prototype._resizeCenter = function () {
  30213. // calculate the horizontal center position
  30214. if (this.xCenter.charAt(this.xCenter.length - 1) === '%') {
  30215. this.currentXCenter = parseFloat(this.xCenter) / 100 * this.frame.canvas.clientWidth;
  30216. } else {
  30217. this.currentXCenter = parseFloat(this.xCenter); // supposed to be in px
  30218. }
  30219. // calculate the vertical center position
  30220. if (this.yCenter.charAt(this.yCenter.length - 1) === '%') {
  30221. this.currentYCenter = parseFloat(this.yCenter) / 100 * (this.frame.canvas.clientHeight - this.frame.filter.clientHeight);
  30222. } else {
  30223. this.currentYCenter = parseFloat(this.yCenter); // supposed to be in px
  30224. }
  30225. };
  30226. /**
  30227. * Retrieve the current camera rotation
  30228. *
  30229. * @returns {object} An object with parameters horizontal, vertical, and
  30230. * distance
  30231. */
  30232. Graph3d.prototype.getCameraPosition = function () {
  30233. var pos = this.camera.getArmRotation();
  30234. pos.distance = this.camera.getArmLength();
  30235. return pos;
  30236. };
  30237. /**
  30238. * Load data into the 3D Graph
  30239. *
  30240. * @param {vis.DataSet} data
  30241. * @private
  30242. */
  30243. Graph3d.prototype._readData = function (data) {
  30244. // read the data
  30245. this.dataPoints = this.dataGroup.initializeData(this, data, this.style);
  30246. this._initializeRanges();
  30247. this._redrawFilter();
  30248. };
  30249. /**
  30250. * Replace the dataset of the Graph3d
  30251. *
  30252. * @param {Array | DataSet | DataView} data
  30253. */
  30254. Graph3d.prototype.setData = function (data) {
  30255. if (data === undefined || data === null) return;
  30256. this._readData(data);
  30257. this.redraw();
  30258. this.animationStart();
  30259. };
  30260. /**
  30261. * Update the options. Options will be merged with current options
  30262. *
  30263. * @param {Object} options
  30264. */
  30265. Graph3d.prototype.setOptions = function (options) {
  30266. if (options === undefined) return;
  30267. var errorFound = Validator.validate(options, allOptions);
  30268. if (errorFound === true) {
  30269. console.log('%cErrors have been found in the supplied options object.', printStyle);
  30270. }
  30271. this.animationStop();
  30272. Settings.setOptions(options, this);
  30273. this.setPointDrawingMethod();
  30274. this._setSize(this.width, this.height);
  30275. this.setData(this.dataGroup.getDataTable());
  30276. this.animationStart();
  30277. };
  30278. /**
  30279. * Determine which point drawing method to use for the current graph style.
  30280. */
  30281. Graph3d.prototype.setPointDrawingMethod = function () {
  30282. var method = undefined;
  30283. switch (this.style) {
  30284. case Graph3d.STYLE.BAR:
  30285. method = Graph3d.prototype._redrawBarGraphPoint;
  30286. break;
  30287. case Graph3d.STYLE.BARCOLOR:
  30288. method = Graph3d.prototype._redrawBarColorGraphPoint;
  30289. break;
  30290. case Graph3d.STYLE.BARSIZE:
  30291. method = Graph3d.prototype._redrawBarSizeGraphPoint;
  30292. break;
  30293. case Graph3d.STYLE.DOT:
  30294. method = Graph3d.prototype._redrawDotGraphPoint;
  30295. break;
  30296. case Graph3d.STYLE.DOTLINE:
  30297. method = Graph3d.prototype._redrawDotLineGraphPoint;
  30298. break;
  30299. case Graph3d.STYLE.DOTCOLOR:
  30300. method = Graph3d.prototype._redrawDotColorGraphPoint;
  30301. break;
  30302. case Graph3d.STYLE.DOTSIZE:
  30303. method = Graph3d.prototype._redrawDotSizeGraphPoint;
  30304. break;
  30305. case Graph3d.STYLE.SURFACE:
  30306. method = Graph3d.prototype._redrawSurfaceGraphPoint;
  30307. break;
  30308. case Graph3d.STYLE.GRID:
  30309. method = Graph3d.prototype._redrawGridGraphPoint;
  30310. break;
  30311. case Graph3d.STYLE.LINE:
  30312. method = Graph3d.prototype._redrawLineGraphPoint;
  30313. break;
  30314. default:
  30315. throw new Error('Can not determine point drawing method ' + 'for graph style \'' + this.style + '\'');
  30316. }
  30317. this._pointDrawingMethod = method;
  30318. };
  30319. /**
  30320. * Redraw the Graph.
  30321. */
  30322. Graph3d.prototype.redraw = function () {
  30323. if (this.dataPoints === undefined) {
  30324. throw new Error('Graph data not initialized');
  30325. }
  30326. this._resizeCanvas();
  30327. this._resizeCenter();
  30328. this._redrawSlider();
  30329. this._redrawClear();
  30330. this._redrawAxis();
  30331. this._redrawDataGraph();
  30332. this._redrawInfo();
  30333. this._redrawLegend();
  30334. };
  30335. /**
  30336. * Get drawing context without exposing canvas
  30337. *
  30338. * @returns {CanvasRenderingContext2D}
  30339. * @private
  30340. */
  30341. Graph3d.prototype._getContext = function () {
  30342. var canvas = this.frame.canvas;
  30343. var ctx = canvas.getContext('2d');
  30344. ctx.lineJoin = 'round';
  30345. ctx.lineCap = 'round';
  30346. return ctx;
  30347. };
  30348. /**
  30349. * Clear the canvas before redrawing
  30350. */
  30351. Graph3d.prototype._redrawClear = function () {
  30352. var canvas = this.frame.canvas;
  30353. var ctx = canvas.getContext('2d');
  30354. ctx.clearRect(0, 0, canvas.width, canvas.height);
  30355. };
  30356. Graph3d.prototype._dotSize = function () {
  30357. return this.frame.clientWidth * this.dotSizeRatio;
  30358. };
  30359. /**
  30360. * Get legend width
  30361. *
  30362. * @returns {*}
  30363. * @private
  30364. */
  30365. Graph3d.prototype._getLegendWidth = function () {
  30366. var width;
  30367. if (this.style === Graph3d.STYLE.DOTSIZE) {
  30368. var dotSize = this._dotSize();
  30369. //width = dotSize / 2 + dotSize * 2;
  30370. width = dotSize * this.dotSizeMaxFraction;
  30371. } else if (this.style === Graph3d.STYLE.BARSIZE) {
  30372. width = this.xBarWidth;
  30373. } else {
  30374. width = 20;
  30375. }
  30376. return width;
  30377. };
  30378. /**
  30379. * Redraw the legend based on size, dot color, or surface height
  30380. */
  30381. Graph3d.prototype._redrawLegend = function () {
  30382. //Return without drawing anything, if no legend is specified
  30383. if (this.showLegend !== true) {
  30384. return;
  30385. }
  30386. // Do not draw legend when graph style does not support
  30387. if (this.style === Graph3d.STYLE.LINE || this.style === Graph3d.STYLE.BARSIZE //TODO add legend support for BARSIZE
  30388. ) {
  30389. return;
  30390. }
  30391. // Legend types - size and color. Determine if size legend.
  30392. var isSizeLegend = this.style === Graph3d.STYLE.BARSIZE || this.style === Graph3d.STYLE.DOTSIZE;
  30393. // Legend is either tracking z values or style values. This flag if false means use z values.
  30394. var isValueLegend = this.style === Graph3d.STYLE.DOTSIZE || this.style === Graph3d.STYLE.DOTCOLOR || this.style === Graph3d.STYLE.BARCOLOR;
  30395. var height = Math.max(this.frame.clientHeight * 0.25, 100);
  30396. var top = this.margin;
  30397. var width = this._getLegendWidth(); // px - overwritten by size legend
  30398. var right = this.frame.clientWidth - this.margin;
  30399. var left = right - width;
  30400. var bottom = top + height;
  30401. var ctx = this._getContext();
  30402. ctx.lineWidth = 1;
  30403. ctx.font = '14px arial'; // TODO: put in options
  30404. if (isSizeLegend === false) {
  30405. // draw the color bar
  30406. var ymin = 0;
  30407. var ymax = height; // Todo: make height customizable
  30408. var y;
  30409. for (y = ymin; y < ymax; y++) {
  30410. var f = (y - ymin) / (ymax - ymin);
  30411. var hue = f * 240;
  30412. var color = this._hsv2rgb(hue, 1, 1);
  30413. ctx.strokeStyle = color;
  30414. ctx.beginPath();
  30415. ctx.moveTo(left, top + y);
  30416. ctx.lineTo(right, top + y);
  30417. ctx.stroke();
  30418. }
  30419. ctx.strokeStyle = this.axisColor;
  30420. ctx.strokeRect(left, top, width, height);
  30421. } else {
  30422. // draw the size legend box
  30423. var widthMin;
  30424. if (this.style === Graph3d.STYLE.DOTSIZE) {
  30425. // Get the proportion to max and min right
  30426. widthMin = width * (this.dotSizeMinFraction / this.dotSizeMaxFraction);
  30427. } else if (this.style === Graph3d.STYLE.BARSIZE) {
  30428. //widthMin = this.xBarWidth * 0.2 this is wrong - barwidth measures in terms of xvalues
  30429. }
  30430. ctx.strokeStyle = this.axisColor;
  30431. ctx.fillStyle = this.dataColor.fill;
  30432. ctx.beginPath();
  30433. ctx.moveTo(left, top);
  30434. ctx.lineTo(right, top);
  30435. ctx.lineTo(left + widthMin, bottom);
  30436. ctx.lineTo(left, bottom);
  30437. ctx.closePath();
  30438. ctx.fill();
  30439. ctx.stroke();
  30440. }
  30441. // print value text along the legend edge
  30442. var gridLineLen = 5; // px
  30443. var legendMin = isValueLegend ? this.valueRange.min : this.zRange.min;
  30444. var legendMax = isValueLegend ? this.valueRange.max : this.zRange.max;
  30445. var step = new StepNumber(legendMin, legendMax, (legendMax - legendMin) / 5, true);
  30446. step.start(true);
  30447. var from;
  30448. var to;
  30449. while (!step.end()) {
  30450. y = bottom - (step.getCurrent() - legendMin) / (legendMax - legendMin) * height;
  30451. from = new Point2d(left - gridLineLen, y);
  30452. to = new Point2d(left, y);
  30453. this._line(ctx, from, to);
  30454. ctx.textAlign = 'right';
  30455. ctx.textBaseline = 'middle';
  30456. ctx.fillStyle = this.axisColor;
  30457. ctx.fillText(step.getCurrent(), left - 2 * gridLineLen, y);
  30458. step.next();
  30459. }
  30460. ctx.textAlign = 'right';
  30461. ctx.textBaseline = 'top';
  30462. var label = this.legendLabel;
  30463. ctx.fillText(label, right, bottom + this.margin);
  30464. };
  30465. /**
  30466. * Redraw the filter
  30467. */
  30468. Graph3d.prototype._redrawFilter = function () {
  30469. var dataFilter = this.dataGroup.dataFilter;
  30470. var filter = this.frame.filter;
  30471. filter.innerHTML = '';
  30472. if (!dataFilter) {
  30473. filter.slider = undefined;
  30474. return;
  30475. }
  30476. var options = {
  30477. 'visible': this.showAnimationControls
  30478. };
  30479. var slider = new Slider(filter, options);
  30480. filter.slider = slider;
  30481. // TODO: css here is not nice here...
  30482. filter.style.padding = '10px';
  30483. //this.frame.filter.style.backgroundColor = '#EFEFEF';
  30484. slider.setValues(dataFilter.values);
  30485. slider.setPlayInterval(this.animationInterval);
  30486. // create an event handler
  30487. var me = this;
  30488. var onchange = function onchange() {
  30489. var dataFilter = me.dataGroup.dataFilter;
  30490. var index = slider.getIndex();
  30491. dataFilter.selectValue(index);
  30492. me.dataPoints = dataFilter._getDataPoints();
  30493. me.redraw();
  30494. };
  30495. slider.setOnChangeCallback(onchange);
  30496. };
  30497. /**
  30498. * Redraw the slider
  30499. */
  30500. Graph3d.prototype._redrawSlider = function () {
  30501. if (this.frame.filter.slider !== undefined) {
  30502. this.frame.filter.slider.redraw();
  30503. }
  30504. };
  30505. /**
  30506. * Redraw common information
  30507. */
  30508. Graph3d.prototype._redrawInfo = function () {
  30509. var info = this.dataGroup.getInfo();
  30510. if (info === undefined) return;
  30511. var ctx = this._getContext();
  30512. ctx.font = '14px arial'; // TODO: put in options
  30513. ctx.lineStyle = 'gray';
  30514. ctx.fillStyle = 'gray';
  30515. ctx.textAlign = 'left';
  30516. ctx.textBaseline = 'top';
  30517. var x = this.margin;
  30518. var y = this.margin;
  30519. ctx.fillText(info, x, y);
  30520. };
  30521. /**
  30522. * Draw a line between 2d points 'from' and 'to'.
  30523. *
  30524. * If stroke style specified, set that as well.
  30525. *
  30526. * @param {CanvasRenderingContext2D} ctx
  30527. * @param {vis.Point2d} from
  30528. * @param {vis.Point2d} to
  30529. * @param {string} [strokeStyle]
  30530. * @private
  30531. */
  30532. Graph3d.prototype._line = function (ctx, from, to, strokeStyle) {
  30533. if (strokeStyle !== undefined) {
  30534. ctx.strokeStyle = strokeStyle;
  30535. }
  30536. ctx.beginPath();
  30537. ctx.moveTo(from.x, from.y);
  30538. ctx.lineTo(to.x, to.y);
  30539. ctx.stroke();
  30540. };
  30541. /**
  30542. *
  30543. * @param {CanvasRenderingContext2D} ctx
  30544. * @param {vis.Point3d} point3d
  30545. * @param {string} text
  30546. * @param {number} armAngle
  30547. * @param {number} [yMargin=0]
  30548. */
  30549. Graph3d.prototype.drawAxisLabelX = function (ctx, point3d, text, armAngle, yMargin) {
  30550. if (yMargin === undefined) {
  30551. yMargin = 0;
  30552. }
  30553. var point2d = this._convert3Dto2D(point3d);
  30554. if (Math.cos(armAngle * 2) > 0) {
  30555. ctx.textAlign = 'center';
  30556. ctx.textBaseline = 'top';
  30557. point2d.y += yMargin;
  30558. } else if (Math.sin(armAngle * 2) < 0) {
  30559. ctx.textAlign = 'right';
  30560. ctx.textBaseline = 'middle';
  30561. } else {
  30562. ctx.textAlign = 'left';
  30563. ctx.textBaseline = 'middle';
  30564. }
  30565. ctx.fillStyle = this.axisColor;
  30566. ctx.fillText(text, point2d.x, point2d.y);
  30567. };
  30568. /**
  30569. *
  30570. * @param {CanvasRenderingContext2D} ctx
  30571. * @param {vis.Point3d} point3d
  30572. * @param {string} text
  30573. * @param {number} armAngle
  30574. * @param {number} [yMargin=0]
  30575. */
  30576. Graph3d.prototype.drawAxisLabelY = function (ctx, point3d, text, armAngle, yMargin) {
  30577. if (yMargin === undefined) {
  30578. yMargin = 0;
  30579. }
  30580. var point2d = this._convert3Dto2D(point3d);
  30581. if (Math.cos(armAngle * 2) < 0) {
  30582. ctx.textAlign = 'center';
  30583. ctx.textBaseline = 'top';
  30584. point2d.y += yMargin;
  30585. } else if (Math.sin(armAngle * 2) > 0) {
  30586. ctx.textAlign = 'right';
  30587. ctx.textBaseline = 'middle';
  30588. } else {
  30589. ctx.textAlign = 'left';
  30590. ctx.textBaseline = 'middle';
  30591. }
  30592. ctx.fillStyle = this.axisColor;
  30593. ctx.fillText(text, point2d.x, point2d.y);
  30594. };
  30595. /**
  30596. *
  30597. * @param {CanvasRenderingContext2D} ctx
  30598. * @param {vis.Point3d} point3d
  30599. * @param {string} text
  30600. * @param {number} [offset=0]
  30601. */
  30602. Graph3d.prototype.drawAxisLabelZ = function (ctx, point3d, text, offset) {
  30603. if (offset === undefined) {
  30604. offset = 0;
  30605. }
  30606. var point2d = this._convert3Dto2D(point3d);
  30607. ctx.textAlign = 'right';
  30608. ctx.textBaseline = 'middle';
  30609. ctx.fillStyle = this.axisColor;
  30610. ctx.fillText(text, point2d.x - offset, point2d.y);
  30611. };
  30612. /**
  30613. /**
  30614. * Draw a line between 2d points 'from' and 'to'.
  30615. *
  30616. * If stroke style specified, set that as well.
  30617. *
  30618. * @param {CanvasRenderingContext2D} ctx
  30619. * @param {vis.Point2d} from
  30620. * @param {vis.Point2d} to
  30621. * @param {string} [strokeStyle]
  30622. * @private
  30623. */
  30624. Graph3d.prototype._line3d = function (ctx, from, to, strokeStyle) {
  30625. var from2d = this._convert3Dto2D(from);
  30626. var to2d = this._convert3Dto2D(to);
  30627. this._line(ctx, from2d, to2d, strokeStyle);
  30628. };
  30629. /**
  30630. * Redraw the axis
  30631. */
  30632. Graph3d.prototype._redrawAxis = function () {
  30633. var ctx = this._getContext(),
  30634. from,
  30635. to,
  30636. step,
  30637. prettyStep,
  30638. text,
  30639. xText,
  30640. yText,
  30641. zText,
  30642. offset,
  30643. xOffset,
  30644. yOffset;
  30645. // TODO: get the actual rendered style of the containerElement
  30646. //ctx.font = this.containerElement.style.font;
  30647. ctx.font = 24 / this.camera.getArmLength() + 'px arial';
  30648. // calculate the length for the short grid lines
  30649. var gridLenX = 0.025 / this.scale.x;
  30650. var gridLenY = 0.025 / this.scale.y;
  30651. var textMargin = 5 / this.camera.getArmLength(); // px
  30652. var armAngle = this.camera.getArmRotation().horizontal;
  30653. var armVector = new Point2d(Math.cos(armAngle), Math.sin(armAngle));
  30654. var xRange = this.xRange;
  30655. var yRange = this.yRange;
  30656. var zRange = this.zRange;
  30657. var point3d;
  30658. // draw x-grid lines
  30659. ctx.lineWidth = 1;
  30660. prettyStep = this.defaultXStep === undefined;
  30661. step = new StepNumber(xRange.min, xRange.max, this.xStep, prettyStep);
  30662. step.start(true);
  30663. while (!step.end()) {
  30664. var x = step.getCurrent();
  30665. if (this.showGrid) {
  30666. from = new Point3d(x, yRange.min, zRange.min);
  30667. to = new Point3d(x, yRange.max, zRange.min);
  30668. this._line3d(ctx, from, to, this.gridColor);
  30669. } else if (this.showXAxis) {
  30670. from = new Point3d(x, yRange.min, zRange.min);
  30671. to = new Point3d(x, yRange.min + gridLenX, zRange.min);
  30672. this._line3d(ctx, from, to, this.axisColor);
  30673. from = new Point3d(x, yRange.max, zRange.min);
  30674. to = new Point3d(x, yRange.max - gridLenX, zRange.min);
  30675. this._line3d(ctx, from, to, this.axisColor);
  30676. }
  30677. if (this.showXAxis) {
  30678. yText = armVector.x > 0 ? yRange.min : yRange.max;
  30679. point3d = new Point3d(x, yText, zRange.min);
  30680. var msg = ' ' + this.xValueLabel(x) + ' ';
  30681. this.drawAxisLabelX(ctx, point3d, msg, armAngle, textMargin);
  30682. }
  30683. step.next();
  30684. }
  30685. // draw y-grid lines
  30686. ctx.lineWidth = 1;
  30687. prettyStep = this.defaultYStep === undefined;
  30688. step = new StepNumber(yRange.min, yRange.max, this.yStep, prettyStep);
  30689. step.start(true);
  30690. while (!step.end()) {
  30691. var y = step.getCurrent();
  30692. if (this.showGrid) {
  30693. from = new Point3d(xRange.min, y, zRange.min);
  30694. to = new Point3d(xRange.max, y, zRange.min);
  30695. this._line3d(ctx, from, to, this.gridColor);
  30696. } else if (this.showYAxis) {
  30697. from = new Point3d(xRange.min, y, zRange.min);
  30698. to = new Point3d(xRange.min + gridLenY, y, zRange.min);
  30699. this._line3d(ctx, from, to, this.axisColor);
  30700. from = new Point3d(xRange.max, y, zRange.min);
  30701. to = new Point3d(xRange.max - gridLenY, y, zRange.min);
  30702. this._line3d(ctx, from, to, this.axisColor);
  30703. }
  30704. if (this.showYAxis) {
  30705. xText = armVector.y > 0 ? xRange.min : xRange.max;
  30706. point3d = new Point3d(xText, y, zRange.min);
  30707. var _msg = ' ' + this.yValueLabel(y) + ' ';
  30708. this.drawAxisLabelY(ctx, point3d, _msg, armAngle, textMargin);
  30709. }
  30710. step.next();
  30711. }
  30712. // draw z-grid lines and axis
  30713. if (this.showZAxis) {
  30714. ctx.lineWidth = 1;
  30715. prettyStep = this.defaultZStep === undefined;
  30716. step = new StepNumber(zRange.min, zRange.max, this.zStep, prettyStep);
  30717. step.start(true);
  30718. xText = armVector.x > 0 ? xRange.min : xRange.max;
  30719. yText = armVector.y < 0 ? yRange.min : yRange.max;
  30720. while (!step.end()) {
  30721. var z = step.getCurrent();
  30722. // TODO: make z-grid lines really 3d?
  30723. var from3d = new Point3d(xText, yText, z);
  30724. var from2d = this._convert3Dto2D(from3d);
  30725. to = new Point2d(from2d.x - textMargin, from2d.y);
  30726. this._line(ctx, from2d, to, this.axisColor);
  30727. var _msg2 = this.zValueLabel(z) + ' ';
  30728. this.drawAxisLabelZ(ctx, from3d, _msg2, 5);
  30729. step.next();
  30730. }
  30731. ctx.lineWidth = 1;
  30732. from = new Point3d(xText, yText, zRange.min);
  30733. to = new Point3d(xText, yText, zRange.max);
  30734. this._line3d(ctx, from, to, this.axisColor);
  30735. }
  30736. // draw x-axis
  30737. if (this.showXAxis) {
  30738. var xMin2d;
  30739. var xMax2d;
  30740. ctx.lineWidth = 1;
  30741. // line at yMin
  30742. xMin2d = new Point3d(xRange.min, yRange.min, zRange.min);
  30743. xMax2d = new Point3d(xRange.max, yRange.min, zRange.min);
  30744. this._line3d(ctx, xMin2d, xMax2d, this.axisColor);
  30745. // line at ymax
  30746. xMin2d = new Point3d(xRange.min, yRange.max, zRange.min);
  30747. xMax2d = new Point3d(xRange.max, yRange.max, zRange.min);
  30748. this._line3d(ctx, xMin2d, xMax2d, this.axisColor);
  30749. }
  30750. // draw y-axis
  30751. if (this.showYAxis) {
  30752. ctx.lineWidth = 1;
  30753. // line at xMin
  30754. from = new Point3d(xRange.min, yRange.min, zRange.min);
  30755. to = new Point3d(xRange.min, yRange.max, zRange.min);
  30756. this._line3d(ctx, from, to, this.axisColor);
  30757. // line at xMax
  30758. from = new Point3d(xRange.max, yRange.min, zRange.min);
  30759. to = new Point3d(xRange.max, yRange.max, zRange.min);
  30760. this._line3d(ctx, from, to, this.axisColor);
  30761. }
  30762. // draw x-label
  30763. var xLabel = this.xLabel;
  30764. if (xLabel.length > 0 && this.showXAxis) {
  30765. yOffset = 0.1 / this.scale.y;
  30766. xText = (xRange.max + 3 * xRange.min) / 4;
  30767. yText = armVector.x > 0 ? yRange.min - yOffset : yRange.max + yOffset;
  30768. text = new Point3d(xText, yText, zRange.min);
  30769. this.drawAxisLabelX(ctx, text, xLabel, armAngle);
  30770. }
  30771. // draw y-label
  30772. var yLabel = this.yLabel;
  30773. if (yLabel.length > 0 && this.showYAxis) {
  30774. xOffset = 0.1 / this.scale.x;
  30775. xText = armVector.y > 0 ? xRange.min - xOffset : xRange.max + xOffset;
  30776. yText = (yRange.max + 3 * yRange.min) / 4;
  30777. text = new Point3d(xText, yText, zRange.min);
  30778. this.drawAxisLabelY(ctx, text, yLabel, armAngle);
  30779. }
  30780. // draw z-label
  30781. var zLabel = this.zLabel;
  30782. if (zLabel.length > 0 && this.showZAxis) {
  30783. offset = 30; // pixels. // TODO: relate to the max width of the values on the z axis?
  30784. xText = armVector.x > 0 ? xRange.min : xRange.max;
  30785. yText = armVector.y < 0 ? yRange.min : yRange.max;
  30786. zText = (zRange.max + 3 * zRange.min) / 4;
  30787. text = new Point3d(xText, yText, zText);
  30788. this.drawAxisLabelZ(ctx, text, zLabel, offset);
  30789. }
  30790. };
  30791. /**
  30792. * Calculate the color based on the given value.
  30793. * @param {number} H Hue, a value be between 0 and 360
  30794. * @param {number} S Saturation, a value between 0 and 1
  30795. * @param {number} V Value, a value between 0 and 1
  30796. * @returns {string}
  30797. * @private
  30798. */
  30799. Graph3d.prototype._hsv2rgb = function (H, S, V) {
  30800. var R, G, B, C, Hi, X;
  30801. C = V * S;
  30802. Hi = Math.floor(H / 60); // hi = 0,1,2,3,4,5
  30803. X = C * (1 - Math.abs(H / 60 % 2 - 1));
  30804. switch (Hi) {
  30805. case 0:
  30806. R = C;G = X;B = 0;break;
  30807. case 1:
  30808. R = X;G = C;B = 0;break;
  30809. case 2:
  30810. R = 0;G = C;B = X;break;
  30811. case 3:
  30812. R = 0;G = X;B = C;break;
  30813. case 4:
  30814. R = X;G = 0;B = C;break;
  30815. case 5:
  30816. R = C;G = 0;B = X;break;
  30817. default:
  30818. R = 0;G = 0;B = 0;break;
  30819. }
  30820. return 'RGB(' + parseInt(R * 255) + ',' + parseInt(G * 255) + ',' + parseInt(B * 255) + ')';
  30821. };
  30822. /**
  30823. *
  30824. * @param {vis.Point3d} point
  30825. * @returns {*}
  30826. * @private
  30827. */
  30828. Graph3d.prototype._getStrokeWidth = function (point) {
  30829. if (point !== undefined) {
  30830. if (this.showPerspective) {
  30831. return 1 / -point.trans.z * this.dataColor.strokeWidth;
  30832. } else {
  30833. return -(this.eye.z / this.camera.getArmLength()) * this.dataColor.strokeWidth;
  30834. }
  30835. }
  30836. return this.dataColor.strokeWidth;
  30837. };
  30838. // -----------------------------------------------------------------------------
  30839. // Drawing primitives for the graphs
  30840. // -----------------------------------------------------------------------------
  30841. /**
  30842. * Draw a bar element in the view with the given properties.
  30843. *
  30844. * @param {CanvasRenderingContext2D} ctx
  30845. * @param {Object} point
  30846. * @param {number} xWidth
  30847. * @param {number} yWidth
  30848. * @param {string} color
  30849. * @param {string} borderColor
  30850. * @private
  30851. */
  30852. Graph3d.prototype._redrawBar = function (ctx, point, xWidth, yWidth, color, borderColor) {
  30853. var surface;
  30854. // calculate all corner points
  30855. var me = this;
  30856. var point3d = point.point;
  30857. var zMin = this.zRange.min;
  30858. 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) }];
  30859. var bottom = [{ point: new Point3d(point3d.x - xWidth, point3d.y - yWidth, zMin) }, { point: new Point3d(point3d.x + xWidth, point3d.y - yWidth, zMin) }, { point: new Point3d(point3d.x + xWidth, point3d.y + yWidth, zMin) }, { point: new Point3d(point3d.x - xWidth, point3d.y + yWidth, zMin) }];
  30860. // calculate screen location of the points
  30861. top.forEach(function (obj) {
  30862. obj.screen = me._convert3Dto2D(obj.point);
  30863. });
  30864. bottom.forEach(function (obj) {
  30865. obj.screen = me._convert3Dto2D(obj.point);
  30866. });
  30867. // create five sides, calculate both corner points and center points
  30868. 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) }];
  30869. point.surfaces = surfaces;
  30870. // calculate the distance of each of the surface centers to the camera
  30871. for (var j = 0; j < surfaces.length; j++) {
  30872. surface = surfaces[j];
  30873. var transCenter = this._convertPointToTranslation(surface.center);
  30874. surface.dist = this.showPerspective ? transCenter.length() : -transCenter.z;
  30875. // TODO: this dept calculation doesn't work 100% of the cases due to perspective,
  30876. // but the current solution is fast/simple and works in 99.9% of all cases
  30877. // the issue is visible in example 14, with graph.setCameraPosition({horizontal: 2.97, vertical: 0.5, distance: 0.9})
  30878. }
  30879. // order the surfaces by their (translated) depth
  30880. surfaces.sort(function (a, b) {
  30881. var diff = b.dist - a.dist;
  30882. if (diff) return diff;
  30883. // if equal depth, sort the top surface last
  30884. if (a.corners === top) return 1;
  30885. if (b.corners === top) return -1;
  30886. // both are equal
  30887. return 0;
  30888. });
  30889. // draw the ordered surfaces
  30890. ctx.lineWidth = this._getStrokeWidth(point);
  30891. ctx.strokeStyle = borderColor;
  30892. ctx.fillStyle = color;
  30893. // NOTE: we start at j=2 instead of j=0 as we don't need to draw the two surfaces at the backside
  30894. for (var _j = 2; _j < surfaces.length; _j++) {
  30895. surface = surfaces[_j];
  30896. this._polygon(ctx, surface.corners);
  30897. }
  30898. };
  30899. /**
  30900. * Draw a polygon using the passed points and fill it with the passed style and stroke.
  30901. *
  30902. * @param {CanvasRenderingContext2D} ctx
  30903. * @param {Array.<vis.Point3d>} points an array of points.
  30904. * @param {string} [fillStyle] the fill style to set
  30905. * @param {string} [strokeStyle] the stroke style to set
  30906. */
  30907. Graph3d.prototype._polygon = function (ctx, points, fillStyle, strokeStyle) {
  30908. if (points.length < 2) {
  30909. return;
  30910. }
  30911. if (fillStyle !== undefined) {
  30912. ctx.fillStyle = fillStyle;
  30913. }
  30914. if (strokeStyle !== undefined) {
  30915. ctx.strokeStyle = strokeStyle;
  30916. }
  30917. ctx.beginPath();
  30918. ctx.moveTo(points[0].screen.x, points[0].screen.y);
  30919. for (var i = 1; i < points.length; ++i) {
  30920. var point = points[i];
  30921. ctx.lineTo(point.screen.x, point.screen.y);
  30922. }
  30923. ctx.closePath();
  30924. ctx.fill();
  30925. ctx.stroke(); // TODO: only draw stroke when strokeWidth > 0
  30926. };
  30927. /**
  30928. * @param {CanvasRenderingContext2D} ctx
  30929. * @param {object} point
  30930. * @param {string} color
  30931. * @param {string} borderColor
  30932. * @param {number} [size=this._dotSize()]
  30933. * @private
  30934. */
  30935. Graph3d.prototype._drawCircle = function (ctx, point, color, borderColor, size) {
  30936. var radius = this._calcRadius(point, size);
  30937. ctx.lineWidth = this._getStrokeWidth(point);
  30938. ctx.strokeStyle = borderColor;
  30939. ctx.fillStyle = color;
  30940. ctx.beginPath();
  30941. ctx.arc(point.screen.x, point.screen.y, radius, 0, Math.PI * 2, true);
  30942. ctx.fill();
  30943. ctx.stroke();
  30944. };
  30945. /**
  30946. * Determine the colors for the 'regular' graph styles.
  30947. *
  30948. * @param {object} point
  30949. * @returns {{fill, border}}
  30950. * @private
  30951. */
  30952. Graph3d.prototype._getColorsRegular = function (point) {
  30953. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  30954. var hue = (1 - (point.point.z - this.zRange.min) * this.scale.z / this.verticalRatio) * 240;
  30955. var color = this._hsv2rgb(hue, 1, 1);
  30956. var borderColor = this._hsv2rgb(hue, 1, 0.8);
  30957. return {
  30958. fill: color,
  30959. border: borderColor
  30960. };
  30961. };
  30962. /**
  30963. * Get the colors for the 'color' graph styles.
  30964. * These styles are currently: 'bar-color' and 'dot-color'
  30965. * Color may be set as a string representation of HTML color, like #ff00ff,
  30966. * or calculated from a number, for example, distance from this point
  30967. * The first option is useful when we have some pre-given legend, to which we have to adjust ourselves
  30968. * The second option is useful when we are interested in automatically setting the color, from some value,
  30969. * using some color scale
  30970. * @param {object} point
  30971. * @returns {{fill: *, border: *}}
  30972. * @private
  30973. */
  30974. Graph3d.prototype._getColorsColor = function (point) {
  30975. // calculate the color based on the value
  30976. var color, borderColor;
  30977. if (typeof point.point.value === "string") {
  30978. color = point.point.value;
  30979. borderColor = point.point.value;
  30980. } else {
  30981. var hue = (1 - (point.point.value - this.valueRange.min) * this.scale.value) * 240;
  30982. color = this._hsv2rgb(hue, 1, 1);
  30983. borderColor = this._hsv2rgb(hue, 1, 0.8);
  30984. }
  30985. return {
  30986. fill: color,
  30987. border: borderColor
  30988. };
  30989. };
  30990. /**
  30991. * Get the colors for the 'size' graph styles.
  30992. * These styles are currently: 'bar-size' and 'dot-size'
  30993. *
  30994. * @returns {{fill: *, border: (string|colorOptions.stroke|{string, undefined}|string|colorOptions.stroke|{string}|*)}}
  30995. * @private
  30996. */
  30997. Graph3d.prototype._getColorsSize = function () {
  30998. return {
  30999. fill: this.dataColor.fill,
  31000. border: this.dataColor.stroke
  31001. };
  31002. };
  31003. /**
  31004. * Determine the size of a point on-screen, as determined by the
  31005. * distance to the camera.
  31006. *
  31007. * @param {Object} point
  31008. * @param {number} [size=this._dotSize()] the size that needs to be translated to screen coordinates.
  31009. * optional; if not passed, use the default point size.
  31010. * @returns {number}
  31011. * @private
  31012. */
  31013. Graph3d.prototype._calcRadius = function (point, size) {
  31014. if (size === undefined) {
  31015. size = this._dotSize();
  31016. }
  31017. var radius;
  31018. if (this.showPerspective) {
  31019. radius = size / -point.trans.z;
  31020. } else {
  31021. radius = size * -(this.eye.z / this.camera.getArmLength());
  31022. }
  31023. if (radius < 0) {
  31024. radius = 0;
  31025. }
  31026. return radius;
  31027. };
  31028. // -----------------------------------------------------------------------------
  31029. // Methods for drawing points per graph style.
  31030. // -----------------------------------------------------------------------------
  31031. /**
  31032. * Draw single datapoint for graph style 'bar'.
  31033. *
  31034. * @param {CanvasRenderingContext2D} ctx
  31035. * @param {Object} point
  31036. * @private
  31037. */
  31038. Graph3d.prototype._redrawBarGraphPoint = function (ctx, point) {
  31039. var xWidth = this.xBarWidth / 2;
  31040. var yWidth = this.yBarWidth / 2;
  31041. var colors = this._getColorsRegular(point);
  31042. this._redrawBar(ctx, point, xWidth, yWidth, colors.fill, colors.border);
  31043. };
  31044. /**
  31045. * Draw single datapoint for graph style 'bar-color'.
  31046. *
  31047. * @param {CanvasRenderingContext2D} ctx
  31048. * @param {Object} point
  31049. * @private
  31050. */
  31051. Graph3d.prototype._redrawBarColorGraphPoint = function (ctx, point) {
  31052. var xWidth = this.xBarWidth / 2;
  31053. var yWidth = this.yBarWidth / 2;
  31054. var colors = this._getColorsColor(point);
  31055. this._redrawBar(ctx, point, xWidth, yWidth, colors.fill, colors.border);
  31056. };
  31057. /**
  31058. * Draw single datapoint for graph style 'bar-size'.
  31059. *
  31060. * @param {CanvasRenderingContext2D} ctx
  31061. * @param {Object} point
  31062. * @private
  31063. */
  31064. Graph3d.prototype._redrawBarSizeGraphPoint = function (ctx, point) {
  31065. // calculate size for the bar
  31066. var fraction = (point.point.value - this.valueRange.min) / this.valueRange.range();
  31067. var xWidth = this.xBarWidth / 2 * (fraction * 0.8 + 0.2);
  31068. var yWidth = this.yBarWidth / 2 * (fraction * 0.8 + 0.2);
  31069. var colors = this._getColorsSize();
  31070. this._redrawBar(ctx, point, xWidth, yWidth, colors.fill, colors.border);
  31071. };
  31072. /**
  31073. * Draw single datapoint for graph style 'dot'.
  31074. *
  31075. * @param {CanvasRenderingContext2D} ctx
  31076. * @param {Object} point
  31077. * @private
  31078. */
  31079. Graph3d.prototype._redrawDotGraphPoint = function (ctx, point) {
  31080. var colors = this._getColorsRegular(point);
  31081. this._drawCircle(ctx, point, colors.fill, colors.border);
  31082. };
  31083. /**
  31084. * Draw single datapoint for graph style 'dot-line'.
  31085. *
  31086. * @param {CanvasRenderingContext2D} ctx
  31087. * @param {Object} point
  31088. * @private
  31089. */
  31090. Graph3d.prototype._redrawDotLineGraphPoint = function (ctx, point) {
  31091. // draw a vertical line from the XY-plane to the graph value
  31092. var from = this._convert3Dto2D(point.bottom);
  31093. ctx.lineWidth = 1;
  31094. this._line(ctx, from, point.screen, this.gridColor);
  31095. this._redrawDotGraphPoint(ctx, point);
  31096. };
  31097. /**
  31098. * Draw single datapoint for graph style 'dot-color'.
  31099. *
  31100. * @param {CanvasRenderingContext2D} ctx
  31101. * @param {Object} point
  31102. * @private
  31103. */
  31104. Graph3d.prototype._redrawDotColorGraphPoint = function (ctx, point) {
  31105. var colors = this._getColorsColor(point);
  31106. this._drawCircle(ctx, point, colors.fill, colors.border);
  31107. };
  31108. /**
  31109. * Draw single datapoint for graph style 'dot-size'.
  31110. *
  31111. * @param {CanvasRenderingContext2D} ctx
  31112. * @param {Object} point
  31113. * @private
  31114. */
  31115. Graph3d.prototype._redrawDotSizeGraphPoint = function (ctx, point) {
  31116. var dotSize = this._dotSize();
  31117. var fraction = (point.point.value - this.valueRange.min) / this.valueRange.range();
  31118. var sizeMin = dotSize * this.dotSizeMinFraction;
  31119. var sizeRange = dotSize * this.dotSizeMaxFraction - sizeMin;
  31120. var size = sizeMin + sizeRange * fraction;
  31121. var colors = this._getColorsSize();
  31122. this._drawCircle(ctx, point, colors.fill, colors.border, size);
  31123. };
  31124. /**
  31125. * Draw single datapoint for graph style 'surface'.
  31126. *
  31127. * @param {CanvasRenderingContext2D} ctx
  31128. * @param {Object} point
  31129. * @private
  31130. */
  31131. Graph3d.prototype._redrawSurfaceGraphPoint = function (ctx, point) {
  31132. var right = point.pointRight;
  31133. var top = point.pointTop;
  31134. var cross = point.pointCross;
  31135. if (point === undefined || right === undefined || top === undefined || cross === undefined) {
  31136. return;
  31137. }
  31138. var topSideVisible = true;
  31139. var fillStyle;
  31140. var strokeStyle;
  31141. if (this.showGrayBottom || this.showShadow) {
  31142. // calculate the cross product of the two vectors from center
  31143. // to left and right, in order to know whether we are looking at the
  31144. // bottom or at the top side. We can also use the cross product
  31145. // for calculating light intensity
  31146. var aDiff = Point3d.subtract(cross.trans, point.trans);
  31147. var bDiff = Point3d.subtract(top.trans, right.trans);
  31148. var crossproduct = Point3d.crossProduct(aDiff, bDiff);
  31149. var len = crossproduct.length();
  31150. // FIXME: there is a bug with determining the surface side (shadow or colored)
  31151. topSideVisible = crossproduct.z > 0;
  31152. }
  31153. if (topSideVisible) {
  31154. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  31155. var zAvg = (point.point.z + right.point.z + top.point.z + cross.point.z) / 4;
  31156. var h = (1 - (zAvg - this.zRange.min) * this.scale.z / this.verticalRatio) * 240;
  31157. var s = 1; // saturation
  31158. var v;
  31159. if (this.showShadow) {
  31160. v = Math.min(1 + crossproduct.x / len / 2, 1); // value. TODO: scale
  31161. fillStyle = this._hsv2rgb(h, s, v);
  31162. strokeStyle = fillStyle;
  31163. } else {
  31164. v = 1;
  31165. fillStyle = this._hsv2rgb(h, s, v);
  31166. strokeStyle = this.axisColor; // TODO: should be customizable
  31167. }
  31168. } else {
  31169. fillStyle = 'gray';
  31170. strokeStyle = this.axisColor;
  31171. }
  31172. ctx.lineWidth = this._getStrokeWidth(point);
  31173. // TODO: only draw stroke when strokeWidth > 0
  31174. var points = [point, right, cross, top];
  31175. this._polygon(ctx, points, fillStyle, strokeStyle);
  31176. };
  31177. /**
  31178. * Helper method for _redrawGridGraphPoint()
  31179. *
  31180. * @param {CanvasRenderingContext2D} ctx
  31181. * @param {Object} from
  31182. * @param {Object} to
  31183. * @private
  31184. */
  31185. Graph3d.prototype._drawGridLine = function (ctx, from, to) {
  31186. if (from === undefined || to === undefined) {
  31187. return;
  31188. }
  31189. // calculate Hue from the current value. At zMin the hue is 240, at zMax the hue is 0
  31190. var zAvg = (from.point.z + to.point.z) / 2;
  31191. var h = (1 - (zAvg - this.zRange.min) * this.scale.z / this.verticalRatio) * 240;
  31192. ctx.lineWidth = this._getStrokeWidth(from) * 2;
  31193. ctx.strokeStyle = this._hsv2rgb(h, 1, 1);
  31194. this._line(ctx, from.screen, to.screen);
  31195. };
  31196. /**
  31197. * Draw single datapoint for graph style 'Grid'.
  31198. *
  31199. * @param {CanvasRenderingContext2D} ctx
  31200. * @param {Object} point
  31201. * @private
  31202. */
  31203. Graph3d.prototype._redrawGridGraphPoint = function (ctx, point) {
  31204. this._drawGridLine(ctx, point, point.pointRight);
  31205. this._drawGridLine(ctx, point, point.pointTop);
  31206. };
  31207. /**
  31208. * Draw single datapoint for graph style 'line'.
  31209. *
  31210. * @param {CanvasRenderingContext2D} ctx
  31211. * @param {Object} point
  31212. * @private
  31213. */
  31214. Graph3d.prototype._redrawLineGraphPoint = function (ctx, point) {
  31215. if (point.pointNext === undefined) {
  31216. return;
  31217. }
  31218. ctx.lineWidth = this._getStrokeWidth(point);
  31219. ctx.strokeStyle = this.dataColor.stroke;
  31220. this._line(ctx, point.screen, point.pointNext.screen);
  31221. };
  31222. /**
  31223. * Draw all datapoints for currently selected graph style.
  31224. *
  31225. */
  31226. Graph3d.prototype._redrawDataGraph = function () {
  31227. var ctx = this._getContext();
  31228. var i;
  31229. if (this.dataPoints === undefined || this.dataPoints.length <= 0) return; // TODO: throw exception?
  31230. this._calcTranslations(this.dataPoints);
  31231. for (i = 0; i < this.dataPoints.length; i++) {
  31232. var point = this.dataPoints[i];
  31233. // Using call() ensures that the correct context is used
  31234. this._pointDrawingMethod.call(this, ctx, point);
  31235. }
  31236. };
  31237. // -----------------------------------------------------------------------------
  31238. // End methods for drawing points per graph style.
  31239. // -----------------------------------------------------------------------------
  31240. /**
  31241. * Store startX, startY and startOffset for mouse operations
  31242. *
  31243. * @param {Event} event The event that occurred
  31244. */
  31245. Graph3d.prototype._storeMousePosition = function (event) {
  31246. // get mouse position (different code for IE and all other browsers)
  31247. this.startMouseX = getMouseX(event);
  31248. this.startMouseY = getMouseY(event);
  31249. this._startCameraOffset = this.camera.getOffset();
  31250. };
  31251. /**
  31252. * Start a moving operation inside the provided parent element
  31253. * @param {Event} event The event that occurred (required for
  31254. * retrieving the mouse position)
  31255. */
  31256. Graph3d.prototype._onMouseDown = function (event) {
  31257. event = event || window.event;
  31258. // check if mouse is still down (may be up when focus is lost for example
  31259. // in an iframe)
  31260. if (this.leftButtonDown) {
  31261. this._onMouseUp(event);
  31262. }
  31263. // only react on left mouse button down
  31264. this.leftButtonDown = event.which ? event.which === 1 : event.button === 1;
  31265. if (!this.leftButtonDown && !this.touchDown) return;
  31266. this._storeMousePosition(event);
  31267. this.startStart = new Date(this.start);
  31268. this.startEnd = new Date(this.end);
  31269. this.startArmRotation = this.camera.getArmRotation();
  31270. this.frame.style.cursor = 'move';
  31271. // add event listeners to handle moving the contents
  31272. // we store the function onmousemove and onmouseup in the graph, so we can
  31273. // remove the eventlisteners lateron in the function mouseUp()
  31274. var me = this;
  31275. this.onmousemove = function (event) {
  31276. me._onMouseMove(event);
  31277. };
  31278. this.onmouseup = function (event) {
  31279. me._onMouseUp(event);
  31280. };
  31281. util.addEventListener(document, 'mousemove', me.onmousemove);
  31282. util.addEventListener(document, 'mouseup', me.onmouseup);
  31283. util.preventDefault(event);
  31284. };
  31285. /**
  31286. * Perform moving operating.
  31287. * This function activated from within the funcion Graph.mouseDown().
  31288. * @param {Event} event Well, eehh, the event
  31289. */
  31290. Graph3d.prototype._onMouseMove = function (event) {
  31291. this.moving = true;
  31292. event = event || window.event;
  31293. // calculate change in mouse position
  31294. var diffX = parseFloat(getMouseX(event)) - this.startMouseX;
  31295. var diffY = parseFloat(getMouseY(event)) - this.startMouseY;
  31296. // move with ctrl or rotate by other
  31297. if (event && event.ctrlKey === true) {
  31298. // calculate change in mouse position
  31299. var scaleX = this.frame.clientWidth * 0.5;
  31300. var scaleY = this.frame.clientHeight * 0.5;
  31301. var offXNew = (this._startCameraOffset.x || 0) - diffX / scaleX * this.camera.armLength * 0.8;
  31302. var offYNew = (this._startCameraOffset.y || 0) + diffY / scaleY * this.camera.armLength * 0.8;
  31303. this.camera.setOffset(offXNew, offYNew);
  31304. this._storeMousePosition(event);
  31305. } else {
  31306. var horizontalNew = this.startArmRotation.horizontal + diffX / 200;
  31307. var verticalNew = this.startArmRotation.vertical + diffY / 200;
  31308. var snapAngle = 4; // degrees
  31309. var snapValue = Math.sin(snapAngle / 360 * 2 * Math.PI);
  31310. // snap horizontally to nice angles at 0pi, 0.5pi, 1pi, 1.5pi, etc...
  31311. // the -0.001 is to take care that the vertical axis is always drawn at the left front corner
  31312. if (Math.abs(Math.sin(horizontalNew)) < snapValue) {
  31313. horizontalNew = Math.round(horizontalNew / Math.PI) * Math.PI - 0.001;
  31314. }
  31315. if (Math.abs(Math.cos(horizontalNew)) < snapValue) {
  31316. horizontalNew = (Math.round(horizontalNew / Math.PI - 0.5) + 0.5) * Math.PI - 0.001;
  31317. }
  31318. // snap vertically to nice angles
  31319. if (Math.abs(Math.sin(verticalNew)) < snapValue) {
  31320. verticalNew = Math.round(verticalNew / Math.PI) * Math.PI;
  31321. }
  31322. if (Math.abs(Math.cos(verticalNew)) < snapValue) {
  31323. verticalNew = (Math.round(verticalNew / Math.PI - 0.5) + 0.5) * Math.PI;
  31324. }
  31325. this.camera.setArmRotation(horizontalNew, verticalNew);
  31326. }
  31327. this.redraw();
  31328. // fire a cameraPositionChange event
  31329. var parameters = this.getCameraPosition();
  31330. this.emit('cameraPositionChange', parameters);
  31331. util.preventDefault(event);
  31332. };
  31333. /**
  31334. * Stop moving operating.
  31335. * This function activated from within the funcion Graph.mouseDown().
  31336. * @param {Event} event The event
  31337. */
  31338. Graph3d.prototype._onMouseUp = function (event) {
  31339. this.frame.style.cursor = 'auto';
  31340. this.leftButtonDown = false;
  31341. // remove event listeners here
  31342. util.removeEventListener(document, 'mousemove', this.onmousemove);
  31343. util.removeEventListener(document, 'mouseup', this.onmouseup);
  31344. util.preventDefault(event);
  31345. };
  31346. /**
  31347. * @param {Event} event The event
  31348. */
  31349. Graph3d.prototype._onClick = function (event) {
  31350. if (!this.onclick_callback) return;
  31351. if (!this.moving) {
  31352. var boundingRect = this.frame.getBoundingClientRect();
  31353. var mouseX = getMouseX(event) - boundingRect.left;
  31354. var mouseY = getMouseY(event) - boundingRect.top;
  31355. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  31356. if (dataPoint) this.onclick_callback(dataPoint.point.data);
  31357. } else {
  31358. // disable onclick callback, if it came immediately after rotate/pan
  31359. this.moving = false;
  31360. }
  31361. util.preventDefault(event);
  31362. };
  31363. /**
  31364. * After having moved the mouse, a tooltip should pop up when the mouse is resting on a data point
  31365. * @param {Event} event A mouse move event
  31366. */
  31367. Graph3d.prototype._onTooltip = function (event) {
  31368. var delay = 300; // ms
  31369. var boundingRect = this.frame.getBoundingClientRect();
  31370. var mouseX = getMouseX(event) - boundingRect.left;
  31371. var mouseY = getMouseY(event) - boundingRect.top;
  31372. if (!this.showTooltip) {
  31373. return;
  31374. }
  31375. if (this.tooltipTimeout) {
  31376. clearTimeout(this.tooltipTimeout);
  31377. }
  31378. // (delayed) display of a tooltip only if no mouse button is down
  31379. if (this.leftButtonDown) {
  31380. this._hideTooltip();
  31381. return;
  31382. }
  31383. if (this.tooltip && this.tooltip.dataPoint) {
  31384. // tooltip is currently visible
  31385. var dataPoint = this._dataPointFromXY(mouseX, mouseY);
  31386. if (dataPoint !== this.tooltip.dataPoint) {
  31387. // datapoint changed
  31388. if (dataPoint) {
  31389. this._showTooltip(dataPoint);
  31390. } else {
  31391. this._hideTooltip();
  31392. }
  31393. }
  31394. } else {
  31395. // tooltip is currently not visible
  31396. var me = this;
  31397. this.tooltipTimeout = setTimeout(function () {
  31398. me.tooltipTimeout = null;
  31399. // show a tooltip if we have a data point
  31400. var dataPoint = me._dataPointFromXY(mouseX, mouseY);
  31401. if (dataPoint) {
  31402. me._showTooltip(dataPoint);
  31403. }
  31404. }, delay);
  31405. }
  31406. };
  31407. /**
  31408. * Event handler for touchstart event on mobile devices
  31409. * @param {Event} event The event
  31410. */
  31411. Graph3d.prototype._onTouchStart = function (event) {
  31412. this.touchDown = true;
  31413. var me = this;
  31414. this.ontouchmove = function (event) {
  31415. me._onTouchMove(event);
  31416. };
  31417. this.ontouchend = function (event) {
  31418. me._onTouchEnd(event);
  31419. };
  31420. util.addEventListener(document, 'touchmove', me.ontouchmove);
  31421. util.addEventListener(document, 'touchend', me.ontouchend);
  31422. this._onMouseDown(event);
  31423. };
  31424. /**
  31425. * Event handler for touchmove event on mobile devices
  31426. * @param {Event} event The event
  31427. */
  31428. Graph3d.prototype._onTouchMove = function (event) {
  31429. this._onMouseMove(event);
  31430. };
  31431. /**
  31432. * Event handler for touchend event on mobile devices
  31433. * @param {Event} event The event
  31434. */
  31435. Graph3d.prototype._onTouchEnd = function (event) {
  31436. this.touchDown = false;
  31437. util.removeEventListener(document, 'touchmove', this.ontouchmove);
  31438. util.removeEventListener(document, 'touchend', this.ontouchend);
  31439. this._onMouseUp(event);
  31440. };
  31441. /**
  31442. * Event handler for mouse wheel event, used to zoom the graph
  31443. * Code from http://adomas.org/javascript-mouse-wheel/
  31444. * @param {Event} event The event
  31445. */
  31446. Graph3d.prototype._onWheel = function (event) {
  31447. if (!event) /* For IE. */
  31448. event = window.event;
  31449. // retrieve delta
  31450. var delta = 0;
  31451. if (event.wheelDelta) {
  31452. /* IE/Opera. */
  31453. delta = event.wheelDelta / 120;
  31454. } else if (event.detail) {
  31455. /* Mozilla case. */
  31456. // In Mozilla, sign of delta is different than in IE.
  31457. // Also, delta is multiple of 3.
  31458. delta = -event.detail / 3;
  31459. }
  31460. // If delta is nonzero, handle it.
  31461. // Basically, delta is now positive if wheel was scrolled up,
  31462. // and negative, if wheel was scrolled down.
  31463. if (delta) {
  31464. var oldLength = this.camera.getArmLength();
  31465. var newLength = oldLength * (1 - delta / 10);
  31466. this.camera.setArmLength(newLength);
  31467. this.redraw();
  31468. this._hideTooltip();
  31469. }
  31470. // fire a cameraPositionChange event
  31471. var parameters = this.getCameraPosition();
  31472. this.emit('cameraPositionChange', parameters);
  31473. // Prevent default actions caused by mouse wheel.
  31474. // That might be ugly, but we handle scrolls somehow
  31475. // anyway, so don't bother here..
  31476. util.preventDefault(event);
  31477. };
  31478. /**
  31479. * Test whether a point lies inside given 2D triangle
  31480. *
  31481. * @param {vis.Point2d} point
  31482. * @param {vis.Point2d[]} triangle
  31483. * @returns {boolean} true if given point lies inside or on the edge of the
  31484. * triangle, false otherwise
  31485. * @private
  31486. */
  31487. Graph3d.prototype._insideTriangle = function (point, triangle) {
  31488. var a = triangle[0],
  31489. b = triangle[1],
  31490. c = triangle[2];
  31491. /**
  31492. *
  31493. * @param {number} x
  31494. * @returns {number}
  31495. */
  31496. function sign(x) {
  31497. return x > 0 ? 1 : x < 0 ? -1 : 0;
  31498. }
  31499. var as = sign((b.x - a.x) * (point.y - a.y) - (b.y - a.y) * (point.x - a.x));
  31500. var bs = sign((c.x - b.x) * (point.y - b.y) - (c.y - b.y) * (point.x - b.x));
  31501. var cs = sign((a.x - c.x) * (point.y - c.y) - (a.y - c.y) * (point.x - c.x));
  31502. // each of the three signs must be either equal to each other or zero
  31503. return (as == 0 || bs == 0 || as == bs) && (bs == 0 || cs == 0 || bs == cs) && (as == 0 || cs == 0 || as == cs);
  31504. };
  31505. /**
  31506. * Find a data point close to given screen position (x, y)
  31507. *
  31508. * @param {number} x
  31509. * @param {number} y
  31510. * @returns {Object | null} The closest data point or null if not close to any
  31511. * data point
  31512. * @private
  31513. */
  31514. Graph3d.prototype._dataPointFromXY = function (x, y) {
  31515. var i,
  31516. distMax = 100,
  31517. // px
  31518. dataPoint = null,
  31519. closestDataPoint = null,
  31520. closestDist = null,
  31521. center = new Point2d(x, y);
  31522. if (this.style === Graph3d.STYLE.BAR || this.style === Graph3d.STYLE.BARCOLOR || this.style === Graph3d.STYLE.BARSIZE) {
  31523. // the data points are ordered from far away to closest
  31524. for (i = this.dataPoints.length - 1; i >= 0; i--) {
  31525. dataPoint = this.dataPoints[i];
  31526. var surfaces = dataPoint.surfaces;
  31527. if (surfaces) {
  31528. for (var s = surfaces.length - 1; s >= 0; s--) {
  31529. // split each surface in two triangles, and see if the center point is inside one of these
  31530. var surface = surfaces[s];
  31531. var corners = surface.corners;
  31532. var triangle1 = [corners[0].screen, corners[1].screen, corners[2].screen];
  31533. var triangle2 = [corners[2].screen, corners[3].screen, corners[0].screen];
  31534. if (this._insideTriangle(center, triangle1) || this._insideTriangle(center, triangle2)) {
  31535. // return immediately at the first hit
  31536. return dataPoint;
  31537. }
  31538. }
  31539. }
  31540. }
  31541. } else {
  31542. // find the closest data point, using distance to the center of the point on 2d screen
  31543. for (i = 0; i < this.dataPoints.length; i++) {
  31544. dataPoint = this.dataPoints[i];
  31545. var point = dataPoint.screen;
  31546. if (point) {
  31547. var distX = Math.abs(x - point.x);
  31548. var distY = Math.abs(y - point.y);
  31549. var dist = Math.sqrt(distX * distX + distY * distY);
  31550. if ((closestDist === null || dist < closestDist) && dist < distMax) {
  31551. closestDist = dist;
  31552. closestDataPoint = dataPoint;
  31553. }
  31554. }
  31555. }
  31556. }
  31557. return closestDataPoint;
  31558. };
  31559. /**
  31560. * Determine if the given style has bars
  31561. *
  31562. * @param {number} style the style to check
  31563. * @returns {boolean} true if bar style, false otherwise
  31564. */
  31565. Graph3d.prototype.hasBars = function (style) {
  31566. return style == Graph3d.STYLE.BAR || style == Graph3d.STYLE.BARCOLOR || style == Graph3d.STYLE.BARSIZE;
  31567. };
  31568. /**
  31569. * Display a tooltip for given data point
  31570. * @param {Object} dataPoint
  31571. * @private
  31572. */
  31573. Graph3d.prototype._showTooltip = function (dataPoint) {
  31574. var content, line, dot;
  31575. if (!this.tooltip) {
  31576. content = document.createElement('div');
  31577. (0, _assign2['default'])(content.style, {}, this.tooltipStyle.content);
  31578. content.style.position = 'absolute';
  31579. line = document.createElement('div');
  31580. (0, _assign2['default'])(line.style, {}, this.tooltipStyle.line);
  31581. line.style.position = 'absolute';
  31582. dot = document.createElement('div');
  31583. (0, _assign2['default'])(dot.style, {}, this.tooltipStyle.dot);
  31584. dot.style.position = 'absolute';
  31585. this.tooltip = {
  31586. dataPoint: null,
  31587. dom: {
  31588. content: content,
  31589. line: line,
  31590. dot: dot
  31591. }
  31592. };
  31593. } else {
  31594. content = this.tooltip.dom.content;
  31595. line = this.tooltip.dom.line;
  31596. dot = this.tooltip.dom.dot;
  31597. }
  31598. this._hideTooltip();
  31599. this.tooltip.dataPoint = dataPoint;
  31600. if (typeof this.showTooltip === 'function') {
  31601. content.innerHTML = this.showTooltip(dataPoint.point);
  31602. } else {
  31603. 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>';
  31604. }
  31605. content.style.left = '0';
  31606. content.style.top = '0';
  31607. this.frame.appendChild(content);
  31608. this.frame.appendChild(line);
  31609. this.frame.appendChild(dot);
  31610. // calculate sizes
  31611. var contentWidth = content.offsetWidth;
  31612. var contentHeight = content.offsetHeight;
  31613. var lineHeight = line.offsetHeight;
  31614. var dotWidth = dot.offsetWidth;
  31615. var dotHeight = dot.offsetHeight;
  31616. var left = dataPoint.screen.x - contentWidth / 2;
  31617. left = Math.min(Math.max(left, 10), this.frame.clientWidth - 10 - contentWidth);
  31618. line.style.left = dataPoint.screen.x + 'px';
  31619. line.style.top = dataPoint.screen.y - lineHeight + 'px';
  31620. content.style.left = left + 'px';
  31621. content.style.top = dataPoint.screen.y - lineHeight - contentHeight + 'px';
  31622. dot.style.left = dataPoint.screen.x - dotWidth / 2 + 'px';
  31623. dot.style.top = dataPoint.screen.y - dotHeight / 2 + 'px';
  31624. };
  31625. /**
  31626. * Hide the tooltip when displayed
  31627. * @private
  31628. */
  31629. Graph3d.prototype._hideTooltip = function () {
  31630. if (this.tooltip) {
  31631. this.tooltip.dataPoint = null;
  31632. for (var prop in this.tooltip.dom) {
  31633. if (this.tooltip.dom.hasOwnProperty(prop)) {
  31634. var elem = this.tooltip.dom[prop];
  31635. if (elem && elem.parentNode) {
  31636. elem.parentNode.removeChild(elem);
  31637. }
  31638. }
  31639. }
  31640. }
  31641. };
  31642. /**--------------------------------------------------------------------------**/
  31643. /**
  31644. * Get the horizontal mouse position from a mouse event
  31645. *
  31646. * @param {Event} event
  31647. * @returns {number} mouse x
  31648. */
  31649. function getMouseX(event) {
  31650. if ('clientX' in event) return event.clientX;
  31651. return event.targetTouches[0] && event.targetTouches[0].clientX || 0;
  31652. }
  31653. /**
  31654. * Get the vertical mouse position from a mouse event
  31655. *
  31656. * @param {Event} event
  31657. * @returns {number} mouse y
  31658. */
  31659. function getMouseY(event) {
  31660. if ('clientY' in event) return event.clientY;
  31661. return event.targetTouches[0] && event.targetTouches[0].clientY || 0;
  31662. }
  31663. // -----------------------------------------------------------------------------
  31664. // Public methods for specific settings
  31665. // -----------------------------------------------------------------------------
  31666. /**
  31667. * Set the rotation and distance of the camera
  31668. *
  31669. * @param {Object} pos An object with the camera position
  31670. * @param {number} [pos.horizontal] The horizontal rotation, between 0 and 2*PI.
  31671. * Optional, can be left undefined.
  31672. * @param {number} [pos.vertical] The vertical rotation, between 0 and 0.5*PI.
  31673. * if vertical=0.5*PI, the graph is shown from
  31674. * the top. Optional, can be left undefined.
  31675. * @param {number} [pos.distance] The (normalized) distance of the camera to the
  31676. * center of the graph, a value between 0.71 and
  31677. * 5.0. Optional, can be left undefined.
  31678. */
  31679. Graph3d.prototype.setCameraPosition = function (pos) {
  31680. Settings.setCameraPosition(pos, this);
  31681. this.redraw();
  31682. };
  31683. /**
  31684. * Set a new size for the graph
  31685. *
  31686. * @param {string} width Width in pixels or percentage (for example '800px'
  31687. * or '50%')
  31688. * @param {string} height Height in pixels or percentage (for example '400px'
  31689. * or '30%')
  31690. */
  31691. Graph3d.prototype.setSize = function (width, height) {
  31692. this._setSize(width, height);
  31693. this.redraw();
  31694. };
  31695. // -----------------------------------------------------------------------------
  31696. // End public methods for specific settings
  31697. // -----------------------------------------------------------------------------
  31698. module.exports = Graph3d;
  31699. /***/ }),
  31700. /* 162 */
  31701. /***/ (function(module, exports, __webpack_require__) {
  31702. __webpack_require__(163);
  31703. module.exports = __webpack_require__(7).Object.assign;
  31704. /***/ }),
  31705. /* 163 */
  31706. /***/ (function(module, exports, __webpack_require__) {
  31707. // 19.1.3.1 Object.assign(target, source)
  31708. var $export = __webpack_require__(17);
  31709. $export($export.S + $export.F, 'Object', { assign: __webpack_require__(164) });
  31710. /***/ }),
  31711. /* 164 */
  31712. /***/ (function(module, exports, __webpack_require__) {
  31713. "use strict";
  31714. // 19.1.2.1 Object.assign(target, source, ...)
  31715. var getKeys = __webpack_require__(33);
  31716. var gOPS = __webpack_require__(63);
  31717. var pIE = __webpack_require__(42);
  31718. var toObject = __webpack_require__(41);
  31719. var IObject = __webpack_require__(78);
  31720. var $assign = Object.assign;
  31721. // should work with symbols and should have deterministic property order (V8 bug)
  31722. module.exports = !$assign || __webpack_require__(28)(function () {
  31723. var A = {};
  31724. var B = {};
  31725. // eslint-disable-next-line no-undef
  31726. var S = Symbol();
  31727. var K = 'abcdefghijklmnopqrst';
  31728. A[S] = 7;
  31729. K.split('').forEach(function (k) { B[k] = k; });
  31730. return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
  31731. }) ? function assign(target, source) { // eslint-disable-line no-unused-vars
  31732. var T = toObject(target);
  31733. var aLen = arguments.length;
  31734. var index = 1;
  31735. var getSymbols = gOPS.f;
  31736. var isEnum = pIE.f;
  31737. while (aLen > index) {
  31738. var S = IObject(arguments[index++]);
  31739. var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S);
  31740. var length = keys.length;
  31741. var j = 0;
  31742. var key;
  31743. while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key];
  31744. } return T;
  31745. } : $assign;
  31746. /***/ }),
  31747. /* 165 */
  31748. /***/ (function(module, exports, __webpack_require__) {
  31749. module.exports = { "default": __webpack_require__(166), __esModule: true };
  31750. /***/ }),
  31751. /* 166 */
  31752. /***/ (function(module, exports, __webpack_require__) {
  31753. __webpack_require__(167);
  31754. module.exports = __webpack_require__(7).Math.sign;
  31755. /***/ }),
  31756. /* 167 */
  31757. /***/ (function(module, exports, __webpack_require__) {
  31758. // 20.2.2.28 Math.sign(x)
  31759. var $export = __webpack_require__(17);
  31760. $export($export.S, 'Math', { sign: __webpack_require__(168) });
  31761. /***/ }),
  31762. /* 168 */
  31763. /***/ (function(module, exports) {
  31764. // 20.2.2.28 Math.sign(x)
  31765. module.exports = Math.sign || function sign(x) {
  31766. // eslint-disable-next-line no-self-compare
  31767. return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
  31768. };
  31769. /***/ }),
  31770. /* 169 */
  31771. /***/ (function(module, exports, __webpack_require__) {
  31772. module.exports = { "default": __webpack_require__(170), __esModule: true };
  31773. /***/ }),
  31774. /* 170 */
  31775. /***/ (function(module, exports, __webpack_require__) {
  31776. __webpack_require__(171);
  31777. var $Object = __webpack_require__(7).Object;
  31778. module.exports = function defineProperty(it, key, desc) {
  31779. return $Object.defineProperty(it, key, desc);
  31780. };
  31781. /***/ }),
  31782. /* 171 */
  31783. /***/ (function(module, exports, __webpack_require__) {
  31784. var $export = __webpack_require__(17);
  31785. // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
  31786. $export($export.S + $export.F * !__webpack_require__(21), 'Object', { defineProperty: __webpack_require__(20).f });
  31787. /***/ }),
  31788. /* 172 */
  31789. /***/ (function(module, exports, __webpack_require__) {
  31790. "use strict";
  31791. Object.defineProperty(exports, "__esModule", {
  31792. value: true
  31793. });
  31794. /**
  31795. * This object contains all possible options. It will check if the types are correct, if required if the option is one
  31796. * of the allowed values.
  31797. *
  31798. * __any__ means that the name of the property does not matter.
  31799. * __type__ is a required field for all objects and contains the allowed types of all objects
  31800. */
  31801. var string = 'string';
  31802. var bool = 'boolean';
  31803. var number = 'number';
  31804. var object = 'object'; // should only be in a __type__ property
  31805. // Following not used here, but useful for reference
  31806. //let array = 'array';
  31807. //let dom = 'dom';
  31808. //let any = 'any';
  31809. var colorOptions = {
  31810. fill: { string: string },
  31811. stroke: { string: string },
  31812. strokeWidth: { number: number },
  31813. __type__: { string: string, object: object, 'undefined': 'undefined' }
  31814. };
  31815. /**
  31816. * Order attempted to be alphabetical.
  31817. * - x/y/z-prefixes ignored in sorting
  31818. * - __type__ always at end
  31819. * - globals at end
  31820. */
  31821. var allOptions = {
  31822. animationAutoStart: { boolean: bool, 'undefined': 'undefined' },
  31823. animationInterval: { number: number },
  31824. animationPreload: { boolean: bool },
  31825. axisColor: { string: string },
  31826. backgroundColor: colorOptions,
  31827. xBarWidth: { number: number, 'undefined': 'undefined' },
  31828. yBarWidth: { number: number, 'undefined': 'undefined' },
  31829. cameraPosition: {
  31830. distance: { number: number },
  31831. horizontal: { number: number },
  31832. vertical: { number: number },
  31833. __type__: { object: object }
  31834. },
  31835. xCenter: { string: string },
  31836. yCenter: { string: string },
  31837. dataColor: colorOptions,
  31838. dotSizeMinFraction: { number: number },
  31839. dotSizeMaxFraction: { number: number },
  31840. dotSizeRatio: { number: number },
  31841. filterLabel: { string: string },
  31842. gridColor: { string: string },
  31843. onclick: { 'function': 'function' },
  31844. keepAspectRatio: { boolean: bool },
  31845. xLabel: { string: string },
  31846. yLabel: { string: string },
  31847. zLabel: { string: string },
  31848. legendLabel: { string: string },
  31849. xMin: { number: number, 'undefined': 'undefined' },
  31850. yMin: { number: number, 'undefined': 'undefined' },
  31851. zMin: { number: number, 'undefined': 'undefined' },
  31852. xMax: { number: number, 'undefined': 'undefined' },
  31853. yMax: { number: number, 'undefined': 'undefined' },
  31854. zMax: { number: number, 'undefined': 'undefined' },
  31855. showAnimationControls: { boolean: bool, 'undefined': 'undefined' },
  31856. showGrid: { boolean: bool },
  31857. showLegend: { boolean: bool, 'undefined': 'undefined' },
  31858. showPerspective: { boolean: bool },
  31859. showShadow: { boolean: bool },
  31860. showXAxis: { boolean: bool },
  31861. showYAxis: { boolean: bool },
  31862. showZAxis: { boolean: bool },
  31863. xStep: { number: number, 'undefined': 'undefined' },
  31864. yStep: { number: number, 'undefined': 'undefined' },
  31865. zStep: { number: number, 'undefined': 'undefined' },
  31866. style: {
  31867. number: number, // TODO: either Graph3d.DEFAULT has string, or number allowed in documentation
  31868. string: ['bar', 'bar-color', 'bar-size', 'dot', 'dot-line', 'dot-color', 'dot-size', 'line', 'grid', 'surface']
  31869. },
  31870. tooltip: { boolean: bool, 'function': 'function' },
  31871. tooltipStyle: {
  31872. content: {
  31873. color: { string: string },
  31874. background: { string: string },
  31875. border: { string: string },
  31876. borderRadius: { string: string },
  31877. boxShadow: { string: string },
  31878. padding: { string: string },
  31879. __type__: { object: object }
  31880. },
  31881. line: {
  31882. borderLeft: { string: string },
  31883. height: { string: string },
  31884. width: { string: string },
  31885. __type__: { object: object }
  31886. },
  31887. dot: {
  31888. border: { string: string },
  31889. borderRadius: { string: string },
  31890. height: { string: string },
  31891. width: { string: string },
  31892. __type__: { object: object }
  31893. },
  31894. __type__: { object: object }
  31895. },
  31896. xValueLabel: { 'function': 'function' },
  31897. yValueLabel: { 'function': 'function' },
  31898. zValueLabel: { 'function': 'function' },
  31899. valueMax: { number: number, 'undefined': 'undefined' },
  31900. valueMin: { number: number, 'undefined': 'undefined' },
  31901. verticalRatio: { number: number },
  31902. //globals :
  31903. height: { string: string },
  31904. width: { string: string },
  31905. __type__: { object: object }
  31906. };
  31907. exports.allOptions = allOptions;
  31908. /***/ }),
  31909. /* 173 */
  31910. /***/ (function(module, exports, __webpack_require__) {
  31911. "use strict";
  31912. var DataSet = __webpack_require__(11);
  31913. var DataView = __webpack_require__(12);
  31914. var Range = __webpack_require__(174);
  31915. var Filter = __webpack_require__(96);
  31916. var Settings = __webpack_require__(94);
  31917. var Point3d = __webpack_require__(34);
  31918. /**
  31919. * Creates a container for all data of one specific 3D-graph.
  31920. *
  31921. * On construction, the container is totally empty; the data
  31922. * needs to be initialized with method initializeData().
  31923. * Failure to do so will result in the following exception begin thrown
  31924. * on instantiation of Graph3D:
  31925. *
  31926. * Error: Array, DataSet, or DataView expected
  31927. *
  31928. * @constructor DataGroup
  31929. */
  31930. function DataGroup() {
  31931. this.dataTable = null; // The original data table
  31932. }
  31933. /**
  31934. * Initializes the instance from the passed data.
  31935. *
  31936. * Calculates minimum and maximum values and column index values.
  31937. *
  31938. * The graph3d instance is used internally to access the settings for
  31939. * the given instance.
  31940. * TODO: Pass settings only instead.
  31941. *
  31942. * @param {vis.Graph3d} graph3d Reference to the calling Graph3D instance.
  31943. * @param {Array | DataSet | DataView} rawData The data containing the items for
  31944. * the Graph.
  31945. * @param {number} style Style Number
  31946. * @returns {Array.<Object>}
  31947. */
  31948. DataGroup.prototype.initializeData = function (graph3d, rawData, style) {
  31949. if (rawData === undefined) return;
  31950. if (Array.isArray(rawData)) {
  31951. rawData = new DataSet(rawData);
  31952. }
  31953. var data;
  31954. if (rawData instanceof DataSet || rawData instanceof DataView) {
  31955. data = rawData.get();
  31956. } else {
  31957. throw new Error('Array, DataSet, or DataView expected');
  31958. }
  31959. if (data.length == 0) return;
  31960. this.style = style;
  31961. // unsubscribe from the dataTable
  31962. if (this.dataSet) {
  31963. this.dataSet.off('*', this._onChange);
  31964. }
  31965. this.dataSet = rawData;
  31966. this.dataTable = data;
  31967. // subscribe to changes in the dataset
  31968. var me = this;
  31969. this._onChange = function () {
  31970. graph3d.setData(me.dataSet);
  31971. };
  31972. this.dataSet.on('*', this._onChange);
  31973. // determine the location of x,y,z,value,filter columns
  31974. this.colX = 'x';
  31975. this.colY = 'y';
  31976. this.colZ = 'z';
  31977. var withBars = graph3d.hasBars(style);
  31978. // determine barWidth from data
  31979. if (withBars) {
  31980. if (graph3d.defaultXBarWidth !== undefined) {
  31981. this.xBarWidth = graph3d.defaultXBarWidth;
  31982. } else {
  31983. this.xBarWidth = this.getSmallestDifference(data, this.colX) || 1;
  31984. }
  31985. if (graph3d.defaultYBarWidth !== undefined) {
  31986. this.yBarWidth = graph3d.defaultYBarWidth;
  31987. } else {
  31988. this.yBarWidth = this.getSmallestDifference(data, this.colY) || 1;
  31989. }
  31990. }
  31991. // calculate minima and maxima
  31992. this._initializeRange(data, this.colX, graph3d, withBars);
  31993. this._initializeRange(data, this.colY, graph3d, withBars);
  31994. this._initializeRange(data, this.colZ, graph3d, false);
  31995. if (data[0].hasOwnProperty('style')) {
  31996. this.colValue = 'style';
  31997. var valueRange = this.getColumnRange(data, this.colValue);
  31998. this._setRangeDefaults(valueRange, graph3d.defaultValueMin, graph3d.defaultValueMax);
  31999. this.valueRange = valueRange;
  32000. }
  32001. // Initialize data filter if a filter column is provided
  32002. var table = this.getDataTable();
  32003. if (table[0].hasOwnProperty('filter')) {
  32004. if (this.dataFilter === undefined) {
  32005. this.dataFilter = new Filter(this, 'filter', graph3d);
  32006. this.dataFilter.setOnLoadCallback(function () {
  32007. graph3d.redraw();
  32008. });
  32009. }
  32010. }
  32011. var dataPoints;
  32012. if (this.dataFilter) {
  32013. // apply filtering
  32014. dataPoints = this.dataFilter._getDataPoints();
  32015. } else {
  32016. // no filtering. load all data
  32017. dataPoints = this._getDataPoints(this.getDataTable());
  32018. }
  32019. return dataPoints;
  32020. };
  32021. /**
  32022. * Collect the range settings for the given data column.
  32023. *
  32024. * This internal method is intended to make the range
  32025. * initalization more generic.
  32026. *
  32027. * TODO: if/when combined settings per axis defined, get rid of this.
  32028. *
  32029. * @private
  32030. *
  32031. * @param {'x'|'y'|'z'} column The data column to process
  32032. * @param {vis.Graph3d} graph3d Reference to the calling Graph3D instance;
  32033. * required for access to settings
  32034. * @returns {Object}
  32035. */
  32036. DataGroup.prototype._collectRangeSettings = function (column, graph3d) {
  32037. var index = ['x', 'y', 'z'].indexOf(column);
  32038. if (index == -1) {
  32039. throw new Error('Column \'' + column + '\' invalid');
  32040. }
  32041. var upper = column.toUpperCase();
  32042. return {
  32043. barWidth: this[column + 'BarWidth'],
  32044. min: graph3d['default' + upper + 'Min'],
  32045. max: graph3d['default' + upper + 'Max'],
  32046. step: graph3d['default' + upper + 'Step'],
  32047. range_label: column + 'Range', // Name of instance field to write to
  32048. step_label: column + 'Step' // Name of instance field to write to
  32049. };
  32050. };
  32051. /**
  32052. * Initializes the settings per given column.
  32053. *
  32054. * TODO: if/when combined settings per axis defined, rewrite this.
  32055. *
  32056. * @private
  32057. *
  32058. * @param {DataSet | DataView} data The data containing the items for the Graph
  32059. * @param {'x'|'y'|'z'} column The data column to process
  32060. * @param {vis.Graph3d} graph3d Reference to the calling Graph3D instance;
  32061. * required for access to settings
  32062. * @param {boolean} withBars True if initializing for bar graph
  32063. */
  32064. DataGroup.prototype._initializeRange = function (data, column, graph3d, withBars) {
  32065. var NUMSTEPS = 5;
  32066. var settings = this._collectRangeSettings(column, graph3d);
  32067. var range = this.getColumnRange(data, column);
  32068. if (withBars && column != 'z') {
  32069. // Safeguard for 'z'; it doesn't have a bar width
  32070. range.expand(settings.barWidth / 2);
  32071. }
  32072. this._setRangeDefaults(range, settings.min, settings.max);
  32073. this[settings.range_label] = range;
  32074. this[settings.step_label] = settings.step !== undefined ? settings.step : range.range() / NUMSTEPS;
  32075. };
  32076. /**
  32077. * Creates a list with all the different values in the data for the given column.
  32078. *
  32079. * If no data passed, use the internal data of this instance.
  32080. *
  32081. * @param {'x'|'y'|'z'} column The data column to process
  32082. * @param {DataSet|DataView|undefined} data The data containing the items for the Graph
  32083. *
  32084. * @returns {Array} All distinct values in the given column data, sorted ascending.
  32085. */
  32086. DataGroup.prototype.getDistinctValues = function (column, data) {
  32087. if (data === undefined) {
  32088. data = this.dataTable;
  32089. }
  32090. var values = [];
  32091. for (var i = 0; i < data.length; i++) {
  32092. var value = data[i][column] || 0;
  32093. if (values.indexOf(value) === -1) {
  32094. values.push(value);
  32095. }
  32096. }
  32097. return values.sort(function (a, b) {
  32098. return a - b;
  32099. });
  32100. };
  32101. /**
  32102. * Determine the smallest difference between the values for given
  32103. * column in the passed data set.
  32104. *
  32105. * @param {DataSet|DataView|undefined} data The data containing the items for the Graph
  32106. * @param {'x'|'y'|'z'} column The data column to process
  32107. *
  32108. * @returns {number|null} Smallest difference value or
  32109. * null, if it can't be determined.
  32110. */
  32111. DataGroup.prototype.getSmallestDifference = function (data, column) {
  32112. var values = this.getDistinctValues(data, column);
  32113. // Get all the distinct diffs
  32114. // Array values is assumed to be sorted here
  32115. var smallest_diff = null;
  32116. for (var i = 1; i < values.length; i++) {
  32117. var diff = values[i] - values[i - 1];
  32118. if (smallest_diff == null || smallest_diff > diff) {
  32119. smallest_diff = diff;
  32120. }
  32121. }
  32122. return smallest_diff;
  32123. };
  32124. /**
  32125. * Get the absolute min/max values for the passed data column.
  32126. *
  32127. * @param {DataSet|DataView|undefined} data The data containing the items for the Graph
  32128. * @param {'x'|'y'|'z'} column The data column to process
  32129. *
  32130. * @returns {Range} A Range instance with min/max members properly set.
  32131. */
  32132. DataGroup.prototype.getColumnRange = function (data, column) {
  32133. var range = new Range();
  32134. // Adjust the range so that it covers all values in the passed data elements.
  32135. for (var i = 0; i < data.length; i++) {
  32136. var item = data[i][column];
  32137. range.adjust(item);
  32138. }
  32139. return range;
  32140. };
  32141. /**
  32142. * Determines the number of rows in the current data.
  32143. *
  32144. * @returns {number}
  32145. */
  32146. DataGroup.prototype.getNumberOfRows = function () {
  32147. return this.dataTable.length;
  32148. };
  32149. /**
  32150. * Set default values for range
  32151. *
  32152. * The default values override the range values, if defined.
  32153. *
  32154. * Because it's possible that only defaultMin or defaultMax is set, it's better
  32155. * to pass in a range already set with the min/max set from the data. Otherwise,
  32156. * it's quite hard to process the min/max properly.
  32157. *
  32158. * @param {vis.Range} range
  32159. * @param {number} [defaultMin=range.min]
  32160. * @param {number} [defaultMax=range.max]
  32161. * @private
  32162. */
  32163. DataGroup.prototype._setRangeDefaults = function (range, defaultMin, defaultMax) {
  32164. if (defaultMin !== undefined) {
  32165. range.min = defaultMin;
  32166. }
  32167. if (defaultMax !== undefined) {
  32168. range.max = defaultMax;
  32169. }
  32170. // This is the original way that the default min/max values were adjusted.
  32171. // TODO: Perhaps it's better if an error is thrown if the values do not agree.
  32172. // But this will change the behaviour.
  32173. if (range.max <= range.min) range.max = range.min + 1;
  32174. };
  32175. DataGroup.prototype.getDataTable = function () {
  32176. return this.dataTable;
  32177. };
  32178. DataGroup.prototype.getDataSet = function () {
  32179. return this.dataSet;
  32180. };
  32181. /**
  32182. * Return all data values as a list of Point3d objects
  32183. * @param {Array.<Object>} data
  32184. * @returns {Array.<Object>}
  32185. */
  32186. DataGroup.prototype.getDataPoints = function (data) {
  32187. var dataPoints = [];
  32188. for (var i = 0; i < data.length; i++) {
  32189. var point = new Point3d();
  32190. point.x = data[i][this.colX] || 0;
  32191. point.y = data[i][this.colY] || 0;
  32192. point.z = data[i][this.colZ] || 0;
  32193. point.data = data[i];
  32194. if (this.colValue !== undefined) {
  32195. point.value = data[i][this.colValue] || 0;
  32196. }
  32197. var obj = {};
  32198. obj.point = point;
  32199. obj.bottom = new Point3d(point.x, point.y, this.zRange.min);
  32200. obj.trans = undefined;
  32201. obj.screen = undefined;
  32202. dataPoints.push(obj);
  32203. }
  32204. return dataPoints;
  32205. };
  32206. /**
  32207. * Copy all values from the data table to a matrix.
  32208. *
  32209. * The provided values are supposed to form a grid of (x,y) positions.
  32210. * @param {Array.<Object>} data
  32211. * @returns {Array.<Object>}
  32212. * @private
  32213. */
  32214. DataGroup.prototype.initDataAsMatrix = function (data) {
  32215. // TODO: store the created matrix dataPoints in the filters instead of
  32216. // reloading each time.
  32217. var x, y, i, obj;
  32218. // create two lists with all present x and y values
  32219. var dataX = this.getDistinctValues(this.colX, data);
  32220. var dataY = this.getDistinctValues(this.colY, data);
  32221. var dataPoints = this.getDataPoints(data);
  32222. // create a grid, a 2d matrix, with all values.
  32223. var dataMatrix = []; // temporary data matrix
  32224. for (i = 0; i < dataPoints.length; i++) {
  32225. obj = dataPoints[i];
  32226. // TODO: implement Array().indexOf() for Internet Explorer
  32227. var xIndex = dataX.indexOf(obj.point.x);
  32228. var yIndex = dataY.indexOf(obj.point.y);
  32229. if (dataMatrix[xIndex] === undefined) {
  32230. dataMatrix[xIndex] = [];
  32231. }
  32232. dataMatrix[xIndex][yIndex] = obj;
  32233. }
  32234. // fill in the pointers to the neighbors.
  32235. for (x = 0; x < dataMatrix.length; x++) {
  32236. for (y = 0; y < dataMatrix[x].length; y++) {
  32237. if (dataMatrix[x][y]) {
  32238. dataMatrix[x][y].pointRight = x < dataMatrix.length - 1 ? dataMatrix[x + 1][y] : undefined;
  32239. dataMatrix[x][y].pointTop = y < dataMatrix[x].length - 1 ? dataMatrix[x][y + 1] : undefined;
  32240. dataMatrix[x][y].pointCross = x < dataMatrix.length - 1 && y < dataMatrix[x].length - 1 ? dataMatrix[x + 1][y + 1] : undefined;
  32241. }
  32242. }
  32243. }
  32244. return dataPoints;
  32245. };
  32246. /**
  32247. * Return common information, if present
  32248. *
  32249. * @returns {string}
  32250. */
  32251. DataGroup.prototype.getInfo = function () {
  32252. var dataFilter = this.dataFilter;
  32253. if (!dataFilter) return undefined;
  32254. return dataFilter.getLabel() + ': ' + dataFilter.getSelectedValue();
  32255. };
  32256. /**
  32257. * Reload the data
  32258. */
  32259. DataGroup.prototype.reload = function () {
  32260. if (this.dataTable) {
  32261. this.setData(this.dataTable);
  32262. }
  32263. };
  32264. /**
  32265. * Filter the data based on the current filter
  32266. *
  32267. * @param {Array} data
  32268. * @returns {Array} dataPoints Array with point objects which can be drawn on
  32269. * screen
  32270. */
  32271. DataGroup.prototype._getDataPoints = function (data) {
  32272. var dataPoints = [];
  32273. if (this.style === Settings.STYLE.GRID || this.style === Settings.STYLE.SURFACE) {
  32274. dataPoints = this.initDataAsMatrix(data);
  32275. } else {
  32276. // 'dot', 'dot-line', etc.
  32277. this._checkValueField(data);
  32278. dataPoints = this.getDataPoints(data);
  32279. if (this.style === Settings.STYLE.LINE) {
  32280. // Add next member points for line drawing
  32281. for (var i = 0; i < dataPoints.length; i++) {
  32282. if (i > 0) {
  32283. dataPoints[i - 1].pointNext = dataPoints[i];
  32284. }
  32285. }
  32286. }
  32287. }
  32288. return dataPoints;
  32289. };
  32290. /**
  32291. * Check if the state is consistent for the use of the value field.
  32292. *
  32293. * Throws if a problem is detected.
  32294. *
  32295. * @param {Array.<Object>} data
  32296. * @private
  32297. */
  32298. DataGroup.prototype._checkValueField = function (data) {
  32299. var hasValueField = this.style === Settings.STYLE.BARCOLOR || this.style === Settings.STYLE.BARSIZE || this.style === Settings.STYLE.DOTCOLOR || this.style === Settings.STYLE.DOTSIZE;
  32300. if (!hasValueField) {
  32301. return; // No need to check further
  32302. }
  32303. // Following field must be present for the current graph style
  32304. if (this.colValue === undefined) {
  32305. throw new Error('Expected data to have ' + ' field \'style\' ' + ' for graph style \'' + this.style + '\'');
  32306. }
  32307. // The data must also contain this field.
  32308. // Note that only first data element is checked.
  32309. if (data[0][this.colValue] === undefined) {
  32310. throw new Error('Expected data to have ' + ' field \'' + this.colValue + '\' ' + ' for graph style \'' + this.style + '\'');
  32311. }
  32312. };
  32313. module.exports = DataGroup;
  32314. /***/ }),
  32315. /* 174 */
  32316. /***/ (function(module, exports, __webpack_require__) {
  32317. "use strict";
  32318. /**
  32319. * @prototype Range
  32320. *
  32321. * Helper class to make working with related min and max values easier.
  32322. *
  32323. * The range is inclusive; a given value is considered part of the range if:
  32324. *
  32325. * this.min <= value <= this.max
  32326. */
  32327. function Range() {
  32328. this.min = undefined;
  32329. this.max = undefined;
  32330. }
  32331. /**
  32332. * Adjust the range so that the passed value fits in it.
  32333. *
  32334. * If the value is outside of the current extremes, adjust
  32335. * the min or max so that the value is within the range.
  32336. *
  32337. * @param {number} value Numeric value to fit in range
  32338. */
  32339. Range.prototype.adjust = function (value) {
  32340. if (value === undefined) return;
  32341. if (this.min === undefined || this.min > value) {
  32342. this.min = value;
  32343. }
  32344. if (this.max === undefined || this.max < value) {
  32345. this.max = value;
  32346. }
  32347. };
  32348. /**
  32349. * Adjust the current range so that the passed range fits in it.
  32350. *
  32351. * @param {Range} range Range instance to fit in current instance
  32352. */
  32353. Range.prototype.combine = function (range) {
  32354. this.add(range.min);
  32355. this.add(range.max);
  32356. };
  32357. /**
  32358. * Expand the range by the given value
  32359. *
  32360. * min will be lowered by given value;
  32361. * max will be raised by given value
  32362. *
  32363. * Shrinking by passing a negative value is allowed.
  32364. *
  32365. * @param {number} val Amount by which to expand or shrink current range with
  32366. */
  32367. Range.prototype.expand = function (val) {
  32368. if (val === undefined) {
  32369. return;
  32370. }
  32371. var newMin = this.min - val;
  32372. var newMax = this.max + val;
  32373. // Note that following allows newMin === newMax.
  32374. // This should be OK, since method expand() allows this also.
  32375. if (newMin > newMax) {
  32376. throw new Error('Passed expansion value makes range invalid');
  32377. }
  32378. this.min = newMin;
  32379. this.max = newMax;
  32380. };
  32381. /**
  32382. * Determine the full range width of current instance.
  32383. *
  32384. * @returns {num} The calculated width of this range
  32385. */
  32386. Range.prototype.range = function () {
  32387. return this.max - this.min;
  32388. };
  32389. /**
  32390. * Determine the central point of current instance.
  32391. *
  32392. * @returns {number} the value in the middle of min and max
  32393. */
  32394. Range.prototype.center = function () {
  32395. return (this.min + this.max) / 2;
  32396. };
  32397. module.exports = Range;
  32398. /***/ }),
  32399. /* 175 */
  32400. /***/ (function(module, exports, __webpack_require__) {
  32401. "use strict";
  32402. var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
  32403. (function (factory) {
  32404. if (true) {
  32405. // AMD. Register as an anonymous module.
  32406. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
  32407. __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
  32408. (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
  32409. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  32410. } else if (typeof exports === 'object') {
  32411. // Node. Does not work with strict CommonJS, but
  32412. // only CommonJS-like environments that support module.exports,
  32413. // like Node.
  32414. module.exports = factory();
  32415. } else {
  32416. // Browser globals (root is window)
  32417. window.propagating = factory();
  32418. }
  32419. }(function () {
  32420. var _firstTarget = null; // singleton, will contain the target element where the touch event started
  32421. /**
  32422. * Extend an Hammer.js instance with event propagation.
  32423. *
  32424. * Features:
  32425. * - Events emitted by hammer will propagate in order from child to parent
  32426. * elements.
  32427. * - Events are extended with a function `event.stopPropagation()` to stop
  32428. * propagation to parent elements.
  32429. * - An option `preventDefault` to stop all default browser behavior.
  32430. *
  32431. * Usage:
  32432. * var hammer = propagatingHammer(new Hammer(element));
  32433. * var hammer = propagatingHammer(new Hammer(element), {preventDefault: true});
  32434. *
  32435. * @param {Hammer.Manager} hammer An hammer instance.
  32436. * @param {Object} [options] Available options:
  32437. * - `preventDefault: true | false | 'mouse' | 'touch' | 'pen'`.
  32438. * Enforce preventing the default browser behavior.
  32439. * Cannot be set to `false`.
  32440. * @return {Hammer.Manager} Returns the same hammer instance with extended
  32441. * functionality
  32442. */
  32443. return function propagating(hammer, options) {
  32444. var _options = options || {
  32445. preventDefault: false
  32446. };
  32447. if (hammer.Manager) {
  32448. // This looks like the Hammer constructor.
  32449. // Overload the constructors with our own.
  32450. var Hammer = hammer;
  32451. var PropagatingHammer = function(element, options) {
  32452. var o = Object.create(_options);
  32453. if (options) Hammer.assign(o, options);
  32454. return propagating(new Hammer(element, o), o);
  32455. };
  32456. Hammer.assign(PropagatingHammer, Hammer);
  32457. PropagatingHammer.Manager = function (element, options) {
  32458. var o = Object.create(_options);
  32459. if (options) Hammer.assign(o, options);
  32460. return propagating(new Hammer.Manager(element, o), o);
  32461. };
  32462. return PropagatingHammer;
  32463. }
  32464. // create a wrapper object which will override the functions
  32465. // `on`, `off`, `destroy`, and `emit` of the hammer instance
  32466. var wrapper = Object.create(hammer);
  32467. // attach to DOM element
  32468. var element = hammer.element;
  32469. if(!element.hammer) element.hammer = [];
  32470. element.hammer.push(wrapper);
  32471. // register an event to catch the start of a gesture and store the
  32472. // target in a singleton
  32473. hammer.on('hammer.input', function (event) {
  32474. if (_options.preventDefault === true || (_options.preventDefault === event.pointerType)) {
  32475. event.preventDefault();
  32476. }
  32477. if (event.isFirst) {
  32478. _firstTarget = event.target;
  32479. }
  32480. });
  32481. /** @type {Object.<String, Array.<function>>} */
  32482. wrapper._handlers = {};
  32483. /**
  32484. * Register a handler for one or multiple events
  32485. * @param {String} events A space separated string with events
  32486. * @param {function} handler A callback function, called as handler(event)
  32487. * @returns {Hammer.Manager} Returns the hammer instance
  32488. */
  32489. wrapper.on = function (events, handler) {
  32490. // register the handler
  32491. split(events).forEach(function (event) {
  32492. var _handlers = wrapper._handlers[event];
  32493. if (!_handlers) {
  32494. wrapper._handlers[event] = _handlers = [];
  32495. // register the static, propagated handler
  32496. hammer.on(event, propagatedHandler);
  32497. }
  32498. _handlers.push(handler);
  32499. });
  32500. return wrapper;
  32501. };
  32502. /**
  32503. * Unregister a handler for one or multiple events
  32504. * @param {String} events A space separated string with events
  32505. * @param {function} [handler] Optional. The registered handler. If not
  32506. * provided, all handlers for given events
  32507. * are removed.
  32508. * @returns {Hammer.Manager} Returns the hammer instance
  32509. */
  32510. wrapper.off = function (events, handler) {
  32511. // unregister the handler
  32512. split(events).forEach(function (event) {
  32513. var _handlers = wrapper._handlers[event];
  32514. if (_handlers) {
  32515. _handlers = handler ? _handlers.filter(function (h) {
  32516. return h !== handler;
  32517. }) : [];
  32518. if (_handlers.length > 0) {
  32519. wrapper._handlers[event] = _handlers;
  32520. }
  32521. else {
  32522. // remove static, propagated handler
  32523. hammer.off(event, propagatedHandler);
  32524. delete wrapper._handlers[event];
  32525. }
  32526. }
  32527. });
  32528. return wrapper;
  32529. };
  32530. /**
  32531. * Emit to the event listeners
  32532. * @param {string} eventType
  32533. * @param {Event} event
  32534. */
  32535. wrapper.emit = function(eventType, event) {
  32536. _firstTarget = event.target;
  32537. hammer.emit(eventType, event);
  32538. };
  32539. wrapper.destroy = function () {
  32540. // Detach from DOM element
  32541. var hammers = hammer.element.hammer;
  32542. var idx = hammers.indexOf(wrapper);
  32543. if(idx !== -1) hammers.splice(idx,1);
  32544. if(!hammers.length) delete hammer.element.hammer;
  32545. // clear all handlers
  32546. wrapper._handlers = {};
  32547. // call original hammer destroy
  32548. hammer.destroy();
  32549. };
  32550. // split a string with space separated words
  32551. function split(events) {
  32552. return events.match(/[^ ]+/g);
  32553. }
  32554. /**
  32555. * A static event handler, applying event propagation.
  32556. * @param {Object} event
  32557. */
  32558. function propagatedHandler(event) {
  32559. // let only a single hammer instance handle this event
  32560. if (event.type !== 'hammer.input') {
  32561. // it is possible that the same srcEvent is used with multiple hammer events,
  32562. // we keep track on which events are handled in an object _handled
  32563. if (!event.srcEvent._handled) {
  32564. event.srcEvent._handled = {};
  32565. }
  32566. if (event.srcEvent._handled[event.type]) {
  32567. return;
  32568. }
  32569. else {
  32570. event.srcEvent._handled[event.type] = true;
  32571. }
  32572. }
  32573. // attach a stopPropagation function to the event
  32574. var stopped = false;
  32575. event.stopPropagation = function () {
  32576. stopped = true;
  32577. };
  32578. //wrap the srcEvent's stopPropagation to also stop hammer propagation:
  32579. var srcStop = event.srcEvent.stopPropagation.bind(event.srcEvent);
  32580. if(typeof srcStop == "function") {
  32581. event.srcEvent.stopPropagation = function(){
  32582. srcStop();
  32583. event.stopPropagation();
  32584. }
  32585. }
  32586. // attach firstTarget property to the event
  32587. event.firstTarget = _firstTarget;
  32588. // propagate over all elements (until stopped)
  32589. var elem = _firstTarget;
  32590. while (elem && !stopped) {
  32591. var elemHammer = elem.hammer;
  32592. if(elemHammer){
  32593. var _handlers;
  32594. for(var k = 0; k < elemHammer.length; k++){
  32595. _handlers = elemHammer[k]._handlers[event.type];
  32596. if(_handlers) for (var i = 0; i < _handlers.length && !stopped; i++) {
  32597. _handlers[i](event);
  32598. }
  32599. }
  32600. }
  32601. elem = elem.parentNode;
  32602. }
  32603. }
  32604. return wrapper;
  32605. };
  32606. }));
  32607. /***/ }),
  32608. /* 176 */
  32609. /***/ (function(module, exports, __webpack_require__) {
  32610. var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v2.0.7 - 2016-04-22
  32611. * http://hammerjs.github.io/
  32612. *
  32613. * Copyright (c) 2016 Jorik Tangelder;
  32614. * Licensed under the MIT license */
  32615. (function(window, document, exportName, undefined) {
  32616. 'use strict';
  32617. var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
  32618. var TEST_ELEMENT = document.createElement('div');
  32619. var TYPE_FUNCTION = 'function';
  32620. var round = Math.round;
  32621. var abs = Math.abs;
  32622. var now = Date.now;
  32623. /**
  32624. * set a timeout with a given scope
  32625. * @param {Function} fn
  32626. * @param {Number} timeout
  32627. * @param {Object} context
  32628. * @returns {number}
  32629. */
  32630. function setTimeoutContext(fn, timeout, context) {
  32631. return setTimeout(bindFn(fn, context), timeout);
  32632. }
  32633. /**
  32634. * if the argument is an array, we want to execute the fn on each entry
  32635. * if it aint an array we don't want to do a thing.
  32636. * this is used by all the methods that accept a single and array argument.
  32637. * @param {*|Array} arg
  32638. * @param {String} fn
  32639. * @param {Object} [context]
  32640. * @returns {Boolean}
  32641. */
  32642. function invokeArrayArg(arg, fn, context) {
  32643. if (Array.isArray(arg)) {
  32644. each(arg, context[fn], context);
  32645. return true;
  32646. }
  32647. return false;
  32648. }
  32649. /**
  32650. * walk objects and arrays
  32651. * @param {Object} obj
  32652. * @param {Function} iterator
  32653. * @param {Object} context
  32654. */
  32655. function each(obj, iterator, context) {
  32656. var i;
  32657. if (!obj) {
  32658. return;
  32659. }
  32660. if (obj.forEach) {
  32661. obj.forEach(iterator, context);
  32662. } else if (obj.length !== undefined) {
  32663. i = 0;
  32664. while (i < obj.length) {
  32665. iterator.call(context, obj[i], i, obj);
  32666. i++;
  32667. }
  32668. } else {
  32669. for (i in obj) {
  32670. obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
  32671. }
  32672. }
  32673. }
  32674. /**
  32675. * wrap a method with a deprecation warning and stack trace
  32676. * @param {Function} method
  32677. * @param {String} name
  32678. * @param {String} message
  32679. * @returns {Function} A new function wrapping the supplied method.
  32680. */
  32681. function deprecate(method, name, message) {
  32682. var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
  32683. return function() {
  32684. var e = new Error('get-stack-trace');
  32685. var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
  32686. .replace(/^\s+at\s+/gm, '')
  32687. .replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';
  32688. var log = window.console && (window.console.warn || window.console.log);
  32689. if (log) {
  32690. log.call(window.console, deprecationMessage, stack);
  32691. }
  32692. return method.apply(this, arguments);
  32693. };
  32694. }
  32695. /**
  32696. * extend object.
  32697. * means that properties in dest will be overwritten by the ones in src.
  32698. * @param {Object} target
  32699. * @param {...Object} objects_to_assign
  32700. * @returns {Object} target
  32701. */
  32702. var assign;
  32703. if (typeof Object.assign !== 'function') {
  32704. assign = function assign(target) {
  32705. if (target === undefined || target === null) {
  32706. throw new TypeError('Cannot convert undefined or null to object');
  32707. }
  32708. var output = Object(target);
  32709. for (var index = 1; index < arguments.length; index++) {
  32710. var source = arguments[index];
  32711. if (source !== undefined && source !== null) {
  32712. for (var nextKey in source) {
  32713. if (source.hasOwnProperty(nextKey)) {
  32714. output[nextKey] = source[nextKey];
  32715. }
  32716. }
  32717. }
  32718. }
  32719. return output;
  32720. };
  32721. } else {
  32722. assign = Object.assign;
  32723. }
  32724. /**
  32725. * extend object.
  32726. * means that properties in dest will be overwritten by the ones in src.
  32727. * @param {Object} dest
  32728. * @param {Object} src
  32729. * @param {Boolean} [merge=false]
  32730. * @returns {Object} dest
  32731. */
  32732. var extend = deprecate(function extend(dest, src, merge) {
  32733. var keys = Object.keys(src);
  32734. var i = 0;
  32735. while (i < keys.length) {
  32736. if (!merge || (merge && dest[keys[i]] === undefined)) {
  32737. dest[keys[i]] = src[keys[i]];
  32738. }
  32739. i++;
  32740. }
  32741. return dest;
  32742. }, 'extend', 'Use `assign`.');
  32743. /**
  32744. * merge the values from src in the dest.
  32745. * means that properties that exist in dest will not be overwritten by src
  32746. * @param {Object} dest
  32747. * @param {Object} src
  32748. * @returns {Object} dest
  32749. */
  32750. var merge = deprecate(function merge(dest, src) {
  32751. return extend(dest, src, true);
  32752. }, 'merge', 'Use `assign`.');
  32753. /**
  32754. * simple class inheritance
  32755. * @param {Function} child
  32756. * @param {Function} base
  32757. * @param {Object} [properties]
  32758. */
  32759. function inherit(child, base, properties) {
  32760. var baseP = base.prototype,
  32761. childP;
  32762. childP = child.prototype = Object.create(baseP);
  32763. childP.constructor = child;
  32764. childP._super = baseP;
  32765. if (properties) {
  32766. assign(childP, properties);
  32767. }
  32768. }
  32769. /**
  32770. * simple function bind
  32771. * @param {Function} fn
  32772. * @param {Object} context
  32773. * @returns {Function}
  32774. */
  32775. function bindFn(fn, context) {
  32776. return function boundFn() {
  32777. return fn.apply(context, arguments);
  32778. };
  32779. }
  32780. /**
  32781. * let a boolean value also be a function that must return a boolean
  32782. * this first item in args will be used as the context
  32783. * @param {Boolean|Function} val
  32784. * @param {Array} [args]
  32785. * @returns {Boolean}
  32786. */
  32787. function boolOrFn(val, args) {
  32788. if (typeof val == TYPE_FUNCTION) {
  32789. return val.apply(args ? args[0] || undefined : undefined, args);
  32790. }
  32791. return val;
  32792. }
  32793. /**
  32794. * use the val2 when val1 is undefined
  32795. * @param {*} val1
  32796. * @param {*} val2
  32797. * @returns {*}
  32798. */
  32799. function ifUndefined(val1, val2) {
  32800. return (val1 === undefined) ? val2 : val1;
  32801. }
  32802. /**
  32803. * addEventListener with multiple events at once
  32804. * @param {EventTarget} target
  32805. * @param {String} types
  32806. * @param {Function} handler
  32807. */
  32808. function addEventListeners(target, types, handler) {
  32809. each(splitStr(types), function(type) {
  32810. target.addEventListener(type, handler, false);
  32811. });
  32812. }
  32813. /**
  32814. * removeEventListener with multiple events at once
  32815. * @param {EventTarget} target
  32816. * @param {String} types
  32817. * @param {Function} handler
  32818. */
  32819. function removeEventListeners(target, types, handler) {
  32820. each(splitStr(types), function(type) {
  32821. target.removeEventListener(type, handler, false);
  32822. });
  32823. }
  32824. /**
  32825. * find if a node is in the given parent
  32826. * @method hasParent
  32827. * @param {HTMLElement} node
  32828. * @param {HTMLElement} parent
  32829. * @return {Boolean} found
  32830. */
  32831. function hasParent(node, parent) {
  32832. while (node) {
  32833. if (node == parent) {
  32834. return true;
  32835. }
  32836. node = node.parentNode;
  32837. }
  32838. return false;
  32839. }
  32840. /**
  32841. * small indexOf wrapper
  32842. * @param {String} str
  32843. * @param {String} find
  32844. * @returns {Boolean} found
  32845. */
  32846. function inStr(str, find) {
  32847. return str.indexOf(find) > -1;
  32848. }
  32849. /**
  32850. * split string on whitespace
  32851. * @param {String} str
  32852. * @returns {Array} words
  32853. */
  32854. function splitStr(str) {
  32855. return str.trim().split(/\s+/g);
  32856. }
  32857. /**
  32858. * find if a array contains the object using indexOf or a simple polyFill
  32859. * @param {Array} src
  32860. * @param {String} find
  32861. * @param {String} [findByKey]
  32862. * @return {Boolean|Number} false when not found, or the index
  32863. */
  32864. function inArray(src, find, findByKey) {
  32865. if (src.indexOf && !findByKey) {
  32866. return src.indexOf(find);
  32867. } else {
  32868. var i = 0;
  32869. while (i < src.length) {
  32870. if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
  32871. return i;
  32872. }
  32873. i++;
  32874. }
  32875. return -1;
  32876. }
  32877. }
  32878. /**
  32879. * convert array-like objects to real arrays
  32880. * @param {Object} obj
  32881. * @returns {Array}
  32882. */
  32883. function toArray(obj) {
  32884. return Array.prototype.slice.call(obj, 0);
  32885. }
  32886. /**
  32887. * unique array with objects based on a key (like 'id') or just by the array's value
  32888. * @param {Array} src [{id:1},{id:2},{id:1}]
  32889. * @param {String} [key]
  32890. * @param {Boolean} [sort=False]
  32891. * @returns {Array} [{id:1},{id:2}]
  32892. */
  32893. function uniqueArray(src, key, sort) {
  32894. var results = [];
  32895. var values = [];
  32896. var i = 0;
  32897. while (i < src.length) {
  32898. var val = key ? src[i][key] : src[i];
  32899. if (inArray(values, val) < 0) {
  32900. results.push(src[i]);
  32901. }
  32902. values[i] = val;
  32903. i++;
  32904. }
  32905. if (sort) {
  32906. if (!key) {
  32907. results = results.sort();
  32908. } else {
  32909. results = results.sort(function sortUniqueArray(a, b) {
  32910. return a[key] > b[key];
  32911. });
  32912. }
  32913. }
  32914. return results;
  32915. }
  32916. /**
  32917. * get the prefixed property
  32918. * @param {Object} obj
  32919. * @param {String} property
  32920. * @returns {String|Undefined} prefixed
  32921. */
  32922. function prefixed(obj, property) {
  32923. var prefix, prop;
  32924. var camelProp = property[0].toUpperCase() + property.slice(1);
  32925. var i = 0;
  32926. while (i < VENDOR_PREFIXES.length) {
  32927. prefix = VENDOR_PREFIXES[i];
  32928. prop = (prefix) ? prefix + camelProp : property;
  32929. if (prop in obj) {
  32930. return prop;
  32931. }
  32932. i++;
  32933. }
  32934. return undefined;
  32935. }
  32936. /**
  32937. * get a unique id
  32938. * @returns {number} uniqueId
  32939. */
  32940. var _uniqueId = 1;
  32941. function uniqueId() {
  32942. return _uniqueId++;
  32943. }
  32944. /**
  32945. * get the window object of an element
  32946. * @param {HTMLElement} element
  32947. * @returns {DocumentView|Window}
  32948. */
  32949. function getWindowForElement(element) {
  32950. var doc = element.ownerDocument || element;
  32951. return (doc.defaultView || doc.parentWindow || window);
  32952. }
  32953. var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  32954. var SUPPORT_TOUCH = ('ontouchstart' in window);
  32955. var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;
  32956. var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
  32957. var INPUT_TYPE_TOUCH = 'touch';
  32958. var INPUT_TYPE_PEN = 'pen';
  32959. var INPUT_TYPE_MOUSE = 'mouse';
  32960. var INPUT_TYPE_KINECT = 'kinect';
  32961. var COMPUTE_INTERVAL = 25;
  32962. var INPUT_START = 1;
  32963. var INPUT_MOVE = 2;
  32964. var INPUT_END = 4;
  32965. var INPUT_CANCEL = 8;
  32966. var DIRECTION_NONE = 1;
  32967. var DIRECTION_LEFT = 2;
  32968. var DIRECTION_RIGHT = 4;
  32969. var DIRECTION_UP = 8;
  32970. var DIRECTION_DOWN = 16;
  32971. var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
  32972. var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
  32973. var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
  32974. var PROPS_XY = ['x', 'y'];
  32975. var PROPS_CLIENT_XY = ['clientX', 'clientY'];
  32976. /**
  32977. * create new input type manager
  32978. * @param {Manager} manager
  32979. * @param {Function} callback
  32980. * @returns {Input}
  32981. * @constructor
  32982. */
  32983. function Input(manager, callback) {
  32984. var self = this;
  32985. this.manager = manager;
  32986. this.callback = callback;
  32987. this.element = manager.element;
  32988. this.target = manager.options.inputTarget;
  32989. // smaller wrapper around the handler, for the scope and the enabled state of the manager,
  32990. // so when disabled the input events are completely bypassed.
  32991. this.domHandler = function(ev) {
  32992. if (boolOrFn(manager.options.enable, [manager])) {
  32993. self.handler(ev);
  32994. }
  32995. };
  32996. this.init();
  32997. }
  32998. Input.prototype = {
  32999. /**
  33000. * should handle the inputEvent data and trigger the callback
  33001. * @virtual
  33002. */
  33003. handler: function() { },
  33004. /**
  33005. * bind the events
  33006. */
  33007. init: function() {
  33008. this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
  33009. this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
  33010. this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
  33011. },
  33012. /**
  33013. * unbind the events
  33014. */
  33015. destroy: function() {
  33016. this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
  33017. this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
  33018. this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
  33019. }
  33020. };
  33021. /**
  33022. * create new input type manager
  33023. * called by the Manager constructor
  33024. * @param {Hammer} manager
  33025. * @returns {Input}
  33026. */
  33027. function createInputInstance(manager) {
  33028. var Type;
  33029. var inputClass = manager.options.inputClass;
  33030. if (inputClass) {
  33031. Type = inputClass;
  33032. } else if (SUPPORT_POINTER_EVENTS) {
  33033. Type = PointerEventInput;
  33034. } else if (SUPPORT_ONLY_TOUCH) {
  33035. Type = TouchInput;
  33036. } else if (!SUPPORT_TOUCH) {
  33037. Type = MouseInput;
  33038. } else {
  33039. Type = TouchMouseInput;
  33040. }
  33041. return new (Type)(manager, inputHandler);
  33042. }
  33043. /**
  33044. * handle input events
  33045. * @param {Manager} manager
  33046. * @param {String} eventType
  33047. * @param {Object} input
  33048. */
  33049. function inputHandler(manager, eventType, input) {
  33050. var pointersLen = input.pointers.length;
  33051. var changedPointersLen = input.changedPointers.length;
  33052. var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0));
  33053. var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0));
  33054. input.isFirst = !!isFirst;
  33055. input.isFinal = !!isFinal;
  33056. if (isFirst) {
  33057. manager.session = {};
  33058. }
  33059. // source event is the normalized value of the domEvents
  33060. // like 'touchstart, mouseup, pointerdown'
  33061. input.eventType = eventType;
  33062. // compute scale, rotation etc
  33063. computeInputData(manager, input);
  33064. // emit secret event
  33065. manager.emit('hammer.input', input);
  33066. manager.recognize(input);
  33067. manager.session.prevInput = input;
  33068. }
  33069. /**
  33070. * extend the data with some usable properties like scale, rotate, velocity etc
  33071. * @param {Object} manager
  33072. * @param {Object} input
  33073. */
  33074. function computeInputData(manager, input) {
  33075. var session = manager.session;
  33076. var pointers = input.pointers;
  33077. var pointersLength = pointers.length;
  33078. // store the first input to calculate the distance and direction
  33079. if (!session.firstInput) {
  33080. session.firstInput = simpleCloneInputData(input);
  33081. }
  33082. // to compute scale and rotation we need to store the multiple touches
  33083. if (pointersLength > 1 && !session.firstMultiple) {
  33084. session.firstMultiple = simpleCloneInputData(input);
  33085. } else if (pointersLength === 1) {
  33086. session.firstMultiple = false;
  33087. }
  33088. var firstInput = session.firstInput;
  33089. var firstMultiple = session.firstMultiple;
  33090. var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
  33091. var center = input.center = getCenter(pointers);
  33092. input.timeStamp = now();
  33093. input.deltaTime = input.timeStamp - firstInput.timeStamp;
  33094. input.angle = getAngle(offsetCenter, center);
  33095. input.distance = getDistance(offsetCenter, center);
  33096. computeDeltaXY(session, input);
  33097. input.offsetDirection = getDirection(input.deltaX, input.deltaY);
  33098. var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
  33099. input.overallVelocityX = overallVelocity.x;
  33100. input.overallVelocityY = overallVelocity.y;
  33101. input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y;
  33102. input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
  33103. input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
  33104. input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length >
  33105. session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers);
  33106. computeIntervalInputData(session, input);
  33107. // find the correct target
  33108. var target = manager.element;
  33109. if (hasParent(input.srcEvent.target, target)) {
  33110. target = input.srcEvent.target;
  33111. }
  33112. input.target = target;
  33113. }
  33114. function computeDeltaXY(session, input) {
  33115. var center = input.center;
  33116. var offset = session.offsetDelta || {};
  33117. var prevDelta = session.prevDelta || {};
  33118. var prevInput = session.prevInput || {};
  33119. if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
  33120. prevDelta = session.prevDelta = {
  33121. x: prevInput.deltaX || 0,
  33122. y: prevInput.deltaY || 0
  33123. };
  33124. offset = session.offsetDelta = {
  33125. x: center.x,
  33126. y: center.y
  33127. };
  33128. }
  33129. input.deltaX = prevDelta.x + (center.x - offset.x);
  33130. input.deltaY = prevDelta.y + (center.y - offset.y);
  33131. }
  33132. /**
  33133. * velocity is calculated every x ms
  33134. * @param {Object} session
  33135. * @param {Object} input
  33136. */
  33137. function computeIntervalInputData(session, input) {
  33138. var last = session.lastInterval || input,
  33139. deltaTime = input.timeStamp - last.timeStamp,
  33140. velocity, velocityX, velocityY, direction;
  33141. if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
  33142. var deltaX = input.deltaX - last.deltaX;
  33143. var deltaY = input.deltaY - last.deltaY;
  33144. var v = getVelocity(deltaTime, deltaX, deltaY);
  33145. velocityX = v.x;
  33146. velocityY = v.y;
  33147. velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
  33148. direction = getDirection(deltaX, deltaY);
  33149. session.lastInterval = input;
  33150. } else {
  33151. // use latest velocity info if it doesn't overtake a minimum period
  33152. velocity = last.velocity;
  33153. velocityX = last.velocityX;
  33154. velocityY = last.velocityY;
  33155. direction = last.direction;
  33156. }
  33157. input.velocity = velocity;
  33158. input.velocityX = velocityX;
  33159. input.velocityY = velocityY;
  33160. input.direction = direction;
  33161. }
  33162. /**
  33163. * create a simple clone from the input used for storage of firstInput and firstMultiple
  33164. * @param {Object} input
  33165. * @returns {Object} clonedInputData
  33166. */
  33167. function simpleCloneInputData(input) {
  33168. // make a simple copy of the pointers because we will get a reference if we don't
  33169. // we only need clientXY for the calculations
  33170. var pointers = [];
  33171. var i = 0;
  33172. while (i < input.pointers.length) {
  33173. pointers[i] = {
  33174. clientX: round(input.pointers[i].clientX),
  33175. clientY: round(input.pointers[i].clientY)
  33176. };
  33177. i++;
  33178. }
  33179. return {
  33180. timeStamp: now(),
  33181. pointers: pointers,
  33182. center: getCenter(pointers),
  33183. deltaX: input.deltaX,
  33184. deltaY: input.deltaY
  33185. };
  33186. }
  33187. /**
  33188. * get the center of all the pointers
  33189. * @param {Array} pointers
  33190. * @return {Object} center contains `x` and `y` properties
  33191. */
  33192. function getCenter(pointers) {
  33193. var pointersLength = pointers.length;
  33194. // no need to loop when only one touch
  33195. if (pointersLength === 1) {
  33196. return {
  33197. x: round(pointers[0].clientX),
  33198. y: round(pointers[0].clientY)
  33199. };
  33200. }
  33201. var x = 0, y = 0, i = 0;
  33202. while (i < pointersLength) {
  33203. x += pointers[i].clientX;
  33204. y += pointers[i].clientY;
  33205. i++;
  33206. }
  33207. return {
  33208. x: round(x / pointersLength),
  33209. y: round(y / pointersLength)
  33210. };
  33211. }
  33212. /**
  33213. * calculate the velocity between two points. unit is in px per ms.
  33214. * @param {Number} deltaTime
  33215. * @param {Number} x
  33216. * @param {Number} y
  33217. * @return {Object} velocity `x` and `y`
  33218. */
  33219. function getVelocity(deltaTime, x, y) {
  33220. return {
  33221. x: x / deltaTime || 0,
  33222. y: y / deltaTime || 0
  33223. };
  33224. }
  33225. /**
  33226. * get the direction between two points
  33227. * @param {Number} x
  33228. * @param {Number} y
  33229. * @return {Number} direction
  33230. */
  33231. function getDirection(x, y) {
  33232. if (x === y) {
  33233. return DIRECTION_NONE;
  33234. }
  33235. if (abs(x) >= abs(y)) {
  33236. return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  33237. }
  33238. return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
  33239. }
  33240. /**
  33241. * calculate the absolute distance between two points
  33242. * @param {Object} p1 {x, y}
  33243. * @param {Object} p2 {x, y}
  33244. * @param {Array} [props] containing x and y keys
  33245. * @return {Number} distance
  33246. */
  33247. function getDistance(p1, p2, props) {
  33248. if (!props) {
  33249. props = PROPS_XY;
  33250. }
  33251. var x = p2[props[0]] - p1[props[0]],
  33252. y = p2[props[1]] - p1[props[1]];
  33253. return Math.sqrt((x * x) + (y * y));
  33254. }
  33255. /**
  33256. * calculate the angle between two coordinates
  33257. * @param {Object} p1
  33258. * @param {Object} p2
  33259. * @param {Array} [props] containing x and y keys
  33260. * @return {Number} angle
  33261. */
  33262. function getAngle(p1, p2, props) {
  33263. if (!props) {
  33264. props = PROPS_XY;
  33265. }
  33266. var x = p2[props[0]] - p1[props[0]],
  33267. y = p2[props[1]] - p1[props[1]];
  33268. return Math.atan2(y, x) * 180 / Math.PI;
  33269. }
  33270. /**
  33271. * calculate the rotation degrees between two pointersets
  33272. * @param {Array} start array of pointers
  33273. * @param {Array} end array of pointers
  33274. * @return {Number} rotation
  33275. */
  33276. function getRotation(start, end) {
  33277. return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
  33278. }
  33279. /**
  33280. * calculate the scale factor between two pointersets
  33281. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  33282. * @param {Array} start array of pointers
  33283. * @param {Array} end array of pointers
  33284. * @return {Number} scale
  33285. */
  33286. function getScale(start, end) {
  33287. return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
  33288. }
  33289. var MOUSE_INPUT_MAP = {
  33290. mousedown: INPUT_START,
  33291. mousemove: INPUT_MOVE,
  33292. mouseup: INPUT_END
  33293. };
  33294. var MOUSE_ELEMENT_EVENTS = 'mousedown';
  33295. var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
  33296. /**
  33297. * Mouse events input
  33298. * @constructor
  33299. * @extends Input
  33300. */
  33301. function MouseInput() {
  33302. this.evEl = MOUSE_ELEMENT_EVENTS;
  33303. this.evWin = MOUSE_WINDOW_EVENTS;
  33304. this.pressed = false; // mousedown state
  33305. Input.apply(this, arguments);
  33306. }
  33307. inherit(MouseInput, Input, {
  33308. /**
  33309. * handle mouse events
  33310. * @param {Object} ev
  33311. */
  33312. handler: function MEhandler(ev) {
  33313. var eventType = MOUSE_INPUT_MAP[ev.type];
  33314. // on start we want to have the left mouse button down
  33315. if (eventType & INPUT_START && ev.button === 0) {
  33316. this.pressed = true;
  33317. }
  33318. if (eventType & INPUT_MOVE && ev.which !== 1) {
  33319. eventType = INPUT_END;
  33320. }
  33321. // mouse must be down
  33322. if (!this.pressed) {
  33323. return;
  33324. }
  33325. if (eventType & INPUT_END) {
  33326. this.pressed = false;
  33327. }
  33328. this.callback(this.manager, eventType, {
  33329. pointers: [ev],
  33330. changedPointers: [ev],
  33331. pointerType: INPUT_TYPE_MOUSE,
  33332. srcEvent: ev
  33333. });
  33334. }
  33335. });
  33336. var POINTER_INPUT_MAP = {
  33337. pointerdown: INPUT_START,
  33338. pointermove: INPUT_MOVE,
  33339. pointerup: INPUT_END,
  33340. pointercancel: INPUT_CANCEL,
  33341. pointerout: INPUT_CANCEL
  33342. };
  33343. // in IE10 the pointer types is defined as an enum
  33344. var IE10_POINTER_TYPE_ENUM = {
  33345. 2: INPUT_TYPE_TOUCH,
  33346. 3: INPUT_TYPE_PEN,
  33347. 4: INPUT_TYPE_MOUSE,
  33348. 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
  33349. };
  33350. var POINTER_ELEMENT_EVENTS = 'pointerdown';
  33351. var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';
  33352. // IE10 has prefixed support, and case-sensitive
  33353. if (window.MSPointerEvent && !window.PointerEvent) {
  33354. POINTER_ELEMENT_EVENTS = 'MSPointerDown';
  33355. POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
  33356. }
  33357. /**
  33358. * Pointer events input
  33359. * @constructor
  33360. * @extends Input
  33361. */
  33362. function PointerEventInput() {
  33363. this.evEl = POINTER_ELEMENT_EVENTS;
  33364. this.evWin = POINTER_WINDOW_EVENTS;
  33365. Input.apply(this, arguments);
  33366. this.store = (this.manager.session.pointerEvents = []);
  33367. }
  33368. inherit(PointerEventInput, Input, {
  33369. /**
  33370. * handle mouse events
  33371. * @param {Object} ev
  33372. */
  33373. handler: function PEhandler(ev) {
  33374. var store = this.store;
  33375. var removePointer = false;
  33376. var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
  33377. var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
  33378. var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
  33379. var isTouch = (pointerType == INPUT_TYPE_TOUCH);
  33380. // get index of the event in the store
  33381. var storeIndex = inArray(store, ev.pointerId, 'pointerId');
  33382. // start and mouse must be down
  33383. if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
  33384. if (storeIndex < 0) {
  33385. store.push(ev);
  33386. storeIndex = store.length - 1;
  33387. }
  33388. } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
  33389. removePointer = true;
  33390. }
  33391. // it not found, so the pointer hasn't been down (so it's probably a hover)
  33392. if (storeIndex < 0) {
  33393. return;
  33394. }
  33395. // update the event in the store
  33396. store[storeIndex] = ev;
  33397. this.callback(this.manager, eventType, {
  33398. pointers: store,
  33399. changedPointers: [ev],
  33400. pointerType: pointerType,
  33401. srcEvent: ev
  33402. });
  33403. if (removePointer) {
  33404. // remove from the store
  33405. store.splice(storeIndex, 1);
  33406. }
  33407. }
  33408. });
  33409. var SINGLE_TOUCH_INPUT_MAP = {
  33410. touchstart: INPUT_START,
  33411. touchmove: INPUT_MOVE,
  33412. touchend: INPUT_END,
  33413. touchcancel: INPUT_CANCEL
  33414. };
  33415. var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
  33416. var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';
  33417. /**
  33418. * Touch events input
  33419. * @constructor
  33420. * @extends Input
  33421. */
  33422. function SingleTouchInput() {
  33423. this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
  33424. this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
  33425. this.started = false;
  33426. Input.apply(this, arguments);
  33427. }
  33428. inherit(SingleTouchInput, Input, {
  33429. handler: function TEhandler(ev) {
  33430. var type = SINGLE_TOUCH_INPUT_MAP[ev.type];
  33431. // should we handle the touch events?
  33432. if (type === INPUT_START) {
  33433. this.started = true;
  33434. }
  33435. if (!this.started) {
  33436. return;
  33437. }
  33438. var touches = normalizeSingleTouches.call(this, ev, type);
  33439. // when done, reset the started state
  33440. if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
  33441. this.started = false;
  33442. }
  33443. this.callback(this.manager, type, {
  33444. pointers: touches[0],
  33445. changedPointers: touches[1],
  33446. pointerType: INPUT_TYPE_TOUCH,
  33447. srcEvent: ev
  33448. });
  33449. }
  33450. });
  33451. /**
  33452. * @this {TouchInput}
  33453. * @param {Object} ev
  33454. * @param {Number} type flag
  33455. * @returns {undefined|Array} [all, changed]
  33456. */
  33457. function normalizeSingleTouches(ev, type) {
  33458. var all = toArray(ev.touches);
  33459. var changed = toArray(ev.changedTouches);
  33460. if (type & (INPUT_END | INPUT_CANCEL)) {
  33461. all = uniqueArray(all.concat(changed), 'identifier', true);
  33462. }
  33463. return [all, changed];
  33464. }
  33465. var TOUCH_INPUT_MAP = {
  33466. touchstart: INPUT_START,
  33467. touchmove: INPUT_MOVE,
  33468. touchend: INPUT_END,
  33469. touchcancel: INPUT_CANCEL
  33470. };
  33471. var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
  33472. /**
  33473. * Multi-user touch events input
  33474. * @constructor
  33475. * @extends Input
  33476. */
  33477. function TouchInput() {
  33478. this.evTarget = TOUCH_TARGET_EVENTS;
  33479. this.targetIds = {};
  33480. Input.apply(this, arguments);
  33481. }
  33482. inherit(TouchInput, Input, {
  33483. handler: function MTEhandler(ev) {
  33484. var type = TOUCH_INPUT_MAP[ev.type];
  33485. var touches = getTouches.call(this, ev, type);
  33486. if (!touches) {
  33487. return;
  33488. }
  33489. this.callback(this.manager, type, {
  33490. pointers: touches[0],
  33491. changedPointers: touches[1],
  33492. pointerType: INPUT_TYPE_TOUCH,
  33493. srcEvent: ev
  33494. });
  33495. }
  33496. });
  33497. /**
  33498. * @this {TouchInput}
  33499. * @param {Object} ev
  33500. * @param {Number} type flag
  33501. * @returns {undefined|Array} [all, changed]
  33502. */
  33503. function getTouches(ev, type) {
  33504. var allTouches = toArray(ev.touches);
  33505. var targetIds = this.targetIds;
  33506. // when there is only one touch, the process can be simplified
  33507. if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
  33508. targetIds[allTouches[0].identifier] = true;
  33509. return [allTouches, allTouches];
  33510. }
  33511. var i,
  33512. targetTouches,
  33513. changedTouches = toArray(ev.changedTouches),
  33514. changedTargetTouches = [],
  33515. target = this.target;
  33516. // get target touches from touches
  33517. targetTouches = allTouches.filter(function(touch) {
  33518. return hasParent(touch.target, target);
  33519. });
  33520. // collect touches
  33521. if (type === INPUT_START) {
  33522. i = 0;
  33523. while (i < targetTouches.length) {
  33524. targetIds[targetTouches[i].identifier] = true;
  33525. i++;
  33526. }
  33527. }
  33528. // filter changed touches to only contain touches that exist in the collected target ids
  33529. i = 0;
  33530. while (i < changedTouches.length) {
  33531. if (targetIds[changedTouches[i].identifier]) {
  33532. changedTargetTouches.push(changedTouches[i]);
  33533. }
  33534. // cleanup removed touches
  33535. if (type & (INPUT_END | INPUT_CANCEL)) {
  33536. delete targetIds[changedTouches[i].identifier];
  33537. }
  33538. i++;
  33539. }
  33540. if (!changedTargetTouches.length) {
  33541. return;
  33542. }
  33543. return [
  33544. // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
  33545. uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),
  33546. changedTargetTouches
  33547. ];
  33548. }
  33549. /**
  33550. * Combined touch and mouse input
  33551. *
  33552. * Touch has a higher priority then mouse, and while touching no mouse events are allowed.
  33553. * This because touch devices also emit mouse events while doing a touch.
  33554. *
  33555. * @constructor
  33556. * @extends Input
  33557. */
  33558. var DEDUP_TIMEOUT = 2500;
  33559. var DEDUP_DISTANCE = 25;
  33560. function TouchMouseInput() {
  33561. Input.apply(this, arguments);
  33562. var handler = bindFn(this.handler, this);
  33563. this.touch = new TouchInput(this.manager, handler);
  33564. this.mouse = new MouseInput(this.manager, handler);
  33565. this.primaryTouch = null;
  33566. this.lastTouches = [];
  33567. }
  33568. inherit(TouchMouseInput, Input, {
  33569. /**
  33570. * handle mouse and touch events
  33571. * @param {Hammer} manager
  33572. * @param {String} inputEvent
  33573. * @param {Object} inputData
  33574. */
  33575. handler: function TMEhandler(manager, inputEvent, inputData) {
  33576. var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH),
  33577. isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);
  33578. if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
  33579. return;
  33580. }
  33581. // when we're in a touch event, record touches to de-dupe synthetic mouse event
  33582. if (isTouch) {
  33583. recordTouches.call(this, inputEvent, inputData);
  33584. } else if (isMouse && isSyntheticEvent.call(this, inputData)) {
  33585. return;
  33586. }
  33587. this.callback(manager, inputEvent, inputData);
  33588. },
  33589. /**
  33590. * remove the event listeners
  33591. */
  33592. destroy: function destroy() {
  33593. this.touch.destroy();
  33594. this.mouse.destroy();
  33595. }
  33596. });
  33597. function recordTouches(eventType, eventData) {
  33598. if (eventType & INPUT_START) {
  33599. this.primaryTouch = eventData.changedPointers[0].identifier;
  33600. setLastTouch.call(this, eventData);
  33601. } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
  33602. setLastTouch.call(this, eventData);
  33603. }
  33604. }
  33605. function setLastTouch(eventData) {
  33606. var touch = eventData.changedPointers[0];
  33607. if (touch.identifier === this.primaryTouch) {
  33608. var lastTouch = {x: touch.clientX, y: touch.clientY};
  33609. this.lastTouches.push(lastTouch);
  33610. var lts = this.lastTouches;
  33611. var removeLastTouch = function() {
  33612. var i = lts.indexOf(lastTouch);
  33613. if (i > -1) {
  33614. lts.splice(i, 1);
  33615. }
  33616. };
  33617. setTimeout(removeLastTouch, DEDUP_TIMEOUT);
  33618. }
  33619. }
  33620. function isSyntheticEvent(eventData) {
  33621. var x = eventData.srcEvent.clientX, y = eventData.srcEvent.clientY;
  33622. for (var i = 0; i < this.lastTouches.length; i++) {
  33623. var t = this.lastTouches[i];
  33624. var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y);
  33625. if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
  33626. return true;
  33627. }
  33628. }
  33629. return false;
  33630. }
  33631. var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
  33632. var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
  33633. // magical touchAction value
  33634. var TOUCH_ACTION_COMPUTE = 'compute';
  33635. var TOUCH_ACTION_AUTO = 'auto';
  33636. var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
  33637. var TOUCH_ACTION_NONE = 'none';
  33638. var TOUCH_ACTION_PAN_X = 'pan-x';
  33639. var TOUCH_ACTION_PAN_Y = 'pan-y';
  33640. var TOUCH_ACTION_MAP = getTouchActionProps();
  33641. /**
  33642. * Touch Action
  33643. * sets the touchAction property or uses the js alternative
  33644. * @param {Manager} manager
  33645. * @param {String} value
  33646. * @constructor
  33647. */
  33648. function TouchAction(manager, value) {
  33649. this.manager = manager;
  33650. this.set(value);
  33651. }
  33652. TouchAction.prototype = {
  33653. /**
  33654. * set the touchAction value on the element or enable the polyfill
  33655. * @param {String} value
  33656. */
  33657. set: function(value) {
  33658. // find out the touch-action by the event handlers
  33659. if (value == TOUCH_ACTION_COMPUTE) {
  33660. value = this.compute();
  33661. }
  33662. if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {
  33663. this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
  33664. }
  33665. this.actions = value.toLowerCase().trim();
  33666. },
  33667. /**
  33668. * just re-set the touchAction value
  33669. */
  33670. update: function() {
  33671. this.set(this.manager.options.touchAction);
  33672. },
  33673. /**
  33674. * compute the value for the touchAction property based on the recognizer's settings
  33675. * @returns {String} value
  33676. */
  33677. compute: function() {
  33678. var actions = [];
  33679. each(this.manager.recognizers, function(recognizer) {
  33680. if (boolOrFn(recognizer.options.enable, [recognizer])) {
  33681. actions = actions.concat(recognizer.getTouchAction());
  33682. }
  33683. });
  33684. return cleanTouchActions(actions.join(' '));
  33685. },
  33686. /**
  33687. * this method is called on each input cycle and provides the preventing of the browser behavior
  33688. * @param {Object} input
  33689. */
  33690. preventDefaults: function(input) {
  33691. var srcEvent = input.srcEvent;
  33692. var direction = input.offsetDirection;
  33693. // if the touch action did prevented once this session
  33694. if (this.manager.session.prevented) {
  33695. srcEvent.preventDefault();
  33696. return;
  33697. }
  33698. var actions = this.actions;
  33699. var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
  33700. var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
  33701. var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];
  33702. if (hasNone) {
  33703. //do not prevent defaults if this is a tap gesture
  33704. var isTapPointer = input.pointers.length === 1;
  33705. var isTapMovement = input.distance < 2;
  33706. var isTapTouchTime = input.deltaTime < 250;
  33707. if (isTapPointer && isTapMovement && isTapTouchTime) {
  33708. return;
  33709. }
  33710. }
  33711. if (hasPanX && hasPanY) {
  33712. // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
  33713. return;
  33714. }
  33715. if (hasNone ||
  33716. (hasPanY && direction & DIRECTION_HORIZONTAL) ||
  33717. (hasPanX && direction & DIRECTION_VERTICAL)) {
  33718. return this.preventSrc(srcEvent);
  33719. }
  33720. },
  33721. /**
  33722. * call preventDefault to prevent the browser's default behavior (scrolling in most cases)
  33723. * @param {Object} srcEvent
  33724. */
  33725. preventSrc: function(srcEvent) {
  33726. this.manager.session.prevented = true;
  33727. srcEvent.preventDefault();
  33728. }
  33729. };
  33730. /**
  33731. * when the touchActions are collected they are not a valid value, so we need to clean things up. *
  33732. * @param {String} actions
  33733. * @returns {*}
  33734. */
  33735. function cleanTouchActions(actions) {
  33736. // none
  33737. if (inStr(actions, TOUCH_ACTION_NONE)) {
  33738. return TOUCH_ACTION_NONE;
  33739. }
  33740. var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
  33741. var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
  33742. // if both pan-x and pan-y are set (different recognizers
  33743. // for different directions, e.g. horizontal pan but vertical swipe?)
  33744. // we need none (as otherwise with pan-x pan-y combined none of these
  33745. // recognizers will work, since the browser would handle all panning
  33746. if (hasPanX && hasPanY) {
  33747. return TOUCH_ACTION_NONE;
  33748. }
  33749. // pan-x OR pan-y
  33750. if (hasPanX || hasPanY) {
  33751. return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
  33752. }
  33753. // manipulation
  33754. if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
  33755. return TOUCH_ACTION_MANIPULATION;
  33756. }
  33757. return TOUCH_ACTION_AUTO;
  33758. }
  33759. function getTouchActionProps() {
  33760. if (!NATIVE_TOUCH_ACTION) {
  33761. return false;
  33762. }
  33763. var touchMap = {};
  33764. var cssSupports = window.CSS && window.CSS.supports;
  33765. ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function(val) {
  33766. // If css.supports is not supported but there is native touch-action assume it supports
  33767. // all values. This is the case for IE 10 and 11.
  33768. touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true;
  33769. });
  33770. return touchMap;
  33771. }
  33772. /**
  33773. * Recognizer flow explained; *
  33774. * All recognizers have the initial state of POSSIBLE when a input session starts.
  33775. * The definition of a input session is from the first input until the last input, with all it's movement in it. *
  33776. * Example session for mouse-input: mousedown -> mousemove -> mouseup
  33777. *
  33778. * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
  33779. * which determines with state it should be.
  33780. *
  33781. * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
  33782. * POSSIBLE to give it another change on the next cycle.
  33783. *
  33784. * Possible
  33785. * |
  33786. * +-----+---------------+
  33787. * | |
  33788. * +-----+-----+ |
  33789. * | | |
  33790. * Failed Cancelled |
  33791. * +-------+------+
  33792. * | |
  33793. * Recognized Began
  33794. * |
  33795. * Changed
  33796. * |
  33797. * Ended/Recognized
  33798. */
  33799. var STATE_POSSIBLE = 1;
  33800. var STATE_BEGAN = 2;
  33801. var STATE_CHANGED = 4;
  33802. var STATE_ENDED = 8;
  33803. var STATE_RECOGNIZED = STATE_ENDED;
  33804. var STATE_CANCELLED = 16;
  33805. var STATE_FAILED = 32;
  33806. /**
  33807. * Recognizer
  33808. * Every recognizer needs to extend from this class.
  33809. * @constructor
  33810. * @param {Object} options
  33811. */
  33812. function Recognizer(options) {
  33813. this.options = assign({}, this.defaults, options || {});
  33814. this.id = uniqueId();
  33815. this.manager = null;
  33816. // default is enable true
  33817. this.options.enable = ifUndefined(this.options.enable, true);
  33818. this.state = STATE_POSSIBLE;
  33819. this.simultaneous = {};
  33820. this.requireFail = [];
  33821. }
  33822. Recognizer.prototype = {
  33823. /**
  33824. * @virtual
  33825. * @type {Object}
  33826. */
  33827. defaults: {},
  33828. /**
  33829. * set options
  33830. * @param {Object} options
  33831. * @return {Recognizer}
  33832. */
  33833. set: function(options) {
  33834. assign(this.options, options);
  33835. // also update the touchAction, in case something changed about the directions/enabled state
  33836. this.manager && this.manager.touchAction.update();
  33837. return this;
  33838. },
  33839. /**
  33840. * recognize simultaneous with an other recognizer.
  33841. * @param {Recognizer} otherRecognizer
  33842. * @returns {Recognizer} this
  33843. */
  33844. recognizeWith: function(otherRecognizer) {
  33845. if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
  33846. return this;
  33847. }
  33848. var simultaneous = this.simultaneous;
  33849. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  33850. if (!simultaneous[otherRecognizer.id]) {
  33851. simultaneous[otherRecognizer.id] = otherRecognizer;
  33852. otherRecognizer.recognizeWith(this);
  33853. }
  33854. return this;
  33855. },
  33856. /**
  33857. * drop the simultaneous link. it doesnt remove the link on the other recognizer.
  33858. * @param {Recognizer} otherRecognizer
  33859. * @returns {Recognizer} this
  33860. */
  33861. dropRecognizeWith: function(otherRecognizer) {
  33862. if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
  33863. return this;
  33864. }
  33865. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  33866. delete this.simultaneous[otherRecognizer.id];
  33867. return this;
  33868. },
  33869. /**
  33870. * recognizer can only run when an other is failing
  33871. * @param {Recognizer} otherRecognizer
  33872. * @returns {Recognizer} this
  33873. */
  33874. requireFailure: function(otherRecognizer) {
  33875. if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
  33876. return this;
  33877. }
  33878. var requireFail = this.requireFail;
  33879. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  33880. if (inArray(requireFail, otherRecognizer) === -1) {
  33881. requireFail.push(otherRecognizer);
  33882. otherRecognizer.requireFailure(this);
  33883. }
  33884. return this;
  33885. },
  33886. /**
  33887. * drop the requireFailure link. it does not remove the link on the other recognizer.
  33888. * @param {Recognizer} otherRecognizer
  33889. * @returns {Recognizer} this
  33890. */
  33891. dropRequireFailure: function(otherRecognizer) {
  33892. if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
  33893. return this;
  33894. }
  33895. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  33896. var index = inArray(this.requireFail, otherRecognizer);
  33897. if (index > -1) {
  33898. this.requireFail.splice(index, 1);
  33899. }
  33900. return this;
  33901. },
  33902. /**
  33903. * has require failures boolean
  33904. * @returns {boolean}
  33905. */
  33906. hasRequireFailures: function() {
  33907. return this.requireFail.length > 0;
  33908. },
  33909. /**
  33910. * if the recognizer can recognize simultaneous with an other recognizer
  33911. * @param {Recognizer} otherRecognizer
  33912. * @returns {Boolean}
  33913. */
  33914. canRecognizeWith: function(otherRecognizer) {
  33915. return !!this.simultaneous[otherRecognizer.id];
  33916. },
  33917. /**
  33918. * You should use `tryEmit` instead of `emit` directly to check
  33919. * that all the needed recognizers has failed before emitting.
  33920. * @param {Object} input
  33921. */
  33922. emit: function(input) {
  33923. var self = this;
  33924. var state = this.state;
  33925. function emit(event) {
  33926. self.manager.emit(event, input);
  33927. }
  33928. // 'panstart' and 'panmove'
  33929. if (state < STATE_ENDED) {
  33930. emit(self.options.event + stateStr(state));
  33931. }
  33932. emit(self.options.event); // simple 'eventName' events
  33933. if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...)
  33934. emit(input.additionalEvent);
  33935. }
  33936. // panend and pancancel
  33937. if (state >= STATE_ENDED) {
  33938. emit(self.options.event + stateStr(state));
  33939. }
  33940. },
  33941. /**
  33942. * Check that all the require failure recognizers has failed,
  33943. * if true, it emits a gesture event,
  33944. * otherwise, setup the state to FAILED.
  33945. * @param {Object} input
  33946. */
  33947. tryEmit: function(input) {
  33948. if (this.canEmit()) {
  33949. return this.emit(input);
  33950. }
  33951. // it's failing anyway
  33952. this.state = STATE_FAILED;
  33953. },
  33954. /**
  33955. * can we emit?
  33956. * @returns {boolean}
  33957. */
  33958. canEmit: function() {
  33959. var i = 0;
  33960. while (i < this.requireFail.length) {
  33961. if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
  33962. return false;
  33963. }
  33964. i++;
  33965. }
  33966. return true;
  33967. },
  33968. /**
  33969. * update the recognizer
  33970. * @param {Object} inputData
  33971. */
  33972. recognize: function(inputData) {
  33973. // make a new copy of the inputData
  33974. // so we can change the inputData without messing up the other recognizers
  33975. var inputDataClone = assign({}, inputData);
  33976. // is is enabled and allow recognizing?
  33977. if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
  33978. this.reset();
  33979. this.state = STATE_FAILED;
  33980. return;
  33981. }
  33982. // reset when we've reached the end
  33983. if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
  33984. this.state = STATE_POSSIBLE;
  33985. }
  33986. this.state = this.process(inputDataClone);
  33987. // the recognizer has recognized a gesture
  33988. // so trigger an event
  33989. if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
  33990. this.tryEmit(inputDataClone);
  33991. }
  33992. },
  33993. /**
  33994. * return the state of the recognizer
  33995. * the actual recognizing happens in this method
  33996. * @virtual
  33997. * @param {Object} inputData
  33998. * @returns {Const} STATE
  33999. */
  34000. process: function(inputData) { }, // jshint ignore:line
  34001. /**
  34002. * return the preferred touch-action
  34003. * @virtual
  34004. * @returns {Array}
  34005. */
  34006. getTouchAction: function() { },
  34007. /**
  34008. * called when the gesture isn't allowed to recognize
  34009. * like when another is being recognized or it is disabled
  34010. * @virtual
  34011. */
  34012. reset: function() { }
  34013. };
  34014. /**
  34015. * get a usable string, used as event postfix
  34016. * @param {Const} state
  34017. * @returns {String} state
  34018. */
  34019. function stateStr(state) {
  34020. if (state & STATE_CANCELLED) {
  34021. return 'cancel';
  34022. } else if (state & STATE_ENDED) {
  34023. return 'end';
  34024. } else if (state & STATE_CHANGED) {
  34025. return 'move';
  34026. } else if (state & STATE_BEGAN) {
  34027. return 'start';
  34028. }
  34029. return '';
  34030. }
  34031. /**
  34032. * direction cons to string
  34033. * @param {Const} direction
  34034. * @returns {String}
  34035. */
  34036. function directionStr(direction) {
  34037. if (direction == DIRECTION_DOWN) {
  34038. return 'down';
  34039. } else if (direction == DIRECTION_UP) {
  34040. return 'up';
  34041. } else if (direction == DIRECTION_LEFT) {
  34042. return 'left';
  34043. } else if (direction == DIRECTION_RIGHT) {
  34044. return 'right';
  34045. }
  34046. return '';
  34047. }
  34048. /**
  34049. * get a recognizer by name if it is bound to a manager
  34050. * @param {Recognizer|String} otherRecognizer
  34051. * @param {Recognizer} recognizer
  34052. * @returns {Recognizer}
  34053. */
  34054. function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
  34055. var manager = recognizer.manager;
  34056. if (manager) {
  34057. return manager.get(otherRecognizer);
  34058. }
  34059. return otherRecognizer;
  34060. }
  34061. /**
  34062. * This recognizer is just used as a base for the simple attribute recognizers.
  34063. * @constructor
  34064. * @extends Recognizer
  34065. */
  34066. function AttrRecognizer() {
  34067. Recognizer.apply(this, arguments);
  34068. }
  34069. inherit(AttrRecognizer, Recognizer, {
  34070. /**
  34071. * @namespace
  34072. * @memberof AttrRecognizer
  34073. */
  34074. defaults: {
  34075. /**
  34076. * @type {Number}
  34077. * @default 1
  34078. */
  34079. pointers: 1
  34080. },
  34081. /**
  34082. * Used to check if it the recognizer receives valid input, like input.distance > 10.
  34083. * @memberof AttrRecognizer
  34084. * @param {Object} input
  34085. * @returns {Boolean} recognized
  34086. */
  34087. attrTest: function(input) {
  34088. var optionPointers = this.options.pointers;
  34089. return optionPointers === 0 || input.pointers.length === optionPointers;
  34090. },
  34091. /**
  34092. * Process the input and return the state for the recognizer
  34093. * @memberof AttrRecognizer
  34094. * @param {Object} input
  34095. * @returns {*} State
  34096. */
  34097. process: function(input) {
  34098. var state = this.state;
  34099. var eventType = input.eventType;
  34100. var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
  34101. var isValid = this.attrTest(input);
  34102. // on cancel input and we've recognized before, return STATE_CANCELLED
  34103. if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
  34104. return state | STATE_CANCELLED;
  34105. } else if (isRecognized || isValid) {
  34106. if (eventType & INPUT_END) {
  34107. return state | STATE_ENDED;
  34108. } else if (!(state & STATE_BEGAN)) {
  34109. return STATE_BEGAN;
  34110. }
  34111. return state | STATE_CHANGED;
  34112. }
  34113. return STATE_FAILED;
  34114. }
  34115. });
  34116. /**
  34117. * Pan
  34118. * Recognized when the pointer is down and moved in the allowed direction.
  34119. * @constructor
  34120. * @extends AttrRecognizer
  34121. */
  34122. function PanRecognizer() {
  34123. AttrRecognizer.apply(this, arguments);
  34124. this.pX = null;
  34125. this.pY = null;
  34126. }
  34127. inherit(PanRecognizer, AttrRecognizer, {
  34128. /**
  34129. * @namespace
  34130. * @memberof PanRecognizer
  34131. */
  34132. defaults: {
  34133. event: 'pan',
  34134. threshold: 10,
  34135. pointers: 1,
  34136. direction: DIRECTION_ALL
  34137. },
  34138. getTouchAction: function() {
  34139. var direction = this.options.direction;
  34140. var actions = [];
  34141. if (direction & DIRECTION_HORIZONTAL) {
  34142. actions.push(TOUCH_ACTION_PAN_Y);
  34143. }
  34144. if (direction & DIRECTION_VERTICAL) {
  34145. actions.push(TOUCH_ACTION_PAN_X);
  34146. }
  34147. return actions;
  34148. },
  34149. directionTest: function(input) {
  34150. var options = this.options;
  34151. var hasMoved = true;
  34152. var distance = input.distance;
  34153. var direction = input.direction;
  34154. var x = input.deltaX;
  34155. var y = input.deltaY;
  34156. // lock to axis?
  34157. if (!(direction & options.direction)) {
  34158. if (options.direction & DIRECTION_HORIZONTAL) {
  34159. direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
  34160. hasMoved = x != this.pX;
  34161. distance = Math.abs(input.deltaX);
  34162. } else {
  34163. direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;
  34164. hasMoved = y != this.pY;
  34165. distance = Math.abs(input.deltaY);
  34166. }
  34167. }
  34168. input.direction = direction;
  34169. return hasMoved && distance > options.threshold && direction & options.direction;
  34170. },
  34171. attrTest: function(input) {
  34172. return AttrRecognizer.prototype.attrTest.call(this, input) &&
  34173. (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));
  34174. },
  34175. emit: function(input) {
  34176. this.pX = input.deltaX;
  34177. this.pY = input.deltaY;
  34178. var direction = directionStr(input.direction);
  34179. if (direction) {
  34180. input.additionalEvent = this.options.event + direction;
  34181. }
  34182. this._super.emit.call(this, input);
  34183. }
  34184. });
  34185. /**
  34186. * Pinch
  34187. * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
  34188. * @constructor
  34189. * @extends AttrRecognizer
  34190. */
  34191. function PinchRecognizer() {
  34192. AttrRecognizer.apply(this, arguments);
  34193. }
  34194. inherit(PinchRecognizer, AttrRecognizer, {
  34195. /**
  34196. * @namespace
  34197. * @memberof PinchRecognizer
  34198. */
  34199. defaults: {
  34200. event: 'pinch',
  34201. threshold: 0,
  34202. pointers: 2
  34203. },
  34204. getTouchAction: function() {
  34205. return [TOUCH_ACTION_NONE];
  34206. },
  34207. attrTest: function(input) {
  34208. return this._super.attrTest.call(this, input) &&
  34209. (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
  34210. },
  34211. emit: function(input) {
  34212. if (input.scale !== 1) {
  34213. var inOut = input.scale < 1 ? 'in' : 'out';
  34214. input.additionalEvent = this.options.event + inOut;
  34215. }
  34216. this._super.emit.call(this, input);
  34217. }
  34218. });
  34219. /**
  34220. * Press
  34221. * Recognized when the pointer is down for x ms without any movement.
  34222. * @constructor
  34223. * @extends Recognizer
  34224. */
  34225. function PressRecognizer() {
  34226. Recognizer.apply(this, arguments);
  34227. this._timer = null;
  34228. this._input = null;
  34229. }
  34230. inherit(PressRecognizer, Recognizer, {
  34231. /**
  34232. * @namespace
  34233. * @memberof PressRecognizer
  34234. */
  34235. defaults: {
  34236. event: 'press',
  34237. pointers: 1,
  34238. time: 251, // minimal time of the pointer to be pressed
  34239. threshold: 9 // a minimal movement is ok, but keep it low
  34240. },
  34241. getTouchAction: function() {
  34242. return [TOUCH_ACTION_AUTO];
  34243. },
  34244. process: function(input) {
  34245. var options = this.options;
  34246. var validPointers = input.pointers.length === options.pointers;
  34247. var validMovement = input.distance < options.threshold;
  34248. var validTime = input.deltaTime > options.time;
  34249. this._input = input;
  34250. // we only allow little movement
  34251. // and we've reached an end event, so a tap is possible
  34252. if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {
  34253. this.reset();
  34254. } else if (input.eventType & INPUT_START) {
  34255. this.reset();
  34256. this._timer = setTimeoutContext(function() {
  34257. this.state = STATE_RECOGNIZED;
  34258. this.tryEmit();
  34259. }, options.time, this);
  34260. } else if (input.eventType & INPUT_END) {
  34261. return STATE_RECOGNIZED;
  34262. }
  34263. return STATE_FAILED;
  34264. },
  34265. reset: function() {
  34266. clearTimeout(this._timer);
  34267. },
  34268. emit: function(input) {
  34269. if (this.state !== STATE_RECOGNIZED) {
  34270. return;
  34271. }
  34272. if (input && (input.eventType & INPUT_END)) {
  34273. this.manager.emit(this.options.event + 'up', input);
  34274. } else {
  34275. this._input.timeStamp = now();
  34276. this.manager.emit(this.options.event, this._input);
  34277. }
  34278. }
  34279. });
  34280. /**
  34281. * Rotate
  34282. * Recognized when two or more pointer are moving in a circular motion.
  34283. * @constructor
  34284. * @extends AttrRecognizer
  34285. */
  34286. function RotateRecognizer() {
  34287. AttrRecognizer.apply(this, arguments);
  34288. }
  34289. inherit(RotateRecognizer, AttrRecognizer, {
  34290. /**
  34291. * @namespace
  34292. * @memberof RotateRecognizer
  34293. */
  34294. defaults: {
  34295. event: 'rotate',
  34296. threshold: 0,
  34297. pointers: 2
  34298. },
  34299. getTouchAction: function() {
  34300. return [TOUCH_ACTION_NONE];
  34301. },
  34302. attrTest: function(input) {
  34303. return this._super.attrTest.call(this, input) &&
  34304. (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
  34305. }
  34306. });
  34307. /**
  34308. * Swipe
  34309. * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
  34310. * @constructor
  34311. * @extends AttrRecognizer
  34312. */
  34313. function SwipeRecognizer() {
  34314. AttrRecognizer.apply(this, arguments);
  34315. }
  34316. inherit(SwipeRecognizer, AttrRecognizer, {
  34317. /**
  34318. * @namespace
  34319. * @memberof SwipeRecognizer
  34320. */
  34321. defaults: {
  34322. event: 'swipe',
  34323. threshold: 10,
  34324. velocity: 0.3,
  34325. direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
  34326. pointers: 1
  34327. },
  34328. getTouchAction: function() {
  34329. return PanRecognizer.prototype.getTouchAction.call(this);
  34330. },
  34331. attrTest: function(input) {
  34332. var direction = this.options.direction;
  34333. var velocity;
  34334. if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
  34335. velocity = input.overallVelocity;
  34336. } else if (direction & DIRECTION_HORIZONTAL) {
  34337. velocity = input.overallVelocityX;
  34338. } else if (direction & DIRECTION_VERTICAL) {
  34339. velocity = input.overallVelocityY;
  34340. }
  34341. return this._super.attrTest.call(this, input) &&
  34342. direction & input.offsetDirection &&
  34343. input.distance > this.options.threshold &&
  34344. input.maxPointers == this.options.pointers &&
  34345. abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
  34346. },
  34347. emit: function(input) {
  34348. var direction = directionStr(input.offsetDirection);
  34349. if (direction) {
  34350. this.manager.emit(this.options.event + direction, input);
  34351. }
  34352. this.manager.emit(this.options.event, input);
  34353. }
  34354. });
  34355. /**
  34356. * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
  34357. * between the given interval and position. The delay option can be used to recognize multi-taps without firing
  34358. * a single tap.
  34359. *
  34360. * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
  34361. * multi-taps being recognized.
  34362. * @constructor
  34363. * @extends Recognizer
  34364. */
  34365. function TapRecognizer() {
  34366. Recognizer.apply(this, arguments);
  34367. // previous time and center,
  34368. // used for tap counting
  34369. this.pTime = false;
  34370. this.pCenter = false;
  34371. this._timer = null;
  34372. this._input = null;
  34373. this.count = 0;
  34374. }
  34375. inherit(TapRecognizer, Recognizer, {
  34376. /**
  34377. * @namespace
  34378. * @memberof PinchRecognizer
  34379. */
  34380. defaults: {
  34381. event: 'tap',
  34382. pointers: 1,
  34383. taps: 1,
  34384. interval: 300, // max time between the multi-tap taps
  34385. time: 250, // max time of the pointer to be down (like finger on the screen)
  34386. threshold: 9, // a minimal movement is ok, but keep it low
  34387. posThreshold: 10 // a multi-tap can be a bit off the initial position
  34388. },
  34389. getTouchAction: function() {
  34390. return [TOUCH_ACTION_MANIPULATION];
  34391. },
  34392. process: function(input) {
  34393. var options = this.options;
  34394. var validPointers = input.pointers.length === options.pointers;
  34395. var validMovement = input.distance < options.threshold;
  34396. var validTouchTime = input.deltaTime < options.time;
  34397. this.reset();
  34398. if ((input.eventType & INPUT_START) && (this.count === 0)) {
  34399. return this.failTimeout();
  34400. }
  34401. // we only allow little movement
  34402. // and we've reached an end event, so a tap is possible
  34403. if (validMovement && validTouchTime && validPointers) {
  34404. if (input.eventType != INPUT_END) {
  34405. return this.failTimeout();
  34406. }
  34407. var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;
  34408. var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
  34409. this.pTime = input.timeStamp;
  34410. this.pCenter = input.center;
  34411. if (!validMultiTap || !validInterval) {
  34412. this.count = 1;
  34413. } else {
  34414. this.count += 1;
  34415. }
  34416. this._input = input;
  34417. // if tap count matches we have recognized it,
  34418. // else it has began recognizing...
  34419. var tapCount = this.count % options.taps;
  34420. if (tapCount === 0) {
  34421. // no failing requirements, immediately trigger the tap event
  34422. // or wait as long as the multitap interval to trigger
  34423. if (!this.hasRequireFailures()) {
  34424. return STATE_RECOGNIZED;
  34425. } else {
  34426. this._timer = setTimeoutContext(function() {
  34427. this.state = STATE_RECOGNIZED;
  34428. this.tryEmit();
  34429. }, options.interval, this);
  34430. return STATE_BEGAN;
  34431. }
  34432. }
  34433. }
  34434. return STATE_FAILED;
  34435. },
  34436. failTimeout: function() {
  34437. this._timer = setTimeoutContext(function() {
  34438. this.state = STATE_FAILED;
  34439. }, this.options.interval, this);
  34440. return STATE_FAILED;
  34441. },
  34442. reset: function() {
  34443. clearTimeout(this._timer);
  34444. },
  34445. emit: function() {
  34446. if (this.state == STATE_RECOGNIZED) {
  34447. this._input.tapCount = this.count;
  34448. this.manager.emit(this.options.event, this._input);
  34449. }
  34450. }
  34451. });
  34452. /**
  34453. * Simple way to create a manager with a default set of recognizers.
  34454. * @param {HTMLElement} element
  34455. * @param {Object} [options]
  34456. * @constructor
  34457. */
  34458. function Hammer(element, options) {
  34459. options = options || {};
  34460. options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
  34461. return new Manager(element, options);
  34462. }
  34463. /**
  34464. * @const {string}
  34465. */
  34466. Hammer.VERSION = '2.0.7';
  34467. /**
  34468. * default settings
  34469. * @namespace
  34470. */
  34471. Hammer.defaults = {
  34472. /**
  34473. * set if DOM events are being triggered.
  34474. * But this is slower and unused by simple implementations, so disabled by default.
  34475. * @type {Boolean}
  34476. * @default false
  34477. */
  34478. domEvents: false,
  34479. /**
  34480. * The value for the touchAction property/fallback.
  34481. * When set to `compute` it will magically set the correct value based on the added recognizers.
  34482. * @type {String}
  34483. * @default compute
  34484. */
  34485. touchAction: TOUCH_ACTION_COMPUTE,
  34486. /**
  34487. * @type {Boolean}
  34488. * @default true
  34489. */
  34490. enable: true,
  34491. /**
  34492. * EXPERIMENTAL FEATURE -- can be removed/changed
  34493. * Change the parent input target element.
  34494. * If Null, then it is being set the to main element.
  34495. * @type {Null|EventTarget}
  34496. * @default null
  34497. */
  34498. inputTarget: null,
  34499. /**
  34500. * force an input class
  34501. * @type {Null|Function}
  34502. * @default null
  34503. */
  34504. inputClass: null,
  34505. /**
  34506. * Default recognizer setup when calling `Hammer()`
  34507. * When creating a new Manager these will be skipped.
  34508. * @type {Array}
  34509. */
  34510. preset: [
  34511. // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
  34512. [RotateRecognizer, {enable: false}],
  34513. [PinchRecognizer, {enable: false}, ['rotate']],
  34514. [SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}],
  34515. [PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']],
  34516. [TapRecognizer],
  34517. [TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']],
  34518. [PressRecognizer]
  34519. ],
  34520. /**
  34521. * Some CSS properties can be used to improve the working of Hammer.
  34522. * Add them to this method and they will be set when creating a new Manager.
  34523. * @namespace
  34524. */
  34525. cssProps: {
  34526. /**
  34527. * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
  34528. * @type {String}
  34529. * @default 'none'
  34530. */
  34531. userSelect: 'none',
  34532. /**
  34533. * Disable the Windows Phone grippers when pressing an element.
  34534. * @type {String}
  34535. * @default 'none'
  34536. */
  34537. touchSelect: 'none',
  34538. /**
  34539. * Disables the default callout shown when you touch and hold a touch target.
  34540. * On iOS, when you touch and hold a touch target such as a link, Safari displays
  34541. * a callout containing information about the link. This property allows you to disable that callout.
  34542. * @type {String}
  34543. * @default 'none'
  34544. */
  34545. touchCallout: 'none',
  34546. /**
  34547. * Specifies whether zooming is enabled. Used by IE10>
  34548. * @type {String}
  34549. * @default 'none'
  34550. */
  34551. contentZooming: 'none',
  34552. /**
  34553. * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
  34554. * @type {String}
  34555. * @default 'none'
  34556. */
  34557. userDrag: 'none',
  34558. /**
  34559. * Overrides the highlight color shown when the user taps a link or a JavaScript
  34560. * clickable element in iOS. This property obeys the alpha value, if specified.
  34561. * @type {String}
  34562. * @default 'rgba(0,0,0,0)'
  34563. */
  34564. tapHighlightColor: 'rgba(0,0,0,0)'
  34565. }
  34566. };
  34567. var STOP = 1;
  34568. var FORCED_STOP = 2;
  34569. /**
  34570. * Manager
  34571. * @param {HTMLElement} element
  34572. * @param {Object} [options]
  34573. * @constructor
  34574. */
  34575. function Manager(element, options) {
  34576. this.options = assign({}, Hammer.defaults, options || {});
  34577. this.options.inputTarget = this.options.inputTarget || element;
  34578. this.handlers = {};
  34579. this.session = {};
  34580. this.recognizers = [];
  34581. this.oldCssProps = {};
  34582. this.element = element;
  34583. this.input = createInputInstance(this);
  34584. this.touchAction = new TouchAction(this, this.options.touchAction);
  34585. toggleCssProps(this, true);
  34586. each(this.options.recognizers, function(item) {
  34587. var recognizer = this.add(new (item[0])(item[1]));
  34588. item[2] && recognizer.recognizeWith(item[2]);
  34589. item[3] && recognizer.requireFailure(item[3]);
  34590. }, this);
  34591. }
  34592. Manager.prototype = {
  34593. /**
  34594. * set options
  34595. * @param {Object} options
  34596. * @returns {Manager}
  34597. */
  34598. set: function(options) {
  34599. assign(this.options, options);
  34600. // Options that need a little more setup
  34601. if (options.touchAction) {
  34602. this.touchAction.update();
  34603. }
  34604. if (options.inputTarget) {
  34605. // Clean up existing event listeners and reinitialize
  34606. this.input.destroy();
  34607. this.input.target = options.inputTarget;
  34608. this.input.init();
  34609. }
  34610. return this;
  34611. },
  34612. /**
  34613. * stop recognizing for this session.
  34614. * This session will be discarded, when a new [input]start event is fired.
  34615. * When forced, the recognizer cycle is stopped immediately.
  34616. * @param {Boolean} [force]
  34617. */
  34618. stop: function(force) {
  34619. this.session.stopped = force ? FORCED_STOP : STOP;
  34620. },
  34621. /**
  34622. * run the recognizers!
  34623. * called by the inputHandler function on every movement of the pointers (touches)
  34624. * it walks through all the recognizers and tries to detect the gesture that is being made
  34625. * @param {Object} inputData
  34626. */
  34627. recognize: function(inputData) {
  34628. var session = this.session;
  34629. if (session.stopped) {
  34630. return;
  34631. }
  34632. // run the touch-action polyfill
  34633. this.touchAction.preventDefaults(inputData);
  34634. var recognizer;
  34635. var recognizers = this.recognizers;
  34636. // this holds the recognizer that is being recognized.
  34637. // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
  34638. // if no recognizer is detecting a thing, it is set to `null`
  34639. var curRecognizer = session.curRecognizer;
  34640. // reset when the last recognizer is recognized
  34641. // or when we're in a new session
  34642. if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {
  34643. curRecognizer = session.curRecognizer = null;
  34644. }
  34645. var i = 0;
  34646. while (i < recognizers.length) {
  34647. recognizer = recognizers[i];
  34648. // find out if we are allowed try to recognize the input for this one.
  34649. // 1. allow if the session is NOT forced stopped (see the .stop() method)
  34650. // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
  34651. // that is being recognized.
  34652. // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
  34653. // this can be setup with the `recognizeWith()` method on the recognizer.
  34654. if (session.stopped !== FORCED_STOP && ( // 1
  34655. !curRecognizer || recognizer == curRecognizer || // 2
  34656. recognizer.canRecognizeWith(curRecognizer))) { // 3
  34657. recognizer.recognize(inputData);
  34658. } else {
  34659. recognizer.reset();
  34660. }
  34661. // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
  34662. // current active recognizer. but only if we don't already have an active recognizer
  34663. if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
  34664. curRecognizer = session.curRecognizer = recognizer;
  34665. }
  34666. i++;
  34667. }
  34668. },
  34669. /**
  34670. * get a recognizer by its event name.
  34671. * @param {Recognizer|String} recognizer
  34672. * @returns {Recognizer|Null}
  34673. */
  34674. get: function(recognizer) {
  34675. if (recognizer instanceof Recognizer) {
  34676. return recognizer;
  34677. }
  34678. var recognizers = this.recognizers;
  34679. for (var i = 0; i < recognizers.length; i++) {
  34680. if (recognizers[i].options.event == recognizer) {
  34681. return recognizers[i];
  34682. }
  34683. }
  34684. return null;
  34685. },
  34686. /**
  34687. * add a recognizer to the manager
  34688. * existing recognizers with the same event name will be removed
  34689. * @param {Recognizer} recognizer
  34690. * @returns {Recognizer|Manager}
  34691. */
  34692. add: function(recognizer) {
  34693. if (invokeArrayArg(recognizer, 'add', this)) {
  34694. return this;
  34695. }
  34696. // remove existing
  34697. var existing = this.get(recognizer.options.event);
  34698. if (existing) {
  34699. this.remove(existing);
  34700. }
  34701. this.recognizers.push(recognizer);
  34702. recognizer.manager = this;
  34703. this.touchAction.update();
  34704. return recognizer;
  34705. },
  34706. /**
  34707. * remove a recognizer by name or instance
  34708. * @param {Recognizer|String} recognizer
  34709. * @returns {Manager}
  34710. */
  34711. remove: function(recognizer) {
  34712. if (invokeArrayArg(recognizer, 'remove', this)) {
  34713. return this;
  34714. }
  34715. recognizer = this.get(recognizer);
  34716. // let's make sure this recognizer exists
  34717. if (recognizer) {
  34718. var recognizers = this.recognizers;
  34719. var index = inArray(recognizers, recognizer);
  34720. if (index !== -1) {
  34721. recognizers.splice(index, 1);
  34722. this.touchAction.update();
  34723. }
  34724. }
  34725. return this;
  34726. },
  34727. /**
  34728. * bind event
  34729. * @param {String} events
  34730. * @param {Function} handler
  34731. * @returns {EventEmitter} this
  34732. */
  34733. on: function(events, handler) {
  34734. if (events === undefined) {
  34735. return;
  34736. }
  34737. if (handler === undefined) {
  34738. return;
  34739. }
  34740. var handlers = this.handlers;
  34741. each(splitStr(events), function(event) {
  34742. handlers[event] = handlers[event] || [];
  34743. handlers[event].push(handler);
  34744. });
  34745. return this;
  34746. },
  34747. /**
  34748. * unbind event, leave emit blank to remove all handlers
  34749. * @param {String} events
  34750. * @param {Function} [handler]
  34751. * @returns {EventEmitter} this
  34752. */
  34753. off: function(events, handler) {
  34754. if (events === undefined) {
  34755. return;
  34756. }
  34757. var handlers = this.handlers;
  34758. each(splitStr(events), function(event) {
  34759. if (!handler) {
  34760. delete handlers[event];
  34761. } else {
  34762. handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
  34763. }
  34764. });
  34765. return this;
  34766. },
  34767. /**
  34768. * emit event to the listeners
  34769. * @param {String} event
  34770. * @param {Object} data
  34771. */
  34772. emit: function(event, data) {
  34773. // we also want to trigger dom events
  34774. if (this.options.domEvents) {
  34775. triggerDomEvent(event, data);
  34776. }
  34777. // no handlers, so skip it all
  34778. var handlers = this.handlers[event] && this.handlers[event].slice();
  34779. if (!handlers || !handlers.length) {
  34780. return;
  34781. }
  34782. data.type = event;
  34783. data.preventDefault = function() {
  34784. data.srcEvent.preventDefault();
  34785. };
  34786. var i = 0;
  34787. while (i < handlers.length) {
  34788. handlers[i](data);
  34789. i++;
  34790. }
  34791. },
  34792. /**
  34793. * destroy the manager and unbinds all events
  34794. * it doesn't unbind dom events, that is the user own responsibility
  34795. */
  34796. destroy: function() {
  34797. this.element && toggleCssProps(this, false);
  34798. this.handlers = {};
  34799. this.session = {};
  34800. this.input.destroy();
  34801. this.element = null;
  34802. }
  34803. };
  34804. /**
  34805. * add/remove the css properties as defined in manager.options.cssProps
  34806. * @param {Manager} manager
  34807. * @param {Boolean} add
  34808. */
  34809. function toggleCssProps(manager, add) {
  34810. var element = manager.element;
  34811. if (!element.style) {
  34812. return;
  34813. }
  34814. var prop;
  34815. each(manager.options.cssProps, function(value, name) {
  34816. prop = prefixed(element.style, name);
  34817. if (add) {
  34818. manager.oldCssProps[prop] = element.style[prop];
  34819. element.style[prop] = value;
  34820. } else {
  34821. element.style[prop] = manager.oldCssProps[prop] || '';
  34822. }
  34823. });
  34824. if (!add) {
  34825. manager.oldCssProps = {};
  34826. }
  34827. }
  34828. /**
  34829. * trigger dom event
  34830. * @param {String} event
  34831. * @param {Object} data
  34832. */
  34833. function triggerDomEvent(event, data) {
  34834. var gestureEvent = document.createEvent('Event');
  34835. gestureEvent.initEvent(event, true, true);
  34836. gestureEvent.gesture = data;
  34837. data.target.dispatchEvent(gestureEvent);
  34838. }
  34839. assign(Hammer, {
  34840. INPUT_START: INPUT_START,
  34841. INPUT_MOVE: INPUT_MOVE,
  34842. INPUT_END: INPUT_END,
  34843. INPUT_CANCEL: INPUT_CANCEL,
  34844. STATE_POSSIBLE: STATE_POSSIBLE,
  34845. STATE_BEGAN: STATE_BEGAN,
  34846. STATE_CHANGED: STATE_CHANGED,
  34847. STATE_ENDED: STATE_ENDED,
  34848. STATE_RECOGNIZED: STATE_RECOGNIZED,
  34849. STATE_CANCELLED: STATE_CANCELLED,
  34850. STATE_FAILED: STATE_FAILED,
  34851. DIRECTION_NONE: DIRECTION_NONE,
  34852. DIRECTION_LEFT: DIRECTION_LEFT,
  34853. DIRECTION_RIGHT: DIRECTION_RIGHT,
  34854. DIRECTION_UP: DIRECTION_UP,
  34855. DIRECTION_DOWN: DIRECTION_DOWN,
  34856. DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
  34857. DIRECTION_VERTICAL: DIRECTION_VERTICAL,
  34858. DIRECTION_ALL: DIRECTION_ALL,
  34859. Manager: Manager,
  34860. Input: Input,
  34861. TouchAction: TouchAction,
  34862. TouchInput: TouchInput,
  34863. MouseInput: MouseInput,
  34864. PointerEventInput: PointerEventInput,
  34865. TouchMouseInput: TouchMouseInput,
  34866. SingleTouchInput: SingleTouchInput,
  34867. Recognizer: Recognizer,
  34868. AttrRecognizer: AttrRecognizer,
  34869. Tap: TapRecognizer,
  34870. Pan: PanRecognizer,
  34871. Swipe: SwipeRecognizer,
  34872. Pinch: PinchRecognizer,
  34873. Rotate: RotateRecognizer,
  34874. Press: PressRecognizer,
  34875. on: addEventListeners,
  34876. off: removeEventListeners,
  34877. each: each,
  34878. merge: merge,
  34879. extend: extend,
  34880. assign: assign,
  34881. inherit: inherit,
  34882. bindFn: bindFn,
  34883. prefixed: prefixed
  34884. });
  34885. // this prevents errors when Hammer is loaded in the presence of an AMD
  34886. // style loader but by script tag, not by the loader.
  34887. var freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line
  34888. freeGlobal.Hammer = Hammer;
  34889. if (true) {
  34890. !(__WEBPACK_AMD_DEFINE_RESULT__ = function() {
  34891. return Hammer;
  34892. }.call(exports, __webpack_require__, exports, module),
  34893. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  34894. } else if (typeof module != 'undefined' && module.exports) {
  34895. module.exports = Hammer;
  34896. } else {
  34897. window[exportName] = Hammer;
  34898. }
  34899. })(window, document, 'Hammer');
  34900. /***/ }),
  34901. /* 177 */
  34902. /***/ (function(module, exports, __webpack_require__) {
  34903. "use strict";
  34904. // utils
  34905. exports.util = __webpack_require__(2);
  34906. exports.DOMutil = __webpack_require__(14);
  34907. // data
  34908. exports.DataSet = __webpack_require__(11);
  34909. exports.DataView = __webpack_require__(12);
  34910. exports.Queue = __webpack_require__(43);
  34911. // Timeline
  34912. exports.Timeline = __webpack_require__(178);
  34913. exports.Graph2d = __webpack_require__(180);
  34914. exports.timeline = {
  34915. Core: __webpack_require__(65),
  34916. DateUtil: __webpack_require__(36),
  34917. Range: __webpack_require__(64),
  34918. stack: __webpack_require__(100),
  34919. TimeStep: __webpack_require__(66),
  34920. components: {
  34921. items: {
  34922. Item: __webpack_require__(38),
  34923. BackgroundItem: __webpack_require__(103),
  34924. BoxItem: __webpack_require__(101),
  34925. PointItem: __webpack_require__(102),
  34926. RangeItem: __webpack_require__(70)
  34927. },
  34928. BackgroundGroup: __webpack_require__(69),
  34929. Component: __webpack_require__(16),
  34930. CurrentTime: __webpack_require__(67),
  34931. CustomTime: __webpack_require__(46),
  34932. DataAxis: __webpack_require__(107),
  34933. DataScale: __webpack_require__(108),
  34934. GraphGroup: __webpack_require__(109),
  34935. Group: __webpack_require__(68),
  34936. ItemSet: __webpack_require__(99),
  34937. Legend: __webpack_require__(112),
  34938. LineGraph: __webpack_require__(106),
  34939. TimeAxis: __webpack_require__(45)
  34940. }
  34941. };
  34942. // bundled external libraries
  34943. exports.moment = __webpack_require__(9);
  34944. exports.Hammer = __webpack_require__(10);
  34945. exports.keycharm = __webpack_require__(35);
  34946. /***/ }),
  34947. /* 178 */
  34948. /***/ (function(module, exports, __webpack_require__) {
  34949. "use strict";
  34950. var moment = __webpack_require__(9);
  34951. var util = __webpack_require__(2);
  34952. var DataSet = __webpack_require__(11);
  34953. var DataView = __webpack_require__(12);
  34954. var Range = __webpack_require__(64);
  34955. var Core = __webpack_require__(65);
  34956. var TimeAxis = __webpack_require__(45);
  34957. var CurrentTime = __webpack_require__(67);
  34958. var CustomTime = __webpack_require__(46);
  34959. var ItemSet = __webpack_require__(99);
  34960. var printStyle = __webpack_require__(15).printStyle;
  34961. var allOptions = __webpack_require__(105).allOptions;
  34962. var configureOptions = __webpack_require__(105).configureOptions;
  34963. var Configurator = __webpack_require__(71)['default'];
  34964. var Validator = __webpack_require__(15)['default'];
  34965. /**
  34966. * Create a timeline visualization
  34967. * @param {HTMLElement} container
  34968. * @param {vis.DataSet | vis.DataView | Array} [items]
  34969. * @param {vis.DataSet | vis.DataView | Array} [groups]
  34970. * @param {Object} [options] See Timeline.setOptions for the available options.
  34971. * @constructor Timeline
  34972. * @extends Core
  34973. */
  34974. function Timeline(container, items, groups, options) {
  34975. if (!(this instanceof Timeline)) {
  34976. throw new SyntaxError('Constructor must be called with the new operator');
  34977. }
  34978. // if the third element is options, the forth is groups (optionally);
  34979. if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) {
  34980. var forthArgument = options;
  34981. options = groups;
  34982. groups = forthArgument;
  34983. }
  34984. // TODO: REMOVE THIS in the next MAJOR release
  34985. // see https://github.com/almende/vis/issues/2511
  34986. if (options && options.throttleRedraw) {
  34987. console.warn("Timeline option \"throttleRedraw\" is DEPRICATED and no longer supported. It will be removed in the next MAJOR release.");
  34988. }
  34989. var me = this;
  34990. this.defaultOptions = {
  34991. start: null,
  34992. end: null,
  34993. autoResize: true,
  34994. orientation: {
  34995. axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both'
  34996. item: 'bottom' // not relevant
  34997. },
  34998. moment: moment,
  34999. width: null,
  35000. height: null,
  35001. maxHeight: null,
  35002. minHeight: null
  35003. };
  35004. this.options = util.deepExtend({}, this.defaultOptions);
  35005. // Create the DOM, props, and emitter
  35006. this._create(container);
  35007. if (!options || options && typeof options.rtl == "undefined") {
  35008. this.dom.root.style.visibility = 'hidden';
  35009. var directionFromDom,
  35010. domNode = this.dom.root;
  35011. while (!directionFromDom && domNode) {
  35012. directionFromDom = window.getComputedStyle(domNode, null).direction;
  35013. domNode = domNode.parentElement;
  35014. }
  35015. this.options.rtl = directionFromDom && directionFromDom.toLowerCase() == "rtl";
  35016. } else {
  35017. this.options.rtl = options.rtl;
  35018. }
  35019. this.options.rollingMode = options && options.rollingMode;
  35020. this.options.onInitialDrawComplete = options && options.onInitialDrawComplete;
  35021. // all components listed here will be repainted automatically
  35022. this.components = [];
  35023. this.body = {
  35024. dom: this.dom,
  35025. domProps: this.props,
  35026. emitter: {
  35027. on: this.on.bind(this),
  35028. off: this.off.bind(this),
  35029. emit: this.emit.bind(this)
  35030. },
  35031. hiddenDates: [],
  35032. util: {
  35033. getScale: function getScale() {
  35034. return me.timeAxis.step.scale;
  35035. },
  35036. getStep: function getStep() {
  35037. return me.timeAxis.step.step;
  35038. },
  35039. toScreen: me._toScreen.bind(me),
  35040. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  35041. toTime: me._toTime.bind(me),
  35042. toGlobalTime: me._toGlobalTime.bind(me)
  35043. }
  35044. };
  35045. // range
  35046. this.range = new Range(this.body, this.options);
  35047. this.components.push(this.range);
  35048. this.body.range = this.range;
  35049. // time axis
  35050. this.timeAxis = new TimeAxis(this.body, this.options);
  35051. this.timeAxis2 = null; // used in case of orientation option 'both'
  35052. this.components.push(this.timeAxis);
  35053. // current time bar
  35054. this.currentTime = new CurrentTime(this.body, this.options);
  35055. this.components.push(this.currentTime);
  35056. // item set
  35057. this.itemSet = new ItemSet(this.body, this.options);
  35058. this.components.push(this.itemSet);
  35059. this.itemsData = null; // DataSet
  35060. this.groupsData = null; // DataSet
  35061. this.dom.root.onclick = function (event) {
  35062. me.emit('click', me.getEventProperties(event));
  35063. };
  35064. this.dom.root.ondblclick = function (event) {
  35065. me.emit('doubleClick', me.getEventProperties(event));
  35066. };
  35067. this.dom.root.oncontextmenu = function (event) {
  35068. me.emit('contextmenu', me.getEventProperties(event));
  35069. };
  35070. this.dom.root.onmouseover = function (event) {
  35071. me.emit('mouseOver', me.getEventProperties(event));
  35072. };
  35073. if (window.PointerEvent) {
  35074. this.dom.root.onpointerdown = function (event) {
  35075. me.emit('mouseDown', me.getEventProperties(event));
  35076. };
  35077. this.dom.root.onpointermove = function (event) {
  35078. me.emit('mouseMove', me.getEventProperties(event));
  35079. };
  35080. this.dom.root.onpointerup = function (event) {
  35081. me.emit('mouseUp', me.getEventProperties(event));
  35082. };
  35083. } else {
  35084. this.dom.root.onmousemove = function (event) {
  35085. me.emit('mouseMove', me.getEventProperties(event));
  35086. };
  35087. this.dom.root.onmousedown = function (event) {
  35088. me.emit('mouseDown', me.getEventProperties(event));
  35089. };
  35090. this.dom.root.onmouseup = function (event) {
  35091. me.emit('mouseUp', me.getEventProperties(event));
  35092. };
  35093. }
  35094. //Single time autoscale/fit
  35095. this.initialFitDone = false;
  35096. this.on('changed', function () {
  35097. if (this.itemsData == null || this.options.rollingMode) return;
  35098. if (!me.initialFitDone) {
  35099. me.initialFitDone = true;
  35100. if (me.options.start != undefined || me.options.end != undefined) {
  35101. if (me.options.start == undefined || me.options.end == undefined) {
  35102. var range = me.getItemRange();
  35103. }
  35104. var start = me.options.start != undefined ? me.options.start : range.min;
  35105. var end = me.options.end != undefined ? me.options.end : range.max;
  35106. me.setWindow(start, end, { animation: false });
  35107. } else {
  35108. me.fit({ animation: false });
  35109. }
  35110. }
  35111. if (!me.initialDrawDone && me.initialRangeChangeDone) {
  35112. me.initialDrawDone = true;
  35113. me.dom.root.style.visibility = 'visible';
  35114. if (me.options.onInitialDrawComplete) {
  35115. setTimeout(function () {
  35116. return me.options.onInitialDrawComplete();
  35117. }, 0);
  35118. }
  35119. }
  35120. });
  35121. // apply options
  35122. if (options) {
  35123. this.setOptions(options);
  35124. }
  35125. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  35126. if (groups) {
  35127. this.setGroups(groups);
  35128. }
  35129. // create itemset
  35130. if (items) {
  35131. this.setItems(items);
  35132. }
  35133. // draw for the first time
  35134. this._redraw();
  35135. }
  35136. // Extend the functionality from Core
  35137. Timeline.prototype = new Core();
  35138. /**
  35139. * Load a configurator
  35140. * @return {Object}
  35141. * @private
  35142. */
  35143. Timeline.prototype._createConfigurator = function () {
  35144. return new Configurator(this, this.dom.container, configureOptions);
  35145. };
  35146. /**
  35147. * Force a redraw. The size of all items will be recalculated.
  35148. * Can be useful to manually redraw when option autoResize=false and the window
  35149. * has been resized, or when the items CSS has been changed.
  35150. *
  35151. * Note: this function will be overridden on construction with a trottled version
  35152. */
  35153. Timeline.prototype.redraw = function () {
  35154. this.itemSet && this.itemSet.markDirty({ refreshItems: true });
  35155. this._redraw();
  35156. };
  35157. Timeline.prototype.setOptions = function (options) {
  35158. // validate options
  35159. var errorFound = Validator.validate(options, allOptions);
  35160. if (errorFound === true) {
  35161. console.log('%cErrors have been found in the supplied options object.', printStyle);
  35162. }
  35163. Core.prototype.setOptions.call(this, options);
  35164. if ('type' in options) {
  35165. if (options.type !== this.options.type) {
  35166. this.options.type = options.type;
  35167. // force recreation of all items
  35168. var itemsData = this.itemsData;
  35169. if (itemsData) {
  35170. var selection = this.getSelection();
  35171. this.setItems(null); // remove all
  35172. this.setItems(itemsData); // add all
  35173. this.setSelection(selection); // restore selection
  35174. }
  35175. }
  35176. }
  35177. };
  35178. /**
  35179. * Set items
  35180. * @param {vis.DataSet | Array | null} items
  35181. */
  35182. Timeline.prototype.setItems = function (items) {
  35183. // convert to type DataSet when needed
  35184. var newDataSet;
  35185. if (!items) {
  35186. newDataSet = null;
  35187. } else if (items instanceof DataSet || items instanceof DataView) {
  35188. newDataSet = items;
  35189. } else {
  35190. // turn an array into a dataset
  35191. newDataSet = new DataSet(items, {
  35192. type: {
  35193. start: 'Date',
  35194. end: 'Date'
  35195. }
  35196. });
  35197. }
  35198. // set items
  35199. this.itemsData = newDataSet;
  35200. this.itemSet && this.itemSet.setItems(newDataSet);
  35201. };
  35202. /**
  35203. * Set groups
  35204. * @param {vis.DataSet | Array} groups
  35205. */
  35206. Timeline.prototype.setGroups = function (groups) {
  35207. // convert to type DataSet when needed
  35208. var newDataSet;
  35209. if (!groups) {
  35210. newDataSet = null;
  35211. } else {
  35212. var filter = function filter(group) {
  35213. return group.visible !== false;
  35214. };
  35215. if (groups instanceof DataSet || groups instanceof DataView) {
  35216. newDataSet = new DataView(groups, { filter: filter });
  35217. } else {
  35218. // turn an array into a dataset
  35219. newDataSet = new DataSet(groups.filter(filter));
  35220. }
  35221. }
  35222. this.groupsData = newDataSet;
  35223. this.itemSet.setGroups(newDataSet);
  35224. };
  35225. /**
  35226. * Set both items and groups in one go
  35227. * @param {{items: (Array | vis.DataSet), groups: (Array | vis.DataSet)}} data
  35228. */
  35229. Timeline.prototype.setData = function (data) {
  35230. if (data && data.groups) {
  35231. this.setGroups(data.groups);
  35232. }
  35233. if (data && data.items) {
  35234. this.setItems(data.items);
  35235. }
  35236. };
  35237. /**
  35238. * Set selected items by their id. Replaces the current selection
  35239. * Unknown id's are silently ignored.
  35240. * @param {string[] | string} [ids] An array with zero or more id's of the items to be
  35241. * selected. If ids is an empty array, all items will be
  35242. * unselected.
  35243. * @param {Object} [options] Available options:
  35244. * `focus: boolean`
  35245. * If true, focus will be set to the selected item(s)
  35246. * `animation: boolean | {duration: number, easingFunction: string}`
  35247. * If true (default), the range is animated
  35248. * smoothly to the new window. An object can be
  35249. * provided to specify duration and easing function.
  35250. * Default duration is 500 ms, and default easing
  35251. * function is 'easeInOutQuad'.
  35252. * Only applicable when option focus is true.
  35253. */
  35254. Timeline.prototype.setSelection = function (ids, options) {
  35255. this.itemSet && this.itemSet.setSelection(ids);
  35256. if (options && options.focus) {
  35257. this.focus(ids, options);
  35258. }
  35259. };
  35260. /**
  35261. * Get the selected items by their id
  35262. * @return {Array} ids The ids of the selected items
  35263. */
  35264. Timeline.prototype.getSelection = function () {
  35265. return this.itemSet && this.itemSet.getSelection() || [];
  35266. };
  35267. /**
  35268. * Adjust the visible window such that the selected item (or multiple items)
  35269. * are centered on screen.
  35270. * @param {string | String[]} id An item id or array with item ids
  35271. * @param {Object} [options] Available options:
  35272. * `animation: boolean | {duration: number, easingFunction: string}`
  35273. * If true (default), the range is animated
  35274. * smoothly to the new window. An object can be
  35275. * provided to specify duration and easing function.
  35276. * Default duration is 500 ms, and default easing
  35277. * function is 'easeInOutQuad'.
  35278. */
  35279. Timeline.prototype.focus = function (id, options) {
  35280. if (!this.itemsData || id == undefined) return;
  35281. var ids = Array.isArray(id) ? id : [id];
  35282. // get the specified item(s)
  35283. var itemsData = this.itemsData.getDataSet().get(ids, {
  35284. type: {
  35285. start: 'Date',
  35286. end: 'Date'
  35287. }
  35288. });
  35289. // calculate minimum start and maximum end of specified items
  35290. var start = null;
  35291. var end = null;
  35292. itemsData.forEach(function (itemData) {
  35293. var s = itemData.start.valueOf();
  35294. var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
  35295. if (start === null || s < start) {
  35296. start = s;
  35297. }
  35298. if (end === null || e > end) {
  35299. end = e;
  35300. }
  35301. });
  35302. if (start !== null && end !== null) {
  35303. var me = this;
  35304. // Use the first item for the vertical focus
  35305. var item = this.itemSet.items[ids[0]];
  35306. var startPos = this._getScrollTop() * -1;
  35307. var initialVerticalScroll = null;
  35308. // Setup a handler for each frame of the vertical scroll
  35309. var verticalAnimationFrame = function verticalAnimationFrame(ease, willDraw, done) {
  35310. var verticalScroll = getItemVerticalScroll(me, item);
  35311. if (!initialVerticalScroll) {
  35312. initialVerticalScroll = verticalScroll;
  35313. }
  35314. if (initialVerticalScroll.itemTop == verticalScroll.itemTop && !initialVerticalScroll.shouldScroll) {
  35315. return; // We don't need to scroll, so do nothing
  35316. } else if (initialVerticalScroll.itemTop != verticalScroll.itemTop && verticalScroll.shouldScroll) {
  35317. // The redraw shifted elements, so reset the animation to correct
  35318. initialVerticalScroll = verticalScroll;
  35319. startPos = me._getScrollTop() * -1;
  35320. }
  35321. var from = startPos;
  35322. var to = initialVerticalScroll.scrollOffset;
  35323. var scrollTop = done ? to : from + (to - from) * ease;
  35324. me._setScrollTop(-scrollTop);
  35325. if (!willDraw) {
  35326. me._redraw();
  35327. }
  35328. };
  35329. // Enforces the final vertical scroll position
  35330. var setFinalVerticalPosition = function setFinalVerticalPosition() {
  35331. var finalVerticalScroll = getItemVerticalScroll(me, item);
  35332. if (finalVerticalScroll.shouldScroll && finalVerticalScroll.itemTop != initialVerticalScroll.itemTop) {
  35333. me._setScrollTop(-finalVerticalScroll.scrollOffset);
  35334. me._redraw();
  35335. }
  35336. };
  35337. // Perform one last check at the end to make sure the final vertical
  35338. // position is correct
  35339. var finalVerticalCallback = function finalVerticalCallback() {
  35340. // Double check we ended at the proper scroll position
  35341. setFinalVerticalPosition();
  35342. // Let the redraw settle and finalize the position.
  35343. setTimeout(setFinalVerticalPosition, 100);
  35344. };
  35345. // calculate the new middle and interval for the window
  35346. var middle = (start + end) / 2;
  35347. var interval = Math.max(this.range.end - this.range.start, (end - start) * 1.1);
  35348. var animation = options && options.animation !== undefined ? options.animation : true;
  35349. if (!animation) {
  35350. // We aren't animating so set a default so that the final callback forces the vertical location
  35351. initialVerticalScroll = { shouldScroll: false, scrollOffset: -1, itemTop: -1 };
  35352. }
  35353. this.range.setRange(middle - interval / 2, middle + interval / 2, { animation: animation }, finalVerticalCallback, verticalAnimationFrame);
  35354. }
  35355. };
  35356. /**
  35357. * Set Timeline window such that it fits all items
  35358. * @param {Object} [options] Available options:
  35359. * `animation: boolean | {duration: number, easingFunction: string}`
  35360. * If true (default), the range is animated
  35361. * smoothly to the new window. An object can be
  35362. * provided to specify duration and easing function.
  35363. * Default duration is 500 ms, and default easing
  35364. * function is 'easeInOutQuad'.
  35365. * @param {function} [callback]
  35366. */
  35367. Timeline.prototype.fit = function (options, callback) {
  35368. var animation = options && options.animation !== undefined ? options.animation : true;
  35369. var range;
  35370. var dataset = this.itemsData && this.itemsData.getDataSet();
  35371. if (dataset.length === 1 && dataset.get()[0].end === undefined) {
  35372. // a single item -> don't fit, just show a range around the item from -4 to +3 days
  35373. range = this.getDataRange();
  35374. this.moveTo(range.min.valueOf(), { animation: animation }, callback);
  35375. } else {
  35376. // exactly fit the items (plus a small margin)
  35377. range = this.getItemRange();
  35378. this.range.setRange(range.min, range.max, { animation: animation }, callback);
  35379. }
  35380. };
  35381. /**
  35382. *
  35383. * @param {vis.Item} item
  35384. * @returns {number}
  35385. */
  35386. function getStart(item) {
  35387. return util.convert(item.data.start, 'Date').valueOf();
  35388. }
  35389. /**
  35390. *
  35391. * @param {vis.Item} item
  35392. * @returns {number}
  35393. */
  35394. function getEnd(item) {
  35395. var end = item.data.end != undefined ? item.data.end : item.data.start;
  35396. return util.convert(end, 'Date').valueOf();
  35397. }
  35398. /**
  35399. * @param {vis.Timeline} timeline
  35400. * @param {vis.Item} item
  35401. * @return {{shouldScroll: bool, scrollOffset: number, itemTop: number}}
  35402. */
  35403. function getItemVerticalScroll(timeline, item) {
  35404. var leftHeight = timeline.props.leftContainer.height;
  35405. var contentHeight = timeline.props.left.height;
  35406. var group = item.parent;
  35407. var offset = group.top;
  35408. var shouldScroll = true;
  35409. var orientation = timeline.timeAxis.options.orientation.axis;
  35410. var itemTop = function itemTop() {
  35411. if (orientation == "bottom") {
  35412. return group.height - item.top - item.height;
  35413. } else {
  35414. return item.top;
  35415. }
  35416. };
  35417. var currentScrollHeight = timeline._getScrollTop() * -1;
  35418. var targetOffset = offset + itemTop();
  35419. var height = item.height;
  35420. if (targetOffset < currentScrollHeight) {
  35421. if (offset + leftHeight <= offset + itemTop() + height) {
  35422. offset += itemTop() - timeline.itemSet.options.margin.item.vertical;
  35423. }
  35424. } else if (targetOffset + height > currentScrollHeight + leftHeight) {
  35425. offset += itemTop() + height - leftHeight + timeline.itemSet.options.margin.item.vertical;
  35426. } else {
  35427. shouldScroll = false;
  35428. }
  35429. offset = Math.min(offset, contentHeight - leftHeight);
  35430. return { shouldScroll: shouldScroll, scrollOffset: offset, itemTop: targetOffset };
  35431. }
  35432. /**
  35433. * Determine the range of the items, taking into account their actual width
  35434. * and a margin of 10 pixels on both sides.
  35435. *
  35436. * @returns {{min: Date, max: Date}}
  35437. */
  35438. Timeline.prototype.getItemRange = function () {
  35439. // get a rough approximation for the range based on the items start and end dates
  35440. var range = this.getDataRange();
  35441. var min = range.min !== null ? range.min.valueOf() : null;
  35442. var max = range.max !== null ? range.max.valueOf() : null;
  35443. var minItem = null;
  35444. var maxItem = null;
  35445. if (min != null && max != null) {
  35446. var interval = max - min; // ms
  35447. if (interval <= 0) {
  35448. interval = 10;
  35449. }
  35450. var factor = interval / this.props.center.width;
  35451. var redrawQueue = {};
  35452. var redrawQueueLength = 0;
  35453. // collect redraw functions
  35454. util.forEach(this.itemSet.items, function (item, key) {
  35455. if (item.groupShowing) {
  35456. var returnQueue = true;
  35457. redrawQueue[key] = item.redraw(returnQueue);
  35458. redrawQueueLength = redrawQueue[key].length;
  35459. }
  35460. });
  35461. var needRedraw = redrawQueueLength > 0;
  35462. if (needRedraw) {
  35463. // redraw all regular items
  35464. for (var i = 0; i < redrawQueueLength; i++) {
  35465. util.forEach(redrawQueue, function (fns) {
  35466. fns[i]();
  35467. });
  35468. }
  35469. }
  35470. // calculate the date of the left side and right side of the items given
  35471. util.forEach(this.itemSet.items, function (item) {
  35472. var start = getStart(item);
  35473. var end = getEnd(item);
  35474. var startSide;
  35475. var endSide;
  35476. if (this.options.rtl) {
  35477. startSide = start - (item.getWidthRight() + 10) * factor;
  35478. endSide = end + (item.getWidthLeft() + 10) * factor;
  35479. } else {
  35480. startSide = start - (item.getWidthLeft() + 10) * factor;
  35481. endSide = end + (item.getWidthRight() + 10) * factor;
  35482. }
  35483. if (startSide < min) {
  35484. min = startSide;
  35485. minItem = item;
  35486. }
  35487. if (endSide > max) {
  35488. max = endSide;
  35489. maxItem = item;
  35490. }
  35491. }.bind(this));
  35492. if (minItem && maxItem) {
  35493. var lhs = minItem.getWidthLeft() + 10;
  35494. var rhs = maxItem.getWidthRight() + 10;
  35495. var delta = this.props.center.width - lhs - rhs; // px
  35496. if (delta > 0) {
  35497. if (this.options.rtl) {
  35498. min = getStart(minItem) - rhs * interval / delta; // ms
  35499. max = getEnd(maxItem) + lhs * interval / delta; // ms
  35500. } else {
  35501. min = getStart(minItem) - lhs * interval / delta; // ms
  35502. max = getEnd(maxItem) + rhs * interval / delta; // ms
  35503. }
  35504. }
  35505. }
  35506. }
  35507. return {
  35508. min: min != null ? new Date(min) : null,
  35509. max: max != null ? new Date(max) : null
  35510. };
  35511. };
  35512. /**
  35513. * Calculate the data range of the items start and end dates
  35514. * @returns {{min: Date, max: Date}}
  35515. */
  35516. Timeline.prototype.getDataRange = function () {
  35517. var min = null;
  35518. var max = null;
  35519. var dataset = this.itemsData && this.itemsData.getDataSet();
  35520. if (dataset) {
  35521. dataset.forEach(function (item) {
  35522. var start = util.convert(item.start, 'Date').valueOf();
  35523. var end = util.convert(item.end != undefined ? item.end : item.start, 'Date').valueOf();
  35524. if (min === null || start < min) {
  35525. min = start;
  35526. }
  35527. if (max === null || end > max) {
  35528. max = end;
  35529. }
  35530. });
  35531. }
  35532. return {
  35533. min: min != null ? new Date(min) : null,
  35534. max: max != null ? new Date(max) : null
  35535. };
  35536. };
  35537. /**
  35538. * Generate Timeline related information from an event
  35539. * @param {Event} event
  35540. * @return {Object} An object with related information, like on which area
  35541. * The event happened, whether clicked on an item, etc.
  35542. */
  35543. Timeline.prototype.getEventProperties = function (event) {
  35544. var clientX = event.center ? event.center.x : event.clientX;
  35545. var clientY = event.center ? event.center.y : event.clientY;
  35546. var x;
  35547. if (this.options.rtl) {
  35548. x = util.getAbsoluteRight(this.dom.centerContainer) - clientX;
  35549. } else {
  35550. x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
  35551. }
  35552. var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
  35553. var item = this.itemSet.itemFromTarget(event);
  35554. var group = this.itemSet.groupFromTarget(event);
  35555. var customTime = CustomTime.customTimeFromTarget(event);
  35556. var snap = this.itemSet.options.snap || null;
  35557. var scale = this.body.util.getScale();
  35558. var step = this.body.util.getStep();
  35559. var time = this._toTime(x);
  35560. var snappedTime = snap ? snap(time, scale, step) : time;
  35561. var element = util.getTarget(event);
  35562. var what = null;
  35563. if (item != null) {
  35564. what = 'item';
  35565. } else if (customTime != null) {
  35566. what = 'custom-time';
  35567. } else if (util.hasParent(element, this.timeAxis.dom.foreground)) {
  35568. what = 'axis';
  35569. } else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {
  35570. what = 'axis';
  35571. } else if (util.hasParent(element, this.itemSet.dom.labelSet)) {
  35572. what = 'group-label';
  35573. } else if (util.hasParent(element, this.currentTime.bar)) {
  35574. what = 'current-time';
  35575. } else if (util.hasParent(element, this.dom.center)) {
  35576. what = 'background';
  35577. }
  35578. return {
  35579. event: event,
  35580. item: item ? item.id : null,
  35581. group: group ? group.groupId : null,
  35582. what: what,
  35583. pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
  35584. pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
  35585. x: x,
  35586. y: y,
  35587. time: time,
  35588. snappedTime: snappedTime
  35589. };
  35590. };
  35591. /**
  35592. * Toggle Timeline rolling mode
  35593. */
  35594. Timeline.prototype.toggleRollingMode = function () {
  35595. if (this.range.rolling) {
  35596. this.range.stopRolling();
  35597. } else {
  35598. if (this.options.rollingMode == undefined) {
  35599. this.setOptions(this.options);
  35600. }
  35601. this.range.startRolling();
  35602. }
  35603. };
  35604. module.exports = Timeline;
  35605. /***/ }),
  35606. /* 179 */
  35607. /***/ (function(module, exports, __webpack_require__) {
  35608. "use strict";
  35609. Object.defineProperty(exports, "__esModule", {
  35610. value: true
  35611. });
  35612. var _stringify = __webpack_require__(19);
  35613. var _stringify2 = _interopRequireDefault(_stringify);
  35614. var _classCallCheck2 = __webpack_require__(0);
  35615. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  35616. var _createClass2 = __webpack_require__(1);
  35617. var _createClass3 = _interopRequireDefault(_createClass2);
  35618. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  35619. var Hammer = __webpack_require__(10);
  35620. var hammerUtil = __webpack_require__(37);
  35621. var util = __webpack_require__(2);
  35622. /**
  35623. * @param {number} [pixelRatio=1]
  35624. */
  35625. var ColorPicker = function () {
  35626. /**
  35627. * @param {number} [pixelRatio=1]
  35628. */
  35629. function ColorPicker() {
  35630. var pixelRatio = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
  35631. (0, _classCallCheck3['default'])(this, ColorPicker);
  35632. this.pixelRatio = pixelRatio;
  35633. this.generated = false;
  35634. this.centerCoordinates = { x: 289 / 2, y: 289 / 2 };
  35635. this.r = 289 * 0.49;
  35636. this.color = { r: 255, g: 255, b: 255, a: 1.0 };
  35637. this.hueCircle = undefined;
  35638. this.initialColor = { r: 255, g: 255, b: 255, a: 1.0 };
  35639. this.previousColor = undefined;
  35640. this.applied = false;
  35641. // bound by
  35642. this.updateCallback = function () {};
  35643. this.closeCallback = function () {};
  35644. // create all DOM elements
  35645. this._create();
  35646. }
  35647. /**
  35648. * this inserts the colorPicker into a div from the DOM
  35649. * @param {Element} container
  35650. */
  35651. (0, _createClass3['default'])(ColorPicker, [{
  35652. key: 'insertTo',
  35653. value: function insertTo(container) {
  35654. if (this.hammer !== undefined) {
  35655. this.hammer.destroy();
  35656. this.hammer = undefined;
  35657. }
  35658. this.container = container;
  35659. this.container.appendChild(this.frame);
  35660. this._bindHammer();
  35661. this._setSize();
  35662. }
  35663. /**
  35664. * the callback is executed on apply and save. Bind it to the application
  35665. * @param {function} callback
  35666. */
  35667. }, {
  35668. key: 'setUpdateCallback',
  35669. value: function setUpdateCallback(callback) {
  35670. if (typeof callback === 'function') {
  35671. this.updateCallback = callback;
  35672. } else {
  35673. throw new Error("Function attempted to set as colorPicker update callback is not a function.");
  35674. }
  35675. }
  35676. /**
  35677. * the callback is executed on apply and save. Bind it to the application
  35678. * @param {function} callback
  35679. */
  35680. }, {
  35681. key: 'setCloseCallback',
  35682. value: function setCloseCallback(callback) {
  35683. if (typeof callback === 'function') {
  35684. this.closeCallback = callback;
  35685. } else {
  35686. throw new Error("Function attempted to set as colorPicker closing callback is not a function.");
  35687. }
  35688. }
  35689. /**
  35690. *
  35691. * @param {string} color
  35692. * @returns {String}
  35693. * @private
  35694. */
  35695. }, {
  35696. key: '_isColorString',
  35697. value: function _isColorString(color) {
  35698. 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' };
  35699. if (typeof color === 'string') {
  35700. return htmlColors[color];
  35701. }
  35702. }
  35703. /**
  35704. * Set the color of the colorPicker
  35705. * Supported formats:
  35706. * 'red' --> HTML color string
  35707. * '#ffffff' --> hex string
  35708. * 'rbg(255,255,255)' --> rgb string
  35709. * 'rgba(255,255,255,1.0)' --> rgba string
  35710. * {r:255,g:255,b:255} --> rgb object
  35711. * {r:255,g:255,b:255,a:1.0} --> rgba object
  35712. * @param {string|Object} color
  35713. * @param {boolean} [setInitial=true]
  35714. */
  35715. }, {
  35716. key: 'setColor',
  35717. value: function setColor(color) {
  35718. var setInitial = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  35719. if (color === 'none') {
  35720. return;
  35721. }
  35722. var rgba = void 0;
  35723. // if a html color shorthand is used, convert to hex
  35724. var htmlColor = this._isColorString(color);
  35725. if (htmlColor !== undefined) {
  35726. color = htmlColor;
  35727. }
  35728. // check format
  35729. if (util.isString(color) === true) {
  35730. if (util.isValidRGB(color) === true) {
  35731. var rgbaArray = color.substr(4).substr(0, color.length - 5).split(',');
  35732. rgba = { r: rgbaArray[0], g: rgbaArray[1], b: rgbaArray[2], a: 1.0 };
  35733. } else if (util.isValidRGBA(color) === true) {
  35734. var _rgbaArray = color.substr(5).substr(0, color.length - 6).split(',');
  35735. rgba = { r: _rgbaArray[0], g: _rgbaArray[1], b: _rgbaArray[2], a: _rgbaArray[3] };
  35736. } else if (util.isValidHex(color) === true) {
  35737. var rgbObj = util.hexToRGB(color);
  35738. rgba = { r: rgbObj.r, g: rgbObj.g, b: rgbObj.b, a: 1.0 };
  35739. }
  35740. } else {
  35741. if (color instanceof Object) {
  35742. if (color.r !== undefined && color.g !== undefined && color.b !== undefined) {
  35743. var alpha = color.a !== undefined ? color.a : '1.0';
  35744. rgba = { r: color.r, g: color.g, b: color.b, a: alpha };
  35745. }
  35746. }
  35747. }
  35748. // set color
  35749. if (rgba === undefined) {
  35750. 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: " + (0, _stringify2['default'])(color));
  35751. } else {
  35752. this._setColor(rgba, setInitial);
  35753. }
  35754. }
  35755. /**
  35756. * this shows the color picker.
  35757. * The hue circle is constructed once and stored.
  35758. */
  35759. }, {
  35760. key: 'show',
  35761. value: function show() {
  35762. if (this.closeCallback !== undefined) {
  35763. this.closeCallback();
  35764. this.closeCallback = undefined;
  35765. }
  35766. this.applied = false;
  35767. this.frame.style.display = 'block';
  35768. this._generateHueCircle();
  35769. }
  35770. // ------------------------------------------ PRIVATE ----------------------------- //
  35771. /**
  35772. * Hide the picker. Is called by the cancel button.
  35773. * Optional boolean to store the previous color for easy access later on.
  35774. * @param {boolean} [storePrevious=true]
  35775. * @private
  35776. */
  35777. }, {
  35778. key: '_hide',
  35779. value: function _hide() {
  35780. var _this = this;
  35781. var storePrevious = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  35782. // store the previous color for next time;
  35783. if (storePrevious === true) {
  35784. this.previousColor = util.extend({}, this.color);
  35785. }
  35786. if (this.applied === true) {
  35787. this.updateCallback(this.initialColor);
  35788. }
  35789. this.frame.style.display = 'none';
  35790. // call the closing callback, restoring the onclick method.
  35791. // this is in a setTimeout because it will trigger the show again before the click is done.
  35792. setTimeout(function () {
  35793. if (_this.closeCallback !== undefined) {
  35794. _this.closeCallback();
  35795. _this.closeCallback = undefined;
  35796. }
  35797. }, 0);
  35798. }
  35799. /**
  35800. * bound to the save button. Saves and hides.
  35801. * @private
  35802. */
  35803. }, {
  35804. key: '_save',
  35805. value: function _save() {
  35806. this.updateCallback(this.color);
  35807. this.applied = false;
  35808. this._hide();
  35809. }
  35810. /**
  35811. * Bound to apply button. Saves but does not close. Is undone by the cancel button.
  35812. * @private
  35813. */
  35814. }, {
  35815. key: '_apply',
  35816. value: function _apply() {
  35817. this.applied = true;
  35818. this.updateCallback(this.color);
  35819. this._updatePicker(this.color);
  35820. }
  35821. /**
  35822. * load the color from the previous session.
  35823. * @private
  35824. */
  35825. }, {
  35826. key: '_loadLast',
  35827. value: function _loadLast() {
  35828. if (this.previousColor !== undefined) {
  35829. this.setColor(this.previousColor, false);
  35830. } else {
  35831. alert("There is no last color to load...");
  35832. }
  35833. }
  35834. /**
  35835. * set the color, place the picker
  35836. * @param {Object} rgba
  35837. * @param {boolean} [setInitial=true]
  35838. * @private
  35839. */
  35840. }, {
  35841. key: '_setColor',
  35842. value: function _setColor(rgba) {
  35843. var setInitial = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  35844. // store the initial color
  35845. if (setInitial === true) {
  35846. this.initialColor = util.extend({}, rgba);
  35847. }
  35848. this.color = rgba;
  35849. var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b);
  35850. var angleConvert = 2 * Math.PI;
  35851. var radius = this.r * hsv.s;
  35852. var x = this.centerCoordinates.x + radius * Math.sin(angleConvert * hsv.h);
  35853. var y = this.centerCoordinates.y + radius * Math.cos(angleConvert * hsv.h);
  35854. this.colorPickerSelector.style.left = x - 0.5 * this.colorPickerSelector.clientWidth + 'px';
  35855. this.colorPickerSelector.style.top = y - 0.5 * this.colorPickerSelector.clientHeight + 'px';
  35856. this._updatePicker(rgba);
  35857. }
  35858. /**
  35859. * bound to opacity control
  35860. * @param {number} value
  35861. * @private
  35862. */
  35863. }, {
  35864. key: '_setOpacity',
  35865. value: function _setOpacity(value) {
  35866. this.color.a = value / 100;
  35867. this._updatePicker(this.color);
  35868. }
  35869. /**
  35870. * bound to brightness control
  35871. * @param {number} value
  35872. * @private
  35873. */
  35874. }, {
  35875. key: '_setBrightness',
  35876. value: function _setBrightness(value) {
  35877. var hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b);
  35878. hsv.v = value / 100;
  35879. var rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v);
  35880. rgba['a'] = this.color.a;
  35881. this.color = rgba;
  35882. this._updatePicker();
  35883. }
  35884. /**
  35885. * update the color picker. A black circle overlays the hue circle to mimic the brightness decreasing.
  35886. * @param {Object} rgba
  35887. * @private
  35888. */
  35889. }, {
  35890. key: '_updatePicker',
  35891. value: function _updatePicker() {
  35892. var rgba = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.color;
  35893. var hsv = util.RGBToHSV(rgba.r, rgba.g, rgba.b);
  35894. var ctx = this.colorPickerCanvas.getContext('2d');
  35895. if (this.pixelRation === undefined) {
  35896. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
  35897. }
  35898. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  35899. // clear the canvas
  35900. var w = this.colorPickerCanvas.clientWidth;
  35901. var h = this.colorPickerCanvas.clientHeight;
  35902. ctx.clearRect(0, 0, w, h);
  35903. ctx.putImageData(this.hueCircle, 0, 0);
  35904. ctx.fillStyle = 'rgba(0,0,0,' + (1 - hsv.v) + ')';
  35905. ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
  35906. ctx.fill();
  35907. this.brightnessRange.value = 100 * hsv.v;
  35908. this.opacityRange.value = 100 * rgba.a;
  35909. this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')';
  35910. this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')';
  35911. }
  35912. /**
  35913. * used by create to set the size of the canvas.
  35914. * @private
  35915. */
  35916. }, {
  35917. key: '_setSize',
  35918. value: function _setSize() {
  35919. this.colorPickerCanvas.style.width = '100%';
  35920. this.colorPickerCanvas.style.height = '100%';
  35921. this.colorPickerCanvas.width = 289 * this.pixelRatio;
  35922. this.colorPickerCanvas.height = 289 * this.pixelRatio;
  35923. }
  35924. /**
  35925. * create all dom elements
  35926. * TODO: cleanup, lots of similar dom elements
  35927. * @private
  35928. */
  35929. }, {
  35930. key: '_create',
  35931. value: function _create() {
  35932. this.frame = document.createElement('div');
  35933. this.frame.className = 'vis-color-picker';
  35934. this.colorPickerDiv = document.createElement('div');
  35935. this.colorPickerSelector = document.createElement('div');
  35936. this.colorPickerSelector.className = 'vis-selector';
  35937. this.colorPickerDiv.appendChild(this.colorPickerSelector);
  35938. this.colorPickerCanvas = document.createElement('canvas');
  35939. this.colorPickerDiv.appendChild(this.colorPickerCanvas);
  35940. if (!this.colorPickerCanvas.getContext) {
  35941. var noCanvas = document.createElement('DIV');
  35942. noCanvas.style.color = 'red';
  35943. noCanvas.style.fontWeight = 'bold';
  35944. noCanvas.style.padding = '10px';
  35945. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  35946. this.colorPickerCanvas.appendChild(noCanvas);
  35947. } else {
  35948. var ctx = this.colorPickerCanvas.getContext("2d");
  35949. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
  35950. this.colorPickerCanvas.getContext("2d").setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  35951. }
  35952. this.colorPickerDiv.className = 'vis-color';
  35953. this.opacityDiv = document.createElement('div');
  35954. this.opacityDiv.className = 'vis-opacity';
  35955. this.brightnessDiv = document.createElement('div');
  35956. this.brightnessDiv.className = 'vis-brightness';
  35957. this.arrowDiv = document.createElement('div');
  35958. this.arrowDiv.className = 'vis-arrow';
  35959. this.opacityRange = document.createElement('input');
  35960. try {
  35961. this.opacityRange.type = 'range'; // Not supported on IE9
  35962. this.opacityRange.min = '0';
  35963. this.opacityRange.max = '100';
  35964. }
  35965. // TODO: Add some error handling and remove this lint exception
  35966. catch (err) {} // eslint-disable-line no-empty
  35967. this.opacityRange.value = '100';
  35968. this.opacityRange.className = 'vis-range';
  35969. this.brightnessRange = document.createElement('input');
  35970. try {
  35971. this.brightnessRange.type = 'range'; // Not supported on IE9
  35972. this.brightnessRange.min = '0';
  35973. this.brightnessRange.max = '100';
  35974. }
  35975. // TODO: Add some error handling and remove this lint exception
  35976. catch (err) {} // eslint-disable-line no-empty
  35977. this.brightnessRange.value = '100';
  35978. this.brightnessRange.className = 'vis-range';
  35979. this.opacityDiv.appendChild(this.opacityRange);
  35980. this.brightnessDiv.appendChild(this.brightnessRange);
  35981. var me = this;
  35982. this.opacityRange.onchange = function () {
  35983. me._setOpacity(this.value);
  35984. };
  35985. this.opacityRange.oninput = function () {
  35986. me._setOpacity(this.value);
  35987. };
  35988. this.brightnessRange.onchange = function () {
  35989. me._setBrightness(this.value);
  35990. };
  35991. this.brightnessRange.oninput = function () {
  35992. me._setBrightness(this.value);
  35993. };
  35994. this.brightnessLabel = document.createElement("div");
  35995. this.brightnessLabel.className = "vis-label vis-brightness";
  35996. this.brightnessLabel.innerHTML = 'brightness:';
  35997. this.opacityLabel = document.createElement("div");
  35998. this.opacityLabel.className = "vis-label vis-opacity";
  35999. this.opacityLabel.innerHTML = 'opacity:';
  36000. this.newColorDiv = document.createElement("div");
  36001. this.newColorDiv.className = "vis-new-color";
  36002. this.newColorDiv.innerHTML = 'new';
  36003. this.initialColorDiv = document.createElement("div");
  36004. this.initialColorDiv.className = "vis-initial-color";
  36005. this.initialColorDiv.innerHTML = 'initial';
  36006. this.cancelButton = document.createElement("div");
  36007. this.cancelButton.className = "vis-button vis-cancel";
  36008. this.cancelButton.innerHTML = 'cancel';
  36009. this.cancelButton.onclick = this._hide.bind(this, false);
  36010. this.applyButton = document.createElement("div");
  36011. this.applyButton.className = "vis-button vis-apply";
  36012. this.applyButton.innerHTML = 'apply';
  36013. this.applyButton.onclick = this._apply.bind(this);
  36014. this.saveButton = document.createElement("div");
  36015. this.saveButton.className = "vis-button vis-save";
  36016. this.saveButton.innerHTML = 'save';
  36017. this.saveButton.onclick = this._save.bind(this);
  36018. this.loadButton = document.createElement("div");
  36019. this.loadButton.className = "vis-button vis-load";
  36020. this.loadButton.innerHTML = 'load last';
  36021. this.loadButton.onclick = this._loadLast.bind(this);
  36022. this.frame.appendChild(this.colorPickerDiv);
  36023. this.frame.appendChild(this.arrowDiv);
  36024. this.frame.appendChild(this.brightnessLabel);
  36025. this.frame.appendChild(this.brightnessDiv);
  36026. this.frame.appendChild(this.opacityLabel);
  36027. this.frame.appendChild(this.opacityDiv);
  36028. this.frame.appendChild(this.newColorDiv);
  36029. this.frame.appendChild(this.initialColorDiv);
  36030. this.frame.appendChild(this.cancelButton);
  36031. this.frame.appendChild(this.applyButton);
  36032. this.frame.appendChild(this.saveButton);
  36033. this.frame.appendChild(this.loadButton);
  36034. }
  36035. /**
  36036. * bind hammer to the color picker
  36037. * @private
  36038. */
  36039. }, {
  36040. key: '_bindHammer',
  36041. value: function _bindHammer() {
  36042. var _this2 = this;
  36043. this.drag = {};
  36044. this.pinch = {};
  36045. this.hammer = new Hammer(this.colorPickerCanvas);
  36046. this.hammer.get('pinch').set({ enable: true });
  36047. hammerUtil.onTouch(this.hammer, function (event) {
  36048. _this2._moveSelector(event);
  36049. });
  36050. this.hammer.on('tap', function (event) {
  36051. _this2._moveSelector(event);
  36052. });
  36053. this.hammer.on('panstart', function (event) {
  36054. _this2._moveSelector(event);
  36055. });
  36056. this.hammer.on('panmove', function (event) {
  36057. _this2._moveSelector(event);
  36058. });
  36059. this.hammer.on('panend', function (event) {
  36060. _this2._moveSelector(event);
  36061. });
  36062. }
  36063. /**
  36064. * generate the hue circle. This is relatively heavy (200ms) and is done only once on the first time it is shown.
  36065. * @private
  36066. */
  36067. }, {
  36068. key: '_generateHueCircle',
  36069. value: function _generateHueCircle() {
  36070. if (this.generated === false) {
  36071. var ctx = this.colorPickerCanvas.getContext('2d');
  36072. if (this.pixelRation === undefined) {
  36073. this.pixelRatio = (window.devicePixelRatio || 1) / (ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1);
  36074. }
  36075. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  36076. // clear the canvas
  36077. var w = this.colorPickerCanvas.clientWidth;
  36078. var h = this.colorPickerCanvas.clientHeight;
  36079. ctx.clearRect(0, 0, w, h);
  36080. // draw hue circle
  36081. var x = void 0,
  36082. y = void 0,
  36083. hue = void 0,
  36084. sat = void 0;
  36085. this.centerCoordinates = { x: w * 0.5, y: h * 0.5 };
  36086. this.r = 0.49 * w;
  36087. var angleConvert = 2 * Math.PI / 360;
  36088. var hfac = 1 / 360;
  36089. var sfac = 1 / this.r;
  36090. var rgb = void 0;
  36091. for (hue = 0; hue < 360; hue++) {
  36092. for (sat = 0; sat < this.r; sat++) {
  36093. x = this.centerCoordinates.x + sat * Math.sin(angleConvert * hue);
  36094. y = this.centerCoordinates.y + sat * Math.cos(angleConvert * hue);
  36095. rgb = util.HSVToRGB(hue * hfac, sat * sfac, 1);
  36096. ctx.fillStyle = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
  36097. ctx.fillRect(x - 0.5, y - 0.5, 2, 2);
  36098. }
  36099. }
  36100. ctx.strokeStyle = 'rgba(0,0,0,1)';
  36101. ctx.circle(this.centerCoordinates.x, this.centerCoordinates.y, this.r);
  36102. ctx.stroke();
  36103. this.hueCircle = ctx.getImageData(0, 0, w, h);
  36104. }
  36105. this.generated = true;
  36106. }
  36107. /**
  36108. * move the selector. This is called by hammer functions.
  36109. *
  36110. * @param {Event} event The event
  36111. * @private
  36112. */
  36113. }, {
  36114. key: '_moveSelector',
  36115. value: function _moveSelector(event) {
  36116. var rect = this.colorPickerDiv.getBoundingClientRect();
  36117. var left = event.center.x - rect.left;
  36118. var top = event.center.y - rect.top;
  36119. var centerY = 0.5 * this.colorPickerDiv.clientHeight;
  36120. var centerX = 0.5 * this.colorPickerDiv.clientWidth;
  36121. var x = left - centerX;
  36122. var y = top - centerY;
  36123. var angle = Math.atan2(x, y);
  36124. var radius = 0.98 * Math.min(Math.sqrt(x * x + y * y), centerX);
  36125. var newTop = Math.cos(angle) * radius + centerY;
  36126. var newLeft = Math.sin(angle) * radius + centerX;
  36127. this.colorPickerSelector.style.top = newTop - 0.5 * this.colorPickerSelector.clientHeight + 'px';
  36128. this.colorPickerSelector.style.left = newLeft - 0.5 * this.colorPickerSelector.clientWidth + 'px';
  36129. // set color
  36130. var h = angle / (2 * Math.PI);
  36131. h = h < 0 ? h + 1 : h;
  36132. var s = radius / this.r;
  36133. var hsv = util.RGBToHSV(this.color.r, this.color.g, this.color.b);
  36134. hsv.h = h;
  36135. hsv.s = s;
  36136. var rgba = util.HSVToRGB(hsv.h, hsv.s, hsv.v);
  36137. rgba['a'] = this.color.a;
  36138. this.color = rgba;
  36139. // update previews
  36140. this.initialColorDiv.style.backgroundColor = 'rgba(' + this.initialColor.r + ',' + this.initialColor.g + ',' + this.initialColor.b + ',' + this.initialColor.a + ')';
  36141. this.newColorDiv.style.backgroundColor = 'rgba(' + this.color.r + ',' + this.color.g + ',' + this.color.b + ',' + this.color.a + ')';
  36142. }
  36143. }]);
  36144. return ColorPicker;
  36145. }();
  36146. exports['default'] = ColorPicker;
  36147. /***/ }),
  36148. /* 180 */
  36149. /***/ (function(module, exports, __webpack_require__) {
  36150. "use strict";
  36151. var moment = __webpack_require__(9);
  36152. var util = __webpack_require__(2);
  36153. var DataSet = __webpack_require__(11);
  36154. var DataView = __webpack_require__(12);
  36155. var Range = __webpack_require__(64);
  36156. var Core = __webpack_require__(65);
  36157. var TimeAxis = __webpack_require__(45);
  36158. var CurrentTime = __webpack_require__(67);
  36159. var CustomTime = __webpack_require__(46);
  36160. var LineGraph = __webpack_require__(106);
  36161. var printStyle = __webpack_require__(15).printStyle;
  36162. var allOptions = __webpack_require__(113).allOptions;
  36163. var configureOptions = __webpack_require__(113).configureOptions;
  36164. var Configurator = __webpack_require__(71)['default'];
  36165. var Validator = __webpack_require__(15)['default'];
  36166. /**
  36167. * Create a timeline visualization
  36168. * @param {HTMLElement} container
  36169. * @param {vis.DataSet | Array} [items]
  36170. * @param {vis.DataSet | Array | vis.DataView | Object} [groups]
  36171. * @param {Object} [options] See Graph2d.setOptions for the available options.
  36172. * @constructor Graph2d
  36173. * @extends Core
  36174. */
  36175. function Graph2d(container, items, groups, options) {
  36176. // if the third element is options, the forth is groups (optionally);
  36177. if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) {
  36178. var forthArgument = options;
  36179. options = groups;
  36180. groups = forthArgument;
  36181. }
  36182. // TODO: REMOVE THIS in the next MAJOR release
  36183. // see https://github.com/almende/vis/issues/2511
  36184. if (options && options.throttleRedraw) {
  36185. console.warn("Graph2d option \"throttleRedraw\" is DEPRICATED and no longer supported. It will be removed in the next MAJOR release.");
  36186. }
  36187. var me = this;
  36188. this.defaultOptions = {
  36189. start: null,
  36190. end: null,
  36191. autoResize: true,
  36192. orientation: {
  36193. axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both'
  36194. item: 'bottom' // not relevant for Graph2d
  36195. },
  36196. moment: moment,
  36197. width: null,
  36198. height: null,
  36199. maxHeight: null,
  36200. minHeight: null
  36201. };
  36202. this.options = util.deepExtend({}, this.defaultOptions);
  36203. // Create the DOM, props, and emitter
  36204. this._create(container);
  36205. // all components listed here will be repainted automatically
  36206. this.components = [];
  36207. this.body = {
  36208. dom: this.dom,
  36209. domProps: this.props,
  36210. emitter: {
  36211. on: this.on.bind(this),
  36212. off: this.off.bind(this),
  36213. emit: this.emit.bind(this)
  36214. },
  36215. hiddenDates: [],
  36216. util: {
  36217. toScreen: me._toScreen.bind(me),
  36218. toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
  36219. toTime: me._toTime.bind(me),
  36220. toGlobalTime: me._toGlobalTime.bind(me)
  36221. }
  36222. };
  36223. // range
  36224. this.range = new Range(this.body);
  36225. this.components.push(this.range);
  36226. this.body.range = this.range;
  36227. // time axis
  36228. this.timeAxis = new TimeAxis(this.body);
  36229. this.components.push(this.timeAxis);
  36230. //this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis);
  36231. // current time bar
  36232. this.currentTime = new CurrentTime(this.body);
  36233. this.components.push(this.currentTime);
  36234. // item set
  36235. this.linegraph = new LineGraph(this.body);
  36236. this.components.push(this.linegraph);
  36237. this.itemsData = null; // DataSet
  36238. this.groupsData = null; // DataSet
  36239. this.on('tap', function (event) {
  36240. me.emit('click', me.getEventProperties(event));
  36241. });
  36242. this.on('doubletap', function (event) {
  36243. me.emit('doubleClick', me.getEventProperties(event));
  36244. });
  36245. this.dom.root.oncontextmenu = function (event) {
  36246. me.emit('contextmenu', me.getEventProperties(event));
  36247. };
  36248. // apply options
  36249. if (options) {
  36250. this.setOptions(options);
  36251. }
  36252. // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
  36253. if (groups) {
  36254. this.setGroups(groups);
  36255. }
  36256. // create itemset
  36257. if (items) {
  36258. this.setItems(items);
  36259. }
  36260. // draw for the first time
  36261. this._redraw();
  36262. }
  36263. // Extend the functionality from Core
  36264. Graph2d.prototype = new Core();
  36265. Graph2d.prototype.setOptions = function (options) {
  36266. // validate options
  36267. var errorFound = Validator.validate(options, allOptions);
  36268. if (errorFound === true) {
  36269. console.log('%cErrors have been found in the supplied options object.', printStyle);
  36270. }
  36271. Core.prototype.setOptions.call(this, options);
  36272. };
  36273. /**
  36274. * Set items
  36275. * @param {vis.DataSet | Array | null} items
  36276. */
  36277. Graph2d.prototype.setItems = function (items) {
  36278. var initialLoad = this.itemsData == null;
  36279. // convert to type DataSet when needed
  36280. var newDataSet;
  36281. if (!items) {
  36282. newDataSet = null;
  36283. } else if (items instanceof DataSet || items instanceof DataView) {
  36284. newDataSet = items;
  36285. } else {
  36286. // turn an array into a dataset
  36287. newDataSet = new DataSet(items, {
  36288. type: {
  36289. start: 'Date',
  36290. end: 'Date'
  36291. }
  36292. });
  36293. }
  36294. // set items
  36295. this.itemsData = newDataSet;
  36296. this.linegraph && this.linegraph.setItems(newDataSet);
  36297. if (initialLoad) {
  36298. if (this.options.start != undefined || this.options.end != undefined) {
  36299. var start = this.options.start != undefined ? this.options.start : null;
  36300. var end = this.options.end != undefined ? this.options.end : null;
  36301. this.setWindow(start, end, { animation: false });
  36302. } else {
  36303. this.fit({ animation: false });
  36304. }
  36305. }
  36306. };
  36307. /**
  36308. * Set groups
  36309. * @param {vis.DataSet | Array} groups
  36310. */
  36311. Graph2d.prototype.setGroups = function (groups) {
  36312. // convert to type DataSet when needed
  36313. var newDataSet;
  36314. if (!groups) {
  36315. newDataSet = null;
  36316. } else if (groups instanceof DataSet || groups instanceof DataView) {
  36317. newDataSet = groups;
  36318. } else {
  36319. // turn an array into a dataset
  36320. newDataSet = new DataSet(groups);
  36321. }
  36322. this.groupsData = newDataSet;
  36323. this.linegraph.setGroups(newDataSet);
  36324. };
  36325. /**
  36326. * 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).
  36327. * @param {vis.GraphGroup.id} groupId
  36328. * @param {number} width
  36329. * @param {number} height
  36330. * @returns {{icon: SVGElement, label: string, orientation: string}|string}
  36331. */
  36332. Graph2d.prototype.getLegend = function (groupId, width, height) {
  36333. if (width === undefined) {
  36334. width = 15;
  36335. }
  36336. if (height === undefined) {
  36337. height = 15;
  36338. }
  36339. if (this.linegraph.groups[groupId] !== undefined) {
  36340. return this.linegraph.groups[groupId].getLegend(width, height);
  36341. } else {
  36342. return "cannot find group:'" + groupId + "'";
  36343. }
  36344. };
  36345. /**
  36346. * This checks if the visible option of the supplied group (by ID) is true or false.
  36347. * @param {vis.GraphGroup.id} groupId
  36348. * @returns {boolean}
  36349. */
  36350. Graph2d.prototype.isGroupVisible = function (groupId) {
  36351. if (this.linegraph.groups[groupId] !== undefined) {
  36352. return this.linegraph.groups[groupId].visible && (this.linegraph.options.groups.visibility[groupId] === undefined || this.linegraph.options.groups.visibility[groupId] == true);
  36353. } else {
  36354. return false;
  36355. }
  36356. };
  36357. /**
  36358. * Get the data range of the item set.
  36359. * @returns {{min: Date, max: Date}} range A range with a start and end Date.
  36360. * When no minimum is found, min==null
  36361. * When no maximum is found, max==null
  36362. */
  36363. Graph2d.prototype.getDataRange = function () {
  36364. var min = null;
  36365. var max = null;
  36366. // calculate min from start filed
  36367. for (var groupId in this.linegraph.groups) {
  36368. if (this.linegraph.groups.hasOwnProperty(groupId)) {
  36369. if (this.linegraph.groups[groupId].visible == true) {
  36370. for (var i = 0; i < this.linegraph.groups[groupId].itemsData.length; i++) {
  36371. var item = this.linegraph.groups[groupId].itemsData[i];
  36372. var value = util.convert(item.x, 'Date').valueOf();
  36373. min = min == null ? value : min > value ? value : min;
  36374. max = max == null ? value : max < value ? value : max;
  36375. }
  36376. }
  36377. }
  36378. }
  36379. return {
  36380. min: min != null ? new Date(min) : null,
  36381. max: max != null ? new Date(max) : null
  36382. };
  36383. };
  36384. /**
  36385. * Generate Timeline related information from an event
  36386. * @param {Event} event
  36387. * @return {Object} An object with related information, like on which area
  36388. * The event happened, whether clicked on an item, etc.
  36389. */
  36390. Graph2d.prototype.getEventProperties = function (event) {
  36391. var clientX = event.center ? event.center.x : event.clientX;
  36392. var clientY = event.center ? event.center.y : event.clientY;
  36393. var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
  36394. var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
  36395. var time = this._toTime(x);
  36396. var customTime = CustomTime.customTimeFromTarget(event);
  36397. var element = util.getTarget(event);
  36398. var what = null;
  36399. if (util.hasParent(element, this.timeAxis.dom.foreground)) {
  36400. what = 'axis';
  36401. } else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {
  36402. what = 'axis';
  36403. } else if (util.hasParent(element, this.linegraph.yAxisLeft.dom.frame)) {
  36404. what = 'data-axis';
  36405. } else if (util.hasParent(element, this.linegraph.yAxisRight.dom.frame)) {
  36406. what = 'data-axis';
  36407. } else if (util.hasParent(element, this.linegraph.legendLeft.dom.frame)) {
  36408. what = 'legend';
  36409. } else if (util.hasParent(element, this.linegraph.legendRight.dom.frame)) {
  36410. what = 'legend';
  36411. } else if (customTime != null) {
  36412. what = 'custom-time';
  36413. } else if (util.hasParent(element, this.currentTime.bar)) {
  36414. what = 'current-time';
  36415. } else if (util.hasParent(element, this.dom.center)) {
  36416. what = 'background';
  36417. }
  36418. var value = [];
  36419. var yAxisLeft = this.linegraph.yAxisLeft;
  36420. var yAxisRight = this.linegraph.yAxisRight;
  36421. if (!yAxisLeft.hidden && this.itemsData.length > 0) {
  36422. value.push(yAxisLeft.screenToValue(y));
  36423. }
  36424. if (!yAxisRight.hidden && this.itemsData.length > 0) {
  36425. value.push(yAxisRight.screenToValue(y));
  36426. }
  36427. return {
  36428. event: event,
  36429. what: what,
  36430. pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
  36431. pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
  36432. x: x,
  36433. y: y,
  36434. time: time,
  36435. value: value
  36436. };
  36437. };
  36438. /**
  36439. * Load a configurator
  36440. * @return {Object}
  36441. * @private
  36442. */
  36443. Graph2d.prototype._createConfigurator = function () {
  36444. return new Configurator(this, this.dom.container, configureOptions);
  36445. };
  36446. module.exports = Graph2d;
  36447. /***/ }),
  36448. /* 181 */
  36449. /***/ (function(module, exports, __webpack_require__) {
  36450. "use strict";
  36451. // utils
  36452. exports.util = __webpack_require__(2);
  36453. exports.DOMutil = __webpack_require__(14);
  36454. // data
  36455. exports.DataSet = __webpack_require__(11);
  36456. exports.DataView = __webpack_require__(12);
  36457. exports.Queue = __webpack_require__(43);
  36458. // Network
  36459. exports.Network = __webpack_require__(182);
  36460. exports.network = {
  36461. Images: __webpack_require__(116),
  36462. dotparser: __webpack_require__(114),
  36463. gephiParser: __webpack_require__(115),
  36464. allOptions: __webpack_require__(122)
  36465. };
  36466. exports.network.convertDot = function (input) {
  36467. return exports.network.dotparser.DOTToGraph(input);
  36468. };
  36469. exports.network.convertGephi = function (input, options) {
  36470. return exports.network.gephiParser.parseGephi(input, options);
  36471. };
  36472. // bundled external libraries
  36473. exports.moment = __webpack_require__(9);
  36474. exports.Hammer = __webpack_require__(10);
  36475. exports.keycharm = __webpack_require__(35);
  36476. /***/ }),
  36477. /* 182 */
  36478. /***/ (function(module, exports, __webpack_require__) {
  36479. "use strict";
  36480. // Load custom shapes into CanvasRenderingContext2D
  36481. __webpack_require__(183);
  36482. var Emitter = __webpack_require__(44);
  36483. var util = __webpack_require__(2);
  36484. var dotparser = __webpack_require__(114);
  36485. var gephiParser = __webpack_require__(115);
  36486. var Activator = __webpack_require__(97);
  36487. var locales = __webpack_require__(184);
  36488. var Images = __webpack_require__(116)['default'];
  36489. var Groups = __webpack_require__(186)['default'];
  36490. var NodesHandler = __webpack_require__(187)['default'];
  36491. var EdgesHandler = __webpack_require__(214)['default'];
  36492. var PhysicsEngine = __webpack_require__(220)['default'];
  36493. var ClusterEngine = __webpack_require__(227)['default'];
  36494. var CanvasRenderer = __webpack_require__(229)['default'];
  36495. var Canvas = __webpack_require__(230)['default'];
  36496. var View = __webpack_require__(231)['default'];
  36497. var InteractionHandler = __webpack_require__(232)['default'];
  36498. var SelectionHandler = __webpack_require__(234)['default'];
  36499. var LayoutEngine = __webpack_require__(235)['default'];
  36500. var ManipulationSystem = __webpack_require__(237)['default'];
  36501. var Configurator = __webpack_require__(71)['default'];
  36502. var Validator = __webpack_require__(15)['default'];
  36503. var _require = __webpack_require__(15),
  36504. printStyle = _require.printStyle;
  36505. var _require2 = __webpack_require__(122),
  36506. allOptions = _require2.allOptions,
  36507. configureOptions = _require2.configureOptions;
  36508. var KamadaKawai = __webpack_require__(238)['default'];
  36509. /**
  36510. * Create a network visualization, displaying nodes and edges.
  36511. *
  36512. * @param {Element} container The DOM element in which the Network will
  36513. * be created. Normally a div element.
  36514. * @param {Object} data An object containing parameters
  36515. * {Array} nodes
  36516. * {Array} edges
  36517. * @param {Object} options Options
  36518. * @constructor Network
  36519. */
  36520. function Network(container, data, options) {
  36521. var _this = this;
  36522. if (!(this instanceof Network)) {
  36523. throw new SyntaxError('Constructor must be called with the new operator');
  36524. }
  36525. // set constant values
  36526. this.options = {};
  36527. this.defaultOptions = {
  36528. locale: 'en',
  36529. locales: locales,
  36530. clickToUse: false
  36531. };
  36532. util.extend(this.options, this.defaultOptions);
  36533. /**
  36534. * Containers for nodes and edges.
  36535. *
  36536. * 'edges' and 'nodes' contain the full definitions of all the network elements.
  36537. * 'nodeIndices' and 'edgeIndices' contain the id's of the active elements.
  36538. *
  36539. * The distinction is important, because a defined node need not be active, i.e.
  36540. * visible on the canvas. This happens in particular when clusters are defined, in
  36541. * that case there will be nodes and edges not displayed.
  36542. * The bottom line is that all code with actions related to visibility, *must* use
  36543. * 'nodeIndices' and 'edgeIndices', not 'nodes' and 'edges' directly.
  36544. */
  36545. this.body = {
  36546. container: container,
  36547. // See comment above for following fields
  36548. nodes: {},
  36549. nodeIndices: [],
  36550. edges: {},
  36551. edgeIndices: [],
  36552. emitter: {
  36553. on: this.on.bind(this),
  36554. off: this.off.bind(this),
  36555. emit: this.emit.bind(this),
  36556. once: this.once.bind(this)
  36557. },
  36558. eventListeners: {
  36559. onTap: function onTap() {},
  36560. onTouch: function onTouch() {},
  36561. onDoubleTap: function onDoubleTap() {},
  36562. onHold: function onHold() {},
  36563. onDragStart: function onDragStart() {},
  36564. onDrag: function onDrag() {},
  36565. onDragEnd: function onDragEnd() {},
  36566. onMouseWheel: function onMouseWheel() {},
  36567. onPinch: function onPinch() {},
  36568. onMouseMove: function onMouseMove() {},
  36569. onRelease: function onRelease() {},
  36570. onContext: function onContext() {}
  36571. },
  36572. data: {
  36573. nodes: null, // A DataSet or DataView
  36574. edges: null // A DataSet or DataView
  36575. },
  36576. functions: {
  36577. createNode: function createNode() {},
  36578. createEdge: function createEdge() {},
  36579. getPointer: function getPointer() {}
  36580. },
  36581. modules: {},
  36582. view: {
  36583. scale: 1,
  36584. translation: { x: 0, y: 0 }
  36585. }
  36586. };
  36587. // bind the event listeners
  36588. this.bindEventListeners();
  36589. // setting up all modules
  36590. this.images = new Images(function () {
  36591. return _this.body.emitter.emit("_requestRedraw");
  36592. }); // object with images
  36593. this.groups = new Groups(); // object with groups
  36594. this.canvas = new Canvas(this.body); // DOM handler
  36595. this.selectionHandler = new SelectionHandler(this.body, this.canvas); // Selection handler
  36596. this.interactionHandler = new InteractionHandler(this.body, this.canvas, this.selectionHandler); // Interaction handler handles all the hammer bindings (that are bound by canvas), key
  36597. this.view = new View(this.body, this.canvas); // camera handler, does animations and zooms
  36598. this.renderer = new CanvasRenderer(this.body, this.canvas); // renderer, starts renderloop, has events that modules can hook into
  36599. this.physics = new PhysicsEngine(this.body); // physics engine, does all the simulations
  36600. this.layoutEngine = new LayoutEngine(this.body); // layout engine for inital layout and hierarchical layout
  36601. this.clustering = new ClusterEngine(this.body); // clustering api
  36602. this.manipulation = new ManipulationSystem(this.body, this.canvas, this.selectionHandler); // data manipulation system
  36603. this.nodesHandler = new NodesHandler(this.body, this.images, this.groups, this.layoutEngine); // Handle adding, deleting and updating of nodes as well as global options
  36604. this.edgesHandler = new EdgesHandler(this.body, this.images, this.groups); // Handle adding, deleting and updating of edges as well as global options
  36605. this.body.modules["kamadaKawai"] = new KamadaKawai(this.body, 150, 0.05); // Layouting algorithm.
  36606. this.body.modules["clustering"] = this.clustering;
  36607. // create the DOM elements
  36608. this.canvas._create();
  36609. // apply options
  36610. this.setOptions(options);
  36611. // load data (the disable start variable will be the same as the enabled clustering)
  36612. this.setData(data);
  36613. }
  36614. // Extend Network with an Emitter mixin
  36615. Emitter(Network.prototype);
  36616. /**
  36617. * Set options
  36618. * @param {Object} options
  36619. */
  36620. Network.prototype.setOptions = function (options) {
  36621. var _this2 = this;
  36622. if (options !== undefined) {
  36623. var errorFound = Validator.validate(options, allOptions);
  36624. if (errorFound === true) {
  36625. console.log('%cErrors have been found in the supplied options object.', printStyle);
  36626. }
  36627. // copy the global fields over
  36628. var fields = ['locale', 'locales', 'clickToUse'];
  36629. util.selectiveDeepExtend(fields, this.options, options);
  36630. // the hierarchical system can adapt the edges and the physics to it's own options because not all combinations work with the hierarichical system.
  36631. options = this.layoutEngine.setOptions(options.layout, options);
  36632. this.canvas.setOptions(options); // options for canvas are in globals
  36633. // pass the options to the modules
  36634. this.groups.setOptions(options.groups);
  36635. this.nodesHandler.setOptions(options.nodes);
  36636. this.edgesHandler.setOptions(options.edges);
  36637. this.physics.setOptions(options.physics);
  36638. this.manipulation.setOptions(options.manipulation, options, this.options); // manipulation uses the locales in the globals
  36639. this.interactionHandler.setOptions(options.interaction);
  36640. this.renderer.setOptions(options.interaction); // options for rendering are in interaction
  36641. this.selectionHandler.setOptions(options.interaction); // options for selection are in interaction
  36642. // reload the settings of the nodes to apply changes in groups that are not referenced by pointer.
  36643. if (options.groups !== undefined) {
  36644. this.body.emitter.emit("refreshNodes");
  36645. }
  36646. // these two do not have options at the moment, here for completeness
  36647. //this.view.setOptions(options.view);
  36648. //this.clustering.setOptions(options.clustering);
  36649. if ('configure' in options) {
  36650. if (!this.configurator) {
  36651. this.configurator = new Configurator(this, this.body.container, configureOptions, this.canvas.pixelRatio);
  36652. }
  36653. this.configurator.setOptions(options.configure);
  36654. }
  36655. // if the configuration system is enabled, copy all options and put them into the config system
  36656. if (this.configurator && this.configurator.options.enabled === true) {
  36657. var networkOptions = { nodes: {}, edges: {}, layout: {}, interaction: {}, manipulation: {}, physics: {}, global: {} };
  36658. util.deepExtend(networkOptions.nodes, this.nodesHandler.options);
  36659. util.deepExtend(networkOptions.edges, this.edgesHandler.options);
  36660. util.deepExtend(networkOptions.layout, this.layoutEngine.options);
  36661. // load the selectionHandler and render default options in to the interaction group
  36662. util.deepExtend(networkOptions.interaction, this.selectionHandler.options);
  36663. util.deepExtend(networkOptions.interaction, this.renderer.options);
  36664. util.deepExtend(networkOptions.interaction, this.interactionHandler.options);
  36665. util.deepExtend(networkOptions.manipulation, this.manipulation.options);
  36666. util.deepExtend(networkOptions.physics, this.physics.options);
  36667. // load globals into the global object
  36668. util.deepExtend(networkOptions.global, this.canvas.options);
  36669. util.deepExtend(networkOptions.global, this.options);
  36670. this.configurator.setModuleOptions(networkOptions);
  36671. }
  36672. // handle network global options
  36673. if (options.clickToUse !== undefined) {
  36674. if (options.clickToUse === true) {
  36675. if (this.activator === undefined) {
  36676. this.activator = new Activator(this.canvas.frame);
  36677. this.activator.on('change', function () {
  36678. _this2.body.emitter.emit("activate");
  36679. });
  36680. }
  36681. } else {
  36682. if (this.activator !== undefined) {
  36683. this.activator.destroy();
  36684. delete this.activator;
  36685. }
  36686. this.body.emitter.emit("activate");
  36687. }
  36688. } else {
  36689. this.body.emitter.emit("activate");
  36690. }
  36691. this.canvas.setSize();
  36692. // start the physics simulation. Can be safely called multiple times.
  36693. this.body.emitter.emit("startSimulation");
  36694. }
  36695. };
  36696. /**
  36697. * Update the visible nodes and edges list with the most recent node state.
  36698. *
  36699. * Visible nodes are stored in this.body.nodeIndices.
  36700. * Visible edges are stored in this.body.edgeIndices.
  36701. * A node or edges is visible if it is not hidden or clustered.
  36702. *
  36703. * @private
  36704. */
  36705. Network.prototype._updateVisibleIndices = function () {
  36706. var nodes = this.body.nodes;
  36707. var edges = this.body.edges;
  36708. this.body.nodeIndices = [];
  36709. this.body.edgeIndices = [];
  36710. for (var nodeId in nodes) {
  36711. if (nodes.hasOwnProperty(nodeId)) {
  36712. if (!this.clustering._isClusteredNode(nodeId) && nodes[nodeId].options.hidden === false) {
  36713. this.body.nodeIndices.push(nodes[nodeId].id);
  36714. }
  36715. }
  36716. }
  36717. for (var edgeId in edges) {
  36718. if (edges.hasOwnProperty(edgeId)) {
  36719. var edge = edges[edgeId];
  36720. // It can happen that this is executed *after* a node edge has been removed,
  36721. // but *before* the edge itself has been removed. Taking this into account.
  36722. var fromNode = nodes[edge.fromId];
  36723. var toNode = nodes[edge.toId];
  36724. var edgeNodesPresent = fromNode !== undefined && toNode !== undefined;
  36725. var isVisible = !this.clustering._isClusteredEdge(edgeId) && edge.options.hidden === false && edgeNodesPresent && fromNode.options.hidden === false // Also hidden if any of its connecting nodes are hidden
  36726. && toNode.options.hidden === false; // idem
  36727. if (isVisible) {
  36728. this.body.edgeIndices.push(edge.id);
  36729. }
  36730. }
  36731. }
  36732. };
  36733. /**
  36734. * Bind all events
  36735. */
  36736. Network.prototype.bindEventListeners = function () {
  36737. var _this3 = this;
  36738. // This event will trigger a rebuilding of the cache everything.
  36739. // Used when nodes or edges have been added or removed.
  36740. this.body.emitter.on("_dataChanged", function () {
  36741. _this3.edgesHandler._updateState();
  36742. _this3.body.emitter.emit("_dataUpdated");
  36743. });
  36744. // this is called when options of EXISTING nodes or edges have changed.
  36745. this.body.emitter.on("_dataUpdated", function () {
  36746. // Order important in following block
  36747. _this3.clustering._updateState();
  36748. _this3._updateVisibleIndices();
  36749. _this3._updateValueRange(_this3.body.nodes);
  36750. _this3._updateValueRange(_this3.body.edges);
  36751. // start simulation (can be called safely, even if already running)
  36752. _this3.body.emitter.emit("startSimulation");
  36753. _this3.body.emitter.emit("_requestRedraw");
  36754. });
  36755. };
  36756. /**
  36757. * Set nodes and edges, and optionally options as well.
  36758. *
  36759. * @param {Object} data Object containing parameters:
  36760. * {Array | DataSet | DataView} [nodes] Array with nodes
  36761. * {Array | DataSet | DataView} [edges] Array with edges
  36762. * {String} [dot] String containing data in DOT format
  36763. * {String} [gephi] String containing data in gephi JSON format
  36764. * {Options} [options] Object with options
  36765. */
  36766. Network.prototype.setData = function (data) {
  36767. // reset the physics engine.
  36768. this.body.emitter.emit("resetPhysics");
  36769. this.body.emitter.emit("_resetData");
  36770. // unselect all to ensure no selections from old data are carried over.
  36771. this.selectionHandler.unselectAll();
  36772. if (data && data.dot && (data.nodes || data.edges)) {
  36773. throw new SyntaxError('Data must contain either parameter "dot" or ' + ' parameter pair "nodes" and "edges", but not both.');
  36774. }
  36775. // set options
  36776. this.setOptions(data && data.options);
  36777. // set all data
  36778. if (data && data.dot) {
  36779. console.log('The dot property has been deprecated. 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);');
  36780. // parse DOT file
  36781. var dotData = dotparser.DOTToGraph(data.dot);
  36782. this.setData(dotData);
  36783. return;
  36784. } else if (data && data.gephi) {
  36785. // parse DOT file
  36786. console.log('The gephi property has been deprecated. 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);');
  36787. var gephiData = gephiParser.parseGephi(data.gephi);
  36788. this.setData(gephiData);
  36789. return;
  36790. } else {
  36791. this.nodesHandler.setData(data && data.nodes, true);
  36792. this.edgesHandler.setData(data && data.edges, true);
  36793. }
  36794. // emit change in data
  36795. this.body.emitter.emit("_dataChanged");
  36796. // emit data loaded
  36797. this.body.emitter.emit("_dataLoaded");
  36798. // find a stable position or start animating to a stable position
  36799. this.body.emitter.emit("initPhysics");
  36800. };
  36801. /**
  36802. * Cleans up all bindings of the network, removing it fully from the memory IF the variable is set to null after calling this function.
  36803. * var network = new vis.Network(..);
  36804. * network.destroy();
  36805. * network = null;
  36806. */
  36807. Network.prototype.destroy = function () {
  36808. this.body.emitter.emit("destroy");
  36809. // clear events
  36810. this.body.emitter.off();
  36811. this.off();
  36812. // delete modules
  36813. delete this.groups;
  36814. delete this.canvas;
  36815. delete this.selectionHandler;
  36816. delete this.interactionHandler;
  36817. delete this.view;
  36818. delete this.renderer;
  36819. delete this.physics;
  36820. delete this.layoutEngine;
  36821. delete this.clustering;
  36822. delete this.manipulation;
  36823. delete this.nodesHandler;
  36824. delete this.edgesHandler;
  36825. delete this.configurator;
  36826. delete this.images;
  36827. for (var nodeId in this.body.nodes) {
  36828. if (!this.body.nodes.hasOwnProperty(nodeId)) continue;
  36829. delete this.body.nodes[nodeId];
  36830. }
  36831. for (var edgeId in this.body.edges) {
  36832. if (!this.body.edges.hasOwnProperty(edgeId)) continue;
  36833. delete this.body.edges[edgeId];
  36834. }
  36835. // remove the container and everything inside it recursively
  36836. util.recursiveDOMDelete(this.body.container);
  36837. };
  36838. /**
  36839. * Update the values of all object in the given array according to the current
  36840. * value range of the objects in the array.
  36841. * @param {Object} obj An object containing a set of Edges or Nodes
  36842. * The objects must have a method getValue() and
  36843. * setValueRange(min, max).
  36844. * @private
  36845. */
  36846. Network.prototype._updateValueRange = function (obj) {
  36847. var id;
  36848. // determine the range of the objects
  36849. var valueMin = undefined;
  36850. var valueMax = undefined;
  36851. var valueTotal = 0;
  36852. for (id in obj) {
  36853. if (obj.hasOwnProperty(id)) {
  36854. var value = obj[id].getValue();
  36855. if (value !== undefined) {
  36856. valueMin = valueMin === undefined ? value : Math.min(value, valueMin);
  36857. valueMax = valueMax === undefined ? value : Math.max(value, valueMax);
  36858. valueTotal += value;
  36859. }
  36860. }
  36861. }
  36862. // adjust the range of all objects
  36863. if (valueMin !== undefined && valueMax !== undefined) {
  36864. for (id in obj) {
  36865. if (obj.hasOwnProperty(id)) {
  36866. obj[id].setValueRange(valueMin, valueMax, valueTotal);
  36867. }
  36868. }
  36869. }
  36870. };
  36871. /**
  36872. * Returns true when the Network is active.
  36873. * @returns {boolean}
  36874. */
  36875. Network.prototype.isActive = function () {
  36876. return !this.activator || this.activator.active;
  36877. };
  36878. Network.prototype.setSize = function () {
  36879. return this.canvas.setSize.apply(this.canvas, arguments);
  36880. };
  36881. Network.prototype.canvasToDOM = function () {
  36882. return this.canvas.canvasToDOM.apply(this.canvas, arguments);
  36883. };
  36884. Network.prototype.DOMtoCanvas = function () {
  36885. return this.canvas.DOMtoCanvas.apply(this.canvas, arguments);
  36886. };
  36887. Network.prototype.findNode = function () {
  36888. return this.clustering.findNode.apply(this.clustering, arguments);
  36889. };
  36890. Network.prototype.isCluster = function () {
  36891. return this.clustering.isCluster.apply(this.clustering, arguments);
  36892. };
  36893. Network.prototype.openCluster = function () {
  36894. return this.clustering.openCluster.apply(this.clustering, arguments);
  36895. };
  36896. Network.prototype.cluster = function () {
  36897. return this.clustering.cluster.apply(this.clustering, arguments);
  36898. };
  36899. Network.prototype.getNodesInCluster = function () {
  36900. return this.clustering.getNodesInCluster.apply(this.clustering, arguments);
  36901. };
  36902. Network.prototype.clusterByConnection = function () {
  36903. return this.clustering.clusterByConnection.apply(this.clustering, arguments);
  36904. };
  36905. Network.prototype.clusterByHubsize = function () {
  36906. return this.clustering.clusterByHubsize.apply(this.clustering, arguments);
  36907. };
  36908. Network.prototype.clusterOutliers = function () {
  36909. return this.clustering.clusterOutliers.apply(this.clustering, arguments);
  36910. };
  36911. Network.prototype.getSeed = function () {
  36912. return this.layoutEngine.getSeed.apply(this.layoutEngine, arguments);
  36913. };
  36914. Network.prototype.enableEditMode = function () {
  36915. return this.manipulation.enableEditMode.apply(this.manipulation, arguments);
  36916. };
  36917. Network.prototype.disableEditMode = function () {
  36918. return this.manipulation.disableEditMode.apply(this.manipulation, arguments);
  36919. };
  36920. Network.prototype.addNodeMode = function () {
  36921. return this.manipulation.addNodeMode.apply(this.manipulation, arguments);
  36922. };
  36923. Network.prototype.editNode = function () {
  36924. return this.manipulation.editNode.apply(this.manipulation, arguments);
  36925. };
  36926. Network.prototype.editNodeMode = function () {
  36927. console.log("Deprecated: Please use editNode instead of editNodeMode.");return this.manipulation.editNode.apply(this.manipulation, arguments);
  36928. };
  36929. Network.prototype.addEdgeMode = function () {
  36930. return this.manipulation.addEdgeMode.apply(this.manipulation, arguments);
  36931. };
  36932. Network.prototype.editEdgeMode = function () {
  36933. return this.manipulation.editEdgeMode.apply(this.manipulation, arguments);
  36934. };
  36935. Network.prototype.deleteSelected = function () {
  36936. return this.manipulation.deleteSelected.apply(this.manipulation, arguments);
  36937. };
  36938. Network.prototype.getPositions = function () {
  36939. return this.nodesHandler.getPositions.apply(this.nodesHandler, arguments);
  36940. };
  36941. Network.prototype.storePositions = function () {
  36942. return this.nodesHandler.storePositions.apply(this.nodesHandler, arguments);
  36943. };
  36944. Network.prototype.moveNode = function () {
  36945. return this.nodesHandler.moveNode.apply(this.nodesHandler, arguments);
  36946. };
  36947. Network.prototype.getBoundingBox = function () {
  36948. return this.nodesHandler.getBoundingBox.apply(this.nodesHandler, arguments);
  36949. };
  36950. Network.prototype.getConnectedNodes = function (objectId) {
  36951. if (this.body.nodes[objectId] !== undefined) {
  36952. return this.nodesHandler.getConnectedNodes.apply(this.nodesHandler, arguments);
  36953. } else {
  36954. return this.edgesHandler.getConnectedNodes.apply(this.edgesHandler, arguments);
  36955. }
  36956. };
  36957. Network.prototype.getConnectedEdges = function () {
  36958. return this.nodesHandler.getConnectedEdges.apply(this.nodesHandler, arguments);
  36959. };
  36960. Network.prototype.startSimulation = function () {
  36961. return this.physics.startSimulation.apply(this.physics, arguments);
  36962. };
  36963. Network.prototype.stopSimulation = function () {
  36964. return this.physics.stopSimulation.apply(this.physics, arguments);
  36965. };
  36966. Network.prototype.stabilize = function () {
  36967. return this.physics.stabilize.apply(this.physics, arguments);
  36968. };
  36969. Network.prototype.getSelection = function () {
  36970. return this.selectionHandler.getSelection.apply(this.selectionHandler, arguments);
  36971. };
  36972. Network.prototype.setSelection = function () {
  36973. return this.selectionHandler.setSelection.apply(this.selectionHandler, arguments);
  36974. };
  36975. Network.prototype.getSelectedNodes = function () {
  36976. return this.selectionHandler.getSelectedNodes.apply(this.selectionHandler, arguments);
  36977. };
  36978. Network.prototype.getSelectedEdges = function () {
  36979. return this.selectionHandler.getSelectedEdges.apply(this.selectionHandler, arguments);
  36980. };
  36981. Network.prototype.getNodeAt = function () {
  36982. var node = this.selectionHandler.getNodeAt.apply(this.selectionHandler, arguments);
  36983. if (node !== undefined && node.id !== undefined) {
  36984. return node.id;
  36985. }
  36986. return node;
  36987. };
  36988. Network.prototype.getEdgeAt = function () {
  36989. var edge = this.selectionHandler.getEdgeAt.apply(this.selectionHandler, arguments);
  36990. if (edge !== undefined && edge.id !== undefined) {
  36991. return edge.id;
  36992. }
  36993. return edge;
  36994. };
  36995. Network.prototype.selectNodes = function () {
  36996. return this.selectionHandler.selectNodes.apply(this.selectionHandler, arguments);
  36997. };
  36998. Network.prototype.selectEdges = function () {
  36999. return this.selectionHandler.selectEdges.apply(this.selectionHandler, arguments);
  37000. };
  37001. Network.prototype.unselectAll = function () {
  37002. this.selectionHandler.unselectAll.apply(this.selectionHandler, arguments);
  37003. this.redraw();
  37004. };
  37005. Network.prototype.redraw = function () {
  37006. return this.renderer.redraw.apply(this.renderer, arguments);
  37007. };
  37008. Network.prototype.getScale = function () {
  37009. return this.view.getScale.apply(this.view, arguments);
  37010. };
  37011. Network.prototype.getViewPosition = function () {
  37012. return this.view.getViewPosition.apply(this.view, arguments);
  37013. };
  37014. Network.prototype.fit = function () {
  37015. return this.view.fit.apply(this.view, arguments);
  37016. };
  37017. Network.prototype.moveTo = function () {
  37018. return this.view.moveTo.apply(this.view, arguments);
  37019. };
  37020. Network.prototype.focus = function () {
  37021. return this.view.focus.apply(this.view, arguments);
  37022. };
  37023. Network.prototype.releaseNode = function () {
  37024. return this.view.releaseNode.apply(this.view, arguments);
  37025. };
  37026. Network.prototype.getOptionsFromConfigurator = function () {
  37027. var options = {};
  37028. if (this.configurator) {
  37029. options = this.configurator.getOptions.apply(this.configurator);
  37030. }
  37031. return options;
  37032. };
  37033. module.exports = Network;
  37034. /***/ }),
  37035. /* 183 */
  37036. /***/ (function(module, exports, __webpack_require__) {
  37037. "use strict";
  37038. /**
  37039. * Canvas shapes used by Network
  37040. */
  37041. if (typeof CanvasRenderingContext2D !== 'undefined') {
  37042. /**
  37043. * Draw a circle shape
  37044. *
  37045. * @param {number} x
  37046. * @param {number} y
  37047. * @param {number} r
  37048. */
  37049. CanvasRenderingContext2D.prototype.circle = function (x, y, r) {
  37050. this.beginPath();
  37051. this.arc(x, y, r, 0, 2 * Math.PI, false);
  37052. this.closePath();
  37053. };
  37054. /**
  37055. * Draw a square shape
  37056. * @param {number} x horizontal center
  37057. * @param {number} y vertical center
  37058. * @param {number} r size, width and height of the square
  37059. */
  37060. CanvasRenderingContext2D.prototype.square = function (x, y, r) {
  37061. this.beginPath();
  37062. this.rect(x - r, y - r, r * 2, r * 2);
  37063. this.closePath();
  37064. };
  37065. /**
  37066. * Draw a triangle shape
  37067. * @param {number} x horizontal center
  37068. * @param {number} y vertical center
  37069. * @param {number} r radius, half the length of the sides of the triangle
  37070. */
  37071. CanvasRenderingContext2D.prototype.triangle = function (x, y, r) {
  37072. // http://en.wikipedia.org/wiki/Equilateral_triangle
  37073. this.beginPath();
  37074. // the change in radius and the offset is here to center the shape
  37075. r *= 1.15;
  37076. y += 0.275 * r;
  37077. var s = r * 2;
  37078. var s2 = s / 2;
  37079. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  37080. var h = Math.sqrt(s * s - s2 * s2); // height
  37081. this.moveTo(x, y - (h - ir));
  37082. this.lineTo(x + s2, y + ir);
  37083. this.lineTo(x - s2, y + ir);
  37084. this.lineTo(x, y - (h - ir));
  37085. this.closePath();
  37086. };
  37087. /**
  37088. * Draw a triangle shape in downward orientation
  37089. * @param {number} x horizontal center
  37090. * @param {number} y vertical center
  37091. * @param {number} r radius
  37092. */
  37093. CanvasRenderingContext2D.prototype.triangleDown = function (x, y, r) {
  37094. // http://en.wikipedia.org/wiki/Equilateral_triangle
  37095. this.beginPath();
  37096. // the change in radius and the offset is here to center the shape
  37097. r *= 1.15;
  37098. y -= 0.275 * r;
  37099. var s = r * 2;
  37100. var s2 = s / 2;
  37101. var ir = Math.sqrt(3) / 6 * s; // radius of inner circle
  37102. var h = Math.sqrt(s * s - s2 * s2); // height
  37103. this.moveTo(x, y + (h - ir));
  37104. this.lineTo(x + s2, y - ir);
  37105. this.lineTo(x - s2, y - ir);
  37106. this.lineTo(x, y + (h - ir));
  37107. this.closePath();
  37108. };
  37109. /**
  37110. * Draw a star shape, a star with 5 points
  37111. * @param {number} x horizontal center
  37112. * @param {number} y vertical center
  37113. * @param {number} r radius, half the length of the sides of the triangle
  37114. */
  37115. CanvasRenderingContext2D.prototype.star = function (x, y, r) {
  37116. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  37117. this.beginPath();
  37118. // the change in radius and the offset is here to center the shape
  37119. r *= 0.82;
  37120. y += 0.1 * r;
  37121. for (var n = 0; n < 10; n++) {
  37122. var radius = n % 2 === 0 ? r * 1.3 : r * 0.5;
  37123. this.lineTo(x + radius * Math.sin(n * 2 * Math.PI / 10), y - radius * Math.cos(n * 2 * Math.PI / 10));
  37124. }
  37125. this.closePath();
  37126. };
  37127. /**
  37128. * Draw a Diamond shape
  37129. * @param {number} x horizontal center
  37130. * @param {number} y vertical center
  37131. * @param {number} r radius, half the length of the sides of the triangle
  37132. */
  37133. CanvasRenderingContext2D.prototype.diamond = function (x, y, r) {
  37134. // http://www.html5canvastutorials.com/labs/html5-canvas-star-spinner/
  37135. this.beginPath();
  37136. this.lineTo(x, y + r);
  37137. this.lineTo(x + r, y);
  37138. this.lineTo(x, y - r);
  37139. this.lineTo(x - r, y);
  37140. this.closePath();
  37141. };
  37142. /**
  37143. * http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
  37144. *
  37145. * @param {number} x
  37146. * @param {number} y
  37147. * @param {number} w
  37148. * @param {number} h
  37149. * @param {number} r
  37150. */
  37151. CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) {
  37152. var r2d = Math.PI / 180;
  37153. if (w - 2 * r < 0) {
  37154. r = w / 2;
  37155. } //ensure that the radius isn't too large for x
  37156. if (h - 2 * r < 0) {
  37157. r = h / 2;
  37158. } //ensure that the radius isn't too large for y
  37159. this.beginPath();
  37160. this.moveTo(x + r, y);
  37161. this.lineTo(x + w - r, y);
  37162. this.arc(x + w - r, y + r, r, r2d * 270, r2d * 360, false);
  37163. this.lineTo(x + w, y + h - r);
  37164. this.arc(x + w - r, y + h - r, r, 0, r2d * 90, false);
  37165. this.lineTo(x + r, y + h);
  37166. this.arc(x + r, y + h - r, r, r2d * 90, r2d * 180, false);
  37167. this.lineTo(x, y + r);
  37168. this.arc(x + r, y + r, r, r2d * 180, r2d * 270, false);
  37169. this.closePath();
  37170. };
  37171. /**
  37172. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  37173. *
  37174. * Postfix '_vis' added to discern it from standard method ellipse().
  37175. *
  37176. * @param {number} x
  37177. * @param {number} y
  37178. * @param {number} w
  37179. * @param {number} h
  37180. */
  37181. CanvasRenderingContext2D.prototype.ellipse_vis = function (x, y, w, h) {
  37182. var kappa = .5522848,
  37183. ox = w / 2 * kappa,
  37184. // control point offset horizontal
  37185. oy = h / 2 * kappa,
  37186. // control point offset vertical
  37187. xe = x + w,
  37188. // x-end
  37189. ye = y + h,
  37190. // y-end
  37191. xm = x + w / 2,
  37192. // x-middle
  37193. ym = y + h / 2; // y-middle
  37194. this.beginPath();
  37195. this.moveTo(x, ym);
  37196. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  37197. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  37198. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  37199. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  37200. this.closePath();
  37201. };
  37202. /**
  37203. * http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  37204. *
  37205. * @param {number} x
  37206. * @param {number} y
  37207. * @param {number} w
  37208. * @param {number} h
  37209. */
  37210. CanvasRenderingContext2D.prototype.database = function (x, y, w, h) {
  37211. var f = 1 / 3;
  37212. var wEllipse = w;
  37213. var hEllipse = h * f;
  37214. var kappa = .5522848,
  37215. ox = wEllipse / 2 * kappa,
  37216. // control point offset horizontal
  37217. oy = hEllipse / 2 * kappa,
  37218. // control point offset vertical
  37219. xe = x + wEllipse,
  37220. // x-end
  37221. ye = y + hEllipse,
  37222. // y-end
  37223. xm = x + wEllipse / 2,
  37224. // x-middle
  37225. ym = y + hEllipse / 2,
  37226. // y-middle
  37227. ymb = y + (h - hEllipse / 2),
  37228. // y-midlle, bottom ellipse
  37229. yeb = y + h; // y-end, bottom ellipse
  37230. this.beginPath();
  37231. this.moveTo(xe, ym);
  37232. this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  37233. this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  37234. this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  37235. this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  37236. this.lineTo(xe, ymb);
  37237. this.bezierCurveTo(xe, ymb + oy, xm + ox, yeb, xm, yeb);
  37238. this.bezierCurveTo(xm - ox, yeb, x, ymb + oy, x, ymb);
  37239. this.lineTo(x, ym);
  37240. };
  37241. /**
  37242. * Sets up the dashedLine functionality for drawing
  37243. * Original code came from http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas
  37244. * @author David Jordan
  37245. * @date 2012-08-08
  37246. *
  37247. * @param {number} x
  37248. * @param {number} y
  37249. * @param {number} x2
  37250. * @param {number} y2
  37251. * @param {string} pattern
  37252. */
  37253. CanvasRenderingContext2D.prototype.dashedLine = function (x, y, x2, y2, pattern) {
  37254. this.beginPath();
  37255. this.moveTo(x, y);
  37256. var patternLength = pattern.length;
  37257. var dx = x2 - x;
  37258. var dy = y2 - y;
  37259. var slope = dy / dx;
  37260. var distRemaining = Math.sqrt(dx * dx + dy * dy);
  37261. var patternIndex = 0;
  37262. var draw = true;
  37263. var xStep = 0;
  37264. var dashLength = pattern[0];
  37265. while (distRemaining >= 0.1) {
  37266. dashLength = pattern[patternIndex++ % patternLength];
  37267. if (dashLength > distRemaining) {
  37268. dashLength = distRemaining;
  37269. }
  37270. xStep = Math.sqrt(dashLength * dashLength / (1 + slope * slope));
  37271. xStep = dx < 0 ? -xStep : xStep;
  37272. x += xStep;
  37273. y += slope * xStep;
  37274. if (draw === true) {
  37275. this.lineTo(x, y);
  37276. } else {
  37277. this.moveTo(x, y);
  37278. }
  37279. distRemaining -= dashLength;
  37280. draw = !draw;
  37281. }
  37282. };
  37283. /**
  37284. * Draw a Hexagon shape with 6 sides
  37285. * @param {Number} x horizontal center
  37286. * @param {Number} y vertical center
  37287. * @param {Number} r radius
  37288. */
  37289. CanvasRenderingContext2D.prototype.hexagon = function (x, y, r) {
  37290. this.beginPath();
  37291. var sides = 6;
  37292. var a = Math.PI * 2 / sides;
  37293. this.moveTo(x + r, y);
  37294. for (var i = 1; i < sides; i++) {
  37295. this.lineTo(x + r * Math.cos(a * i), y + r * Math.sin(a * i));
  37296. }
  37297. this.closePath();
  37298. };
  37299. }
  37300. /***/ }),
  37301. /* 184 */
  37302. /***/ (function(module, exports, __webpack_require__) {
  37303. "use strict";
  37304. // English
  37305. exports['en'] = {
  37306. edit: 'Edit',
  37307. del: 'Delete selected',
  37308. back: 'Back',
  37309. addNode: 'Add Node',
  37310. addEdge: 'Add Edge',
  37311. editNode: 'Edit Node',
  37312. editEdge: 'Edit Edge',
  37313. addDescription: 'Click in an empty space to place a new node.',
  37314. edgeDescription: 'Click on a node and drag the edge to another node to connect them.',
  37315. editEdgeDescription: 'Click on the control points and drag them to a node to connect to it.',
  37316. createEdgeError: 'Cannot link edges to a cluster.',
  37317. deleteClusterError: 'Clusters cannot be deleted.',
  37318. editClusterError: 'Clusters cannot be edited.'
  37319. };
  37320. exports['en_EN'] = exports['en'];
  37321. exports['en_US'] = exports['en'];
  37322. // German
  37323. exports['de'] = {
  37324. edit: 'Editieren',
  37325. del: 'L\xF6sche Auswahl',
  37326. back: 'Zur\xFCck',
  37327. addNode: 'Knoten hinzuf\xFCgen',
  37328. addEdge: 'Kante hinzuf\xFCgen',
  37329. editNode: 'Knoten editieren',
  37330. editEdge: 'Kante editieren',
  37331. addDescription: 'Klicke auf eine freie Stelle, um einen neuen Knoten zu plazieren.',
  37332. edgeDescription: 'Klicke auf einen Knoten und ziehe die Kante zu einem anderen Knoten, um diese zu verbinden.',
  37333. editEdgeDescription: 'Klicke auf die Verbindungspunkte und ziehe diese auf einen Knoten, um sie zu verbinden.',
  37334. createEdgeError: 'Es ist nicht m\xF6glich, Kanten mit Clustern zu verbinden.',
  37335. deleteClusterError: 'Cluster k\xF6nnen nicht gel\xF6scht werden.',
  37336. editClusterError: 'Cluster k\xF6nnen nicht editiert werden.'
  37337. };
  37338. exports['de_DE'] = exports['de'];
  37339. // Spanish
  37340. exports['es'] = {
  37341. edit: 'Editar',
  37342. del: 'Eliminar selecci\xF3n',
  37343. back: '\xC1tras',
  37344. addNode: 'A\xF1adir nodo',
  37345. addEdge: 'A\xF1adir arista',
  37346. editNode: 'Editar nodo',
  37347. editEdge: 'Editar arista',
  37348. addDescription: 'Haga clic en un lugar vac\xEDo para colocar un nuevo nodo.',
  37349. edgeDescription: 'Haga clic en un nodo y arrastre la arista hacia otro nodo para conectarlos.',
  37350. editEdgeDescription: 'Haga clic en un punto de control y arrastrelo a un nodo para conectarlo.',
  37351. createEdgeError: 'No se puede conectar una arista a un grupo.',
  37352. deleteClusterError: 'No es posible eliminar grupos.',
  37353. editClusterError: 'No es posible editar grupos.'
  37354. };
  37355. exports['es_ES'] = exports['es'];
  37356. //Italiano
  37357. exports['it'] = {
  37358. edit: 'Modifica',
  37359. del: 'Cancella la selezione',
  37360. back: 'Indietro',
  37361. addNode: 'Aggiungi un nodo',
  37362. addEdge: 'Aggiungi un vertice',
  37363. editNode: 'Modifica il nodo',
  37364. editEdge: 'Modifica il vertice',
  37365. addDescription: 'Clicca per aggiungere un nuovo nodo',
  37366. edgeDescription: 'Clicca su un nodo e trascinalo ad un altro nodo per connetterli.',
  37367. editEdgeDescription: 'Clicca sui Punti di controllo e trascinali ad un nodo per connetterli.',
  37368. createEdgeError: 'Non si possono collegare vertici ad un cluster',
  37369. deleteClusterError: 'I cluster non possono essere cancellati',
  37370. editClusterError: 'I clusters non possono essere modificati.'
  37371. };
  37372. exports['it_IT'] = exports['it'];
  37373. // Dutch
  37374. exports['nl'] = {
  37375. edit: 'Wijzigen',
  37376. del: 'Selectie verwijderen',
  37377. back: 'Terug',
  37378. addNode: 'Node toevoegen',
  37379. addEdge: 'Link toevoegen',
  37380. editNode: 'Node wijzigen',
  37381. editEdge: 'Link wijzigen',
  37382. addDescription: 'Klik op een leeg gebied om een nieuwe node te maken.',
  37383. edgeDescription: 'Klik op een node en sleep de link naar een andere node om ze te verbinden.',
  37384. editEdgeDescription: 'Klik op de verbindingspunten en sleep ze naar een node om daarmee te verbinden.',
  37385. createEdgeError: 'Kan geen link maken naar een cluster.',
  37386. deleteClusterError: 'Clusters kunnen niet worden verwijderd.',
  37387. editClusterError: 'Clusters kunnen niet worden aangepast.'
  37388. };
  37389. exports['nl_NL'] = exports['nl'];
  37390. exports['nl_BE'] = exports['nl'];
  37391. // Portuguese Brazil
  37392. exports['pt-br'] = {
  37393. edit: 'Editar',
  37394. del: 'Remover selecionado',
  37395. back: 'Voltar',
  37396. addNode: 'Adicionar nó',
  37397. addEdge: 'Adicionar aresta',
  37398. editNode: 'Editar nó',
  37399. editEdge: 'Editar aresta',
  37400. addDescription: 'Clique em um espaço em branco para adicionar um novo nó',
  37401. edgeDescription: 'Clique em um nó e arraste a aresta até outro nó para conectá-los',
  37402. editEdgeDescription: 'Clique nos pontos de controle e os arraste para um nó para conectá-los',
  37403. createEdgeError: 'Não foi possível linkar arestas a um cluster.',
  37404. deleteClusterError: 'Clusters não puderam ser removidos.',
  37405. editClusterError: 'Clusters não puderam ser editados.'
  37406. };
  37407. exports['pt-BR'] = exports['pt-br'];
  37408. exports['pt_BR'] = exports['pt-br'];
  37409. exports['pt_br'] = exports['pt-br'];
  37410. // Russian
  37411. exports['ru'] = {
  37412. edit: 'Редактировать',
  37413. del: 'Удалить выбранное',
  37414. back: 'Назад',
  37415. addNode: 'Добавить узел',
  37416. addEdge: 'Добавить ребро',
  37417. editNode: 'Редактировать узел',
  37418. editEdge: 'Редактировать ребро',
  37419. addDescription: 'Кликните в свободное место, чтобы добавить новый узел.',
  37420. edgeDescription: 'Кликните на узел и протяните ребро к другому узлу, чтобы соединить их.',
  37421. editEdgeDescription: 'Кликните на контрольные точки и перетащите их в узел, чтобы подключиться к нему.',
  37422. createEdgeError: 'Невозможно соединить ребра в кластер.',
  37423. deleteClusterError: 'Кластеры не могут быть удалены',
  37424. editClusterError: 'Кластеры недоступны для редактирования.'
  37425. };
  37426. exports['ru_RU'] = exports['ru'];
  37427. // Chinese
  37428. exports['cn'] = {
  37429. edit: '编辑',
  37430. del: '删除选定',
  37431. back: '返回',
  37432. addNode: '添加节点',
  37433. addEdge: '添加连接线',
  37434. editNode: '编辑节点',
  37435. editEdge: '编辑连接线',
  37436. addDescription: '单击空白处放置新节点。',
  37437. edgeDescription: '单击某个节点并将该连接线拖动到另一个节点以连接它们。',
  37438. editEdgeDescription: '单击控制节点并将它们拖到节点上连接。',
  37439. createEdgeError: '无法将连接线连接到群集。',
  37440. deleteClusterError: '无法删除群集。',
  37441. editClusterError: '无法编辑群集。'
  37442. };
  37443. exports['zh_CN'] = exports['cn'];
  37444. /***/ }),
  37445. /* 185 */
  37446. /***/ (function(module, exports, __webpack_require__) {
  37447. "use strict";
  37448. Object.defineProperty(exports, "__esModule", {
  37449. value: true
  37450. });
  37451. var _classCallCheck2 = __webpack_require__(0);
  37452. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  37453. var _createClass2 = __webpack_require__(1);
  37454. var _createClass3 = _interopRequireDefault(_createClass2);
  37455. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  37456. /**
  37457. * Associates a canvas to a given image, containing a number of renderings
  37458. * of the image at various sizes.
  37459. *
  37460. * This technique is known as 'mipmapping'.
  37461. *
  37462. * NOTE: Images can also be of type 'data:svg+xml`. This code also works
  37463. * for svg, but the mipmapping may not be necessary.
  37464. *
  37465. * @param {Image} image
  37466. */
  37467. var CachedImage = function () {
  37468. /**
  37469. * @ignore
  37470. */
  37471. function CachedImage() {
  37472. (0, _classCallCheck3['default'])(this, CachedImage);
  37473. // eslint-disable-line no-unused-vars
  37474. this.NUM_ITERATIONS = 4; // Number of items in the coordinates array
  37475. this.image = new Image();
  37476. this.canvas = document.createElement('canvas');
  37477. }
  37478. /**
  37479. * Called when the image has been successfully loaded.
  37480. */
  37481. (0, _createClass3['default'])(CachedImage, [{
  37482. key: 'init',
  37483. value: function init() {
  37484. if (this.initialized()) return;
  37485. this.src = this.image.src; // For same interface with Image
  37486. var w = this.image.width;
  37487. var h = this.image.height;
  37488. // Ease external access
  37489. this.width = w;
  37490. this.height = h;
  37491. var h2 = Math.floor(h / 2);
  37492. var h4 = Math.floor(h / 4);
  37493. var h8 = Math.floor(h / 8);
  37494. var h16 = Math.floor(h / 16);
  37495. var w2 = Math.floor(w / 2);
  37496. var w4 = Math.floor(w / 4);
  37497. var w8 = Math.floor(w / 8);
  37498. var w16 = Math.floor(w / 16);
  37499. // Make canvas as small as possible
  37500. this.canvas.width = 3 * w4;
  37501. this.canvas.height = h2;
  37502. // Coordinates and sizes of images contained in the canvas
  37503. // Values per row: [top x, left y, width, height]
  37504. this.coordinates = [[0, 0, w2, h2], [w2, 0, w4, h4], [w2, h4, w8, h8], [5 * w8, h4, w16, h16]];
  37505. this._fillMipMap();
  37506. }
  37507. /**
  37508. * @return {Boolean} true if init() has been called, false otherwise.
  37509. */
  37510. }, {
  37511. key: 'initialized',
  37512. value: function initialized() {
  37513. return this.coordinates !== undefined;
  37514. }
  37515. /**
  37516. * Redraw main image in various sizes to the context.
  37517. *
  37518. * The rationale behind this is to reduce artefacts due to interpolation
  37519. * at differing zoom levels.
  37520. *
  37521. * Source: http://stackoverflow.com/q/18761404/1223531
  37522. *
  37523. * This methods takes the resizing out of the drawing loop, in order to
  37524. * reduce performance overhead.
  37525. *
  37526. * TODO: The code assumes that a 2D context can always be gotten. This is
  37527. * not necessarily true! OTOH, if not true then usage of this class
  37528. * is senseless.
  37529. *
  37530. * @private
  37531. */
  37532. }, {
  37533. key: '_fillMipMap',
  37534. value: function _fillMipMap() {
  37535. var ctx = this.canvas.getContext('2d');
  37536. // First zoom-level comes from the image
  37537. var to = this.coordinates[0];
  37538. ctx.drawImage(this.image, to[0], to[1], to[2], to[3]);
  37539. // The rest are copy actions internal to the canvas/context
  37540. for (var iterations = 1; iterations < this.NUM_ITERATIONS; iterations++) {
  37541. var from = this.coordinates[iterations - 1];
  37542. var _to = this.coordinates[iterations];
  37543. ctx.drawImage(this.canvas, from[0], from[1], from[2], from[3], _to[0], _to[1], _to[2], _to[3]);
  37544. }
  37545. }
  37546. /**
  37547. * Draw the image, using the mipmap if necessary.
  37548. *
  37549. * MipMap is only used if param factor > 2; otherwise, original bitmap
  37550. * is resized. This is also used to skip mipmap usage, e.g. by setting factor = 1
  37551. *
  37552. * Credits to 'Alex de Mulder' for original implementation.
  37553. *
  37554. * @param {CanvasRenderingContext2D} ctx context on which to draw zoomed image
  37555. * @param {Float} factor scale factor at which to draw
  37556. * @param {number} left
  37557. * @param {number} top
  37558. * @param {number} width
  37559. * @param {number} height
  37560. */
  37561. }, {
  37562. key: 'drawImageAtPosition',
  37563. value: function drawImageAtPosition(ctx, factor, left, top, width, height) {
  37564. if (!this.initialized()) return; //can't draw image yet not intialized
  37565. if (factor > 2) {
  37566. // Determine which zoomed image to use
  37567. factor *= 0.5;
  37568. var iterations = 0;
  37569. while (factor > 2 && iterations < this.NUM_ITERATIONS) {
  37570. factor *= 0.5;
  37571. iterations += 1;
  37572. }
  37573. if (iterations >= this.NUM_ITERATIONS) {
  37574. iterations = this.NUM_ITERATIONS - 1;
  37575. }
  37576. //console.log("iterations: " + iterations);
  37577. var from = this.coordinates[iterations];
  37578. ctx.drawImage(this.canvas, from[0], from[1], from[2], from[3], left, top, width, height);
  37579. } else {
  37580. // Draw image directly
  37581. ctx.drawImage(this.image, left, top, width, height);
  37582. }
  37583. }
  37584. }]);
  37585. return CachedImage;
  37586. }();
  37587. exports['default'] = CachedImage;
  37588. /***/ }),
  37589. /* 186 */
  37590. /***/ (function(module, exports, __webpack_require__) {
  37591. "use strict";
  37592. Object.defineProperty(exports, "__esModule", {
  37593. value: true
  37594. });
  37595. var _classCallCheck2 = __webpack_require__(0);
  37596. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  37597. var _createClass2 = __webpack_require__(1);
  37598. var _createClass3 = _interopRequireDefault(_createClass2);
  37599. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  37600. var util = __webpack_require__(2);
  37601. /**
  37602. * This class can store groups and options specific for groups.
  37603. */
  37604. var Groups = function () {
  37605. /**
  37606. * @ignore
  37607. */
  37608. function Groups() {
  37609. (0, _classCallCheck3["default"])(this, Groups);
  37610. this.clear();
  37611. this.defaultIndex = 0;
  37612. this.groupsArray = [];
  37613. this.groupIndex = 0;
  37614. this.defaultGroups = [{ border: "#2B7CE9", background: "#97C2FC", highlight: { border: "#2B7CE9", background: "#D2E5FF" }, hover: { border: "#2B7CE9", background: "#D2E5FF" } }, // 0: blue
  37615. { border: "#FFA500", background: "#FFFF00", highlight: { border: "#FFA500", background: "#FFFFA3" }, hover: { border: "#FFA500", background: "#FFFFA3" } }, // 1: yellow
  37616. { border: "#FA0A10", background: "#FB7E81", highlight: { border: "#FA0A10", background: "#FFAFB1" }, hover: { border: "#FA0A10", background: "#FFAFB1" } }, // 2: red
  37617. { border: "#41A906", background: "#7BE141", highlight: { border: "#41A906", background: "#A1EC76" }, hover: { border: "#41A906", background: "#A1EC76" } }, // 3: green
  37618. { border: "#E129F0", background: "#EB7DF4", highlight: { border: "#E129F0", background: "#F0B3F5" }, hover: { border: "#E129F0", background: "#F0B3F5" } }, // 4: magenta
  37619. { border: "#7C29F0", background: "#AD85E4", highlight: { border: "#7C29F0", background: "#D3BDF0" }, hover: { border: "#7C29F0", background: "#D3BDF0" } }, // 5: purple
  37620. { border: "#C37F00", background: "#FFA807", highlight: { border: "#C37F00", background: "#FFCA66" }, hover: { border: "#C37F00", background: "#FFCA66" } }, // 6: orange
  37621. { border: "#4220FB", background: "#6E6EFD", highlight: { border: "#4220FB", background: "#9B9BFD" }, hover: { border: "#4220FB", background: "#9B9BFD" } }, // 7: darkblue
  37622. { border: "#FD5A77", background: "#FFC0CB", highlight: { border: "#FD5A77", background: "#FFD1D9" }, hover: { border: "#FD5A77", background: "#FFD1D9" } }, // 8: pink
  37623. { border: "#4AD63A", background: "#C2FABC", highlight: { border: "#4AD63A", background: "#E6FFE3" }, hover: { border: "#4AD63A", background: "#E6FFE3" } }, // 9: mint
  37624. { border: "#990000", background: "#EE0000", highlight: { border: "#BB0000", background: "#FF3333" }, hover: { border: "#BB0000", background: "#FF3333" } }, // 10:bright red
  37625. { border: "#FF6000", background: "#FF6000", highlight: { border: "#FF6000", background: "#FF6000" }, hover: { border: "#FF6000", background: "#FF6000" } }, // 12: real orange
  37626. { border: "#97C2FC", background: "#2B7CE9", highlight: { border: "#D2E5FF", background: "#2B7CE9" }, hover: { border: "#D2E5FF", background: "#2B7CE9" } }, // 13: blue
  37627. { border: "#399605", background: "#255C03", highlight: { border: "#399605", background: "#255C03" }, hover: { border: "#399605", background: "#255C03" } }, // 14: green
  37628. { border: "#B70054", background: "#FF007E", highlight: { border: "#B70054", background: "#FF007E" }, hover: { border: "#B70054", background: "#FF007E" } }, // 15: magenta
  37629. { border: "#AD85E4", background: "#7C29F0", highlight: { border: "#D3BDF0", background: "#7C29F0" }, hover: { border: "#D3BDF0", background: "#7C29F0" } }, // 16: purple
  37630. { border: "#4557FA", background: "#000EA1", highlight: { border: "#6E6EFD", background: "#000EA1" }, hover: { border: "#6E6EFD", background: "#000EA1" } }, // 17: darkblue
  37631. { border: "#FFC0CB", background: "#FD5A77", highlight: { border: "#FFD1D9", background: "#FD5A77" }, hover: { border: "#FFD1D9", background: "#FD5A77" } }, // 18: pink
  37632. { border: "#C2FABC", background: "#74D66A", highlight: { border: "#E6FFE3", background: "#74D66A" }, hover: { border: "#E6FFE3", background: "#74D66A" } }, // 19: mint
  37633. { border: "#EE0000", background: "#990000", highlight: { border: "#FF3333", background: "#BB0000" }, hover: { border: "#FF3333", background: "#BB0000" } // 20:bright red
  37634. }];
  37635. this.options = {};
  37636. this.defaultOptions = {
  37637. useDefaultGroups: true
  37638. };
  37639. util.extend(this.options, this.defaultOptions);
  37640. }
  37641. /**
  37642. *
  37643. * @param {Object} options
  37644. */
  37645. (0, _createClass3["default"])(Groups, [{
  37646. key: "setOptions",
  37647. value: function setOptions(options) {
  37648. var optionFields = ['useDefaultGroups'];
  37649. if (options !== undefined) {
  37650. for (var groupName in options) {
  37651. if (options.hasOwnProperty(groupName)) {
  37652. if (optionFields.indexOf(groupName) === -1) {
  37653. var group = options[groupName];
  37654. this.add(groupName, group);
  37655. }
  37656. }
  37657. }
  37658. }
  37659. }
  37660. /**
  37661. * Clear all groups
  37662. */
  37663. }, {
  37664. key: "clear",
  37665. value: function clear() {
  37666. this.groups = {};
  37667. this.groupsArray = [];
  37668. }
  37669. /**
  37670. * Get group options of a groupname.
  37671. * If groupname is not found, a new group may be created.
  37672. *
  37673. * @param {*} groupname Can be a number, string, Date, etc.
  37674. * @param {boolean} [shouldCreate=true] If true, create a new group
  37675. * @return {Object} The found or created group
  37676. */
  37677. }, {
  37678. key: "get",
  37679. value: function get(groupname) {
  37680. var shouldCreate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  37681. var group = this.groups[groupname];
  37682. if (group === undefined && shouldCreate) {
  37683. if (this.options.useDefaultGroups === false && this.groupsArray.length > 0) {
  37684. // create new group
  37685. var index = this.groupIndex % this.groupsArray.length;
  37686. this.groupIndex++;
  37687. group = {};
  37688. group.color = this.groups[this.groupsArray[index]];
  37689. this.groups[groupname] = group;
  37690. } else {
  37691. // create new group
  37692. var _index = this.defaultIndex % this.defaultGroups.length;
  37693. this.defaultIndex++;
  37694. group = {};
  37695. group.color = this.defaultGroups[_index];
  37696. this.groups[groupname] = group;
  37697. }
  37698. }
  37699. return group;
  37700. }
  37701. /**
  37702. * Add a custom group style
  37703. * @param {string} groupName
  37704. * @param {Object} style An object containing borderColor,
  37705. * backgroundColor, etc.
  37706. * @return {Object} group The created group object
  37707. */
  37708. }, {
  37709. key: "add",
  37710. value: function add(groupName, style) {
  37711. this.groups[groupName] = style;
  37712. this.groupsArray.push(groupName);
  37713. return style;
  37714. }
  37715. }]);
  37716. return Groups;
  37717. }();
  37718. exports["default"] = Groups;
  37719. /***/ }),
  37720. /* 187 */
  37721. /***/ (function(module, exports, __webpack_require__) {
  37722. "use strict";
  37723. Object.defineProperty(exports, "__esModule", {
  37724. value: true
  37725. });
  37726. var _classCallCheck2 = __webpack_require__(0);
  37727. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  37728. var _createClass2 = __webpack_require__(1);
  37729. var _createClass3 = _interopRequireDefault(_createClass2);
  37730. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  37731. var util = __webpack_require__(2);
  37732. var DataSet = __webpack_require__(11);
  37733. var DataView = __webpack_require__(12);
  37734. var Node = __webpack_require__(47)['default'];
  37735. /**
  37736. * Handler for Nodes
  37737. */
  37738. var NodesHandler = function () {
  37739. /**
  37740. * @param {Object} body
  37741. * @param {Images} images
  37742. * @param {Array.<Group>} groups
  37743. * @param {LayoutEngine} layoutEngine
  37744. */
  37745. function NodesHandler(body, images, groups, layoutEngine) {
  37746. var _this = this;
  37747. (0, _classCallCheck3['default'])(this, NodesHandler);
  37748. this.body = body;
  37749. this.images = images;
  37750. this.groups = groups;
  37751. this.layoutEngine = layoutEngine;
  37752. // create the node API in the body container
  37753. this.body.functions.createNode = this.create.bind(this);
  37754. this.nodesListeners = {
  37755. add: function add(event, params) {
  37756. _this.add(params.items);
  37757. },
  37758. update: function update(event, params) {
  37759. _this.update(params.items, params.data, params.oldData);
  37760. },
  37761. remove: function remove(event, params) {
  37762. _this.remove(params.items);
  37763. }
  37764. };
  37765. this.defaultOptions = {
  37766. borderWidth: 1,
  37767. borderWidthSelected: 2,
  37768. brokenImage: undefined,
  37769. color: {
  37770. border: '#2B7CE9',
  37771. background: '#97C2FC',
  37772. highlight: {
  37773. border: '#2B7CE9',
  37774. background: '#D2E5FF'
  37775. },
  37776. hover: {
  37777. border: '#2B7CE9',
  37778. background: '#D2E5FF'
  37779. }
  37780. },
  37781. fixed: {
  37782. x: false,
  37783. y: false
  37784. },
  37785. font: {
  37786. color: '#343434',
  37787. size: 14, // px
  37788. face: 'arial',
  37789. background: 'none',
  37790. strokeWidth: 0, // px
  37791. strokeColor: '#ffffff',
  37792. align: 'center',
  37793. vadjust: 0,
  37794. multi: false,
  37795. bold: {
  37796. mod: 'bold'
  37797. },
  37798. boldital: {
  37799. mod: 'bold italic'
  37800. },
  37801. ital: {
  37802. mod: 'italic'
  37803. },
  37804. mono: {
  37805. mod: '',
  37806. size: 15, // px
  37807. face: 'monospace',
  37808. vadjust: 2
  37809. }
  37810. },
  37811. group: undefined,
  37812. hidden: false,
  37813. icon: {
  37814. face: 'FontAwesome', //'FontAwesome',
  37815. code: undefined, //'\uf007',
  37816. size: 50, //50,
  37817. color: '#2B7CE9' //'#aa00ff'
  37818. },
  37819. image: undefined, // --> URL
  37820. label: undefined,
  37821. labelHighlightBold: true,
  37822. level: undefined,
  37823. margin: {
  37824. top: 5,
  37825. right: 5,
  37826. bottom: 5,
  37827. left: 5
  37828. },
  37829. mass: 1,
  37830. physics: true,
  37831. scaling: {
  37832. min: 10,
  37833. max: 30,
  37834. label: {
  37835. enabled: false,
  37836. min: 14,
  37837. max: 30,
  37838. maxVisible: 30,
  37839. drawThreshold: 5
  37840. },
  37841. customScalingFunction: function customScalingFunction(min, max, total, value) {
  37842. if (max === min) {
  37843. return 0.5;
  37844. } else {
  37845. var scale = 1 / (max - min);
  37846. return Math.max(0, (value - min) * scale);
  37847. }
  37848. }
  37849. },
  37850. shadow: {
  37851. enabled: false,
  37852. color: 'rgba(0,0,0,0.5)',
  37853. size: 10,
  37854. x: 5,
  37855. y: 5
  37856. },
  37857. shape: 'ellipse',
  37858. shapeProperties: {
  37859. borderDashes: false, // only for borders
  37860. borderRadius: 6, // only for box shape
  37861. interpolation: true, // only for image and circularImage shapes
  37862. useImageSize: false, // only for image and circularImage shapes
  37863. useBorderWithImage: false // only for image shape
  37864. },
  37865. size: 25,
  37866. title: undefined,
  37867. value: undefined,
  37868. x: undefined,
  37869. y: undefined
  37870. };
  37871. // Protect from idiocy
  37872. if (this.defaultOptions.mass <= 0) {
  37873. throw 'Internal error: mass in defaultOptions of NodesHandler may not be zero or negative';
  37874. }
  37875. this.options = util.bridgeObject(this.defaultOptions);
  37876. this.bindEventListeners();
  37877. }
  37878. /**
  37879. * Binds event listeners
  37880. */
  37881. (0, _createClass3['default'])(NodesHandler, [{
  37882. key: 'bindEventListeners',
  37883. value: function bindEventListeners() {
  37884. var _this2 = this;
  37885. // refresh the nodes. Used when reverting from hierarchical layout
  37886. this.body.emitter.on('refreshNodes', this.refresh.bind(this));
  37887. this.body.emitter.on('refresh', this.refresh.bind(this));
  37888. this.body.emitter.on('destroy', function () {
  37889. util.forEach(_this2.nodesListeners, function (callback, event) {
  37890. if (_this2.body.data.nodes) _this2.body.data.nodes.off(event, callback);
  37891. });
  37892. delete _this2.body.functions.createNode;
  37893. delete _this2.nodesListeners.add;
  37894. delete _this2.nodesListeners.update;
  37895. delete _this2.nodesListeners.remove;
  37896. delete _this2.nodesListeners;
  37897. });
  37898. }
  37899. /**
  37900. *
  37901. * @param {Object} options
  37902. */
  37903. }, {
  37904. key: 'setOptions',
  37905. value: function setOptions(options) {
  37906. if (options !== undefined) {
  37907. Node.parseOptions(this.options, options);
  37908. // update the shape in all nodes
  37909. if (options.shape !== undefined) {
  37910. for (var nodeId in this.body.nodes) {
  37911. if (this.body.nodes.hasOwnProperty(nodeId)) {
  37912. this.body.nodes[nodeId].updateShape();
  37913. }
  37914. }
  37915. }
  37916. // update the font in all nodes
  37917. if (options.font !== undefined) {
  37918. for (var _nodeId in this.body.nodes) {
  37919. if (this.body.nodes.hasOwnProperty(_nodeId)) {
  37920. this.body.nodes[_nodeId].updateLabelModule();
  37921. this.body.nodes[_nodeId].needsRefresh();
  37922. }
  37923. }
  37924. }
  37925. // update the shape size in all nodes
  37926. if (options.size !== undefined) {
  37927. for (var _nodeId2 in this.body.nodes) {
  37928. if (this.body.nodes.hasOwnProperty(_nodeId2)) {
  37929. this.body.nodes[_nodeId2].needsRefresh();
  37930. }
  37931. }
  37932. }
  37933. // update the state of the variables if needed
  37934. if (options.hidden !== undefined || options.physics !== undefined) {
  37935. this.body.emitter.emit('_dataChanged');
  37936. }
  37937. }
  37938. }
  37939. /**
  37940. * Set a data set with nodes for the network
  37941. * @param {Array | DataSet | DataView} nodes The data containing the nodes.
  37942. * @param {boolean} [doNotEmit=false]
  37943. * @private
  37944. */
  37945. }, {
  37946. key: 'setData',
  37947. value: function setData(nodes) {
  37948. var doNotEmit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  37949. var oldNodesData = this.body.data.nodes;
  37950. if (nodes instanceof DataSet || nodes instanceof DataView) {
  37951. this.body.data.nodes = nodes;
  37952. } else if (Array.isArray(nodes)) {
  37953. this.body.data.nodes = new DataSet();
  37954. this.body.data.nodes.add(nodes);
  37955. } else if (!nodes) {
  37956. this.body.data.nodes = new DataSet();
  37957. } else {
  37958. throw new TypeError('Array or DataSet expected');
  37959. }
  37960. if (oldNodesData) {
  37961. // unsubscribe from old dataset
  37962. util.forEach(this.nodesListeners, function (callback, event) {
  37963. oldNodesData.off(event, callback);
  37964. });
  37965. }
  37966. // remove drawn nodes
  37967. this.body.nodes = {};
  37968. if (this.body.data.nodes) {
  37969. // subscribe to new dataset
  37970. var me = this;
  37971. util.forEach(this.nodesListeners, function (callback, event) {
  37972. me.body.data.nodes.on(event, callback);
  37973. });
  37974. // draw all new nodes
  37975. var ids = this.body.data.nodes.getIds();
  37976. this.add(ids, true);
  37977. }
  37978. if (doNotEmit === false) {
  37979. this.body.emitter.emit("_dataChanged");
  37980. }
  37981. }
  37982. /**
  37983. * Add nodes
  37984. * @param {number[] | string[]} ids
  37985. * @param {boolean} [doNotEmit=false]
  37986. * @private
  37987. */
  37988. }, {
  37989. key: 'add',
  37990. value: function add(ids) {
  37991. var doNotEmit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  37992. var id = void 0;
  37993. var newNodes = [];
  37994. for (var i = 0; i < ids.length; i++) {
  37995. id = ids[i];
  37996. var properties = this.body.data.nodes.get(id);
  37997. var node = this.create(properties);
  37998. newNodes.push(node);
  37999. this.body.nodes[id] = node; // note: this may replace an existing node
  38000. }
  38001. this.layoutEngine.positionInitially(newNodes);
  38002. if (doNotEmit === false) {
  38003. this.body.emitter.emit("_dataChanged");
  38004. }
  38005. }
  38006. /**
  38007. * Update existing nodes, or create them when not yet existing
  38008. * @param {number[] | string[]} ids id's of changed nodes
  38009. * @param {Array} changedData array with changed data
  38010. * @param {Array|undefined} oldData optional; array with previous data
  38011. * @private
  38012. */
  38013. }, {
  38014. key: 'update',
  38015. value: function update(ids, changedData, oldData) {
  38016. var nodes = this.body.nodes;
  38017. var dataChanged = false;
  38018. for (var i = 0; i < ids.length; i++) {
  38019. var id = ids[i];
  38020. var node = nodes[id];
  38021. var data = changedData[i];
  38022. if (node !== undefined) {
  38023. // update node
  38024. if (node.setOptions(data)) {
  38025. dataChanged = true;
  38026. }
  38027. } else {
  38028. dataChanged = true;
  38029. // create node
  38030. node = this.create(data);
  38031. nodes[id] = node;
  38032. }
  38033. }
  38034. if (!dataChanged && oldData !== undefined) {
  38035. // Check for any changes which should trigger a layout recalculation
  38036. // For now, this is just 'level' for hierarchical layout
  38037. // Assumption: old and new data arranged in same order; at time of writing, this holds.
  38038. dataChanged = changedData.some(function (newValue, index) {
  38039. var oldValue = oldData[index];
  38040. return oldValue && oldValue.level !== newValue.level;
  38041. });
  38042. }
  38043. if (dataChanged === true) {
  38044. this.body.emitter.emit("_dataChanged");
  38045. } else {
  38046. this.body.emitter.emit("_dataUpdated");
  38047. }
  38048. }
  38049. /**
  38050. * Remove existing nodes. If nodes do not exist, the method will just ignore it.
  38051. * @param {number[] | string[]} ids
  38052. * @private
  38053. */
  38054. }, {
  38055. key: 'remove',
  38056. value: function remove(ids) {
  38057. var nodes = this.body.nodes;
  38058. for (var i = 0; i < ids.length; i++) {
  38059. var id = ids[i];
  38060. delete nodes[id];
  38061. }
  38062. this.body.emitter.emit("_dataChanged");
  38063. }
  38064. /**
  38065. * create a node
  38066. * @param {Object} properties
  38067. * @param {class} [constructorClass=Node.default]
  38068. * @returns {*}
  38069. */
  38070. }, {
  38071. key: 'create',
  38072. value: function create(properties) {
  38073. var constructorClass = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Node;
  38074. return new constructorClass(properties, this.body, this.images, this.groups, this.options, this.defaultOptions);
  38075. }
  38076. /**
  38077. *
  38078. * @param {boolean} [clearPositions=false]
  38079. */
  38080. }, {
  38081. key: 'refresh',
  38082. value: function refresh() {
  38083. var _this3 = this;
  38084. var clearPositions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  38085. util.forEach(this.body.nodes, function (node, nodeId) {
  38086. var data = _this3.body.data.nodes.get(nodeId);
  38087. if (data !== undefined) {
  38088. if (clearPositions === true) {
  38089. node.setOptions({ x: null, y: null });
  38090. }
  38091. node.setOptions({ fixed: false });
  38092. node.setOptions(data);
  38093. }
  38094. });
  38095. }
  38096. /**
  38097. * Returns the positions of the nodes.
  38098. * @param {Array.<Node.id>|String} [ids] --> optional, can be array of nodeIds, can be string
  38099. * @returns {{}}
  38100. */
  38101. }, {
  38102. key: 'getPositions',
  38103. value: function getPositions(ids) {
  38104. var dataArray = {};
  38105. if (ids !== undefined) {
  38106. if (Array.isArray(ids) === true) {
  38107. for (var i = 0; i < ids.length; i++) {
  38108. if (this.body.nodes[ids[i]] !== undefined) {
  38109. var node = this.body.nodes[ids[i]];
  38110. dataArray[ids[i]] = { x: Math.round(node.x), y: Math.round(node.y) };
  38111. }
  38112. }
  38113. } else {
  38114. if (this.body.nodes[ids] !== undefined) {
  38115. var _node = this.body.nodes[ids];
  38116. dataArray[ids] = { x: Math.round(_node.x), y: Math.round(_node.y) };
  38117. }
  38118. }
  38119. } else {
  38120. for (var _i = 0; _i < this.body.nodeIndices.length; _i++) {
  38121. var _node2 = this.body.nodes[this.body.nodeIndices[_i]];
  38122. dataArray[this.body.nodeIndices[_i]] = { x: Math.round(_node2.x), y: Math.round(_node2.y) };
  38123. }
  38124. }
  38125. return dataArray;
  38126. }
  38127. /**
  38128. * Load the XY positions of the nodes into the dataset.
  38129. */
  38130. }, {
  38131. key: 'storePositions',
  38132. value: function storePositions() {
  38133. // todo: add support for clusters and hierarchical.
  38134. var dataArray = [];
  38135. var dataset = this.body.data.nodes.getDataSet();
  38136. for (var nodeId in dataset._data) {
  38137. if (dataset._data.hasOwnProperty(nodeId)) {
  38138. var node = this.body.nodes[nodeId];
  38139. if (dataset._data[nodeId].x != Math.round(node.x) || dataset._data[nodeId].y != Math.round(node.y)) {
  38140. dataArray.push({ id: node.id, x: Math.round(node.x), y: Math.round(node.y) });
  38141. }
  38142. }
  38143. }
  38144. dataset.update(dataArray);
  38145. }
  38146. /**
  38147. * get the bounding box of a node.
  38148. * @param {Node.id} nodeId
  38149. * @returns {j|*}
  38150. */
  38151. }, {
  38152. key: 'getBoundingBox',
  38153. value: function getBoundingBox(nodeId) {
  38154. if (this.body.nodes[nodeId] !== undefined) {
  38155. return this.body.nodes[nodeId].shape.boundingBox;
  38156. }
  38157. }
  38158. /**
  38159. * Get the Ids of nodes connected to this node.
  38160. * @param {Node.id} nodeId
  38161. * @param {'to'|'from'|undefined} direction values 'from' and 'to' select respectively parent and child nodes only.
  38162. * Any other value returns both parent and child nodes.
  38163. * @returns {Array}
  38164. */
  38165. }, {
  38166. key: 'getConnectedNodes',
  38167. value: function getConnectedNodes(nodeId, direction) {
  38168. var nodeList = [];
  38169. if (this.body.nodes[nodeId] !== undefined) {
  38170. var node = this.body.nodes[nodeId];
  38171. var nodeObj = {}; // used to quickly check if node already exists
  38172. for (var i = 0; i < node.edges.length; i++) {
  38173. var edge = node.edges[i];
  38174. if (direction !== 'to' && edge.toId == node.id) {
  38175. // these are double equals since ids can be numeric or string
  38176. if (nodeObj[edge.fromId] === undefined) {
  38177. nodeList.push(edge.fromId);
  38178. nodeObj[edge.fromId] = true;
  38179. }
  38180. } else if (direction !== 'from' && edge.fromId == node.id) {
  38181. // these are double equals since ids can be numeric or string
  38182. if (nodeObj[edge.toId] === undefined) {
  38183. nodeList.push(edge.toId);
  38184. nodeObj[edge.toId] = true;
  38185. }
  38186. }
  38187. }
  38188. }
  38189. return nodeList;
  38190. }
  38191. /**
  38192. * Get the ids of the edges connected to this node.
  38193. * @param {Node.id} nodeId
  38194. * @returns {*}
  38195. */
  38196. }, {
  38197. key: 'getConnectedEdges',
  38198. value: function getConnectedEdges(nodeId) {
  38199. var edgeList = [];
  38200. if (this.body.nodes[nodeId] !== undefined) {
  38201. var node = this.body.nodes[nodeId];
  38202. for (var i = 0; i < node.edges.length; i++) {
  38203. edgeList.push(node.edges[i].id);
  38204. }
  38205. } else {
  38206. console.log("NodeId provided for getConnectedEdges does not exist. Provided: ", nodeId);
  38207. }
  38208. return edgeList;
  38209. }
  38210. /**
  38211. * Move a node.
  38212. *
  38213. * @param {Node.id} nodeId
  38214. * @param {number} x
  38215. * @param {number} y
  38216. */
  38217. }, {
  38218. key: 'moveNode',
  38219. value: function moveNode(nodeId, x, y) {
  38220. var _this4 = this;
  38221. if (this.body.nodes[nodeId] !== undefined) {
  38222. this.body.nodes[nodeId].x = Number(x);
  38223. this.body.nodes[nodeId].y = Number(y);
  38224. setTimeout(function () {
  38225. _this4.body.emitter.emit("startSimulation");
  38226. }, 0);
  38227. } else {
  38228. console.log("Node id supplied to moveNode does not exist. Provided: ", nodeId);
  38229. }
  38230. }
  38231. }]);
  38232. return NodesHandler;
  38233. }();
  38234. exports['default'] = NodesHandler;
  38235. /***/ }),
  38236. /* 188 */
  38237. /***/ (function(module, exports, __webpack_require__) {
  38238. module.exports = { "default": __webpack_require__(189), __esModule: true };
  38239. /***/ }),
  38240. /* 189 */
  38241. /***/ (function(module, exports, __webpack_require__) {
  38242. __webpack_require__(49);
  38243. __webpack_require__(60);
  38244. module.exports = __webpack_require__(190);
  38245. /***/ }),
  38246. /* 190 */
  38247. /***/ (function(module, exports, __webpack_require__) {
  38248. var classof = __webpack_require__(86);
  38249. var ITERATOR = __webpack_require__(13)('iterator');
  38250. var Iterators = __webpack_require__(31);
  38251. module.exports = __webpack_require__(7).isIterable = function (it) {
  38252. var O = Object(it);
  38253. return O[ITERATOR] !== undefined
  38254. || '@@iterator' in O
  38255. // eslint-disable-next-line no-prototype-builtins
  38256. || Iterators.hasOwnProperty(classof(O));
  38257. };
  38258. /***/ }),
  38259. /* 191 */
  38260. /***/ (function(module, exports, __webpack_require__) {
  38261. "use strict";
  38262. Object.defineProperty(exports, "__esModule", {
  38263. value: true
  38264. });
  38265. var _classCallCheck2 = __webpack_require__(0);
  38266. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  38267. var _createClass2 = __webpack_require__(1);
  38268. var _createClass3 = _interopRequireDefault(_createClass2);
  38269. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  38270. var LabelAccumulator = __webpack_require__(192)['default'];
  38271. var ComponentUtil = __webpack_require__(48)['default'];
  38272. /**
  38273. * Helper class for Label which explodes the label text into lines and blocks within lines
  38274. *
  38275. * @private
  38276. */
  38277. var LabelSplitter = function () {
  38278. /**
  38279. * @param {CanvasRenderingContext2D} ctx Canvas rendering context
  38280. * @param {Label} parent reference to the Label instance using current instance
  38281. * @param {boolean} selected
  38282. * @param {boolean} hover
  38283. */
  38284. function LabelSplitter(ctx, parent, selected, hover) {
  38285. var _this = this;
  38286. (0, _classCallCheck3['default'])(this, LabelSplitter);
  38287. this.ctx = ctx;
  38288. this.parent = parent;
  38289. /**
  38290. * Callback to determine text width; passed to LabelAccumulator instance
  38291. *
  38292. * @param {String} text string to determine width of
  38293. * @param {String} mod font type to use for this text
  38294. * @return {Object} { width, values} width in pixels and font attributes
  38295. */
  38296. var textWidth = function textWidth(text, mod) {
  38297. if (text === undefined) return 0;
  38298. // TODO: This can be done more efficiently with caching
  38299. var values = _this.parent.getFormattingValues(ctx, selected, hover, mod);
  38300. var width = 0;
  38301. if (text !== '') {
  38302. // NOTE: The following may actually be *incorrect* for the mod fonts!
  38303. // This returns the size with a regular font, bold etc. may
  38304. // have different sizes.
  38305. var measure = _this.ctx.measureText(text);
  38306. width = measure.width;
  38307. }
  38308. return { width: width, values: values };
  38309. };
  38310. this.lines = new LabelAccumulator(textWidth);
  38311. }
  38312. /**
  38313. * Split passed text of a label into lines and blocks.
  38314. *
  38315. * # NOTE
  38316. *
  38317. * The handling of spacing is option dependent:
  38318. *
  38319. * - if `font.multi : false`, all spaces are retained
  38320. * - if `font.multi : true`, every sequence of spaces is compressed to a single space
  38321. *
  38322. * This might not be the best way to do it, but this is as it has been working till now.
  38323. * In order not to break existing functionality, for the time being this behaviour will
  38324. * be retained in any code changes.
  38325. *
  38326. * @param {string} text text to split
  38327. * @returns {Array<line>}
  38328. */
  38329. (0, _createClass3['default'])(LabelSplitter, [{
  38330. key: 'process',
  38331. value: function process(text) {
  38332. if (!ComponentUtil.isValidLabel(text)) {
  38333. return this.lines.finalize();
  38334. }
  38335. var font = this.parent.fontOptions;
  38336. // Normalize the end-of-line's to a single representation - order important
  38337. text = text.replace(/\r\n/g, '\n'); // Dos EOL's
  38338. text = text.replace(/\r/g, '\n'); // Mac EOL's
  38339. // Note that at this point, there can be no \r's in the text.
  38340. // This is used later on splitStringIntoLines() to split multifont texts.
  38341. var nlLines = String(text).split('\n');
  38342. var lineCount = nlLines.length;
  38343. if (font.multi) {
  38344. // Multi-font case: styling tags active
  38345. for (var i = 0; i < lineCount; i++) {
  38346. var blocks = this.splitBlocks(nlLines[i], font.multi);
  38347. // Post: Sequences of tabs and spaces are reduced to single space
  38348. if (blocks === undefined) continue;
  38349. if (blocks.length === 0) {
  38350. this.lines.newLine("");
  38351. continue;
  38352. }
  38353. if (font.maxWdt > 0) {
  38354. // widthConstraint.maximum defined
  38355. //console.log('Running widthConstraint multi, max: ' + this.fontOptions.maxWdt);
  38356. for (var j = 0; j < blocks.length; j++) {
  38357. var mod = blocks[j].mod;
  38358. var _text = blocks[j].text;
  38359. this.splitStringIntoLines(_text, mod, true);
  38360. }
  38361. } else {
  38362. // widthConstraint.maximum NOT defined
  38363. for (var _j = 0; _j < blocks.length; _j++) {
  38364. var _mod = blocks[_j].mod;
  38365. var _text2 = blocks[_j].text;
  38366. this.lines.append(_text2, _mod);
  38367. }
  38368. }
  38369. this.lines.newLine();
  38370. }
  38371. } else {
  38372. // Single-font case
  38373. if (font.maxWdt > 0) {
  38374. // widthConstraint.maximum defined
  38375. // console.log('Running widthConstraint normal, max: ' + this.fontOptions.maxWdt);
  38376. for (var _i = 0; _i < lineCount; _i++) {
  38377. this.splitStringIntoLines(nlLines[_i]);
  38378. }
  38379. } else {
  38380. // widthConstraint.maximum NOT defined
  38381. for (var _i2 = 0; _i2 < lineCount; _i2++) {
  38382. this.lines.newLine(nlLines[_i2]);
  38383. }
  38384. }
  38385. }
  38386. return this.lines.finalize();
  38387. }
  38388. /**
  38389. * normalize the markup system
  38390. *
  38391. * @param {boolean|'md'|'markdown'|'html'} markupSystem
  38392. * @returns {string}
  38393. */
  38394. }, {
  38395. key: 'decodeMarkupSystem',
  38396. value: function decodeMarkupSystem(markupSystem) {
  38397. var system = 'none';
  38398. if (markupSystem === 'markdown' || markupSystem === 'md') {
  38399. system = 'markdown';
  38400. } else if (markupSystem === true || markupSystem === 'html') {
  38401. system = 'html';
  38402. }
  38403. return system;
  38404. }
  38405. /**
  38406. *
  38407. * @param {string} text
  38408. * @returns {Array}
  38409. */
  38410. }, {
  38411. key: 'splitHtmlBlocks',
  38412. value: function splitHtmlBlocks(text) {
  38413. var blocks = [];
  38414. // TODO: consolidate following + methods/closures with splitMarkdownBlocks()
  38415. // NOTE: sequences of tabs and spaces are reduced to single space; scan usage of `this.spacing` within method
  38416. var s = {
  38417. bold: false,
  38418. ital: false,
  38419. mono: false,
  38420. spacing: false,
  38421. position: 0,
  38422. buffer: "",
  38423. modStack: []
  38424. };
  38425. s.mod = function () {
  38426. return this.modStack.length === 0 ? 'normal' : this.modStack[0];
  38427. };
  38428. s.modName = function () {
  38429. if (this.modStack.length === 0) return 'normal';else if (this.modStack[0] === 'mono') return 'mono';else {
  38430. if (s.bold && s.ital) {
  38431. return 'boldital';
  38432. } else if (s.bold) {
  38433. return 'bold';
  38434. } else if (s.ital) {
  38435. return 'ital';
  38436. }
  38437. }
  38438. };
  38439. s.emitBlock = function () {
  38440. var override = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  38441. // eslint-disable-line no-unused-vars
  38442. if (this.spacing) {
  38443. this.add(" ");
  38444. this.spacing = false;
  38445. }
  38446. if (this.buffer.length > 0) {
  38447. blocks.push({ text: this.buffer, mod: this.modName() });
  38448. this.buffer = "";
  38449. }
  38450. };
  38451. s.add = function (text) {
  38452. if (text === " ") {
  38453. s.spacing = true;
  38454. }
  38455. if (s.spacing) {
  38456. this.buffer += " ";
  38457. this.spacing = false;
  38458. }
  38459. if (text != " ") {
  38460. this.buffer += text;
  38461. }
  38462. };
  38463. while (s.position < text.length) {
  38464. var ch = text.charAt(s.position);
  38465. if (/[ \t]/.test(ch)) {
  38466. if (!s.mono) {
  38467. s.spacing = true;
  38468. } else {
  38469. s.add(ch);
  38470. }
  38471. } else if (/</.test(ch)) {
  38472. if (!s.mono && !s.bold && /<b>/.test(text.substr(s.position, 3))) {
  38473. s.emitBlock();
  38474. s.bold = true;
  38475. s.modStack.unshift("bold");
  38476. s.position += 2;
  38477. } else if (!s.mono && !s.ital && /<i>/.test(text.substr(s.position, 3))) {
  38478. s.emitBlock();
  38479. s.ital = true;
  38480. s.modStack.unshift("ital");
  38481. s.position += 2;
  38482. } else if (!s.mono && /<code>/.test(text.substr(s.position, 6))) {
  38483. s.emitBlock();
  38484. s.mono = true;
  38485. s.modStack.unshift("mono");
  38486. s.position += 5;
  38487. } else if (!s.mono && s.mod() === 'bold' && /<\/b>/.test(text.substr(s.position, 4))) {
  38488. s.emitBlock();
  38489. s.bold = false;
  38490. s.modStack.shift();
  38491. s.position += 3;
  38492. } else if (!s.mono && s.mod() === 'ital' && /<\/i>/.test(text.substr(s.position, 4))) {
  38493. s.emitBlock();
  38494. s.ital = false;
  38495. s.modStack.shift();
  38496. s.position += 3;
  38497. } else if (s.mod() === 'mono' && /<\/code>/.test(text.substr(s.position, 7))) {
  38498. s.emitBlock();
  38499. s.mono = false;
  38500. s.modStack.shift();
  38501. s.position += 6;
  38502. } else {
  38503. s.add(ch);
  38504. }
  38505. } else if (/&/.test(ch)) {
  38506. if (/&lt;/.test(text.substr(s.position, 4))) {
  38507. s.add("<");
  38508. s.position += 3;
  38509. } else if (/&amp;/.test(text.substr(s.position, 5))) {
  38510. s.add("&");
  38511. s.position += 4;
  38512. } else {
  38513. s.add("&");
  38514. }
  38515. } else {
  38516. s.add(ch);
  38517. }
  38518. s.position++;
  38519. }
  38520. s.emitBlock();
  38521. return blocks;
  38522. }
  38523. /**
  38524. *
  38525. * @param {string} text
  38526. * @returns {Array}
  38527. */
  38528. }, {
  38529. key: 'splitMarkdownBlocks',
  38530. value: function splitMarkdownBlocks(text) {
  38531. var blocks = [];
  38532. // TODO: consolidate following + methods/closures with splitHtmlBlocks()
  38533. // NOTE: sequences of tabs and spaces are reduced to single space; scan usage of `this.spacing` within method
  38534. var s = {
  38535. bold: false,
  38536. ital: false,
  38537. mono: false,
  38538. beginable: true,
  38539. spacing: false,
  38540. position: 0,
  38541. buffer: "",
  38542. modStack: []
  38543. };
  38544. s.mod = function () {
  38545. return this.modStack.length === 0 ? 'normal' : this.modStack[0];
  38546. };
  38547. s.modName = function () {
  38548. if (this.modStack.length === 0) return 'normal';else if (this.modStack[0] === 'mono') return 'mono';else {
  38549. if (s.bold && s.ital) {
  38550. return 'boldital';
  38551. } else if (s.bold) {
  38552. return 'bold';
  38553. } else if (s.ital) {
  38554. return 'ital';
  38555. }
  38556. }
  38557. };
  38558. s.emitBlock = function () {
  38559. var override = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  38560. // eslint-disable-line no-unused-vars
  38561. if (this.spacing) {
  38562. this.add(" ");
  38563. this.spacing = false;
  38564. }
  38565. if (this.buffer.length > 0) {
  38566. blocks.push({ text: this.buffer, mod: this.modName() });
  38567. this.buffer = "";
  38568. }
  38569. };
  38570. s.add = function (text) {
  38571. if (text === " ") {
  38572. s.spacing = true;
  38573. }
  38574. if (s.spacing) {
  38575. this.buffer += " ";
  38576. this.spacing = false;
  38577. }
  38578. if (text != " ") {
  38579. this.buffer += text;
  38580. }
  38581. };
  38582. while (s.position < text.length) {
  38583. var ch = text.charAt(s.position);
  38584. if (/[ \t]/.test(ch)) {
  38585. if (!s.mono) {
  38586. s.spacing = true;
  38587. } else {
  38588. s.add(ch);
  38589. }
  38590. s.beginable = true;
  38591. } else if (/\\/.test(ch)) {
  38592. if (s.position < text.length + 1) {
  38593. s.position++;
  38594. ch = text.charAt(s.position);
  38595. if (/ \t/.test(ch)) {
  38596. s.spacing = true;
  38597. } else {
  38598. s.add(ch);
  38599. s.beginable = false;
  38600. }
  38601. }
  38602. } else if (!s.mono && !s.bold && (s.beginable || s.spacing) && /\*/.test(ch)) {
  38603. s.emitBlock();
  38604. s.bold = true;
  38605. s.modStack.unshift("bold");
  38606. } else if (!s.mono && !s.ital && (s.beginable || s.spacing) && /\_/.test(ch)) {
  38607. s.emitBlock();
  38608. s.ital = true;
  38609. s.modStack.unshift("ital");
  38610. } else if (!s.mono && (s.beginable || s.spacing) && /`/.test(ch)) {
  38611. s.emitBlock();
  38612. s.mono = true;
  38613. s.modStack.unshift("mono");
  38614. } else if (!s.mono && s.mod() === "bold" && /\*/.test(ch)) {
  38615. if (s.position === text.length - 1 || /[.,_` \t\n]/.test(text.charAt(s.position + 1))) {
  38616. s.emitBlock();
  38617. s.bold = false;
  38618. s.modStack.shift();
  38619. } else {
  38620. s.add(ch);
  38621. }
  38622. } else if (!s.mono && s.mod() === "ital" && /\_/.test(ch)) {
  38623. if (s.position === text.length - 1 || /[.,*` \t\n]/.test(text.charAt(s.position + 1))) {
  38624. s.emitBlock();
  38625. s.ital = false;
  38626. s.modStack.shift();
  38627. } else {
  38628. s.add(ch);
  38629. }
  38630. } else if (s.mono && s.mod() === "mono" && /`/.test(ch)) {
  38631. if (s.position === text.length - 1 || /[.,*_ \t\n]/.test(text.charAt(s.position + 1))) {
  38632. s.emitBlock();
  38633. s.mono = false;
  38634. s.modStack.shift();
  38635. } else {
  38636. s.add(ch);
  38637. }
  38638. } else {
  38639. s.add(ch);
  38640. s.beginable = false;
  38641. }
  38642. s.position++;
  38643. }
  38644. s.emitBlock();
  38645. return blocks;
  38646. }
  38647. /**
  38648. * Explodes a piece of text into single-font blocks using a given markup
  38649. *
  38650. * @param {string} text
  38651. * @param {boolean|'md'|'markdown'|'html'} markupSystem
  38652. * @returns {Array.<{text: string, mod: string}>}
  38653. * @private
  38654. */
  38655. }, {
  38656. key: 'splitBlocks',
  38657. value: function splitBlocks(text, markupSystem) {
  38658. var system = this.decodeMarkupSystem(markupSystem);
  38659. if (system === 'none') {
  38660. return [{
  38661. text: text,
  38662. mod: 'normal'
  38663. }];
  38664. } else if (system === 'markdown') {
  38665. return this.splitMarkdownBlocks(text);
  38666. } else if (system === 'html') {
  38667. return this.splitHtmlBlocks(text);
  38668. }
  38669. }
  38670. /**
  38671. * @param {string} text
  38672. * @returns {boolean} true if text length over the current max with
  38673. * @private
  38674. */
  38675. }, {
  38676. key: 'overMaxWidth',
  38677. value: function overMaxWidth(text) {
  38678. var width = this.ctx.measureText(text).width;
  38679. return this.lines.curWidth() + width > this.parent.fontOptions.maxWdt;
  38680. }
  38681. /**
  38682. * Determine the longest part of the sentence which still fits in the
  38683. * current max width.
  38684. *
  38685. * @param {Array} words Array of strings signifying a text lines
  38686. * @return {number} index of first item in string making string go over max
  38687. * @private
  38688. */
  38689. }, {
  38690. key: 'getLongestFit',
  38691. value: function getLongestFit(words) {
  38692. var text = '';
  38693. var w = 0;
  38694. while (w < words.length) {
  38695. var pre = text === '' ? '' : ' ';
  38696. var newText = text + pre + words[w];
  38697. if (this.overMaxWidth(newText)) break;
  38698. text = newText;
  38699. w++;
  38700. }
  38701. return w;
  38702. }
  38703. /**
  38704. * Determine the longest part of the string which still fits in the
  38705. * current max width.
  38706. *
  38707. * @param {Array} words Array of strings signifying a text lines
  38708. * @return {number} index of first item in string making string go over max
  38709. */
  38710. }, {
  38711. key: 'getLongestFitWord',
  38712. value: function getLongestFitWord(words) {
  38713. var w = 0;
  38714. while (w < words.length) {
  38715. if (this.overMaxWidth(words.slice(0, w))) break;
  38716. w++;
  38717. }
  38718. return w;
  38719. }
  38720. /**
  38721. * Split the passed text into lines, according to width constraint (if any).
  38722. *
  38723. * The method assumes that the input string is a single line, i.e. without lines break.
  38724. *
  38725. * This method retains spaces, if still present (case `font.multi: false`).
  38726. * A space which falls on an internal line break, will be replaced by a newline.
  38727. * There is no special handling of tabs; these go along with the flow.
  38728. *
  38729. * @param {string} str
  38730. * @param {string} [mod='normal']
  38731. * @param {boolean} [appendLast=false]
  38732. * @private
  38733. */
  38734. }, {
  38735. key: 'splitStringIntoLines',
  38736. value: function splitStringIntoLines(str) {
  38737. var mod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'normal';
  38738. var appendLast = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  38739. // Still-present spaces are relevant, retain them
  38740. str = str.replace(/^( +)/g, '$1\r');
  38741. str = str.replace(/([^\r][^ ]*)( +)/g, '$1\r$2\r');
  38742. var words = str.split('\r');
  38743. while (words.length > 0) {
  38744. var w = this.getLongestFit(words);
  38745. if (w === 0) {
  38746. // Special case: the first word is already larger than the max width.
  38747. var word = words[0];
  38748. // Break the word to the largest part that fits the line
  38749. var x = this.getLongestFitWord(word);
  38750. this.lines.newLine(word.slice(0, x), mod);
  38751. // Adjust the word, so that the rest will be done next iteration
  38752. words[0] = word.slice(x);
  38753. } else {
  38754. // skip any space that is replaced by a newline
  38755. var newW = w;
  38756. if (words[w - 1] === ' ') {
  38757. w--;
  38758. } else if (words[newW] === ' ') {
  38759. newW++;
  38760. }
  38761. var text = words.slice(0, w).join("");
  38762. if (w == words.length && appendLast) {
  38763. this.lines.append(text, mod);
  38764. } else {
  38765. this.lines.newLine(text, mod);
  38766. }
  38767. // Adjust the word, so that the rest will be done next iteration
  38768. words = words.slice(newW);
  38769. }
  38770. }
  38771. }
  38772. }]);
  38773. return LabelSplitter;
  38774. }();
  38775. exports['default'] = LabelSplitter;
  38776. /***/ }),
  38777. /* 192 */
  38778. /***/ (function(module, exports, __webpack_require__) {
  38779. "use strict";
  38780. Object.defineProperty(exports, "__esModule", {
  38781. value: true
  38782. });
  38783. var _assign = __webpack_require__(90);
  38784. var _assign2 = _interopRequireDefault(_assign);
  38785. var _classCallCheck2 = __webpack_require__(0);
  38786. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  38787. var _createClass2 = __webpack_require__(1);
  38788. var _createClass3 = _interopRequireDefault(_createClass2);
  38789. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  38790. /**
  38791. * Callback to determine text dimensions, using the parent label settings.
  38792. * @callback MeasureText
  38793. * @param {text} text
  38794. * @param {text} mod
  38795. * @return {Object} { width, values} width in pixels and font attributes
  38796. */
  38797. /**
  38798. * Helper class for Label which collects results of splitting labels into lines and blocks.
  38799. *
  38800. * @private
  38801. */
  38802. var LabelAccumulator = function () {
  38803. /**
  38804. * @param {MeasureText} measureText
  38805. */
  38806. function LabelAccumulator(measureText) {
  38807. (0, _classCallCheck3["default"])(this, LabelAccumulator);
  38808. this.measureText = measureText;
  38809. this.current = 0;
  38810. this.width = 0;
  38811. this.height = 0;
  38812. this.lines = [];
  38813. }
  38814. /**
  38815. * Append given text to the given line.
  38816. *
  38817. * @param {number} l index of line to add to
  38818. * @param {string} text string to append to line
  38819. * @param {'bold'|'ital'|'boldital'|'mono'|'normal'} [mod='normal']
  38820. * @private
  38821. */
  38822. (0, _createClass3["default"])(LabelAccumulator, [{
  38823. key: "_add",
  38824. value: function _add(l, text) {
  38825. var mod = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'normal';
  38826. if (this.lines[l] === undefined) {
  38827. this.lines[l] = {
  38828. width: 0,
  38829. height: 0,
  38830. blocks: []
  38831. };
  38832. }
  38833. // We still need to set a block for undefined and empty texts, hence return at this point
  38834. // This is necessary because we don't know at this point if we're at the
  38835. // start of an empty line or not.
  38836. // To compensate, empty blocks are removed in `finalize()`.
  38837. //
  38838. // Empty strings should still have a height
  38839. var tmpText = text;
  38840. if (text === undefined || text === "") tmpText = " ";
  38841. // Determine width and get the font properties
  38842. var result = this.measureText(tmpText, mod);
  38843. var block = (0, _assign2["default"])({}, result.values);
  38844. block.text = text;
  38845. block.width = result.width;
  38846. block.mod = mod;
  38847. if (text === undefined || text === "") {
  38848. block.width = 0;
  38849. }
  38850. this.lines[l].blocks.push(block);
  38851. // Update the line width. We need this for determining if a string goes over max width
  38852. this.lines[l].width += block.width;
  38853. }
  38854. /**
  38855. * Returns the width in pixels of the current line.
  38856. *
  38857. * @returns {number}
  38858. */
  38859. }, {
  38860. key: "curWidth",
  38861. value: function curWidth() {
  38862. var line = this.lines[this.current];
  38863. if (line === undefined) return 0;
  38864. return line.width;
  38865. }
  38866. /**
  38867. * Add text in block to current line
  38868. *
  38869. * @param {string} text
  38870. * @param {'bold'|'ital'|'boldital'|'mono'|'normal'} [mod='normal']
  38871. */
  38872. }, {
  38873. key: "append",
  38874. value: function append(text) {
  38875. var mod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'normal';
  38876. this._add(this.current, text, mod);
  38877. }
  38878. /**
  38879. * Add text in block to current line and start a new line
  38880. *
  38881. * @param {string} text
  38882. * @param {'bold'|'ital'|'boldital'|'mono'|'normal'} [mod='normal']
  38883. */
  38884. }, {
  38885. key: "newLine",
  38886. value: function newLine(text) {
  38887. var mod = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'normal';
  38888. this._add(this.current, text, mod);
  38889. this.current++;
  38890. }
  38891. /**
  38892. * Determine and set the heights of all the lines currently contained in this instance
  38893. *
  38894. * Note that width has already been set.
  38895. *
  38896. * @private
  38897. */
  38898. }, {
  38899. key: "determineLineHeights",
  38900. value: function determineLineHeights() {
  38901. for (var k = 0; k < this.lines.length; k++) {
  38902. var line = this.lines[k];
  38903. // Looking for max height of blocks in line
  38904. var height = 0;
  38905. if (line.blocks !== undefined) {
  38906. // Can happen if text contains e.g. '\n '
  38907. for (var l = 0; l < line.blocks.length; l++) {
  38908. var block = line.blocks[l];
  38909. if (height < block.height) {
  38910. height = block.height;
  38911. }
  38912. }
  38913. }
  38914. line.height = height;
  38915. }
  38916. }
  38917. /**
  38918. * Determine the full size of the label text, as determined by current lines and blocks
  38919. *
  38920. * @private
  38921. */
  38922. }, {
  38923. key: "determineLabelSize",
  38924. value: function determineLabelSize() {
  38925. var width = 0;
  38926. var height = 0;
  38927. for (var k = 0; k < this.lines.length; k++) {
  38928. var line = this.lines[k];
  38929. if (line.width > width) {
  38930. width = line.width;
  38931. }
  38932. height += line.height;
  38933. }
  38934. this.width = width;
  38935. this.height = height;
  38936. }
  38937. /**
  38938. * Remove all empty blocks and empty lines we don't need
  38939. *
  38940. * This must be done after the width/height determination,
  38941. * so that these are set properly for processing here.
  38942. *
  38943. * @returns {Array<Line>} Lines with empty blocks (and some empty lines) removed
  38944. * @private
  38945. */
  38946. }, {
  38947. key: "removeEmptyBlocks",
  38948. value: function removeEmptyBlocks() {
  38949. var tmpLines = [];
  38950. for (var k = 0; k < this.lines.length; k++) {
  38951. var line = this.lines[k];
  38952. // Note: an empty line in between text has width zero but is still relevant to layout.
  38953. // So we can't use width for testing empty line here
  38954. if (line.blocks.length === 0) continue;
  38955. // Discard final empty line always
  38956. if (k === this.lines.length - 1) {
  38957. if (line.width === 0) continue;
  38958. }
  38959. var tmpLine = {};
  38960. (0, _assign2["default"])(tmpLine, line);
  38961. tmpLine.blocks = [];
  38962. var firstEmptyBlock = void 0;
  38963. var tmpBlocks = [];
  38964. for (var l = 0; l < line.blocks.length; l++) {
  38965. var block = line.blocks[l];
  38966. if (block.width !== 0) {
  38967. tmpBlocks.push(block);
  38968. } else {
  38969. if (firstEmptyBlock === undefined) {
  38970. firstEmptyBlock = block;
  38971. }
  38972. }
  38973. }
  38974. // Ensure that there is *some* text present
  38975. if (tmpBlocks.length === 0 && firstEmptyBlock !== undefined) {
  38976. tmpBlocks.push(firstEmptyBlock);
  38977. }
  38978. tmpLine.blocks = tmpBlocks;
  38979. tmpLines.push(tmpLine);
  38980. }
  38981. return tmpLines;
  38982. }
  38983. /**
  38984. * Set the sizes for all lines and the whole thing.
  38985. *
  38986. * @returns {{width: (number|*), height: (number|*), lines: Array}}
  38987. */
  38988. }, {
  38989. key: "finalize",
  38990. value: function finalize() {
  38991. //console.log(JSON.stringify(this.lines, null, 2));
  38992. this.determineLineHeights();
  38993. this.determineLabelSize();
  38994. var tmpLines = this.removeEmptyBlocks();
  38995. // Return a simple hash object for further processing.
  38996. return {
  38997. width: this.width,
  38998. height: this.height,
  38999. lines: tmpLines
  39000. };
  39001. }
  39002. }]);
  39003. return LabelAccumulator;
  39004. }();
  39005. exports["default"] = LabelAccumulator;
  39006. /***/ }),
  39007. /* 193 */
  39008. /***/ (function(module, exports, __webpack_require__) {
  39009. "use strict";
  39010. Object.defineProperty(exports, "__esModule", {
  39011. value: true
  39012. });
  39013. var _getPrototypeOf = __webpack_require__(3);
  39014. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  39015. var _classCallCheck2 = __webpack_require__(0);
  39016. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  39017. var _createClass2 = __webpack_require__(1);
  39018. var _createClass3 = _interopRequireDefault(_createClass2);
  39019. var _possibleConstructorReturn2 = __webpack_require__(4);
  39020. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  39021. var _inherits2 = __webpack_require__(5);
  39022. var _inherits3 = _interopRequireDefault(_inherits2);
  39023. var _NodeBase2 = __webpack_require__(23);
  39024. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  39025. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  39026. /**
  39027. * A Box Node/Cluster shape.
  39028. *
  39029. * @extends NodeBase
  39030. */
  39031. var Box = function (_NodeBase) {
  39032. (0, _inherits3['default'])(Box, _NodeBase);
  39033. /**
  39034. * @param {Object} options
  39035. * @param {Object} body
  39036. * @param {Label} labelModule
  39037. */
  39038. function Box(options, body, labelModule) {
  39039. (0, _classCallCheck3['default'])(this, Box);
  39040. var _this = (0, _possibleConstructorReturn3['default'])(this, (Box.__proto__ || (0, _getPrototypeOf2['default'])(Box)).call(this, options, body, labelModule));
  39041. _this._setMargins(labelModule);
  39042. return _this;
  39043. }
  39044. /**
  39045. *
  39046. * @param {CanvasRenderingContext2D} ctx
  39047. * @param {boolean} [selected]
  39048. * @param {boolean} [hover]
  39049. */
  39050. (0, _createClass3['default'])(Box, [{
  39051. key: 'resize',
  39052. value: function resize(ctx) {
  39053. var selected = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.selected;
  39054. var hover = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.hover;
  39055. if (this.needsRefresh(selected, hover)) {
  39056. var dimensions = this.getDimensionsFromLabel(ctx, selected, hover);
  39057. this.width = dimensions.width + this.margin.right + this.margin.left;
  39058. this.height = dimensions.height + this.margin.top + this.margin.bottom;
  39059. this.radius = this.width / 2;
  39060. }
  39061. }
  39062. /**
  39063. *
  39064. * @param {CanvasRenderingContext2D} ctx
  39065. * @param {number} x width
  39066. * @param {number} y height
  39067. * @param {boolean} selected
  39068. * @param {boolean} hover
  39069. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  39070. */
  39071. }, {
  39072. key: 'draw',
  39073. value: function draw(ctx, x, y, selected, hover, values) {
  39074. this.resize(ctx, selected, hover);
  39075. this.left = x - this.width / 2;
  39076. this.top = y - this.height / 2;
  39077. this.initContextForDraw(ctx, values);
  39078. ctx.roundRect(this.left, this.top, this.width, this.height, values.borderRadius);
  39079. this.performFill(ctx, values);
  39080. this.updateBoundingBox(x, y, ctx, selected, hover);
  39081. this.labelModule.draw(ctx, this.left + this.textSize.width / 2 + this.margin.left, this.top + this.textSize.height / 2 + this.margin.top, selected, hover);
  39082. }
  39083. /**
  39084. *
  39085. * @param {number} x width
  39086. * @param {number} y height
  39087. * @param {CanvasRenderingContext2D} ctx
  39088. * @param {boolean} selected
  39089. * @param {boolean} hover
  39090. */
  39091. }, {
  39092. key: 'updateBoundingBox',
  39093. value: function updateBoundingBox(x, y, ctx, selected, hover) {
  39094. this._updateBoundingBox(x, y, ctx, selected, hover);
  39095. var borderRadius = this.options.shapeProperties.borderRadius; // only effective for box
  39096. this._addBoundingBoxMargin(borderRadius);
  39097. }
  39098. /**
  39099. *
  39100. * @param {CanvasRenderingContext2D} ctx
  39101. * @param {number} angle
  39102. * @returns {number}
  39103. */
  39104. }, {
  39105. key: 'distanceToBorder',
  39106. value: function distanceToBorder(ctx, angle) {
  39107. this.resize(ctx);
  39108. var borderWidth = this.options.borderWidth;
  39109. return Math.min(Math.abs(this.width / 2 / Math.cos(angle)), Math.abs(this.height / 2 / Math.sin(angle))) + borderWidth;
  39110. }
  39111. }]);
  39112. return Box;
  39113. }(_NodeBase3['default']);
  39114. exports['default'] = Box;
  39115. /***/ }),
  39116. /* 194 */
  39117. /***/ (function(module, exports, __webpack_require__) {
  39118. __webpack_require__(195);
  39119. module.exports = __webpack_require__(7).Object.getPrototypeOf;
  39120. /***/ }),
  39121. /* 195 */
  39122. /***/ (function(module, exports, __webpack_require__) {
  39123. // 19.1.2.9 Object.getPrototypeOf(O)
  39124. var toObject = __webpack_require__(41);
  39125. var $getPrototypeOf = __webpack_require__(85);
  39126. __webpack_require__(87)('getPrototypeOf', function () {
  39127. return function getPrototypeOf(it) {
  39128. return $getPrototypeOf(toObject(it));
  39129. };
  39130. });
  39131. /***/ }),
  39132. /* 196 */
  39133. /***/ (function(module, exports, __webpack_require__) {
  39134. module.exports = { "default": __webpack_require__(197), __esModule: true };
  39135. /***/ }),
  39136. /* 197 */
  39137. /***/ (function(module, exports, __webpack_require__) {
  39138. __webpack_require__(198);
  39139. module.exports = __webpack_require__(7).Object.setPrototypeOf;
  39140. /***/ }),
  39141. /* 198 */
  39142. /***/ (function(module, exports, __webpack_require__) {
  39143. // 19.1.3.19 Object.setPrototypeOf(O, proto)
  39144. var $export = __webpack_require__(17);
  39145. $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(199).set });
  39146. /***/ }),
  39147. /* 199 */
  39148. /***/ (function(module, exports, __webpack_require__) {
  39149. // Works with __proto__ only. Old v8 can't work with null proto objects.
  39150. /* eslint-disable no-proto */
  39151. var isObject = __webpack_require__(32);
  39152. var anObject = __webpack_require__(27);
  39153. var check = function (O, proto) {
  39154. anObject(O);
  39155. if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!");
  39156. };
  39157. module.exports = {
  39158. set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
  39159. function (test, buggy, set) {
  39160. try {
  39161. set = __webpack_require__(80)(Function.call, __webpack_require__(89).f(Object.prototype, '__proto__').set, 2);
  39162. set(test, []);
  39163. buggy = !(test instanceof Array);
  39164. } catch (e) { buggy = true; }
  39165. return function setPrototypeOf(O, proto) {
  39166. check(O, proto);
  39167. if (buggy) O.__proto__ = proto;
  39168. else set(O, proto);
  39169. return O;
  39170. };
  39171. }({}, false) : undefined),
  39172. check: check
  39173. };
  39174. /***/ }),
  39175. /* 200 */
  39176. /***/ (function(module, exports, __webpack_require__) {
  39177. "use strict";
  39178. Object.defineProperty(exports, "__esModule", {
  39179. value: true
  39180. });
  39181. var _getPrototypeOf = __webpack_require__(3);
  39182. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  39183. var _classCallCheck2 = __webpack_require__(0);
  39184. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  39185. var _createClass2 = __webpack_require__(1);
  39186. var _createClass3 = _interopRequireDefault(_createClass2);
  39187. var _possibleConstructorReturn2 = __webpack_require__(4);
  39188. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  39189. var _inherits2 = __webpack_require__(5);
  39190. var _inherits3 = _interopRequireDefault(_inherits2);
  39191. var _CircleImageBase2 = __webpack_require__(73);
  39192. var _CircleImageBase3 = _interopRequireDefault(_CircleImageBase2);
  39193. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  39194. /**
  39195. * A Circle Node/Cluster shape.
  39196. *
  39197. * @extends CircleImageBase
  39198. */
  39199. var Circle = function (_CircleImageBase) {
  39200. (0, _inherits3['default'])(Circle, _CircleImageBase);
  39201. /**
  39202. * @param {Object} options
  39203. * @param {Object} body
  39204. * @param {Label} labelModule
  39205. */
  39206. function Circle(options, body, labelModule) {
  39207. (0, _classCallCheck3['default'])(this, Circle);
  39208. var _this = (0, _possibleConstructorReturn3['default'])(this, (Circle.__proto__ || (0, _getPrototypeOf2['default'])(Circle)).call(this, options, body, labelModule));
  39209. _this._setMargins(labelModule);
  39210. return _this;
  39211. }
  39212. /**
  39213. *
  39214. * @param {CanvasRenderingContext2D} ctx
  39215. * @param {boolean} [selected]
  39216. * @param {boolean} [hover]
  39217. */
  39218. (0, _createClass3['default'])(Circle, [{
  39219. key: 'resize',
  39220. value: function resize(ctx) {
  39221. var selected = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.selected;
  39222. var hover = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.hover;
  39223. if (this.needsRefresh(selected, hover)) {
  39224. var dimensions = this.getDimensionsFromLabel(ctx, selected, hover);
  39225. var diameter = Math.max(dimensions.width + this.margin.right + this.margin.left, dimensions.height + this.margin.top + this.margin.bottom);
  39226. this.options.size = diameter / 2; // NOTE: this size field only set here, not in Ellipse, Database, Box
  39227. this.width = diameter;
  39228. this.height = diameter;
  39229. this.radius = this.width / 2;
  39230. }
  39231. }
  39232. /**
  39233. *
  39234. * @param {CanvasRenderingContext2D} ctx
  39235. * @param {number} x width
  39236. * @param {number} y height
  39237. * @param {boolean} selected
  39238. * @param {boolean} hover
  39239. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  39240. */
  39241. }, {
  39242. key: 'draw',
  39243. value: function draw(ctx, x, y, selected, hover, values) {
  39244. this.resize(ctx, selected, hover);
  39245. this.left = x - this.width / 2;
  39246. this.top = y - this.height / 2;
  39247. this._drawRawCircle(ctx, x, y, values);
  39248. this.updateBoundingBox(x, y);
  39249. this.labelModule.draw(ctx, this.left + this.textSize.width / 2 + this.margin.left, y, selected, hover);
  39250. }
  39251. /**
  39252. *
  39253. * @param {number} x width
  39254. * @param {number} y height
  39255. */
  39256. }, {
  39257. key: 'updateBoundingBox',
  39258. value: function updateBoundingBox(x, y) {
  39259. this.boundingBox.top = y - this.options.size;
  39260. this.boundingBox.left = x - this.options.size;
  39261. this.boundingBox.right = x + this.options.size;
  39262. this.boundingBox.bottom = y + this.options.size;
  39263. }
  39264. /**
  39265. *
  39266. * @param {CanvasRenderingContext2D} ctx
  39267. * @param {number} angle - Unused
  39268. * @returns {number}
  39269. */
  39270. }, {
  39271. key: 'distanceToBorder',
  39272. value: function distanceToBorder(ctx, angle) {
  39273. // eslint-disable-line no-unused-vars
  39274. this.resize(ctx);
  39275. return this.width * 0.5;
  39276. }
  39277. }]);
  39278. return Circle;
  39279. }(_CircleImageBase3['default']);
  39280. exports['default'] = Circle;
  39281. /***/ }),
  39282. /* 201 */
  39283. /***/ (function(module, exports, __webpack_require__) {
  39284. "use strict";
  39285. Object.defineProperty(exports, "__esModule", {
  39286. value: true
  39287. });
  39288. var _getPrototypeOf = __webpack_require__(3);
  39289. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  39290. var _classCallCheck2 = __webpack_require__(0);
  39291. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  39292. var _createClass2 = __webpack_require__(1);
  39293. var _createClass3 = _interopRequireDefault(_createClass2);
  39294. var _possibleConstructorReturn2 = __webpack_require__(4);
  39295. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  39296. var _inherits2 = __webpack_require__(5);
  39297. var _inherits3 = _interopRequireDefault(_inherits2);
  39298. var _CircleImageBase2 = __webpack_require__(73);
  39299. var _CircleImageBase3 = _interopRequireDefault(_CircleImageBase2);
  39300. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  39301. /**
  39302. * A CircularImage Node/Cluster shape.
  39303. *
  39304. * @extends CircleImageBase
  39305. */
  39306. var CircularImage = function (_CircleImageBase) {
  39307. (0, _inherits3['default'])(CircularImage, _CircleImageBase);
  39308. /**
  39309. * @param {Object} options
  39310. * @param {Object} body
  39311. * @param {Label} labelModule
  39312. * @param {Image} imageObj
  39313. * @param {Image} imageObjAlt
  39314. */
  39315. function CircularImage(options, body, labelModule, imageObj, imageObjAlt) {
  39316. (0, _classCallCheck3['default'])(this, CircularImage);
  39317. var _this = (0, _possibleConstructorReturn3['default'])(this, (CircularImage.__proto__ || (0, _getPrototypeOf2['default'])(CircularImage)).call(this, options, body, labelModule));
  39318. _this.setImages(imageObj, imageObjAlt);
  39319. return _this;
  39320. }
  39321. /**
  39322. *
  39323. * @param {CanvasRenderingContext2D} ctx
  39324. * @param {boolean} [selected]
  39325. * @param {boolean} [hover]
  39326. */
  39327. (0, _createClass3['default'])(CircularImage, [{
  39328. key: 'resize',
  39329. value: function resize(ctx) {
  39330. var selected = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.selected;
  39331. var hover = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.hover;
  39332. var imageAbsent = this.imageObj.src === undefined || this.imageObj.width === undefined || this.imageObj.height === undefined;
  39333. if (imageAbsent) {
  39334. var diameter = this.options.size * 2;
  39335. this.width = diameter;
  39336. this.height = diameter;
  39337. this.radius = 0.5 * this.width;
  39338. return;
  39339. }
  39340. // At this point, an image is present, i.e. this.imageObj is valid.
  39341. if (this.needsRefresh(selected, hover)) {
  39342. this._resizeImage();
  39343. }
  39344. }
  39345. /**
  39346. *
  39347. * @param {CanvasRenderingContext2D} ctx
  39348. * @param {number} x width
  39349. * @param {number} y height
  39350. * @param {boolean} selected
  39351. * @param {boolean} hover
  39352. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  39353. */
  39354. }, {
  39355. key: 'draw',
  39356. value: function draw(ctx, x, y, selected, hover, values) {
  39357. this.switchImages(selected);
  39358. this.resize();
  39359. this.left = x - this.width / 2;
  39360. this.top = y - this.height / 2;
  39361. // draw the background circle. IMPORTANT: the stroke in this method is used by the clip method below.
  39362. this._drawRawCircle(ctx, x, y, values);
  39363. // now we draw in the circle, we save so we can revert the clip operation after drawing.
  39364. ctx.save();
  39365. // clip is used to use the stroke in drawRawCircle as an area that we can draw in.
  39366. ctx.clip();
  39367. // draw the image
  39368. this._drawImageAtPosition(ctx, values);
  39369. // restore so we can again draw on the full canvas
  39370. ctx.restore();
  39371. this._drawImageLabel(ctx, x, y, selected, hover);
  39372. this.updateBoundingBox(x, y);
  39373. }
  39374. // TODO: compare with Circle.updateBoundingBox(), consolidate? More stuff is happening here
  39375. /**
  39376. *
  39377. * @param {number} x width
  39378. * @param {number} y height
  39379. */
  39380. }, {
  39381. key: 'updateBoundingBox',
  39382. value: function updateBoundingBox(x, y) {
  39383. this.boundingBox.top = y - this.options.size;
  39384. this.boundingBox.left = x - this.options.size;
  39385. this.boundingBox.right = x + this.options.size;
  39386. this.boundingBox.bottom = y + this.options.size;
  39387. // TODO: compare with Image.updateBoundingBox(), consolidate?
  39388. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left);
  39389. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width);
  39390. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelOffset);
  39391. }
  39392. /**
  39393. *
  39394. * @param {CanvasRenderingContext2D} ctx
  39395. * @param {number} angle - Unused
  39396. * @returns {number}
  39397. */
  39398. }, {
  39399. key: 'distanceToBorder',
  39400. value: function distanceToBorder(ctx, angle) {
  39401. // eslint-disable-line no-unused-vars
  39402. this.resize(ctx);
  39403. return this.width * 0.5;
  39404. }
  39405. }]);
  39406. return CircularImage;
  39407. }(_CircleImageBase3['default']);
  39408. exports['default'] = CircularImage;
  39409. /***/ }),
  39410. /* 202 */
  39411. /***/ (function(module, exports, __webpack_require__) {
  39412. "use strict";
  39413. Object.defineProperty(exports, "__esModule", {
  39414. value: true
  39415. });
  39416. var _getPrototypeOf = __webpack_require__(3);
  39417. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  39418. var _classCallCheck2 = __webpack_require__(0);
  39419. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  39420. var _createClass2 = __webpack_require__(1);
  39421. var _createClass3 = _interopRequireDefault(_createClass2);
  39422. var _possibleConstructorReturn2 = __webpack_require__(4);
  39423. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  39424. var _inherits2 = __webpack_require__(5);
  39425. var _inherits3 = _interopRequireDefault(_inherits2);
  39426. var _NodeBase2 = __webpack_require__(23);
  39427. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  39428. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  39429. /**
  39430. * A Database Node/Cluster shape.
  39431. *
  39432. * @extends NodeBase
  39433. */
  39434. var Database = function (_NodeBase) {
  39435. (0, _inherits3['default'])(Database, _NodeBase);
  39436. /**
  39437. * @param {Object} options
  39438. * @param {Object} body
  39439. * @param {Label} labelModule
  39440. */
  39441. function Database(options, body, labelModule) {
  39442. (0, _classCallCheck3['default'])(this, Database);
  39443. var _this = (0, _possibleConstructorReturn3['default'])(this, (Database.__proto__ || (0, _getPrototypeOf2['default'])(Database)).call(this, options, body, labelModule));
  39444. _this._setMargins(labelModule);
  39445. return _this;
  39446. }
  39447. /**
  39448. *
  39449. * @param {CanvasRenderingContext2D} ctx
  39450. * @param {boolean} selected
  39451. * @param {boolean} hover
  39452. */
  39453. (0, _createClass3['default'])(Database, [{
  39454. key: 'resize',
  39455. value: function resize(ctx, selected, hover) {
  39456. if (this.needsRefresh(selected, hover)) {
  39457. var dimensions = this.getDimensionsFromLabel(ctx, selected, hover);
  39458. var size = dimensions.width + this.margin.right + this.margin.left;
  39459. this.width = size;
  39460. this.height = size;
  39461. this.radius = this.width / 2;
  39462. }
  39463. }
  39464. /**
  39465. *
  39466. * @param {CanvasRenderingContext2D} ctx
  39467. * @param {number} x width
  39468. * @param {number} y height
  39469. * @param {boolean} selected
  39470. * @param {boolean} hover
  39471. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  39472. */
  39473. }, {
  39474. key: 'draw',
  39475. value: function draw(ctx, x, y, selected, hover, values) {
  39476. this.resize(ctx, selected, hover);
  39477. this.left = x - this.width / 2;
  39478. this.top = y - this.height / 2;
  39479. this.initContextForDraw(ctx, values);
  39480. ctx.database(x - this.width / 2, y - this.height / 2, this.width, this.height);
  39481. this.performFill(ctx, values);
  39482. this.updateBoundingBox(x, y, ctx, selected, hover);
  39483. this.labelModule.draw(ctx, this.left + this.textSize.width / 2 + this.margin.left, this.top + this.textSize.height / 2 + this.margin.top, selected, hover);
  39484. }
  39485. /**
  39486. *
  39487. * @param {CanvasRenderingContext2D} ctx
  39488. * @param {number} angle
  39489. * @returns {number}
  39490. */
  39491. }, {
  39492. key: 'distanceToBorder',
  39493. value: function distanceToBorder(ctx, angle) {
  39494. return this._distanceToBorder(ctx, angle);
  39495. }
  39496. }]);
  39497. return Database;
  39498. }(_NodeBase3['default']);
  39499. exports['default'] = Database;
  39500. /***/ }),
  39501. /* 203 */
  39502. /***/ (function(module, exports, __webpack_require__) {
  39503. "use strict";
  39504. Object.defineProperty(exports, "__esModule", {
  39505. value: true
  39506. });
  39507. var _getPrototypeOf = __webpack_require__(3);
  39508. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  39509. var _classCallCheck2 = __webpack_require__(0);
  39510. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  39511. var _createClass2 = __webpack_require__(1);
  39512. var _createClass3 = _interopRequireDefault(_createClass2);
  39513. var _possibleConstructorReturn2 = __webpack_require__(4);
  39514. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  39515. var _inherits2 = __webpack_require__(5);
  39516. var _inherits3 = _interopRequireDefault(_inherits2);
  39517. var _ShapeBase2 = __webpack_require__(24);
  39518. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  39519. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  39520. /**
  39521. * A Diamond Node/Cluster shape.
  39522. *
  39523. * @extends ShapeBase
  39524. */
  39525. var Diamond = function (_ShapeBase) {
  39526. (0, _inherits3['default'])(Diamond, _ShapeBase);
  39527. /**
  39528. * @param {Object} options
  39529. * @param {Object} body
  39530. * @param {Label} labelModule
  39531. */
  39532. function Diamond(options, body, labelModule) {
  39533. (0, _classCallCheck3['default'])(this, Diamond);
  39534. return (0, _possibleConstructorReturn3['default'])(this, (Diamond.__proto__ || (0, _getPrototypeOf2['default'])(Diamond)).call(this, options, body, labelModule));
  39535. }
  39536. /**
  39537. *
  39538. * @param {CanvasRenderingContext2D} ctx
  39539. * @param {number} x width
  39540. * @param {number} y height
  39541. * @param {boolean} selected
  39542. * @param {boolean} hover
  39543. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  39544. */
  39545. (0, _createClass3['default'])(Diamond, [{
  39546. key: 'draw',
  39547. value: function draw(ctx, x, y, selected, hover, values) {
  39548. this._drawShape(ctx, 'diamond', 4, x, y, selected, hover, values);
  39549. }
  39550. /**
  39551. *
  39552. * @param {CanvasRenderingContext2D} ctx
  39553. * @param {number} angle
  39554. * @returns {number}
  39555. */
  39556. }, {
  39557. key: 'distanceToBorder',
  39558. value: function distanceToBorder(ctx, angle) {
  39559. return this._distanceToBorder(ctx, angle);
  39560. }
  39561. }]);
  39562. return Diamond;
  39563. }(_ShapeBase3['default']);
  39564. exports['default'] = Diamond;
  39565. /***/ }),
  39566. /* 204 */
  39567. /***/ (function(module, exports, __webpack_require__) {
  39568. "use strict";
  39569. Object.defineProperty(exports, "__esModule", {
  39570. value: true
  39571. });
  39572. var _getPrototypeOf = __webpack_require__(3);
  39573. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  39574. var _classCallCheck2 = __webpack_require__(0);
  39575. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  39576. var _createClass2 = __webpack_require__(1);
  39577. var _createClass3 = _interopRequireDefault(_createClass2);
  39578. var _possibleConstructorReturn2 = __webpack_require__(4);
  39579. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  39580. var _inherits2 = __webpack_require__(5);
  39581. var _inherits3 = _interopRequireDefault(_inherits2);
  39582. var _ShapeBase2 = __webpack_require__(24);
  39583. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  39584. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  39585. /**
  39586. * A Dot Node/Cluster shape.
  39587. *
  39588. * @extends ShapeBase
  39589. */
  39590. var Dot = function (_ShapeBase) {
  39591. (0, _inherits3['default'])(Dot, _ShapeBase);
  39592. /**
  39593. * @param {Object} options
  39594. * @param {Object} body
  39595. * @param {Label} labelModule
  39596. */
  39597. function Dot(options, body, labelModule) {
  39598. (0, _classCallCheck3['default'])(this, Dot);
  39599. return (0, _possibleConstructorReturn3['default'])(this, (Dot.__proto__ || (0, _getPrototypeOf2['default'])(Dot)).call(this, options, body, labelModule));
  39600. }
  39601. /**
  39602. *
  39603. * @param {CanvasRenderingContext2D} ctx
  39604. * @param {number} x width
  39605. * @param {number} y height
  39606. * @param {boolean} selected
  39607. * @param {boolean} hover
  39608. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  39609. */
  39610. (0, _createClass3['default'])(Dot, [{
  39611. key: 'draw',
  39612. value: function draw(ctx, x, y, selected, hover, values) {
  39613. this._drawShape(ctx, 'circle', 2, x, y, selected, hover, values);
  39614. }
  39615. /**
  39616. *
  39617. * @param {CanvasRenderingContext2D} ctx
  39618. * @param {number} angle
  39619. * @returns {number}
  39620. */
  39621. }, {
  39622. key: 'distanceToBorder',
  39623. value: function distanceToBorder(ctx, angle) {
  39624. // eslint-disable-line no-unused-vars
  39625. this.resize(ctx);
  39626. return this.options.size;
  39627. }
  39628. }]);
  39629. return Dot;
  39630. }(_ShapeBase3['default']);
  39631. exports['default'] = Dot;
  39632. /***/ }),
  39633. /* 205 */
  39634. /***/ (function(module, exports, __webpack_require__) {
  39635. "use strict";
  39636. Object.defineProperty(exports, "__esModule", {
  39637. value: true
  39638. });
  39639. var _getPrototypeOf = __webpack_require__(3);
  39640. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  39641. var _classCallCheck2 = __webpack_require__(0);
  39642. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  39643. var _createClass2 = __webpack_require__(1);
  39644. var _createClass3 = _interopRequireDefault(_createClass2);
  39645. var _possibleConstructorReturn2 = __webpack_require__(4);
  39646. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  39647. var _inherits2 = __webpack_require__(5);
  39648. var _inherits3 = _interopRequireDefault(_inherits2);
  39649. var _NodeBase2 = __webpack_require__(23);
  39650. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  39651. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  39652. /**
  39653. * Am Ellipse Node/Cluster shape.
  39654. *
  39655. * @extends NodeBase
  39656. */
  39657. var Ellipse = function (_NodeBase) {
  39658. (0, _inherits3['default'])(Ellipse, _NodeBase);
  39659. /**
  39660. * @param {Object} options
  39661. * @param {Object} body
  39662. * @param {Label} labelModule
  39663. */
  39664. function Ellipse(options, body, labelModule) {
  39665. (0, _classCallCheck3['default'])(this, Ellipse);
  39666. return (0, _possibleConstructorReturn3['default'])(this, (Ellipse.__proto__ || (0, _getPrototypeOf2['default'])(Ellipse)).call(this, options, body, labelModule));
  39667. }
  39668. /**
  39669. *
  39670. * @param {CanvasRenderingContext2D} ctx
  39671. * @param {boolean} [selected]
  39672. * @param {boolean} [hover]
  39673. */
  39674. (0, _createClass3['default'])(Ellipse, [{
  39675. key: 'resize',
  39676. value: function resize(ctx) {
  39677. var selected = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.selected;
  39678. var hover = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.hover;
  39679. if (this.needsRefresh(selected, hover)) {
  39680. var dimensions = this.getDimensionsFromLabel(ctx, selected, hover);
  39681. this.height = dimensions.height * 2;
  39682. this.width = dimensions.width + dimensions.height;
  39683. this.radius = 0.5 * this.width;
  39684. }
  39685. }
  39686. /**
  39687. *
  39688. * @param {CanvasRenderingContext2D} ctx
  39689. * @param {number} x width
  39690. * @param {number} y height
  39691. * @param {boolean} selected
  39692. * @param {boolean} hover
  39693. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  39694. */
  39695. }, {
  39696. key: 'draw',
  39697. value: function draw(ctx, x, y, selected, hover, values) {
  39698. this.resize(ctx, selected, hover);
  39699. this.left = x - this.width * 0.5;
  39700. this.top = y - this.height * 0.5;
  39701. this.initContextForDraw(ctx, values);
  39702. ctx.ellipse_vis(this.left, this.top, this.width, this.height);
  39703. this.performFill(ctx, values);
  39704. this.updateBoundingBox(x, y, ctx, selected, hover);
  39705. this.labelModule.draw(ctx, x, y, selected, hover);
  39706. }
  39707. /**
  39708. *
  39709. * @param {CanvasRenderingContext2D} ctx
  39710. * @param {number} angle
  39711. * @returns {number}
  39712. */
  39713. }, {
  39714. key: 'distanceToBorder',
  39715. value: function distanceToBorder(ctx, angle) {
  39716. this.resize(ctx);
  39717. var a = this.width * 0.5;
  39718. var b = this.height * 0.5;
  39719. var w = Math.sin(angle) * a;
  39720. var h = Math.cos(angle) * b;
  39721. return a * b / Math.sqrt(w * w + h * h);
  39722. }
  39723. }]);
  39724. return Ellipse;
  39725. }(_NodeBase3['default']);
  39726. exports['default'] = Ellipse;
  39727. /***/ }),
  39728. /* 206 */
  39729. /***/ (function(module, exports, __webpack_require__) {
  39730. "use strict";
  39731. Object.defineProperty(exports, "__esModule", {
  39732. value: true
  39733. });
  39734. var _getPrototypeOf = __webpack_require__(3);
  39735. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  39736. var _classCallCheck2 = __webpack_require__(0);
  39737. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  39738. var _createClass2 = __webpack_require__(1);
  39739. var _createClass3 = _interopRequireDefault(_createClass2);
  39740. var _possibleConstructorReturn2 = __webpack_require__(4);
  39741. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  39742. var _inherits2 = __webpack_require__(5);
  39743. var _inherits3 = _interopRequireDefault(_inherits2);
  39744. var _NodeBase2 = __webpack_require__(23);
  39745. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  39746. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  39747. /**
  39748. * An icon replacement for the default Node shape.
  39749. *
  39750. * @extends NodeBase
  39751. */
  39752. var Icon = function (_NodeBase) {
  39753. (0, _inherits3['default'])(Icon, _NodeBase);
  39754. /**
  39755. * @param {Object} options
  39756. * @param {Object} body
  39757. * @param {Label} labelModule
  39758. */
  39759. function Icon(options, body, labelModule) {
  39760. (0, _classCallCheck3['default'])(this, Icon);
  39761. var _this = (0, _possibleConstructorReturn3['default'])(this, (Icon.__proto__ || (0, _getPrototypeOf2['default'])(Icon)).call(this, options, body, labelModule));
  39762. _this._setMargins(labelModule);
  39763. return _this;
  39764. }
  39765. /**
  39766. *
  39767. * @param {CanvasRenderingContext2D} ctx - Unused.
  39768. * @param {boolean} [selected]
  39769. * @param {boolean} [hover]
  39770. */
  39771. (0, _createClass3['default'])(Icon, [{
  39772. key: 'resize',
  39773. value: function resize(ctx, selected, hover) {
  39774. if (this.needsRefresh(selected, hover)) {
  39775. this.iconSize = {
  39776. width: Number(this.options.icon.size),
  39777. height: Number(this.options.icon.size)
  39778. };
  39779. this.width = this.iconSize.width + this.margin.right + this.margin.left;
  39780. this.height = this.iconSize.height + this.margin.top + this.margin.bottom;
  39781. this.radius = 0.5 * this.width;
  39782. }
  39783. }
  39784. /**
  39785. *
  39786. * @param {CanvasRenderingContext2D} ctx
  39787. * @param {number} x width
  39788. * @param {number} y height
  39789. * @param {boolean} selected
  39790. * @param {boolean} hover
  39791. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  39792. */
  39793. }, {
  39794. key: 'draw',
  39795. value: function draw(ctx, x, y, selected, hover, values) {
  39796. this.resize(ctx, selected, hover);
  39797. this.options.icon.size = this.options.icon.size || 50;
  39798. this.left = x - this.width / 2;
  39799. this.top = y - this.height / 2;
  39800. this._icon(ctx, x, y, selected, hover, values);
  39801. if (this.options.label !== undefined) {
  39802. var iconTextSpacing = 5;
  39803. this.labelModule.draw(ctx, this.left + this.iconSize.width / 2 + this.margin.left, y + this.height / 2 + iconTextSpacing, selected);
  39804. }
  39805. this.updateBoundingBox(x, y);
  39806. }
  39807. /**
  39808. *
  39809. * @param {number} x
  39810. * @param {number} y
  39811. */
  39812. }, {
  39813. key: 'updateBoundingBox',
  39814. value: function updateBoundingBox(x, y) {
  39815. this.boundingBox.top = y - this.options.icon.size * 0.5;
  39816. this.boundingBox.left = x - this.options.icon.size * 0.5;
  39817. this.boundingBox.right = x + this.options.icon.size * 0.5;
  39818. this.boundingBox.bottom = y + this.options.icon.size * 0.5;
  39819. if (this.options.label !== undefined && this.labelModule.size.width > 0) {
  39820. var iconTextSpacing = 5;
  39821. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left);
  39822. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width);
  39823. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelModule.size.height + iconTextSpacing);
  39824. }
  39825. }
  39826. /**
  39827. *
  39828. * @param {CanvasRenderingContext2D} ctx
  39829. * @param {number} x width
  39830. * @param {number} y height
  39831. * @param {boolean} selected
  39832. * @param {boolean} hover - Unused
  39833. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  39834. */
  39835. }, {
  39836. key: '_icon',
  39837. value: function _icon(ctx, x, y, selected, hover, values) {
  39838. var iconSize = Number(this.options.icon.size);
  39839. if (this.options.icon.code !== undefined) {
  39840. ctx.font = (selected ? "bold " : "") + iconSize + "px " + this.options.icon.face;
  39841. // draw icon
  39842. ctx.fillStyle = this.options.icon.color || "black";
  39843. ctx.textAlign = "center";
  39844. ctx.textBaseline = "middle";
  39845. // draw shadow if enabled
  39846. this.enableShadow(ctx, values);
  39847. ctx.fillText(this.options.icon.code, x, y);
  39848. // disable shadows for other elements.
  39849. this.disableShadow(ctx, values);
  39850. } else {
  39851. 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.');
  39852. }
  39853. }
  39854. /**
  39855. *
  39856. * @param {CanvasRenderingContext2D} ctx
  39857. * @param {number} angle
  39858. * @returns {number}
  39859. */
  39860. }, {
  39861. key: 'distanceToBorder',
  39862. value: function distanceToBorder(ctx, angle) {
  39863. return this._distanceToBorder(ctx, angle);
  39864. }
  39865. }]);
  39866. return Icon;
  39867. }(_NodeBase3['default']);
  39868. exports['default'] = Icon;
  39869. /***/ }),
  39870. /* 207 */
  39871. /***/ (function(module, exports, __webpack_require__) {
  39872. "use strict";
  39873. Object.defineProperty(exports, "__esModule", {
  39874. value: true
  39875. });
  39876. var _getPrototypeOf = __webpack_require__(3);
  39877. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  39878. var _classCallCheck2 = __webpack_require__(0);
  39879. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  39880. var _createClass2 = __webpack_require__(1);
  39881. var _createClass3 = _interopRequireDefault(_createClass2);
  39882. var _possibleConstructorReturn2 = __webpack_require__(4);
  39883. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  39884. var _inherits2 = __webpack_require__(5);
  39885. var _inherits3 = _interopRequireDefault(_inherits2);
  39886. var _CircleImageBase2 = __webpack_require__(73);
  39887. var _CircleImageBase3 = _interopRequireDefault(_CircleImageBase2);
  39888. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  39889. /**
  39890. * An image-based replacement for the default Node shape.
  39891. *
  39892. * @extends CircleImageBase
  39893. */
  39894. var Image = function (_CircleImageBase) {
  39895. (0, _inherits3['default'])(Image, _CircleImageBase);
  39896. /**
  39897. * @param {Object} options
  39898. * @param {Object} body
  39899. * @param {Label} labelModule
  39900. * @param {Image} imageObj
  39901. * @param {Image} imageObjAlt
  39902. */
  39903. function Image(options, body, labelModule, imageObj, imageObjAlt) {
  39904. (0, _classCallCheck3['default'])(this, Image);
  39905. var _this = (0, _possibleConstructorReturn3['default'])(this, (Image.__proto__ || (0, _getPrototypeOf2['default'])(Image)).call(this, options, body, labelModule));
  39906. _this.setImages(imageObj, imageObjAlt);
  39907. return _this;
  39908. }
  39909. /**
  39910. *
  39911. * @param {CanvasRenderingContext2D} ctx - Unused.
  39912. * @param {boolean} [selected]
  39913. * @param {boolean} [hover]
  39914. */
  39915. (0, _createClass3['default'])(Image, [{
  39916. key: 'resize',
  39917. value: function resize(ctx) {
  39918. var selected = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.selected;
  39919. var hover = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.hover;
  39920. var imageAbsent = this.imageObj.src === undefined || this.imageObj.width === undefined || this.imageObj.height === undefined;
  39921. if (imageAbsent) {
  39922. var side = this.options.size * 2;
  39923. this.width = side;
  39924. this.height = side;
  39925. return;
  39926. }
  39927. if (this.needsRefresh(selected, hover)) {
  39928. this._resizeImage();
  39929. }
  39930. }
  39931. /**
  39932. *
  39933. * @param {CanvasRenderingContext2D} ctx
  39934. * @param {number} x width
  39935. * @param {number} y height
  39936. * @param {boolean} selected
  39937. * @param {boolean} hover
  39938. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  39939. */
  39940. }, {
  39941. key: 'draw',
  39942. value: function draw(ctx, x, y, selected, hover, values) {
  39943. this.switchImages(selected);
  39944. this.resize();
  39945. this.left = x - this.width / 2;
  39946. this.top = y - this.height / 2;
  39947. if (this.options.shapeProperties.useBorderWithImage === true) {
  39948. var neutralborderWidth = this.options.borderWidth;
  39949. var selectionLineWidth = this.options.borderWidthSelected || 2 * this.options.borderWidth;
  39950. var borderWidth = (selected ? selectionLineWidth : neutralborderWidth) / this.body.view.scale;
  39951. ctx.lineWidth = Math.min(this.width, borderWidth);
  39952. ctx.beginPath();
  39953. // setup the line properties.
  39954. ctx.strokeStyle = selected ? this.options.color.highlight.border : hover ? this.options.color.hover.border : this.options.color.border;
  39955. // set a fillstyle
  39956. ctx.fillStyle = selected ? this.options.color.highlight.background : hover ? this.options.color.hover.background : this.options.color.background;
  39957. // 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
  39958. ctx.rect(this.left - 0.5 * ctx.lineWidth, this.top - 0.5 * ctx.lineWidth, this.width + ctx.lineWidth, this.height + ctx.lineWidth);
  39959. ctx.fill();
  39960. this.performStroke(ctx, values);
  39961. ctx.closePath();
  39962. }
  39963. this._drawImageAtPosition(ctx, values);
  39964. this._drawImageLabel(ctx, x, y, selected, hover);
  39965. this.updateBoundingBox(x, y);
  39966. }
  39967. /**
  39968. *
  39969. * @param {number} x
  39970. * @param {number} y
  39971. */
  39972. }, {
  39973. key: 'updateBoundingBox',
  39974. value: function updateBoundingBox(x, y) {
  39975. this.resize();
  39976. this._updateBoundingBox(x, y);
  39977. if (this.options.label !== undefined && this.labelModule.size.width > 0) {
  39978. this.boundingBox.left = Math.min(this.boundingBox.left, this.labelModule.size.left);
  39979. this.boundingBox.right = Math.max(this.boundingBox.right, this.labelModule.size.left + this.labelModule.size.width);
  39980. this.boundingBox.bottom = Math.max(this.boundingBox.bottom, this.boundingBox.bottom + this.labelOffset);
  39981. }
  39982. }
  39983. /**
  39984. *
  39985. * @param {CanvasRenderingContext2D} ctx
  39986. * @param {number} angle
  39987. * @returns {number}
  39988. */
  39989. }, {
  39990. key: 'distanceToBorder',
  39991. value: function distanceToBorder(ctx, angle) {
  39992. return this._distanceToBorder(ctx, angle);
  39993. }
  39994. }]);
  39995. return Image;
  39996. }(_CircleImageBase3['default']);
  39997. exports['default'] = Image;
  39998. /***/ }),
  39999. /* 208 */
  40000. /***/ (function(module, exports, __webpack_require__) {
  40001. "use strict";
  40002. Object.defineProperty(exports, "__esModule", {
  40003. value: true
  40004. });
  40005. var _getPrototypeOf = __webpack_require__(3);
  40006. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  40007. var _classCallCheck2 = __webpack_require__(0);
  40008. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  40009. var _createClass2 = __webpack_require__(1);
  40010. var _createClass3 = _interopRequireDefault(_createClass2);
  40011. var _possibleConstructorReturn2 = __webpack_require__(4);
  40012. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  40013. var _inherits2 = __webpack_require__(5);
  40014. var _inherits3 = _interopRequireDefault(_inherits2);
  40015. var _ShapeBase2 = __webpack_require__(24);
  40016. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  40017. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  40018. /**
  40019. * A Square Node/Cluster shape.
  40020. *
  40021. * @extends ShapeBase
  40022. */
  40023. var Square = function (_ShapeBase) {
  40024. (0, _inherits3['default'])(Square, _ShapeBase);
  40025. /**
  40026. * @param {Object} options
  40027. * @param {Object} body
  40028. * @param {Label} labelModule
  40029. */
  40030. function Square(options, body, labelModule) {
  40031. (0, _classCallCheck3['default'])(this, Square);
  40032. return (0, _possibleConstructorReturn3['default'])(this, (Square.__proto__ || (0, _getPrototypeOf2['default'])(Square)).call(this, options, body, labelModule));
  40033. }
  40034. /**
  40035. *
  40036. * @param {CanvasRenderingContext2D} ctx
  40037. * @param {number} x width
  40038. * @param {number} y height
  40039. * @param {boolean} selected
  40040. * @param {boolean} hover
  40041. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  40042. */
  40043. (0, _createClass3['default'])(Square, [{
  40044. key: 'draw',
  40045. value: function draw(ctx, x, y, selected, hover, values) {
  40046. this._drawShape(ctx, 'square', 2, x, y, selected, hover, values);
  40047. }
  40048. /**
  40049. *
  40050. * @param {CanvasRenderingContext2D} ctx
  40051. * @param {number} angle
  40052. * @returns {number}
  40053. */
  40054. }, {
  40055. key: 'distanceToBorder',
  40056. value: function distanceToBorder(ctx, angle) {
  40057. return this._distanceToBorder(ctx, angle);
  40058. }
  40059. }]);
  40060. return Square;
  40061. }(_ShapeBase3['default']);
  40062. exports['default'] = Square;
  40063. /***/ }),
  40064. /* 209 */
  40065. /***/ (function(module, exports, __webpack_require__) {
  40066. "use strict";
  40067. Object.defineProperty(exports, "__esModule", {
  40068. value: true
  40069. });
  40070. var _getPrototypeOf = __webpack_require__(3);
  40071. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  40072. var _classCallCheck2 = __webpack_require__(0);
  40073. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  40074. var _createClass2 = __webpack_require__(1);
  40075. var _createClass3 = _interopRequireDefault(_createClass2);
  40076. var _possibleConstructorReturn2 = __webpack_require__(4);
  40077. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  40078. var _inherits2 = __webpack_require__(5);
  40079. var _inherits3 = _interopRequireDefault(_inherits2);
  40080. var _ShapeBase2 = __webpack_require__(24);
  40081. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  40082. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  40083. /**
  40084. * A Hexagon Node/Cluster shape.
  40085. *
  40086. * @extends ShapeBase
  40087. */
  40088. var Hexagon = function (_ShapeBase) {
  40089. (0, _inherits3['default'])(Hexagon, _ShapeBase);
  40090. /**
  40091. * @param {Object} options
  40092. * @param {Object} body
  40093. * @param {Label} labelModule
  40094. */
  40095. function Hexagon(options, body, labelModule) {
  40096. (0, _classCallCheck3['default'])(this, Hexagon);
  40097. return (0, _possibleConstructorReturn3['default'])(this, (Hexagon.__proto__ || (0, _getPrototypeOf2['default'])(Hexagon)).call(this, options, body, labelModule));
  40098. }
  40099. /**
  40100. *
  40101. * @param {CanvasRenderingContext2D} ctx
  40102. * @param {number} x width
  40103. * @param {number} y height
  40104. * @param {boolean} selected
  40105. * @param {boolean} hover
  40106. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  40107. */
  40108. (0, _createClass3['default'])(Hexagon, [{
  40109. key: 'draw',
  40110. value: function draw(ctx, x, y, selected, hover, values) {
  40111. this._drawShape(ctx, 'hexagon', 4, x, y, selected, hover, values);
  40112. }
  40113. /**
  40114. *
  40115. * @param {CanvasRenderingContext2D} ctx
  40116. * @param {number} angle
  40117. * @returns {number}
  40118. */
  40119. }, {
  40120. key: 'distanceToBorder',
  40121. value: function distanceToBorder(ctx, angle) {
  40122. return this._distanceToBorder(ctx, angle);
  40123. }
  40124. }]);
  40125. return Hexagon;
  40126. }(_ShapeBase3['default']);
  40127. exports['default'] = Hexagon;
  40128. /***/ }),
  40129. /* 210 */
  40130. /***/ (function(module, exports, __webpack_require__) {
  40131. "use strict";
  40132. Object.defineProperty(exports, "__esModule", {
  40133. value: true
  40134. });
  40135. var _getPrototypeOf = __webpack_require__(3);
  40136. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  40137. var _classCallCheck2 = __webpack_require__(0);
  40138. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  40139. var _createClass2 = __webpack_require__(1);
  40140. var _createClass3 = _interopRequireDefault(_createClass2);
  40141. var _possibleConstructorReturn2 = __webpack_require__(4);
  40142. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  40143. var _inherits2 = __webpack_require__(5);
  40144. var _inherits3 = _interopRequireDefault(_inherits2);
  40145. var _ShapeBase2 = __webpack_require__(24);
  40146. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  40147. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  40148. /**
  40149. * A Star Node/Cluster shape.
  40150. *
  40151. * @extends ShapeBase
  40152. */
  40153. var Star = function (_ShapeBase) {
  40154. (0, _inherits3['default'])(Star, _ShapeBase);
  40155. /**
  40156. * @param {Object} options
  40157. * @param {Object} body
  40158. * @param {Label} labelModule
  40159. */
  40160. function Star(options, body, labelModule) {
  40161. (0, _classCallCheck3['default'])(this, Star);
  40162. return (0, _possibleConstructorReturn3['default'])(this, (Star.__proto__ || (0, _getPrototypeOf2['default'])(Star)).call(this, options, body, labelModule));
  40163. }
  40164. /**
  40165. *
  40166. * @param {CanvasRenderingContext2D} ctx
  40167. * @param {number} x width
  40168. * @param {number} y height
  40169. * @param {boolean} selected
  40170. * @param {boolean} hover
  40171. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  40172. */
  40173. (0, _createClass3['default'])(Star, [{
  40174. key: 'draw',
  40175. value: function draw(ctx, x, y, selected, hover, values) {
  40176. this._drawShape(ctx, 'star', 4, x, y, selected, hover, values);
  40177. }
  40178. /**
  40179. *
  40180. * @param {CanvasRenderingContext2D} ctx
  40181. * @param {number} angle
  40182. * @returns {number}
  40183. */
  40184. }, {
  40185. key: 'distanceToBorder',
  40186. value: function distanceToBorder(ctx, angle) {
  40187. return this._distanceToBorder(ctx, angle);
  40188. }
  40189. }]);
  40190. return Star;
  40191. }(_ShapeBase3['default']);
  40192. exports['default'] = Star;
  40193. /***/ }),
  40194. /* 211 */
  40195. /***/ (function(module, exports, __webpack_require__) {
  40196. "use strict";
  40197. Object.defineProperty(exports, "__esModule", {
  40198. value: true
  40199. });
  40200. var _getPrototypeOf = __webpack_require__(3);
  40201. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  40202. var _classCallCheck2 = __webpack_require__(0);
  40203. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  40204. var _createClass2 = __webpack_require__(1);
  40205. var _createClass3 = _interopRequireDefault(_createClass2);
  40206. var _possibleConstructorReturn2 = __webpack_require__(4);
  40207. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  40208. var _inherits2 = __webpack_require__(5);
  40209. var _inherits3 = _interopRequireDefault(_inherits2);
  40210. var _NodeBase2 = __webpack_require__(23);
  40211. var _NodeBase3 = _interopRequireDefault(_NodeBase2);
  40212. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  40213. /**
  40214. * A text-based replacement for the default Node shape.
  40215. *
  40216. * @extends NodeBase
  40217. */
  40218. var Text = function (_NodeBase) {
  40219. (0, _inherits3['default'])(Text, _NodeBase);
  40220. /**
  40221. * @param {Object} options
  40222. * @param {Object} body
  40223. * @param {Label} labelModule
  40224. */
  40225. function Text(options, body, labelModule) {
  40226. (0, _classCallCheck3['default'])(this, Text);
  40227. var _this = (0, _possibleConstructorReturn3['default'])(this, (Text.__proto__ || (0, _getPrototypeOf2['default'])(Text)).call(this, options, body, labelModule));
  40228. _this._setMargins(labelModule);
  40229. return _this;
  40230. }
  40231. /**
  40232. *
  40233. * @param {CanvasRenderingContext2D} ctx
  40234. * @param {boolean} selected
  40235. * @param {boolean} hover
  40236. */
  40237. (0, _createClass3['default'])(Text, [{
  40238. key: 'resize',
  40239. value: function resize(ctx, selected, hover) {
  40240. if (this.needsRefresh(selected, hover)) {
  40241. this.textSize = this.labelModule.getTextSize(ctx, selected, hover);
  40242. this.width = this.textSize.width + this.margin.right + this.margin.left;
  40243. this.height = this.textSize.height + this.margin.top + this.margin.bottom;
  40244. this.radius = 0.5 * this.width;
  40245. }
  40246. }
  40247. /**
  40248. *
  40249. * @param {CanvasRenderingContext2D} ctx
  40250. * @param {number} x width
  40251. * @param {number} y height
  40252. * @param {boolean} selected
  40253. * @param {boolean} hover
  40254. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  40255. */
  40256. }, {
  40257. key: 'draw',
  40258. value: function draw(ctx, x, y, selected, hover, values) {
  40259. this.resize(ctx, selected, hover);
  40260. this.left = x - this.width / 2;
  40261. this.top = y - this.height / 2;
  40262. // draw shadow if enabled
  40263. this.enableShadow(ctx, values);
  40264. this.labelModule.draw(ctx, this.left + this.textSize.width / 2 + this.margin.left, this.top + this.textSize.height / 2 + this.margin.top, selected, hover);
  40265. // disable shadows for other elements.
  40266. this.disableShadow(ctx, values);
  40267. this.updateBoundingBox(x, y, ctx, selected, hover);
  40268. }
  40269. /**
  40270. *
  40271. * @param {CanvasRenderingContext2D} ctx
  40272. * @param {number} angle
  40273. * @returns {number}
  40274. */
  40275. }, {
  40276. key: 'distanceToBorder',
  40277. value: function distanceToBorder(ctx, angle) {
  40278. return this._distanceToBorder(ctx, angle);
  40279. }
  40280. }]);
  40281. return Text;
  40282. }(_NodeBase3['default']);
  40283. exports['default'] = Text;
  40284. /***/ }),
  40285. /* 212 */
  40286. /***/ (function(module, exports, __webpack_require__) {
  40287. "use strict";
  40288. Object.defineProperty(exports, "__esModule", {
  40289. value: true
  40290. });
  40291. var _getPrototypeOf = __webpack_require__(3);
  40292. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  40293. var _classCallCheck2 = __webpack_require__(0);
  40294. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  40295. var _createClass2 = __webpack_require__(1);
  40296. var _createClass3 = _interopRequireDefault(_createClass2);
  40297. var _possibleConstructorReturn2 = __webpack_require__(4);
  40298. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  40299. var _inherits2 = __webpack_require__(5);
  40300. var _inherits3 = _interopRequireDefault(_inherits2);
  40301. var _ShapeBase2 = __webpack_require__(24);
  40302. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  40303. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  40304. /**
  40305. * A Triangle Node/Cluster shape.
  40306. *
  40307. * @extends ShapeBase
  40308. */
  40309. var Triangle = function (_ShapeBase) {
  40310. (0, _inherits3['default'])(Triangle, _ShapeBase);
  40311. /**
  40312. * @param {Object} options
  40313. * @param {Object} body
  40314. * @param {Label} labelModule
  40315. */
  40316. function Triangle(options, body, labelModule) {
  40317. (0, _classCallCheck3['default'])(this, Triangle);
  40318. return (0, _possibleConstructorReturn3['default'])(this, (Triangle.__proto__ || (0, _getPrototypeOf2['default'])(Triangle)).call(this, options, body, labelModule));
  40319. }
  40320. /**
  40321. *
  40322. * @param {CanvasRenderingContext2D} ctx
  40323. * @param {number} x
  40324. * @param {number} y
  40325. * @param {boolean} selected
  40326. * @param {boolean} hover
  40327. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  40328. */
  40329. (0, _createClass3['default'])(Triangle, [{
  40330. key: 'draw',
  40331. value: function draw(ctx, x, y, selected, hover, values) {
  40332. this._drawShape(ctx, 'triangle', 3, x, y, selected, hover, values);
  40333. }
  40334. /**
  40335. *
  40336. * @param {CanvasRenderingContext2D} ctx
  40337. * @param {number} angle
  40338. * @returns {number}
  40339. */
  40340. }, {
  40341. key: 'distanceToBorder',
  40342. value: function distanceToBorder(ctx, angle) {
  40343. return this._distanceToBorder(ctx, angle);
  40344. }
  40345. }]);
  40346. return Triangle;
  40347. }(_ShapeBase3['default']);
  40348. exports['default'] = Triangle;
  40349. /***/ }),
  40350. /* 213 */
  40351. /***/ (function(module, exports, __webpack_require__) {
  40352. "use strict";
  40353. Object.defineProperty(exports, "__esModule", {
  40354. value: true
  40355. });
  40356. var _getPrototypeOf = __webpack_require__(3);
  40357. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  40358. var _classCallCheck2 = __webpack_require__(0);
  40359. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  40360. var _createClass2 = __webpack_require__(1);
  40361. var _createClass3 = _interopRequireDefault(_createClass2);
  40362. var _possibleConstructorReturn2 = __webpack_require__(4);
  40363. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  40364. var _inherits2 = __webpack_require__(5);
  40365. var _inherits3 = _interopRequireDefault(_inherits2);
  40366. var _ShapeBase2 = __webpack_require__(24);
  40367. var _ShapeBase3 = _interopRequireDefault(_ShapeBase2);
  40368. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  40369. /**
  40370. * A downward facing Triangle Node/Cluster shape.
  40371. *
  40372. * @extends ShapeBase
  40373. */
  40374. var TriangleDown = function (_ShapeBase) {
  40375. (0, _inherits3['default'])(TriangleDown, _ShapeBase);
  40376. /**
  40377. * @param {Object} options
  40378. * @param {Object} body
  40379. * @param {Label} labelModule
  40380. */
  40381. function TriangleDown(options, body, labelModule) {
  40382. (0, _classCallCheck3['default'])(this, TriangleDown);
  40383. return (0, _possibleConstructorReturn3['default'])(this, (TriangleDown.__proto__ || (0, _getPrototypeOf2['default'])(TriangleDown)).call(this, options, body, labelModule));
  40384. }
  40385. /**
  40386. *
  40387. * @param {CanvasRenderingContext2D} ctx
  40388. * @param {number} x
  40389. * @param {number} y
  40390. * @param {boolean} selected
  40391. * @param {boolean} hover
  40392. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  40393. */
  40394. (0, _createClass3['default'])(TriangleDown, [{
  40395. key: 'draw',
  40396. value: function draw(ctx, x, y, selected, hover, values) {
  40397. this._drawShape(ctx, 'triangleDown', 3, x, y, selected, hover, values);
  40398. }
  40399. /**
  40400. *
  40401. * @param {CanvasRenderingContext2D} ctx
  40402. * @param {number} angle
  40403. * @returns {number}
  40404. */
  40405. }, {
  40406. key: 'distanceToBorder',
  40407. value: function distanceToBorder(ctx, angle) {
  40408. return this._distanceToBorder(ctx, angle);
  40409. }
  40410. }]);
  40411. return TriangleDown;
  40412. }(_ShapeBase3['default']);
  40413. exports['default'] = TriangleDown;
  40414. /***/ }),
  40415. /* 214 */
  40416. /***/ (function(module, exports, __webpack_require__) {
  40417. "use strict";
  40418. Object.defineProperty(exports, "__esModule", {
  40419. value: true
  40420. });
  40421. var _classCallCheck2 = __webpack_require__(0);
  40422. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  40423. var _createClass2 = __webpack_require__(1);
  40424. var _createClass3 = _interopRequireDefault(_createClass2);
  40425. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  40426. var util = __webpack_require__(2);
  40427. var DataSet = __webpack_require__(11);
  40428. var DataView = __webpack_require__(12);
  40429. var Edge = __webpack_require__(74)['default'];
  40430. /**
  40431. * Handler for Edges
  40432. */
  40433. var EdgesHandler = function () {
  40434. /**
  40435. * @param {Object} body
  40436. * @param {Array.<Image>} images
  40437. * @param {Array.<Group>} groups
  40438. */
  40439. function EdgesHandler(body, images, groups) {
  40440. var _this = this;
  40441. (0, _classCallCheck3['default'])(this, EdgesHandler);
  40442. this.body = body;
  40443. this.images = images;
  40444. this.groups = groups;
  40445. // create the edge API in the body container
  40446. this.body.functions.createEdge = this.create.bind(this);
  40447. this.edgesListeners = {
  40448. add: function add(event, params) {
  40449. _this.add(params.items);
  40450. },
  40451. update: function update(event, params) {
  40452. _this.update(params.items);
  40453. },
  40454. remove: function remove(event, params) {
  40455. _this.remove(params.items);
  40456. }
  40457. };
  40458. this.options = {};
  40459. this.defaultOptions = {
  40460. arrows: {
  40461. to: { enabled: false, scaleFactor: 1, type: 'arrow' }, // boolean / {arrowScaleFactor:1} / {enabled: false, arrowScaleFactor:1}
  40462. middle: { enabled: false, scaleFactor: 1, type: 'arrow' },
  40463. from: { enabled: false, scaleFactor: 1, type: 'arrow' }
  40464. },
  40465. arrowStrikethrough: true,
  40466. color: {
  40467. color: '#848484',
  40468. highlight: '#848484',
  40469. hover: '#848484',
  40470. inherit: 'from',
  40471. opacity: 1.0
  40472. },
  40473. dashes: false,
  40474. font: {
  40475. color: '#343434',
  40476. size: 14, // px
  40477. face: 'arial',
  40478. background: 'none',
  40479. strokeWidth: 2, // px
  40480. strokeColor: '#ffffff',
  40481. align: 'horizontal',
  40482. multi: false,
  40483. vadjust: 0,
  40484. bold: {
  40485. mod: 'bold'
  40486. },
  40487. boldital: {
  40488. mod: 'bold italic'
  40489. },
  40490. ital: {
  40491. mod: 'italic'
  40492. },
  40493. mono: {
  40494. mod: '',
  40495. size: 15, // px
  40496. face: 'courier new',
  40497. vadjust: 2
  40498. }
  40499. },
  40500. hidden: false,
  40501. hoverWidth: 1.5,
  40502. label: undefined,
  40503. labelHighlightBold: true,
  40504. length: undefined,
  40505. physics: true,
  40506. scaling: {
  40507. min: 1,
  40508. max: 15,
  40509. label: {
  40510. enabled: true,
  40511. min: 14,
  40512. max: 30,
  40513. maxVisible: 30,
  40514. drawThreshold: 5
  40515. },
  40516. customScalingFunction: function customScalingFunction(min, max, total, value) {
  40517. if (max === min) {
  40518. return 0.5;
  40519. } else {
  40520. var scale = 1 / (max - min);
  40521. return Math.max(0, (value - min) * scale);
  40522. }
  40523. }
  40524. },
  40525. selectionWidth: 1.5,
  40526. selfReferenceSize: 20,
  40527. shadow: {
  40528. enabled: false,
  40529. color: 'rgba(0,0,0,0.5)',
  40530. size: 10,
  40531. x: 5,
  40532. y: 5
  40533. },
  40534. smooth: {
  40535. enabled: true,
  40536. type: "dynamic",
  40537. forceDirection: 'none',
  40538. roundness: 0.5
  40539. },
  40540. title: undefined,
  40541. width: 1,
  40542. value: undefined
  40543. };
  40544. util.deepExtend(this.options, this.defaultOptions);
  40545. this.bindEventListeners();
  40546. }
  40547. /**
  40548. * Binds event listeners
  40549. */
  40550. (0, _createClass3['default'])(EdgesHandler, [{
  40551. key: 'bindEventListeners',
  40552. value: function bindEventListeners() {
  40553. var _this2 = this;
  40554. // this allows external modules to force all dynamic curves to turn static.
  40555. this.body.emitter.on("_forceDisableDynamicCurves", function (type) {
  40556. var emit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  40557. if (type === 'dynamic') {
  40558. type = 'continuous';
  40559. }
  40560. var dataChanged = false;
  40561. for (var edgeId in _this2.body.edges) {
  40562. if (_this2.body.edges.hasOwnProperty(edgeId)) {
  40563. var edge = _this2.body.edges[edgeId];
  40564. var edgeData = _this2.body.data.edges._data[edgeId];
  40565. // only forcibly remove the smooth curve if the data has been set of the edge has the smooth curves defined.
  40566. // this is because a change in the global would not affect these curves.
  40567. if (edgeData !== undefined) {
  40568. var smoothOptions = edgeData.smooth;
  40569. if (smoothOptions !== undefined) {
  40570. if (smoothOptions.enabled === true && smoothOptions.type === 'dynamic') {
  40571. if (type === undefined) {
  40572. edge.setOptions({ smooth: false });
  40573. } else {
  40574. edge.setOptions({ smooth: { type: type } });
  40575. }
  40576. dataChanged = true;
  40577. }
  40578. }
  40579. }
  40580. }
  40581. }
  40582. if (emit === true && dataChanged === true) {
  40583. _this2.body.emitter.emit("_dataChanged");
  40584. }
  40585. });
  40586. // this is called when options of EXISTING nodes or edges have changed.
  40587. //
  40588. // NOTE: Not true, called when options have NOT changed, for both existing as well as new nodes.
  40589. // See update() for logic.
  40590. // TODO: Verify and examine the consequences of this. It might still trigger when
  40591. // non-option fields have changed, but then reconnecting edges is still useless.
  40592. // Alternatively, it might also be called when edges are removed.
  40593. //
  40594. this.body.emitter.on("_dataUpdated", function () {
  40595. _this2.reconnectEdges();
  40596. });
  40597. // refresh the edges. Used when reverting from hierarchical layout
  40598. this.body.emitter.on("refreshEdges", this.refresh.bind(this));
  40599. this.body.emitter.on("refresh", this.refresh.bind(this));
  40600. this.body.emitter.on("destroy", function () {
  40601. util.forEach(_this2.edgesListeners, function (callback, event) {
  40602. if (_this2.body.data.edges) _this2.body.data.edges.off(event, callback);
  40603. });
  40604. delete _this2.body.functions.createEdge;
  40605. delete _this2.edgesListeners.add;
  40606. delete _this2.edgesListeners.update;
  40607. delete _this2.edgesListeners.remove;
  40608. delete _this2.edgesListeners;
  40609. });
  40610. }
  40611. /**
  40612. *
  40613. * @param {Object} options
  40614. */
  40615. }, {
  40616. key: 'setOptions',
  40617. value: function setOptions(options) {
  40618. if (options !== undefined) {
  40619. // use the parser from the Edge class to fill in all shorthand notations
  40620. Edge.parseOptions(this.options, options, true, this.defaultOptions, true);
  40621. // update smooth settings in all edges
  40622. var dataChanged = false;
  40623. if (options.smooth !== undefined) {
  40624. for (var edgeId in this.body.edges) {
  40625. if (this.body.edges.hasOwnProperty(edgeId)) {
  40626. dataChanged = this.body.edges[edgeId].updateEdgeType() || dataChanged;
  40627. }
  40628. }
  40629. }
  40630. // update fonts in all edges
  40631. if (options.font !== undefined) {
  40632. for (var _edgeId in this.body.edges) {
  40633. if (this.body.edges.hasOwnProperty(_edgeId)) {
  40634. this.body.edges[_edgeId].updateLabelModule();
  40635. }
  40636. }
  40637. }
  40638. // update the state of the variables if needed
  40639. if (options.hidden !== undefined || options.physics !== undefined || dataChanged === true) {
  40640. this.body.emitter.emit('_dataChanged');
  40641. }
  40642. }
  40643. }
  40644. /**
  40645. * Load edges by reading the data table
  40646. * @param {Array | DataSet | DataView} edges The data containing the edges.
  40647. * @param {boolean} [doNotEmit=false]
  40648. * @private
  40649. */
  40650. }, {
  40651. key: 'setData',
  40652. value: function setData(edges) {
  40653. var _this3 = this;
  40654. var doNotEmit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  40655. var oldEdgesData = this.body.data.edges;
  40656. if (edges instanceof DataSet || edges instanceof DataView) {
  40657. this.body.data.edges = edges;
  40658. } else if (Array.isArray(edges)) {
  40659. this.body.data.edges = new DataSet();
  40660. this.body.data.edges.add(edges);
  40661. } else if (!edges) {
  40662. this.body.data.edges = new DataSet();
  40663. } else {
  40664. throw new TypeError('Array or DataSet expected');
  40665. }
  40666. // TODO: is this null or undefined or false?
  40667. if (oldEdgesData) {
  40668. // unsubscribe from old dataset
  40669. util.forEach(this.edgesListeners, function (callback, event) {
  40670. oldEdgesData.off(event, callback);
  40671. });
  40672. }
  40673. // remove drawn edges
  40674. this.body.edges = {};
  40675. // TODO: is this null or undefined or false?
  40676. if (this.body.data.edges) {
  40677. // subscribe to new dataset
  40678. util.forEach(this.edgesListeners, function (callback, event) {
  40679. _this3.body.data.edges.on(event, callback);
  40680. });
  40681. // draw all new nodes
  40682. var ids = this.body.data.edges.getIds();
  40683. this.add(ids, true);
  40684. }
  40685. this.body.emitter.emit('_adjustEdgesForHierarchicalLayout');
  40686. if (doNotEmit === false) {
  40687. this.body.emitter.emit("_dataChanged");
  40688. }
  40689. }
  40690. /**
  40691. * Add edges
  40692. * @param {number[] | string[]} ids
  40693. * @param {boolean} [doNotEmit=false]
  40694. * @private
  40695. */
  40696. }, {
  40697. key: 'add',
  40698. value: function add(ids) {
  40699. var doNotEmit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  40700. var edges = this.body.edges;
  40701. var edgesData = this.body.data.edges;
  40702. for (var i = 0; i < ids.length; i++) {
  40703. var id = ids[i];
  40704. var oldEdge = edges[id];
  40705. if (oldEdge) {
  40706. oldEdge.disconnect();
  40707. }
  40708. var data = edgesData.get(id, { "showInternalIds": true });
  40709. edges[id] = this.create(data);
  40710. }
  40711. this.body.emitter.emit('_adjustEdgesForHierarchicalLayout');
  40712. if (doNotEmit === false) {
  40713. this.body.emitter.emit("_dataChanged");
  40714. }
  40715. }
  40716. /**
  40717. * Update existing edges, or create them when not yet existing
  40718. * @param {number[] | string[]} ids
  40719. * @private
  40720. */
  40721. }, {
  40722. key: 'update',
  40723. value: function update(ids) {
  40724. var edges = this.body.edges;
  40725. var edgesData = this.body.data.edges;
  40726. var dataChanged = false;
  40727. for (var i = 0; i < ids.length; i++) {
  40728. var id = ids[i];
  40729. var data = edgesData.get(id);
  40730. var edge = edges[id];
  40731. if (edge !== undefined) {
  40732. // update edge
  40733. edge.disconnect();
  40734. dataChanged = edge.setOptions(data) || dataChanged; // if a support node is added, data can be changed.
  40735. edge.connect();
  40736. } else {
  40737. // create edge
  40738. this.body.edges[id] = this.create(data);
  40739. dataChanged = true;
  40740. }
  40741. }
  40742. if (dataChanged === true) {
  40743. this.body.emitter.emit('_adjustEdgesForHierarchicalLayout');
  40744. this.body.emitter.emit("_dataChanged");
  40745. } else {
  40746. this.body.emitter.emit("_dataUpdated");
  40747. }
  40748. }
  40749. /**
  40750. * Remove existing edges. Non existing ids will be ignored
  40751. * @param {number[] | string[]} ids
  40752. * @param {boolean} [emit=true]
  40753. * @private
  40754. */
  40755. }, {
  40756. key: 'remove',
  40757. value: function remove(ids) {
  40758. var emit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  40759. if (ids.length === 0) return; // early out
  40760. var edges = this.body.edges;
  40761. util.forEach(ids, function (id) {
  40762. var edge = edges[id];
  40763. if (edge !== undefined) {
  40764. edge.remove();
  40765. }
  40766. });
  40767. if (emit) {
  40768. this.body.emitter.emit("_dataChanged");
  40769. }
  40770. }
  40771. /**
  40772. * Refreshes Edge Handler
  40773. */
  40774. }, {
  40775. key: 'refresh',
  40776. value: function refresh() {
  40777. var _this4 = this;
  40778. util.forEach(this.body.edges, function (edge, edgeId) {
  40779. var data = _this4.body.data.edges._data[edgeId];
  40780. if (data !== undefined) {
  40781. edge.setOptions(data);
  40782. }
  40783. });
  40784. }
  40785. /**
  40786. *
  40787. * @param {Object} properties
  40788. * @returns {Edge}
  40789. */
  40790. }, {
  40791. key: 'create',
  40792. value: function create(properties) {
  40793. return new Edge(properties, this.body, this.options, this.defaultOptions);
  40794. }
  40795. /**
  40796. * Reconnect all edges
  40797. * @private
  40798. */
  40799. }, {
  40800. key: 'reconnectEdges',
  40801. value: function reconnectEdges() {
  40802. var id;
  40803. var nodes = this.body.nodes;
  40804. var edges = this.body.edges;
  40805. for (id in nodes) {
  40806. if (nodes.hasOwnProperty(id)) {
  40807. nodes[id].edges = [];
  40808. }
  40809. }
  40810. for (id in edges) {
  40811. if (edges.hasOwnProperty(id)) {
  40812. var edge = edges[id];
  40813. edge.from = null;
  40814. edge.to = null;
  40815. edge.connect();
  40816. }
  40817. }
  40818. }
  40819. /**
  40820. *
  40821. * @param {Edge.id} edgeId
  40822. * @returns {Array}
  40823. */
  40824. }, {
  40825. key: 'getConnectedNodes',
  40826. value: function getConnectedNodes(edgeId) {
  40827. var nodeList = [];
  40828. if (this.body.edges[edgeId] !== undefined) {
  40829. var edge = this.body.edges[edgeId];
  40830. if (edge.fromId !== undefined) {
  40831. nodeList.push(edge.fromId);
  40832. }
  40833. if (edge.toId !== undefined) {
  40834. nodeList.push(edge.toId);
  40835. }
  40836. }
  40837. return nodeList;
  40838. }
  40839. /**
  40840. * There is no direct relation between the nodes and the edges DataSet,
  40841. * so the right place to do call this is in the handler for event `_dataUpdated`.
  40842. */
  40843. }, {
  40844. key: '_updateState',
  40845. value: function _updateState() {
  40846. this._addMissingEdges();
  40847. this._removeInvalidEdges();
  40848. }
  40849. /**
  40850. * Scan for missing nodes and remove corresponding edges, if any.
  40851. * @private
  40852. */
  40853. }, {
  40854. key: '_removeInvalidEdges',
  40855. value: function _removeInvalidEdges() {
  40856. var _this5 = this;
  40857. var edgesToDelete = [];
  40858. util.forEach(this.body.edges, function (edge, id) {
  40859. var toNode = _this5.body.nodes[edge.toId];
  40860. var fromNode = _this5.body.nodes[edge.fromId];
  40861. // Skip clustering edges here, let the Clustering module handle those
  40862. if (toNode !== undefined && toNode.isCluster === true || fromNode !== undefined && fromNode.isCluster === true) {
  40863. return;
  40864. }
  40865. if (toNode === undefined || fromNode === undefined) {
  40866. edgesToDelete.push(id);
  40867. }
  40868. });
  40869. this.remove(edgesToDelete, false);
  40870. }
  40871. /**
  40872. * add all edges from dataset that are not in the cached state
  40873. * @private
  40874. */
  40875. }, {
  40876. key: '_addMissingEdges',
  40877. value: function _addMissingEdges() {
  40878. var edges = this.body.edges;
  40879. var edgesData = this.body.data.edges;
  40880. var addIds = [];
  40881. edgesData.forEach(function (edgeData, edgeId) {
  40882. var edge = edges[edgeId];
  40883. if (edge === undefined) {
  40884. addIds.push(edgeId);
  40885. }
  40886. });
  40887. this.add(addIds, true);
  40888. }
  40889. }]);
  40890. return EdgesHandler;
  40891. }();
  40892. exports['default'] = EdgesHandler;
  40893. /***/ }),
  40894. /* 215 */
  40895. /***/ (function(module, exports, __webpack_require__) {
  40896. "use strict";
  40897. Object.defineProperty(exports, "__esModule", {
  40898. value: true
  40899. });
  40900. var _slicedToArray2 = __webpack_require__(30);
  40901. var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
  40902. var _getPrototypeOf = __webpack_require__(3);
  40903. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  40904. var _classCallCheck2 = __webpack_require__(0);
  40905. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  40906. var _createClass2 = __webpack_require__(1);
  40907. var _createClass3 = _interopRequireDefault(_createClass2);
  40908. var _possibleConstructorReturn2 = __webpack_require__(4);
  40909. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  40910. var _inherits2 = __webpack_require__(5);
  40911. var _inherits3 = _interopRequireDefault(_inherits2);
  40912. var _CubicBezierEdgeBase2 = __webpack_require__(216);
  40913. var _CubicBezierEdgeBase3 = _interopRequireDefault(_CubicBezierEdgeBase2);
  40914. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  40915. /**
  40916. * A Cubic Bezier Edge. Bezier curves are used to model smooth gradual
  40917. * curves in paths between nodes.
  40918. *
  40919. * @extends CubicBezierEdgeBase
  40920. */
  40921. var CubicBezierEdge = function (_CubicBezierEdgeBase) {
  40922. (0, _inherits3['default'])(CubicBezierEdge, _CubicBezierEdgeBase);
  40923. /**
  40924. * @param {Object} options
  40925. * @param {Object} body
  40926. * @param {Label} labelModule
  40927. */
  40928. function CubicBezierEdge(options, body, labelModule) {
  40929. (0, _classCallCheck3['default'])(this, CubicBezierEdge);
  40930. return (0, _possibleConstructorReturn3['default'])(this, (CubicBezierEdge.__proto__ || (0, _getPrototypeOf2['default'])(CubicBezierEdge)).call(this, options, body, labelModule));
  40931. }
  40932. /**
  40933. * Draw a line between two nodes
  40934. * @param {CanvasRenderingContext2D} ctx
  40935. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  40936. * @param {Array.<Node>} viaNodes
  40937. * @private
  40938. */
  40939. (0, _createClass3['default'])(CubicBezierEdge, [{
  40940. key: '_line',
  40941. value: function _line(ctx, values, viaNodes) {
  40942. // get the coordinates of the support points.
  40943. var via1 = viaNodes[0];
  40944. var via2 = viaNodes[1];
  40945. this._bezierCurve(ctx, values, via1, via2);
  40946. }
  40947. /**
  40948. *
  40949. * @returns {Array.<{x: number, y: number}>}
  40950. * @private
  40951. */
  40952. }, {
  40953. key: '_getViaCoordinates',
  40954. value: function _getViaCoordinates() {
  40955. var dx = this.from.x - this.to.x;
  40956. var dy = this.from.y - this.to.y;
  40957. var x1 = void 0,
  40958. y1 = void 0,
  40959. x2 = void 0,
  40960. y2 = void 0;
  40961. var roundness = this.options.smooth.roundness;
  40962. // horizontal if x > y or if direction is forced or if direction is horizontal
  40963. if ((Math.abs(dx) > Math.abs(dy) || this.options.smooth.forceDirection === true || this.options.smooth.forceDirection === 'horizontal') && this.options.smooth.forceDirection !== 'vertical') {
  40964. y1 = this.from.y;
  40965. y2 = this.to.y;
  40966. x1 = this.from.x - roundness * dx;
  40967. x2 = this.to.x + roundness * dx;
  40968. } else {
  40969. y1 = this.from.y - roundness * dy;
  40970. y2 = this.to.y + roundness * dy;
  40971. x1 = this.from.x;
  40972. x2 = this.to.x;
  40973. }
  40974. return [{ x: x1, y: y1 }, { x: x2, y: y2 }];
  40975. }
  40976. /**
  40977. *
  40978. * @returns {Array.<{x: number, y: number}>}
  40979. */
  40980. }, {
  40981. key: 'getViaNode',
  40982. value: function getViaNode() {
  40983. return this._getViaCoordinates();
  40984. }
  40985. /**
  40986. *
  40987. * @param {Node} nearNode
  40988. * @param {CanvasRenderingContext2D} ctx
  40989. * @returns {{x: number, y: number, t: number}}
  40990. * @private
  40991. */
  40992. }, {
  40993. key: '_findBorderPosition',
  40994. value: function _findBorderPosition(nearNode, ctx) {
  40995. return this._findBorderPositionBezier(nearNode, ctx);
  40996. }
  40997. /**
  40998. *
  40999. * @param {number} x1
  41000. * @param {number} y1
  41001. * @param {number} x2
  41002. * @param {number} y2
  41003. * @param {number} x3
  41004. * @param {number} y3
  41005. * @param {Node} via1
  41006. * @param {Node} via2
  41007. * @returns {number}
  41008. * @private
  41009. */
  41010. }, {
  41011. key: '_getDistanceToEdge',
  41012. value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) {
  41013. var _ref = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : this._getViaCoordinates(),
  41014. _ref2 = (0, _slicedToArray3['default'])(_ref, 2),
  41015. via1 = _ref2[0],
  41016. via2 = _ref2[1];
  41017. // x3,y3 is the point
  41018. return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via1, via2);
  41019. }
  41020. /**
  41021. * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way
  41022. * @param {number} percentage
  41023. * @param {{x: number, y: number}} [via1=this._getViaCoordinates()[0]]
  41024. * @param {{x: number, y: number}} [via2=this._getViaCoordinates()[1]]
  41025. * @returns {{x: number, y: number}}
  41026. * @private
  41027. */
  41028. }, {
  41029. key: 'getPoint',
  41030. value: function getPoint(percentage) {
  41031. var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this._getViaCoordinates(),
  41032. _ref4 = (0, _slicedToArray3['default'])(_ref3, 2),
  41033. via1 = _ref4[0],
  41034. via2 = _ref4[1];
  41035. var t = percentage;
  41036. var vec = [];
  41037. vec[0] = Math.pow(1 - t, 3);
  41038. vec[1] = 3 * t * Math.pow(1 - t, 2);
  41039. vec[2] = 3 * Math.pow(t, 2) * (1 - t);
  41040. vec[3] = Math.pow(t, 3);
  41041. var x = vec[0] * this.fromPoint.x + vec[1] * via1.x + vec[2] * via2.x + vec[3] * this.toPoint.x;
  41042. var y = vec[0] * this.fromPoint.y + vec[1] * via1.y + vec[2] * via2.y + vec[3] * this.toPoint.y;
  41043. return { x: x, y: y };
  41044. }
  41045. }]);
  41046. return CubicBezierEdge;
  41047. }(_CubicBezierEdgeBase3['default']);
  41048. exports['default'] = CubicBezierEdge;
  41049. /***/ }),
  41050. /* 216 */
  41051. /***/ (function(module, exports, __webpack_require__) {
  41052. "use strict";
  41053. Object.defineProperty(exports, "__esModule", {
  41054. value: true
  41055. });
  41056. var _getPrototypeOf = __webpack_require__(3);
  41057. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  41058. var _classCallCheck2 = __webpack_require__(0);
  41059. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  41060. var _createClass2 = __webpack_require__(1);
  41061. var _createClass3 = _interopRequireDefault(_createClass2);
  41062. var _possibleConstructorReturn2 = __webpack_require__(4);
  41063. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  41064. var _inherits2 = __webpack_require__(5);
  41065. var _inherits3 = _interopRequireDefault(_inherits2);
  41066. var _BezierEdgeBase2 = __webpack_require__(75);
  41067. var _BezierEdgeBase3 = _interopRequireDefault(_BezierEdgeBase2);
  41068. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  41069. /**
  41070. * A Base Class for all Cubic Bezier Edges. Bezier curves are used to model
  41071. * smooth gradual curves in paths between nodes.
  41072. *
  41073. * @extends BezierEdgeBase
  41074. */
  41075. var CubicBezierEdgeBase = function (_BezierEdgeBase) {
  41076. (0, _inherits3['default'])(CubicBezierEdgeBase, _BezierEdgeBase);
  41077. /**
  41078. * @param {Object} options
  41079. * @param {Object} body
  41080. * @param {Label} labelModule
  41081. */
  41082. function CubicBezierEdgeBase(options, body, labelModule) {
  41083. (0, _classCallCheck3['default'])(this, CubicBezierEdgeBase);
  41084. return (0, _possibleConstructorReturn3['default'])(this, (CubicBezierEdgeBase.__proto__ || (0, _getPrototypeOf2['default'])(CubicBezierEdgeBase)).call(this, options, body, labelModule));
  41085. }
  41086. /**
  41087. * Calculate the distance between a point (x3,y3) and a line segment from
  41088. * (x1,y1) to (x2,y2).
  41089. * http://stackoverflow.com/questions/849211/shortest-distancae-between-a-point-and-a-line-segment
  41090. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  41091. * @param {number} x1 from x
  41092. * @param {number} y1 from y
  41093. * @param {number} x2 to x
  41094. * @param {number} y2 to y
  41095. * @param {number} x3 point to check x
  41096. * @param {number} y3 point to check y
  41097. * @param {Node} via1
  41098. * @param {Node} via2
  41099. * @returns {number}
  41100. * @private
  41101. */
  41102. (0, _createClass3['default'])(CubicBezierEdgeBase, [{
  41103. key: '_getDistanceToBezierEdge',
  41104. value: function _getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, via1, via2) {
  41105. // x3,y3 is the point
  41106. var minDistance = 1e9;
  41107. var distance = void 0;
  41108. var i = void 0,
  41109. t = void 0,
  41110. x = void 0,
  41111. y = void 0;
  41112. var lastX = x1;
  41113. var lastY = y1;
  41114. var vec = [0, 0, 0, 0];
  41115. for (i = 1; i < 10; i++) {
  41116. t = 0.1 * i;
  41117. vec[0] = Math.pow(1 - t, 3);
  41118. vec[1] = 3 * t * Math.pow(1 - t, 2);
  41119. vec[2] = 3 * Math.pow(t, 2) * (1 - t);
  41120. vec[3] = Math.pow(t, 3);
  41121. x = vec[0] * x1 + vec[1] * via1.x + vec[2] * via2.x + vec[3] * x2;
  41122. y = vec[0] * y1 + vec[1] * via1.y + vec[2] * via2.y + vec[3] * y2;
  41123. if (i > 0) {
  41124. distance = this._getDistanceToLine(lastX, lastY, x, y, x3, y3);
  41125. minDistance = distance < minDistance ? distance : minDistance;
  41126. }
  41127. lastX = x;
  41128. lastY = y;
  41129. }
  41130. return minDistance;
  41131. }
  41132. }]);
  41133. return CubicBezierEdgeBase;
  41134. }(_BezierEdgeBase3['default']);
  41135. exports['default'] = CubicBezierEdgeBase;
  41136. /***/ }),
  41137. /* 217 */
  41138. /***/ (function(module, exports, __webpack_require__) {
  41139. "use strict";
  41140. Object.defineProperty(exports, "__esModule", {
  41141. value: true
  41142. });
  41143. var _slicedToArray2 = __webpack_require__(30);
  41144. var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
  41145. var _getPrototypeOf = __webpack_require__(3);
  41146. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  41147. var _classCallCheck2 = __webpack_require__(0);
  41148. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  41149. var _createClass2 = __webpack_require__(1);
  41150. var _createClass3 = _interopRequireDefault(_createClass2);
  41151. var _possibleConstructorReturn2 = __webpack_require__(4);
  41152. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  41153. var _inherits2 = __webpack_require__(5);
  41154. var _inherits3 = _interopRequireDefault(_inherits2);
  41155. var _BezierEdgeBase2 = __webpack_require__(75);
  41156. var _BezierEdgeBase3 = _interopRequireDefault(_BezierEdgeBase2);
  41157. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  41158. /**
  41159. * A Dynamic Bezier Edge. Bezier curves are used to model smooth gradual
  41160. * curves in paths between nodes. The Dynamic piece refers to how the curve
  41161. * reacts to physics changes.
  41162. *
  41163. * @extends BezierEdgeBase
  41164. */
  41165. var BezierEdgeDynamic = function (_BezierEdgeBase) {
  41166. (0, _inherits3["default"])(BezierEdgeDynamic, _BezierEdgeBase);
  41167. /**
  41168. * @param {Object} options
  41169. * @param {Object} body
  41170. * @param {Label} labelModule
  41171. */
  41172. function BezierEdgeDynamic(options, body, labelModule) {
  41173. (0, _classCallCheck3["default"])(this, BezierEdgeDynamic);
  41174. // --> this calls the setOptions below
  41175. var _this = (0, _possibleConstructorReturn3["default"])(this, (BezierEdgeDynamic.__proto__ || (0, _getPrototypeOf2["default"])(BezierEdgeDynamic)).call(this, options, body, labelModule));
  41176. //this.via = undefined; // Here for completeness but not allowed to defined before super() is invoked.
  41177. _this._boundFunction = function () {
  41178. _this.positionBezierNode();
  41179. };
  41180. _this.body.emitter.on("_repositionBezierNodes", _this._boundFunction);
  41181. return _this;
  41182. }
  41183. /**
  41184. *
  41185. * @param {Object} options
  41186. */
  41187. (0, _createClass3["default"])(BezierEdgeDynamic, [{
  41188. key: "setOptions",
  41189. value: function setOptions(options) {
  41190. // check if the physics has changed.
  41191. var physicsChange = false;
  41192. if (this.options.physics !== options.physics) {
  41193. physicsChange = true;
  41194. }
  41195. // set the options and the to and from nodes
  41196. this.options = options;
  41197. this.id = this.options.id;
  41198. this.from = this.body.nodes[this.options.from];
  41199. this.to = this.body.nodes[this.options.to];
  41200. // setup the support node and connect
  41201. this.setupSupportNode();
  41202. this.connect();
  41203. // when we change the physics state of the edge, we reposition the support node.
  41204. if (physicsChange === true) {
  41205. this.via.setOptions({ physics: this.options.physics });
  41206. this.positionBezierNode();
  41207. }
  41208. }
  41209. /**
  41210. * Connects an edge to node(s)
  41211. */
  41212. }, {
  41213. key: "connect",
  41214. value: function connect() {
  41215. this.from = this.body.nodes[this.options.from];
  41216. this.to = this.body.nodes[this.options.to];
  41217. if (this.from === undefined || this.to === undefined || this.options.physics === false) {
  41218. this.via.setOptions({ physics: false });
  41219. } else {
  41220. // fix weird behaviour where a self referencing node has physics enabled
  41221. if (this.from.id === this.to.id) {
  41222. this.via.setOptions({ physics: false });
  41223. } else {
  41224. this.via.setOptions({ physics: true });
  41225. }
  41226. }
  41227. }
  41228. /**
  41229. * remove the support nodes
  41230. * @returns {boolean}
  41231. */
  41232. }, {
  41233. key: "cleanup",
  41234. value: function cleanup() {
  41235. this.body.emitter.off("_repositionBezierNodes", this._boundFunction);
  41236. if (this.via !== undefined) {
  41237. delete this.body.nodes[this.via.id];
  41238. this.via = undefined;
  41239. return true;
  41240. }
  41241. return false;
  41242. }
  41243. /**
  41244. * Bezier curves require an anchor point to calculate the smooth flow. These points are nodes. These nodes are invisible but
  41245. * are used for the force calculation.
  41246. *
  41247. * The changed data is not called, if needed, it is returned by the main edge constructor.
  41248. * @private
  41249. */
  41250. }, {
  41251. key: "setupSupportNode",
  41252. value: function setupSupportNode() {
  41253. if (this.via === undefined) {
  41254. var nodeId = "edgeId:" + this.id;
  41255. var node = this.body.functions.createNode({
  41256. id: nodeId,
  41257. shape: 'circle',
  41258. physics: true,
  41259. hidden: true
  41260. });
  41261. this.body.nodes[nodeId] = node;
  41262. this.via = node;
  41263. this.via.parentEdgeId = this.id;
  41264. this.positionBezierNode();
  41265. }
  41266. }
  41267. /**
  41268. * Positions bezier node
  41269. */
  41270. }, {
  41271. key: "positionBezierNode",
  41272. value: function positionBezierNode() {
  41273. if (this.via !== undefined && this.from !== undefined && this.to !== undefined) {
  41274. this.via.x = 0.5 * (this.from.x + this.to.x);
  41275. this.via.y = 0.5 * (this.from.y + this.to.y);
  41276. } else if (this.via !== undefined) {
  41277. this.via.x = 0;
  41278. this.via.y = 0;
  41279. }
  41280. }
  41281. /**
  41282. * Draw a line between two nodes
  41283. * @param {CanvasRenderingContext2D} ctx
  41284. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  41285. * @param {Node} viaNode
  41286. * @private
  41287. */
  41288. }, {
  41289. key: "_line",
  41290. value: function _line(ctx, values, viaNode) {
  41291. this._bezierCurve(ctx, values, viaNode);
  41292. }
  41293. /**
  41294. *
  41295. * @returns {Node|undefined|*|{index, line, column}}
  41296. */
  41297. }, {
  41298. key: "getViaNode",
  41299. value: function getViaNode() {
  41300. return this.via;
  41301. }
  41302. /**
  41303. * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way
  41304. *
  41305. * @param {number} percentage
  41306. * @param {Node} viaNode
  41307. * @returns {{x: number, y: number}}
  41308. * @private
  41309. */
  41310. }, {
  41311. key: "getPoint",
  41312. value: function getPoint(percentage) {
  41313. var viaNode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.via;
  41314. var t = percentage;
  41315. var x = void 0,
  41316. y = void 0;
  41317. if (this.from === this.to) {
  41318. var _getCircleData = this._getCircleData(this.from),
  41319. _getCircleData2 = (0, _slicedToArray3["default"])(_getCircleData, 3),
  41320. cx = _getCircleData2[0],
  41321. cy = _getCircleData2[1],
  41322. cr = _getCircleData2[2];
  41323. var a = 2 * Math.PI * (1 - t);
  41324. x = cx + cr * Math.sin(a);
  41325. y = cy + cr - cr * (1 - Math.cos(a));
  41326. } else {
  41327. x = Math.pow(1 - t, 2) * this.fromPoint.x + 2 * t * (1 - t) * viaNode.x + Math.pow(t, 2) * this.toPoint.x;
  41328. y = Math.pow(1 - t, 2) * this.fromPoint.y + 2 * t * (1 - t) * viaNode.y + Math.pow(t, 2) * this.toPoint.y;
  41329. }
  41330. return { x: x, y: y };
  41331. }
  41332. /**
  41333. *
  41334. * @param {Node} nearNode
  41335. * @param {CanvasRenderingContext2D} ctx
  41336. * @returns {*}
  41337. * @private
  41338. */
  41339. }, {
  41340. key: "_findBorderPosition",
  41341. value: function _findBorderPosition(nearNode, ctx) {
  41342. return this._findBorderPositionBezier(nearNode, ctx, this.via);
  41343. }
  41344. /**
  41345. *
  41346. * @param {number} x1
  41347. * @param {number} y1
  41348. * @param {number} x2
  41349. * @param {number} y2
  41350. * @param {number} x3
  41351. * @param {number} y3
  41352. * @returns {number}
  41353. * @private
  41354. */
  41355. }, {
  41356. key: "_getDistanceToEdge",
  41357. value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) {
  41358. // x3,y3 is the point
  41359. return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, this.via);
  41360. }
  41361. }]);
  41362. return BezierEdgeDynamic;
  41363. }(_BezierEdgeBase3["default"]);
  41364. exports["default"] = BezierEdgeDynamic;
  41365. /***/ }),
  41366. /* 218 */
  41367. /***/ (function(module, exports, __webpack_require__) {
  41368. "use strict";
  41369. Object.defineProperty(exports, "__esModule", {
  41370. value: true
  41371. });
  41372. var _getPrototypeOf = __webpack_require__(3);
  41373. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  41374. var _classCallCheck2 = __webpack_require__(0);
  41375. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  41376. var _createClass2 = __webpack_require__(1);
  41377. var _createClass3 = _interopRequireDefault(_createClass2);
  41378. var _possibleConstructorReturn2 = __webpack_require__(4);
  41379. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  41380. var _inherits2 = __webpack_require__(5);
  41381. var _inherits3 = _interopRequireDefault(_inherits2);
  41382. var _BezierEdgeBase2 = __webpack_require__(75);
  41383. var _BezierEdgeBase3 = _interopRequireDefault(_BezierEdgeBase2);
  41384. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  41385. /**
  41386. * A Static Bezier Edge. Bezier curves are used to model smooth gradual
  41387. * curves in paths between nodes.
  41388. *
  41389. * @extends BezierEdgeBase
  41390. */
  41391. var BezierEdgeStatic = function (_BezierEdgeBase) {
  41392. (0, _inherits3['default'])(BezierEdgeStatic, _BezierEdgeBase);
  41393. /**
  41394. * @param {Object} options
  41395. * @param {Object} body
  41396. * @param {Label} labelModule
  41397. */
  41398. function BezierEdgeStatic(options, body, labelModule) {
  41399. (0, _classCallCheck3['default'])(this, BezierEdgeStatic);
  41400. return (0, _possibleConstructorReturn3['default'])(this, (BezierEdgeStatic.__proto__ || (0, _getPrototypeOf2['default'])(BezierEdgeStatic)).call(this, options, body, labelModule));
  41401. }
  41402. /**
  41403. * Draw a line between two nodes
  41404. * @param {CanvasRenderingContext2D} ctx
  41405. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  41406. * @param {Node} viaNode
  41407. * @private
  41408. */
  41409. (0, _createClass3['default'])(BezierEdgeStatic, [{
  41410. key: '_line',
  41411. value: function _line(ctx, values, viaNode) {
  41412. this._bezierCurve(ctx, values, viaNode);
  41413. }
  41414. /**
  41415. *
  41416. * @returns {Array.<{x: number, y: number}>}
  41417. */
  41418. }, {
  41419. key: 'getViaNode',
  41420. value: function getViaNode() {
  41421. return this._getViaCoordinates();
  41422. }
  41423. /**
  41424. * We do not use the to and fromPoints here to make the via nodes the same as edges without arrows.
  41425. * @returns {{x: undefined, y: undefined}}
  41426. * @private
  41427. */
  41428. }, {
  41429. key: '_getViaCoordinates',
  41430. value: function _getViaCoordinates() {
  41431. // Assumption: x/y coordinates in from/to always defined
  41432. var xVia = undefined;
  41433. var yVia = undefined;
  41434. var factor = this.options.smooth.roundness;
  41435. var type = this.options.smooth.type;
  41436. var dx = Math.abs(this.from.x - this.to.x);
  41437. var dy = Math.abs(this.from.y - this.to.y);
  41438. if (type === 'discrete' || type === 'diagonalCross') {
  41439. var stepX = void 0;
  41440. var stepY = void 0;
  41441. if (dx <= dy) {
  41442. stepX = stepY = factor * dy;
  41443. } else {
  41444. stepX = stepY = factor * dx;
  41445. }
  41446. if (this.from.x > this.to.x) stepX = -stepX;
  41447. if (this.from.y >= this.to.y) stepY = -stepY;
  41448. xVia = this.from.x + stepX;
  41449. yVia = this.from.y + stepY;
  41450. if (type === "discrete") {
  41451. if (dx <= dy) {
  41452. xVia = dx < factor * dy ? this.from.x : xVia;
  41453. } else {
  41454. yVia = dy < factor * dx ? this.from.y : yVia;
  41455. }
  41456. }
  41457. } else if (type === "straightCross") {
  41458. var _stepX = (1 - factor) * dx;
  41459. var _stepY = (1 - factor) * dy;
  41460. if (dx <= dy) {
  41461. // up - down
  41462. _stepX = 0;
  41463. if (this.from.y < this.to.y) _stepY = -_stepY;
  41464. } else {
  41465. // left - right
  41466. if (this.from.x < this.to.x) _stepX = -_stepX;
  41467. _stepY = 0;
  41468. }
  41469. xVia = this.to.x + _stepX;
  41470. yVia = this.to.y + _stepY;
  41471. } else if (type === 'horizontal') {
  41472. var _stepX2 = (1 - factor) * dx;
  41473. if (this.from.x < this.to.x) _stepX2 = -_stepX2;
  41474. xVia = this.to.x + _stepX2;
  41475. yVia = this.from.y;
  41476. } else if (type === 'vertical') {
  41477. var _stepY2 = (1 - factor) * dy;
  41478. if (this.from.y < this.to.y) _stepY2 = -_stepY2;
  41479. xVia = this.from.x;
  41480. yVia = this.to.y + _stepY2;
  41481. } else if (type === 'curvedCW') {
  41482. dx = this.to.x - this.from.x;
  41483. dy = this.from.y - this.to.y;
  41484. var radius = Math.sqrt(dx * dx + dy * dy);
  41485. var pi = Math.PI;
  41486. var originalAngle = Math.atan2(dy, dx);
  41487. var myAngle = (originalAngle + (factor * 0.5 + 0.5) * pi) % (2 * pi);
  41488. xVia = this.from.x + (factor * 0.5 + 0.5) * radius * Math.sin(myAngle);
  41489. yVia = this.from.y + (factor * 0.5 + 0.5) * radius * Math.cos(myAngle);
  41490. } else if (type === 'curvedCCW') {
  41491. dx = this.to.x - this.from.x;
  41492. dy = this.from.y - this.to.y;
  41493. var _radius = Math.sqrt(dx * dx + dy * dy);
  41494. var _pi = Math.PI;
  41495. var _originalAngle = Math.atan2(dy, dx);
  41496. var _myAngle = (_originalAngle + (-factor * 0.5 + 0.5) * _pi) % (2 * _pi);
  41497. xVia = this.from.x + (factor * 0.5 + 0.5) * _radius * Math.sin(_myAngle);
  41498. yVia = this.from.y + (factor * 0.5 + 0.5) * _radius * Math.cos(_myAngle);
  41499. } else {
  41500. // continuous
  41501. var _stepX3 = void 0;
  41502. var _stepY3 = void 0;
  41503. if (dx <= dy) {
  41504. _stepX3 = _stepY3 = factor * dy;
  41505. } else {
  41506. _stepX3 = _stepY3 = factor * dx;
  41507. }
  41508. if (this.from.x > this.to.x) _stepX3 = -_stepX3;
  41509. if (this.from.y >= this.to.y) _stepY3 = -_stepY3;
  41510. xVia = this.from.x + _stepX3;
  41511. yVia = this.from.y + _stepY3;
  41512. if (dx <= dy) {
  41513. if (this.from.x <= this.to.x) {
  41514. xVia = this.to.x < xVia ? this.to.x : xVia;
  41515. } else {
  41516. xVia = this.to.x > xVia ? this.to.x : xVia;
  41517. }
  41518. } else {
  41519. if (this.from.y >= this.to.y) {
  41520. yVia = this.to.y > yVia ? this.to.y : yVia;
  41521. } else {
  41522. yVia = this.to.y < yVia ? this.to.y : yVia;
  41523. }
  41524. }
  41525. }
  41526. return { x: xVia, y: yVia };
  41527. }
  41528. /**
  41529. *
  41530. * @param {Node} nearNode
  41531. * @param {CanvasRenderingContext2D} ctx
  41532. * @param {Object} options
  41533. * @returns {*}
  41534. * @private
  41535. */
  41536. }, {
  41537. key: '_findBorderPosition',
  41538. value: function _findBorderPosition(nearNode, ctx) {
  41539. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  41540. return this._findBorderPositionBezier(nearNode, ctx, options.via);
  41541. }
  41542. /**
  41543. *
  41544. * @param {number} x1
  41545. * @param {number} y1
  41546. * @param {number} x2
  41547. * @param {number} y2
  41548. * @param {number} x3
  41549. * @param {number} y3
  41550. * @param {Node} viaNode
  41551. * @returns {number}
  41552. * @private
  41553. */
  41554. }, {
  41555. key: '_getDistanceToEdge',
  41556. value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) {
  41557. var viaNode = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : this._getViaCoordinates();
  41558. // x3,y3 is the point
  41559. return this._getDistanceToBezierEdge(x1, y1, x2, y2, x3, y3, viaNode);
  41560. }
  41561. /**
  41562. * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way
  41563. * @param {number} percentage
  41564. * @param {Node} viaNode
  41565. * @returns {{x: number, y: number}}
  41566. * @private
  41567. */
  41568. }, {
  41569. key: 'getPoint',
  41570. value: function getPoint(percentage) {
  41571. var viaNode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this._getViaCoordinates();
  41572. var t = percentage;
  41573. var x = Math.pow(1 - t, 2) * this.fromPoint.x + 2 * t * (1 - t) * viaNode.x + Math.pow(t, 2) * this.toPoint.x;
  41574. var y = Math.pow(1 - t, 2) * this.fromPoint.y + 2 * t * (1 - t) * viaNode.y + Math.pow(t, 2) * this.toPoint.y;
  41575. return { x: x, y: y };
  41576. }
  41577. }]);
  41578. return BezierEdgeStatic;
  41579. }(_BezierEdgeBase3['default']);
  41580. exports['default'] = BezierEdgeStatic;
  41581. /***/ }),
  41582. /* 219 */
  41583. /***/ (function(module, exports, __webpack_require__) {
  41584. "use strict";
  41585. Object.defineProperty(exports, "__esModule", {
  41586. value: true
  41587. });
  41588. var _getPrototypeOf = __webpack_require__(3);
  41589. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  41590. var _classCallCheck2 = __webpack_require__(0);
  41591. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  41592. var _createClass2 = __webpack_require__(1);
  41593. var _createClass3 = _interopRequireDefault(_createClass2);
  41594. var _possibleConstructorReturn2 = __webpack_require__(4);
  41595. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  41596. var _inherits2 = __webpack_require__(5);
  41597. var _inherits3 = _interopRequireDefault(_inherits2);
  41598. var _EdgeBase2 = __webpack_require__(118);
  41599. var _EdgeBase3 = _interopRequireDefault(_EdgeBase2);
  41600. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  41601. /**
  41602. * A Straight Edge.
  41603. *
  41604. * @extends EdgeBase
  41605. */
  41606. var StraightEdge = function (_EdgeBase) {
  41607. (0, _inherits3['default'])(StraightEdge, _EdgeBase);
  41608. /**
  41609. * @param {Object} options
  41610. * @param {Object} body
  41611. * @param {Label} labelModule
  41612. */
  41613. function StraightEdge(options, body, labelModule) {
  41614. (0, _classCallCheck3['default'])(this, StraightEdge);
  41615. return (0, _possibleConstructorReturn3['default'])(this, (StraightEdge.__proto__ || (0, _getPrototypeOf2['default'])(StraightEdge)).call(this, options, body, labelModule));
  41616. }
  41617. /**
  41618. * Draw a line between two nodes
  41619. * @param {CanvasRenderingContext2D} ctx
  41620. * @param {{toArrow: boolean, toArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), toArrowType: *, middleArrow: boolean, middleArrowScale: (number|allOptions.edges.arrows.middle.scaleFactor|{number}|Array), middleArrowType: (allOptions.edges.arrows.middle.type|{string}|string|*), fromArrow: boolean, fromArrowScale: (allOptions.edges.arrows.to.scaleFactor|{number}|allOptions.edges.arrows.middle.scaleFactor|allOptions.edges.arrows.from.scaleFactor|Array|number), fromArrowType: *, arrowStrikethrough: (*|boolean|allOptions.edges.arrowStrikethrough|{boolean}), color: undefined, inheritsColor: (string|string|string|allOptions.edges.color.inherit|{string, boolean}|Array|*), opacity: *, hidden: *, length: *, shadow: *, shadowColor: *, shadowSize: *, shadowX: *, shadowY: *, dashes: (*|boolean|Array|allOptions.edges.dashes|{boolean, array}), width: *}} values
  41621. * @private
  41622. */
  41623. (0, _createClass3['default'])(StraightEdge, [{
  41624. key: '_line',
  41625. value: function _line(ctx, values) {
  41626. // draw a straight line
  41627. ctx.beginPath();
  41628. ctx.moveTo(this.fromPoint.x, this.fromPoint.y);
  41629. ctx.lineTo(this.toPoint.x, this.toPoint.y);
  41630. // draw shadow if enabled
  41631. this.enableShadow(ctx, values);
  41632. ctx.stroke();
  41633. this.disableShadow(ctx, values);
  41634. }
  41635. /**
  41636. *
  41637. * @returns {undefined}
  41638. */
  41639. }, {
  41640. key: 'getViaNode',
  41641. value: function getViaNode() {
  41642. return undefined;
  41643. }
  41644. /**
  41645. * Combined function of pointOnLine and pointOnBezier. This gives the coordinates of a point on the line at a certain percentage of the way
  41646. *
  41647. * @param {number} percentage
  41648. * @returns {{x: number, y: number}}
  41649. * @private
  41650. */
  41651. }, {
  41652. key: 'getPoint',
  41653. value: function getPoint(percentage) {
  41654. return {
  41655. x: (1 - percentage) * this.fromPoint.x + percentage * this.toPoint.x,
  41656. y: (1 - percentage) * this.fromPoint.y + percentage * this.toPoint.y
  41657. };
  41658. }
  41659. /**
  41660. *
  41661. * @param {Node} nearNode
  41662. * @param {CanvasRenderingContext2D} ctx
  41663. * @returns {{x: number, y: number}}
  41664. * @private
  41665. */
  41666. }, {
  41667. key: '_findBorderPosition',
  41668. value: function _findBorderPosition(nearNode, ctx) {
  41669. var node1 = this.to;
  41670. var node2 = this.from;
  41671. if (nearNode.id === this.from.id) {
  41672. node1 = this.from;
  41673. node2 = this.to;
  41674. }
  41675. var angle = Math.atan2(node1.y - node2.y, node1.x - node2.x);
  41676. var dx = node1.x - node2.x;
  41677. var dy = node1.y - node2.y;
  41678. var edgeSegmentLength = Math.sqrt(dx * dx + dy * dy);
  41679. var toBorderDist = nearNode.distanceToBorder(ctx, angle);
  41680. var toBorderPoint = (edgeSegmentLength - toBorderDist) / edgeSegmentLength;
  41681. var borderPos = {};
  41682. borderPos.x = (1 - toBorderPoint) * node2.x + toBorderPoint * node1.x;
  41683. borderPos.y = (1 - toBorderPoint) * node2.y + toBorderPoint * node1.y;
  41684. return borderPos;
  41685. }
  41686. /**
  41687. *
  41688. * @param {number} x1
  41689. * @param {number} y1
  41690. * @param {number} x2
  41691. * @param {number} y2
  41692. * @param {number} x3
  41693. * @param {number} y3
  41694. * @returns {number}
  41695. * @private
  41696. */
  41697. }, {
  41698. key: '_getDistanceToEdge',
  41699. value: function _getDistanceToEdge(x1, y1, x2, y2, x3, y3) {
  41700. // x3,y3 is the point
  41701. return this._getDistanceToLine(x1, y1, x2, y2, x3, y3);
  41702. }
  41703. }]);
  41704. return StraightEdge;
  41705. }(_EdgeBase3['default']);
  41706. exports['default'] = StraightEdge;
  41707. /***/ }),
  41708. /* 220 */
  41709. /***/ (function(module, exports, __webpack_require__) {
  41710. "use strict";
  41711. Object.defineProperty(exports, "__esModule", {
  41712. value: true
  41713. });
  41714. var _keys = __webpack_require__(8);
  41715. var _keys2 = _interopRequireDefault(_keys);
  41716. var _classCallCheck2 = __webpack_require__(0);
  41717. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  41718. var _createClass2 = __webpack_require__(1);
  41719. var _createClass3 = _interopRequireDefault(_createClass2);
  41720. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  41721. var BarnesHutSolver = __webpack_require__(120)['default'];
  41722. var Repulsion = __webpack_require__(221)['default'];
  41723. var HierarchicalRepulsion = __webpack_require__(222)['default'];
  41724. var SpringSolver = __webpack_require__(223)['default'];
  41725. var HierarchicalSpringSolver = __webpack_require__(224)['default'];
  41726. var CentralGravitySolver = __webpack_require__(121)['default'];
  41727. var ForceAtlas2BasedRepulsionSolver = __webpack_require__(225)['default'];
  41728. var ForceAtlas2BasedCentralGravitySolver = __webpack_require__(226)['default'];
  41729. var util = __webpack_require__(2);
  41730. var EndPoints = __webpack_require__(119)['default']; // for debugging with _drawForces()
  41731. /**
  41732. * The physics engine
  41733. */
  41734. var PhysicsEngine = function () {
  41735. /**
  41736. * @param {Object} body
  41737. */
  41738. function PhysicsEngine(body) {
  41739. (0, _classCallCheck3['default'])(this, PhysicsEngine);
  41740. this.body = body;
  41741. this.physicsBody = { physicsNodeIndices: [], physicsEdgeIndices: [], forces: {}, velocities: {} };
  41742. this.physicsEnabled = true;
  41743. this.simulationInterval = 1000 / 60;
  41744. this.requiresTimeout = true;
  41745. this.previousStates = {};
  41746. this.referenceState = {};
  41747. this.freezeCache = {};
  41748. this.renderTimer = undefined;
  41749. // parameters for the adaptive timestep
  41750. this.adaptiveTimestep = false;
  41751. this.adaptiveTimestepEnabled = false;
  41752. this.adaptiveCounter = 0;
  41753. this.adaptiveInterval = 3;
  41754. this.stabilized = false;
  41755. this.startedStabilization = false;
  41756. this.stabilizationIterations = 0;
  41757. this.ready = false; // will be set to true if the stabilize
  41758. // default options
  41759. this.options = {};
  41760. this.defaultOptions = {
  41761. enabled: true,
  41762. barnesHut: {
  41763. theta: 0.5,
  41764. gravitationalConstant: -2000,
  41765. centralGravity: 0.3,
  41766. springLength: 95,
  41767. springConstant: 0.04,
  41768. damping: 0.09,
  41769. avoidOverlap: 0
  41770. },
  41771. forceAtlas2Based: {
  41772. theta: 0.5,
  41773. gravitationalConstant: -50,
  41774. centralGravity: 0.01,
  41775. springConstant: 0.08,
  41776. springLength: 100,
  41777. damping: 0.4,
  41778. avoidOverlap: 0
  41779. },
  41780. repulsion: {
  41781. centralGravity: 0.2,
  41782. springLength: 200,
  41783. springConstant: 0.05,
  41784. nodeDistance: 100,
  41785. damping: 0.09,
  41786. avoidOverlap: 0
  41787. },
  41788. hierarchicalRepulsion: {
  41789. centralGravity: 0.0,
  41790. springLength: 100,
  41791. springConstant: 0.01,
  41792. nodeDistance: 120,
  41793. damping: 0.09
  41794. },
  41795. maxVelocity: 50,
  41796. minVelocity: 0.75, // px/s
  41797. solver: 'barnesHut',
  41798. stabilization: {
  41799. enabled: true,
  41800. iterations: 1000, // maximum number of iteration to stabilize
  41801. updateInterval: 50,
  41802. onlyDynamicEdges: false,
  41803. fit: true
  41804. },
  41805. timestep: 0.5,
  41806. adaptiveTimestep: true
  41807. };
  41808. util.extend(this.options, this.defaultOptions);
  41809. this.timestep = 0.5;
  41810. this.layoutFailed = false;
  41811. this.bindEventListeners();
  41812. }
  41813. /**
  41814. * Binds event listeners
  41815. */
  41816. (0, _createClass3['default'])(PhysicsEngine, [{
  41817. key: 'bindEventListeners',
  41818. value: function bindEventListeners() {
  41819. var _this = this;
  41820. this.body.emitter.on('initPhysics', function () {
  41821. _this.initPhysics();
  41822. });
  41823. this.body.emitter.on('_layoutFailed', function () {
  41824. _this.layoutFailed = true;
  41825. });
  41826. this.body.emitter.on('resetPhysics', function () {
  41827. _this.stopSimulation();_this.ready = false;
  41828. });
  41829. this.body.emitter.on('disablePhysics', function () {
  41830. _this.physicsEnabled = false;_this.stopSimulation();
  41831. });
  41832. this.body.emitter.on('restorePhysics', function () {
  41833. _this.setOptions(_this.options);
  41834. if (_this.ready === true) {
  41835. _this.startSimulation();
  41836. }
  41837. });
  41838. this.body.emitter.on('startSimulation', function () {
  41839. if (_this.ready === true) {
  41840. _this.startSimulation();
  41841. }
  41842. });
  41843. this.body.emitter.on('stopSimulation', function () {
  41844. _this.stopSimulation();
  41845. });
  41846. this.body.emitter.on('destroy', function () {
  41847. _this.stopSimulation(false);
  41848. _this.body.emitter.off();
  41849. });
  41850. this.body.emitter.on("_dataChanged", function () {
  41851. // Nodes and/or edges have been added or removed, update shortcut lists.
  41852. _this.updatePhysicsData();
  41853. });
  41854. // debug: show forces
  41855. // this.body.emitter.on("afterDrawing", (ctx) => {this._drawForces(ctx);});
  41856. }
  41857. /**
  41858. * set the physics options
  41859. * @param {Object} options
  41860. */
  41861. }, {
  41862. key: 'setOptions',
  41863. value: function setOptions(options) {
  41864. if (options !== undefined) {
  41865. if (options === false) {
  41866. this.options.enabled = false;
  41867. this.physicsEnabled = false;
  41868. this.stopSimulation();
  41869. } else if (options === true) {
  41870. this.options.enabled = true;
  41871. this.physicsEnabled = true;
  41872. this.startSimulation();
  41873. } else {
  41874. this.physicsEnabled = true;
  41875. util.selectiveNotDeepExtend(['stabilization'], this.options, options);
  41876. util.mergeOptions(this.options, options, 'stabilization');
  41877. if (options.enabled === undefined) {
  41878. this.options.enabled = true;
  41879. }
  41880. if (this.options.enabled === false) {
  41881. this.physicsEnabled = false;
  41882. this.stopSimulation();
  41883. }
  41884. // set the timestep
  41885. this.timestep = this.options.timestep;
  41886. }
  41887. }
  41888. this.init();
  41889. }
  41890. /**
  41891. * configure the engine.
  41892. */
  41893. }, {
  41894. key: 'init',
  41895. value: function init() {
  41896. var options;
  41897. if (this.options.solver === 'forceAtlas2Based') {
  41898. options = this.options.forceAtlas2Based;
  41899. this.nodesSolver = new ForceAtlas2BasedRepulsionSolver(this.body, this.physicsBody, options);
  41900. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  41901. this.gravitySolver = new ForceAtlas2BasedCentralGravitySolver(this.body, this.physicsBody, options);
  41902. } else if (this.options.solver === 'repulsion') {
  41903. options = this.options.repulsion;
  41904. this.nodesSolver = new Repulsion(this.body, this.physicsBody, options);
  41905. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  41906. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  41907. } else if (this.options.solver === 'hierarchicalRepulsion') {
  41908. options = this.options.hierarchicalRepulsion;
  41909. this.nodesSolver = new HierarchicalRepulsion(this.body, this.physicsBody, options);
  41910. this.edgesSolver = new HierarchicalSpringSolver(this.body, this.physicsBody, options);
  41911. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  41912. } else {
  41913. // barnesHut
  41914. options = this.options.barnesHut;
  41915. this.nodesSolver = new BarnesHutSolver(this.body, this.physicsBody, options);
  41916. this.edgesSolver = new SpringSolver(this.body, this.physicsBody, options);
  41917. this.gravitySolver = new CentralGravitySolver(this.body, this.physicsBody, options);
  41918. }
  41919. this.modelOptions = options;
  41920. }
  41921. /**
  41922. * initialize the engine
  41923. */
  41924. }, {
  41925. key: 'initPhysics',
  41926. value: function initPhysics() {
  41927. if (this.physicsEnabled === true && this.options.enabled === true) {
  41928. if (this.options.stabilization.enabled === true) {
  41929. this.stabilize();
  41930. } else {
  41931. this.stabilized = false;
  41932. this.ready = true;
  41933. this.body.emitter.emit('fit', {}, this.layoutFailed); // if the layout failed, we use the approximation for the zoom
  41934. this.startSimulation();
  41935. }
  41936. } else {
  41937. this.ready = true;
  41938. this.body.emitter.emit('fit');
  41939. }
  41940. }
  41941. /**
  41942. * Start the simulation
  41943. */
  41944. }, {
  41945. key: 'startSimulation',
  41946. value: function startSimulation() {
  41947. if (this.physicsEnabled === true && this.options.enabled === true) {
  41948. this.stabilized = false;
  41949. // when visible, adaptivity is disabled.
  41950. this.adaptiveTimestep = false;
  41951. // this sets the width of all nodes initially which could be required for the avoidOverlap
  41952. this.body.emitter.emit("_resizeNodes");
  41953. if (this.viewFunction === undefined) {
  41954. this.viewFunction = this.simulationStep.bind(this);
  41955. this.body.emitter.on('initRedraw', this.viewFunction);
  41956. this.body.emitter.emit('_startRendering');
  41957. }
  41958. } else {
  41959. this.body.emitter.emit('_redraw');
  41960. }
  41961. }
  41962. /**
  41963. * Stop the simulation, force stabilization.
  41964. * @param {boolean} [emit=true]
  41965. */
  41966. }, {
  41967. key: 'stopSimulation',
  41968. value: function stopSimulation() {
  41969. var emit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  41970. this.stabilized = true;
  41971. if (emit === true) {
  41972. this._emitStabilized();
  41973. }
  41974. if (this.viewFunction !== undefined) {
  41975. this.body.emitter.off('initRedraw', this.viewFunction);
  41976. this.viewFunction = undefined;
  41977. if (emit === true) {
  41978. this.body.emitter.emit('_stopRendering');
  41979. }
  41980. }
  41981. }
  41982. /**
  41983. * The viewFunction inserts this step into each render loop. It calls the physics tick and handles the cleanup at stabilized.
  41984. *
  41985. */
  41986. }, {
  41987. key: 'simulationStep',
  41988. value: function simulationStep() {
  41989. // check if the physics have settled
  41990. var startTime = Date.now();
  41991. this.physicsTick();
  41992. var physicsTime = Date.now() - startTime;
  41993. // run double speed if it is a little graph
  41994. if ((physicsTime < 0.4 * this.simulationInterval || this.runDoubleSpeed === true) && this.stabilized === false) {
  41995. this.physicsTick();
  41996. // this makes sure there is no jitter. The decision is taken once to run it at double speed.
  41997. this.runDoubleSpeed = true;
  41998. }
  41999. if (this.stabilized === true) {
  42000. this.stopSimulation();
  42001. }
  42002. }
  42003. /**
  42004. * trigger the stabilized event.
  42005. *
  42006. * @param {number} [amountOfIterations=this.stabilizationIterations]
  42007. * @private
  42008. */
  42009. }, {
  42010. key: '_emitStabilized',
  42011. value: function _emitStabilized() {
  42012. var _this2 = this;
  42013. var amountOfIterations = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.stabilizationIterations;
  42014. if (this.stabilizationIterations > 1 || this.startedStabilization === true) {
  42015. setTimeout(function () {
  42016. _this2.body.emitter.emit('stabilized', { iterations: amountOfIterations });
  42017. _this2.startedStabilization = false;
  42018. _this2.stabilizationIterations = 0;
  42019. }, 0);
  42020. }
  42021. }
  42022. /**
  42023. * Calculate the forces for one physics iteration and move the nodes.
  42024. * @private
  42025. */
  42026. }, {
  42027. key: 'physicsStep',
  42028. value: function physicsStep() {
  42029. this.gravitySolver.solve();
  42030. this.nodesSolver.solve();
  42031. this.edgesSolver.solve();
  42032. this.moveNodes();
  42033. }
  42034. /**
  42035. * Make dynamic adjustments to the timestep, based on current state.
  42036. *
  42037. * Helper function for physicsTick().
  42038. * @private
  42039. */
  42040. }, {
  42041. key: 'adjustTimeStep',
  42042. value: function adjustTimeStep() {
  42043. var factor = 1.2; // Factor for increasing the timestep on success.
  42044. // we compare the two steps. if it is acceptable we double the step.
  42045. if (this._evaluateStepQuality() === true) {
  42046. this.timestep = factor * this.timestep;
  42047. } else {
  42048. // if not, we decrease the step to a minimum of the options timestep.
  42049. // if the decreased timestep is smaller than the options step, we do not reset the counter
  42050. // we assume that the options timestep is stable enough.
  42051. if (this.timestep / factor < this.options.timestep) {
  42052. this.timestep = this.options.timestep;
  42053. } else {
  42054. // if the timestep was larger than 2 times the option one we check the adaptivity again to ensure
  42055. // that large instabilities do not form.
  42056. this.adaptiveCounter = -1; // check again next iteration
  42057. this.timestep = Math.max(this.options.timestep, this.timestep / factor);
  42058. }
  42059. }
  42060. }
  42061. /**
  42062. * A single simulation step (or 'tick') in the physics simulation
  42063. *
  42064. * @private
  42065. */
  42066. }, {
  42067. key: 'physicsTick',
  42068. value: function physicsTick() {
  42069. this._startStabilizing(); // this ensures that there is no start event when the network is already stable.
  42070. if (this.stabilized === true) return;
  42071. // adaptivity means the timestep adapts to the situation, only applicable for stabilization
  42072. if (this.adaptiveTimestep === true && this.adaptiveTimestepEnabled === true) {
  42073. // timestep remains stable for "interval" iterations.
  42074. var doAdaptive = this.adaptiveCounter % this.adaptiveInterval === 0;
  42075. if (doAdaptive) {
  42076. // first the big step and revert.
  42077. this.timestep = 2 * this.timestep;
  42078. this.physicsStep();
  42079. this.revert(); // saves the reference state
  42080. // now the normal step. Since this is the last step, it is the more stable one and we will take this.
  42081. this.timestep = 0.5 * this.timestep;
  42082. // since it's half the step, we do it twice.
  42083. this.physicsStep();
  42084. this.physicsStep();
  42085. this.adjustTimeStep();
  42086. } else {
  42087. this.physicsStep(); // normal step, keeping timestep constant
  42088. }
  42089. this.adaptiveCounter += 1;
  42090. } else {
  42091. // case for the static timestep, we reset it to the one in options and take a normal step.
  42092. this.timestep = this.options.timestep;
  42093. this.physicsStep();
  42094. }
  42095. if (this.stabilized === true) this.revert();
  42096. this.stabilizationIterations++;
  42097. }
  42098. /**
  42099. * 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.
  42100. *
  42101. * @private
  42102. */
  42103. }, {
  42104. key: 'updatePhysicsData',
  42105. value: function updatePhysicsData() {
  42106. this.physicsBody.forces = {};
  42107. this.physicsBody.physicsNodeIndices = [];
  42108. this.physicsBody.physicsEdgeIndices = [];
  42109. var nodes = this.body.nodes;
  42110. var edges = this.body.edges;
  42111. // get node indices for physics
  42112. for (var nodeId in nodes) {
  42113. if (nodes.hasOwnProperty(nodeId)) {
  42114. if (nodes[nodeId].options.physics === true) {
  42115. this.physicsBody.physicsNodeIndices.push(nodes[nodeId].id);
  42116. }
  42117. }
  42118. }
  42119. // get edge indices for physics
  42120. for (var edgeId in edges) {
  42121. if (edges.hasOwnProperty(edgeId)) {
  42122. if (edges[edgeId].options.physics === true) {
  42123. this.physicsBody.physicsEdgeIndices.push(edges[edgeId].id);
  42124. }
  42125. }
  42126. }
  42127. // get the velocity and the forces vector
  42128. for (var i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  42129. var _nodeId = this.physicsBody.physicsNodeIndices[i];
  42130. this.physicsBody.forces[_nodeId] = { x: 0, y: 0 };
  42131. // forces can be reset because they are recalculated. Velocities have to persist.
  42132. if (this.physicsBody.velocities[_nodeId] === undefined) {
  42133. this.physicsBody.velocities[_nodeId] = { x: 0, y: 0 };
  42134. }
  42135. }
  42136. // clean deleted nodes from the velocity vector
  42137. for (var _nodeId2 in this.physicsBody.velocities) {
  42138. if (nodes[_nodeId2] === undefined) {
  42139. delete this.physicsBody.velocities[_nodeId2];
  42140. }
  42141. }
  42142. }
  42143. /**
  42144. * Revert the simulation one step. This is done so after stabilization, every new start of the simulation will also say stabilized.
  42145. */
  42146. }, {
  42147. key: 'revert',
  42148. value: function revert() {
  42149. var nodeIds = (0, _keys2['default'])(this.previousStates);
  42150. var nodes = this.body.nodes;
  42151. var velocities = this.physicsBody.velocities;
  42152. this.referenceState = {};
  42153. for (var i = 0; i < nodeIds.length; i++) {
  42154. var nodeId = nodeIds[i];
  42155. if (nodes[nodeId] !== undefined) {
  42156. if (nodes[nodeId].options.physics === true) {
  42157. this.referenceState[nodeId] = {
  42158. positions: { x: nodes[nodeId].x, y: nodes[nodeId].y }
  42159. };
  42160. velocities[nodeId].x = this.previousStates[nodeId].vx;
  42161. velocities[nodeId].y = this.previousStates[nodeId].vy;
  42162. nodes[nodeId].x = this.previousStates[nodeId].x;
  42163. nodes[nodeId].y = this.previousStates[nodeId].y;
  42164. }
  42165. } else {
  42166. delete this.previousStates[nodeId];
  42167. }
  42168. }
  42169. }
  42170. /**
  42171. * This compares the reference state to the current state
  42172. *
  42173. * @returns {boolean}
  42174. * @private
  42175. */
  42176. }, {
  42177. key: '_evaluateStepQuality',
  42178. value: function _evaluateStepQuality() {
  42179. var dx = void 0,
  42180. dy = void 0,
  42181. dpos = void 0;
  42182. var nodes = this.body.nodes;
  42183. var reference = this.referenceState;
  42184. var posThreshold = 0.3;
  42185. for (var nodeId in this.referenceState) {
  42186. if (this.referenceState.hasOwnProperty(nodeId) && nodes[nodeId] !== undefined) {
  42187. dx = nodes[nodeId].x - reference[nodeId].positions.x;
  42188. dy = nodes[nodeId].y - reference[nodeId].positions.y;
  42189. dpos = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  42190. if (dpos > posThreshold) {
  42191. return false;
  42192. }
  42193. }
  42194. }
  42195. return true;
  42196. }
  42197. /**
  42198. * move the nodes one timestep and check if they are stabilized
  42199. */
  42200. }, {
  42201. key: 'moveNodes',
  42202. value: function moveNodes() {
  42203. var nodeIndices = this.physicsBody.physicsNodeIndices;
  42204. var maxNodeVelocity = 0;
  42205. var averageNodeVelocity = 0;
  42206. // the velocity threshold (energy in the system) for the adaptivity toggle
  42207. var velocityAdaptiveThreshold = 5;
  42208. for (var i = 0; i < nodeIndices.length; i++) {
  42209. var nodeId = nodeIndices[i];
  42210. var nodeVelocity = this._performStep(nodeId);
  42211. // stabilized is true if stabilized is true and velocity is smaller than vmin --> all nodes must be stabilized
  42212. maxNodeVelocity = Math.max(maxNodeVelocity, nodeVelocity);
  42213. averageNodeVelocity += nodeVelocity;
  42214. }
  42215. // evaluating the stabilized and adaptiveTimestepEnabled conditions
  42216. this.adaptiveTimestepEnabled = averageNodeVelocity / nodeIndices.length < velocityAdaptiveThreshold;
  42217. this.stabilized = maxNodeVelocity < this.options.minVelocity;
  42218. }
  42219. /**
  42220. * Calculate new velocity for a coordinate direction
  42221. *
  42222. * @param {number} v velocity for current coordinate
  42223. * @param {number} f regular force for current coordinate
  42224. * @param {number} m mass of current node
  42225. * @returns {number} new velocity for current coordinate
  42226. * @private
  42227. */
  42228. }, {
  42229. key: 'calculateComponentVelocity',
  42230. value: function calculateComponentVelocity(v, f, m) {
  42231. var df = this.modelOptions.damping * v; // damping force
  42232. var a = (f - df) / m; // acceleration
  42233. v += a * this.timestep;
  42234. // Put a limit on the velocities if it is really high
  42235. var maxV = this.options.maxVelocity || 1e9;
  42236. if (Math.abs(v) > maxV) {
  42237. v = v > 0 ? maxV : -maxV;
  42238. }
  42239. return v;
  42240. }
  42241. /**
  42242. * Perform the actual step
  42243. *
  42244. * @param {Node.id} nodeId
  42245. * @returns {number} the new velocity of given node
  42246. * @private
  42247. */
  42248. }, {
  42249. key: '_performStep',
  42250. value: function _performStep(nodeId) {
  42251. var node = this.body.nodes[nodeId];
  42252. var force = this.physicsBody.forces[nodeId];
  42253. var velocity = this.physicsBody.velocities[nodeId];
  42254. // store the state so we can revert
  42255. this.previousStates[nodeId] = { x: node.x, y: node.y, vx: velocity.x, vy: velocity.y };
  42256. if (node.options.fixed.x === false) {
  42257. velocity.x = this.calculateComponentVelocity(velocity.x, force.x, node.options.mass);
  42258. node.x += velocity.x * this.timestep;
  42259. } else {
  42260. force.x = 0;
  42261. velocity.x = 0;
  42262. }
  42263. if (node.options.fixed.y === false) {
  42264. velocity.y = this.calculateComponentVelocity(velocity.y, force.y, node.options.mass);
  42265. node.y += velocity.y * this.timestep;
  42266. } else {
  42267. force.y = 0;
  42268. velocity.y = 0;
  42269. }
  42270. var totalVelocity = Math.sqrt(Math.pow(velocity.x, 2) + Math.pow(velocity.y, 2));
  42271. return totalVelocity;
  42272. }
  42273. /**
  42274. * When initializing and stabilizing, we can freeze nodes with a predefined position.
  42275. * This greatly speeds up stabilization because only the supportnodes for the smoothCurves have to settle.
  42276. *
  42277. * @private
  42278. */
  42279. }, {
  42280. key: '_freezeNodes',
  42281. value: function _freezeNodes() {
  42282. var nodes = this.body.nodes;
  42283. for (var id in nodes) {
  42284. if (nodes.hasOwnProperty(id)) {
  42285. if (nodes[id].x && nodes[id].y) {
  42286. var fixed = nodes[id].options.fixed;
  42287. this.freezeCache[id] = { x: fixed.x, y: fixed.y };
  42288. fixed.x = true;
  42289. fixed.y = true;
  42290. }
  42291. }
  42292. }
  42293. }
  42294. /**
  42295. * Unfreezes the nodes that have been frozen by _freezeDefinedNodes.
  42296. *
  42297. * @private
  42298. */
  42299. }, {
  42300. key: '_restoreFrozenNodes',
  42301. value: function _restoreFrozenNodes() {
  42302. var nodes = this.body.nodes;
  42303. for (var id in nodes) {
  42304. if (nodes.hasOwnProperty(id)) {
  42305. if (this.freezeCache[id] !== undefined) {
  42306. nodes[id].options.fixed.x = this.freezeCache[id].x;
  42307. nodes[id].options.fixed.y = this.freezeCache[id].y;
  42308. }
  42309. }
  42310. }
  42311. this.freezeCache = {};
  42312. }
  42313. /**
  42314. * Find a stable position for all nodes
  42315. *
  42316. * @param {number} [iterations=this.options.stabilization.iterations]
  42317. */
  42318. }, {
  42319. key: 'stabilize',
  42320. value: function stabilize() {
  42321. var _this3 = this;
  42322. var iterations = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.options.stabilization.iterations;
  42323. if (typeof iterations !== 'number') {
  42324. iterations = this.options.stabilization.iterations;
  42325. console.log('The stabilize method needs a numeric amount of iterations. Switching to default: ', iterations);
  42326. }
  42327. if (this.physicsBody.physicsNodeIndices.length === 0) {
  42328. this.ready = true;
  42329. return;
  42330. }
  42331. // enable adaptive timesteps
  42332. this.adaptiveTimestep = true && this.options.adaptiveTimestep;
  42333. // this sets the width of all nodes initially which could be required for the avoidOverlap
  42334. this.body.emitter.emit("_resizeNodes");
  42335. this.stopSimulation(); // stop the render loop
  42336. this.stabilized = false;
  42337. // block redraw requests
  42338. this.body.emitter.emit('_blockRedraw');
  42339. this.targetIterations = iterations;
  42340. // start the stabilization
  42341. if (this.options.stabilization.onlyDynamicEdges === true) {
  42342. this._freezeNodes();
  42343. }
  42344. this.stabilizationIterations = 0;
  42345. setTimeout(function () {
  42346. return _this3._stabilizationBatch();
  42347. }, 0);
  42348. }
  42349. /**
  42350. * If not already stabilizing, start it and emit a start event.
  42351. *
  42352. * @returns {boolean} true if stabilization started with this call
  42353. * @private
  42354. */
  42355. }, {
  42356. key: '_startStabilizing',
  42357. value: function _startStabilizing() {
  42358. if (this.startedStabilization === true) return false;
  42359. this.body.emitter.emit('startStabilizing');
  42360. this.startedStabilization = true;
  42361. return true;
  42362. }
  42363. /**
  42364. * One batch of stabilization
  42365. * @private
  42366. */
  42367. }, {
  42368. key: '_stabilizationBatch',
  42369. value: function _stabilizationBatch() {
  42370. var _this4 = this;
  42371. var running = function running() {
  42372. return _this4.stabilized === false && _this4.stabilizationIterations < _this4.targetIterations;
  42373. };
  42374. var sendProgress = function sendProgress() {
  42375. _this4.body.emitter.emit('stabilizationProgress', {
  42376. iterations: _this4.stabilizationIterations,
  42377. total: _this4.targetIterations
  42378. });
  42379. };
  42380. if (this._startStabilizing()) {
  42381. sendProgress(); // Ensure that there is at least one start event.
  42382. }
  42383. var count = 0;
  42384. while (running() && count < this.options.stabilization.updateInterval) {
  42385. this.physicsTick();
  42386. count++;
  42387. }
  42388. sendProgress();
  42389. if (running()) {
  42390. setTimeout(this._stabilizationBatch.bind(this), 0);
  42391. } else {
  42392. this._finalizeStabilization();
  42393. }
  42394. }
  42395. /**
  42396. * Wrap up the stabilization, fit and emit the events.
  42397. * @private
  42398. */
  42399. }, {
  42400. key: '_finalizeStabilization',
  42401. value: function _finalizeStabilization() {
  42402. this.body.emitter.emit('_allowRedraw');
  42403. if (this.options.stabilization.fit === true) {
  42404. this.body.emitter.emit('fit');
  42405. }
  42406. if (this.options.stabilization.onlyDynamicEdges === true) {
  42407. this._restoreFrozenNodes();
  42408. }
  42409. this.body.emitter.emit('stabilizationIterationsDone');
  42410. this.body.emitter.emit('_requestRedraw');
  42411. if (this.stabilized === true) {
  42412. this._emitStabilized();
  42413. } else {
  42414. this.startSimulation();
  42415. }
  42416. this.ready = true;
  42417. }
  42418. //--------------------------- DEBUGGING BELOW ---------------------------//
  42419. /**
  42420. * Debug function that display arrows for the forces currently active in the network.
  42421. *
  42422. * Use this when debugging only.
  42423. *
  42424. * @param {CanvasRenderingContext2D} ctx
  42425. * @private
  42426. */
  42427. }, {
  42428. key: '_drawForces',
  42429. value: function _drawForces(ctx) {
  42430. for (var i = 0; i < this.physicsBody.physicsNodeIndices.length; i++) {
  42431. var index = this.physicsBody.physicsNodeIndices[i];
  42432. var node = this.body.nodes[index];
  42433. var force = this.physicsBody.forces[index];
  42434. var factor = 20;
  42435. var colorFactor = 0.03;
  42436. var forceSize = Math.sqrt(Math.pow(force.x, 2) + Math.pow(force.x, 2));
  42437. var size = Math.min(Math.max(5, forceSize), 15);
  42438. var arrowSize = 3 * size;
  42439. var color = util.HSVToHex((180 - Math.min(1, Math.max(0, colorFactor * forceSize)) * 180) / 360, 1, 1);
  42440. var point = {
  42441. x: node.x + factor * force.x,
  42442. y: node.y + factor * force.y
  42443. };
  42444. ctx.lineWidth = size;
  42445. ctx.strokeStyle = color;
  42446. ctx.beginPath();
  42447. ctx.moveTo(node.x, node.y);
  42448. ctx.lineTo(point.x, point.y);
  42449. ctx.stroke();
  42450. var angle = Math.atan2(force.y, force.x);
  42451. ctx.fillStyle = color;
  42452. EndPoints.draw(ctx, { type: 'arrow', point: point, angle: angle, length: arrowSize });
  42453. ctx.fill();
  42454. }
  42455. }
  42456. }]);
  42457. return PhysicsEngine;
  42458. }();
  42459. exports['default'] = PhysicsEngine;
  42460. /***/ }),
  42461. /* 221 */
  42462. /***/ (function(module, exports, __webpack_require__) {
  42463. "use strict";
  42464. Object.defineProperty(exports, "__esModule", {
  42465. value: true
  42466. });
  42467. var _classCallCheck2 = __webpack_require__(0);
  42468. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  42469. var _createClass2 = __webpack_require__(1);
  42470. var _createClass3 = _interopRequireDefault(_createClass2);
  42471. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  42472. /**
  42473. * Repulsion Solver
  42474. */
  42475. var RepulsionSolver = function () {
  42476. /**
  42477. * @param {Object} body
  42478. * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
  42479. * @param {Object} options
  42480. */
  42481. function RepulsionSolver(body, physicsBody, options) {
  42482. (0, _classCallCheck3["default"])(this, RepulsionSolver);
  42483. this.body = body;
  42484. this.physicsBody = physicsBody;
  42485. this.setOptions(options);
  42486. }
  42487. /**
  42488. *
  42489. * @param {Object} options
  42490. */
  42491. (0, _createClass3["default"])(RepulsionSolver, [{
  42492. key: "setOptions",
  42493. value: function setOptions(options) {
  42494. this.options = options;
  42495. }
  42496. /**
  42497. * Calculate the forces the nodes apply on each other based on a repulsion field.
  42498. * This field is linearly approximated.
  42499. *
  42500. * @private
  42501. */
  42502. }, {
  42503. key: "solve",
  42504. value: function solve() {
  42505. var dx, dy, distance, fx, fy, repulsingForce, node1, node2;
  42506. var nodes = this.body.nodes;
  42507. var nodeIndices = this.physicsBody.physicsNodeIndices;
  42508. var forces = this.physicsBody.forces;
  42509. // repulsing forces between nodes
  42510. var nodeDistance = this.options.nodeDistance;
  42511. // approximation constants
  42512. var a = -2 / 3 / nodeDistance;
  42513. var b = 4 / 3;
  42514. // we loop from i over all but the last entree in the array
  42515. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j
  42516. for (var i = 0; i < nodeIndices.length - 1; i++) {
  42517. node1 = nodes[nodeIndices[i]];
  42518. for (var j = i + 1; j < nodeIndices.length; j++) {
  42519. node2 = nodes[nodeIndices[j]];
  42520. dx = node2.x - node1.x;
  42521. dy = node2.y - node1.y;
  42522. distance = Math.sqrt(dx * dx + dy * dy);
  42523. // same condition as BarnesHutSolver, making sure nodes are never 100% overlapping.
  42524. if (distance === 0) {
  42525. distance = 0.1 * Math.random();
  42526. dx = distance;
  42527. }
  42528. if (distance < 2 * nodeDistance) {
  42529. if (distance < 0.5 * nodeDistance) {
  42530. repulsingForce = 1.0;
  42531. } else {
  42532. repulsingForce = a * distance + b; // linear approx of 1 / (1 + Math.exp((distance / nodeDistance - 1) * steepness))
  42533. }
  42534. repulsingForce = repulsingForce / distance;
  42535. fx = dx * repulsingForce;
  42536. fy = dy * repulsingForce;
  42537. forces[node1.id].x -= fx;
  42538. forces[node1.id].y -= fy;
  42539. forces[node2.id].x += fx;
  42540. forces[node2.id].y += fy;
  42541. }
  42542. }
  42543. }
  42544. }
  42545. }]);
  42546. return RepulsionSolver;
  42547. }();
  42548. exports["default"] = RepulsionSolver;
  42549. /***/ }),
  42550. /* 222 */
  42551. /***/ (function(module, exports, __webpack_require__) {
  42552. "use strict";
  42553. Object.defineProperty(exports, "__esModule", {
  42554. value: true
  42555. });
  42556. var _classCallCheck2 = __webpack_require__(0);
  42557. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  42558. var _createClass2 = __webpack_require__(1);
  42559. var _createClass3 = _interopRequireDefault(_createClass2);
  42560. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  42561. /**
  42562. * Hierarchical Repulsion Solver
  42563. */
  42564. var HierarchicalRepulsionSolver = function () {
  42565. /**
  42566. * @param {Object} body
  42567. * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
  42568. * @param {Object} options
  42569. */
  42570. function HierarchicalRepulsionSolver(body, physicsBody, options) {
  42571. (0, _classCallCheck3["default"])(this, HierarchicalRepulsionSolver);
  42572. this.body = body;
  42573. this.physicsBody = physicsBody;
  42574. this.setOptions(options);
  42575. }
  42576. /**
  42577. *
  42578. * @param {Object} options
  42579. */
  42580. (0, _createClass3["default"])(HierarchicalRepulsionSolver, [{
  42581. key: "setOptions",
  42582. value: function setOptions(options) {
  42583. this.options = options;
  42584. }
  42585. /**
  42586. * Calculate the forces the nodes apply on each other based on a repulsion field.
  42587. * This field is linearly approximated.
  42588. *
  42589. * @private
  42590. */
  42591. }, {
  42592. key: "solve",
  42593. value: function solve() {
  42594. var dx, dy, distance, fx, fy, repulsingForce, node1, node2, i, j;
  42595. var nodes = this.body.nodes;
  42596. var nodeIndices = this.physicsBody.physicsNodeIndices;
  42597. var forces = this.physicsBody.forces;
  42598. // repulsing forces between nodes
  42599. var nodeDistance = this.options.nodeDistance;
  42600. // we loop from i over all but the last entree in the array
  42601. // j loops from i+1 to the last. This way we do not double count any of the indices, nor i === j
  42602. for (i = 0; i < nodeIndices.length - 1; i++) {
  42603. node1 = nodes[nodeIndices[i]];
  42604. for (j = i + 1; j < nodeIndices.length; j++) {
  42605. node2 = nodes[nodeIndices[j]];
  42606. // nodes only affect nodes on their level
  42607. if (node1.level === node2.level) {
  42608. dx = node2.x - node1.x;
  42609. dy = node2.y - node1.y;
  42610. distance = Math.sqrt(dx * dx + dy * dy);
  42611. var steepness = 0.05;
  42612. if (distance < nodeDistance) {
  42613. repulsingForce = -Math.pow(steepness * distance, 2) + Math.pow(steepness * nodeDistance, 2);
  42614. } else {
  42615. repulsingForce = 0;
  42616. }
  42617. // normalize force with
  42618. if (distance === 0) {
  42619. distance = 0.01;
  42620. } else {
  42621. repulsingForce = repulsingForce / distance;
  42622. }
  42623. fx = dx * repulsingForce;
  42624. fy = dy * repulsingForce;
  42625. forces[node1.id].x -= fx;
  42626. forces[node1.id].y -= fy;
  42627. forces[node2.id].x += fx;
  42628. forces[node2.id].y += fy;
  42629. }
  42630. }
  42631. }
  42632. }
  42633. }]);
  42634. return HierarchicalRepulsionSolver;
  42635. }();
  42636. exports["default"] = HierarchicalRepulsionSolver;
  42637. /***/ }),
  42638. /* 223 */
  42639. /***/ (function(module, exports, __webpack_require__) {
  42640. "use strict";
  42641. Object.defineProperty(exports, "__esModule", {
  42642. value: true
  42643. });
  42644. var _classCallCheck2 = __webpack_require__(0);
  42645. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  42646. var _createClass2 = __webpack_require__(1);
  42647. var _createClass3 = _interopRequireDefault(_createClass2);
  42648. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  42649. /**
  42650. * Spring Solver
  42651. */
  42652. var SpringSolver = function () {
  42653. /**
  42654. * @param {Object} body
  42655. * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
  42656. * @param {Object} options
  42657. */
  42658. function SpringSolver(body, physicsBody, options) {
  42659. (0, _classCallCheck3["default"])(this, SpringSolver);
  42660. this.body = body;
  42661. this.physicsBody = physicsBody;
  42662. this.setOptions(options);
  42663. }
  42664. /**
  42665. *
  42666. * @param {Object} options
  42667. */
  42668. (0, _createClass3["default"])(SpringSolver, [{
  42669. key: "setOptions",
  42670. value: function setOptions(options) {
  42671. this.options = options;
  42672. }
  42673. /**
  42674. * This function calculates the springforces on the nodes, accounting for the support nodes.
  42675. *
  42676. * @private
  42677. */
  42678. }, {
  42679. key: "solve",
  42680. value: function solve() {
  42681. var edgeLength = void 0,
  42682. edge = void 0;
  42683. var edgeIndices = this.physicsBody.physicsEdgeIndices;
  42684. var edges = this.body.edges;
  42685. var node1 = void 0,
  42686. node2 = void 0,
  42687. node3 = void 0;
  42688. // forces caused by the edges, modelled as springs
  42689. for (var i = 0; i < edgeIndices.length; i++) {
  42690. edge = edges[edgeIndices[i]];
  42691. if (edge.connected === true && edge.toId !== edge.fromId) {
  42692. // only calculate forces if nodes are in the same sector
  42693. if (this.body.nodes[edge.toId] !== undefined && this.body.nodes[edge.fromId] !== undefined) {
  42694. if (edge.edgeType.via !== undefined) {
  42695. edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length;
  42696. node1 = edge.to;
  42697. node2 = edge.edgeType.via;
  42698. node3 = edge.from;
  42699. this._calculateSpringForce(node1, node2, 0.5 * edgeLength);
  42700. this._calculateSpringForce(node2, node3, 0.5 * edgeLength);
  42701. } else {
  42702. // the * 1.5 is here so the edge looks as large as a smooth edge. It does not initially because the smooth edges use
  42703. // the support nodes which exert a repulsive force on the to and from nodes, making the edge appear larger.
  42704. edgeLength = edge.options.length === undefined ? this.options.springLength * 1.5 : edge.options.length;
  42705. this._calculateSpringForce(edge.from, edge.to, edgeLength);
  42706. }
  42707. }
  42708. }
  42709. }
  42710. }
  42711. /**
  42712. * This is the code actually performing the calculation for the function above.
  42713. *
  42714. * @param {Node} node1
  42715. * @param {Node} node2
  42716. * @param {number} edgeLength
  42717. * @private
  42718. */
  42719. }, {
  42720. key: "_calculateSpringForce",
  42721. value: function _calculateSpringForce(node1, node2, edgeLength) {
  42722. var dx = node1.x - node2.x;
  42723. var dy = node1.y - node2.y;
  42724. var distance = Math.max(Math.sqrt(dx * dx + dy * dy), 0.01);
  42725. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  42726. var springForce = this.options.springConstant * (edgeLength - distance) / distance;
  42727. var fx = dx * springForce;
  42728. var fy = dy * springForce;
  42729. // handle the case where one node is not part of the physcis
  42730. if (this.physicsBody.forces[node1.id] !== undefined) {
  42731. this.physicsBody.forces[node1.id].x += fx;
  42732. this.physicsBody.forces[node1.id].y += fy;
  42733. }
  42734. if (this.physicsBody.forces[node2.id] !== undefined) {
  42735. this.physicsBody.forces[node2.id].x -= fx;
  42736. this.physicsBody.forces[node2.id].y -= fy;
  42737. }
  42738. }
  42739. }]);
  42740. return SpringSolver;
  42741. }();
  42742. exports["default"] = SpringSolver;
  42743. /***/ }),
  42744. /* 224 */
  42745. /***/ (function(module, exports, __webpack_require__) {
  42746. "use strict";
  42747. Object.defineProperty(exports, "__esModule", {
  42748. value: true
  42749. });
  42750. var _classCallCheck2 = __webpack_require__(0);
  42751. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  42752. var _createClass2 = __webpack_require__(1);
  42753. var _createClass3 = _interopRequireDefault(_createClass2);
  42754. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  42755. /**
  42756. * Hierarchical Spring Solver
  42757. */
  42758. var HierarchicalSpringSolver = function () {
  42759. /**
  42760. * @param {Object} body
  42761. * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
  42762. * @param {Object} options
  42763. */
  42764. function HierarchicalSpringSolver(body, physicsBody, options) {
  42765. (0, _classCallCheck3["default"])(this, HierarchicalSpringSolver);
  42766. this.body = body;
  42767. this.physicsBody = physicsBody;
  42768. this.setOptions(options);
  42769. }
  42770. /**
  42771. *
  42772. * @param {Object} options
  42773. */
  42774. (0, _createClass3["default"])(HierarchicalSpringSolver, [{
  42775. key: "setOptions",
  42776. value: function setOptions(options) {
  42777. this.options = options;
  42778. }
  42779. /**
  42780. * This function calculates the springforces on the nodes, accounting for the support nodes.
  42781. *
  42782. * @private
  42783. */
  42784. }, {
  42785. key: "solve",
  42786. value: function solve() {
  42787. var edgeLength, edge;
  42788. var dx, dy, fx, fy, springForce, distance;
  42789. var edges = this.body.edges;
  42790. var factor = 0.5;
  42791. var edgeIndices = this.physicsBody.physicsEdgeIndices;
  42792. var nodeIndices = this.physicsBody.physicsNodeIndices;
  42793. var forces = this.physicsBody.forces;
  42794. // initialize the spring force counters
  42795. for (var i = 0; i < nodeIndices.length; i++) {
  42796. var nodeId = nodeIndices[i];
  42797. forces[nodeId].springFx = 0;
  42798. forces[nodeId].springFy = 0;
  42799. }
  42800. // forces caused by the edges, modelled as springs
  42801. for (var _i = 0; _i < edgeIndices.length; _i++) {
  42802. edge = edges[edgeIndices[_i]];
  42803. if (edge.connected === true) {
  42804. edgeLength = edge.options.length === undefined ? this.options.springLength : edge.options.length;
  42805. dx = edge.from.x - edge.to.x;
  42806. dy = edge.from.y - edge.to.y;
  42807. distance = Math.sqrt(dx * dx + dy * dy);
  42808. distance = distance === 0 ? 0.01 : distance;
  42809. // the 1/distance is so the fx and fy can be calculated without sine or cosine.
  42810. springForce = this.options.springConstant * (edgeLength - distance) / distance;
  42811. fx = dx * springForce;
  42812. fy = dy * springForce;
  42813. if (edge.to.level != edge.from.level) {
  42814. if (forces[edge.toId] !== undefined) {
  42815. forces[edge.toId].springFx -= fx;
  42816. forces[edge.toId].springFy -= fy;
  42817. }
  42818. if (forces[edge.fromId] !== undefined) {
  42819. forces[edge.fromId].springFx += fx;
  42820. forces[edge.fromId].springFy += fy;
  42821. }
  42822. } else {
  42823. if (forces[edge.toId] !== undefined) {
  42824. forces[edge.toId].x -= factor * fx;
  42825. forces[edge.toId].y -= factor * fy;
  42826. }
  42827. if (forces[edge.fromId] !== undefined) {
  42828. forces[edge.fromId].x += factor * fx;
  42829. forces[edge.fromId].y += factor * fy;
  42830. }
  42831. }
  42832. }
  42833. }
  42834. // normalize spring forces
  42835. springForce = 1;
  42836. var springFx, springFy;
  42837. for (var _i2 = 0; _i2 < nodeIndices.length; _i2++) {
  42838. var _nodeId = nodeIndices[_i2];
  42839. springFx = Math.min(springForce, Math.max(-springForce, forces[_nodeId].springFx));
  42840. springFy = Math.min(springForce, Math.max(-springForce, forces[_nodeId].springFy));
  42841. forces[_nodeId].x += springFx;
  42842. forces[_nodeId].y += springFy;
  42843. }
  42844. // retain energy balance
  42845. var totalFx = 0;
  42846. var totalFy = 0;
  42847. for (var _i3 = 0; _i3 < nodeIndices.length; _i3++) {
  42848. var _nodeId2 = nodeIndices[_i3];
  42849. totalFx += forces[_nodeId2].x;
  42850. totalFy += forces[_nodeId2].y;
  42851. }
  42852. var correctionFx = totalFx / nodeIndices.length;
  42853. var correctionFy = totalFy / nodeIndices.length;
  42854. for (var _i4 = 0; _i4 < nodeIndices.length; _i4++) {
  42855. var _nodeId3 = nodeIndices[_i4];
  42856. forces[_nodeId3].x -= correctionFx;
  42857. forces[_nodeId3].y -= correctionFy;
  42858. }
  42859. }
  42860. }]);
  42861. return HierarchicalSpringSolver;
  42862. }();
  42863. exports["default"] = HierarchicalSpringSolver;
  42864. /***/ }),
  42865. /* 225 */
  42866. /***/ (function(module, exports, __webpack_require__) {
  42867. "use strict";
  42868. Object.defineProperty(exports, "__esModule", {
  42869. value: true
  42870. });
  42871. var _getPrototypeOf = __webpack_require__(3);
  42872. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  42873. var _classCallCheck2 = __webpack_require__(0);
  42874. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  42875. var _createClass2 = __webpack_require__(1);
  42876. var _createClass3 = _interopRequireDefault(_createClass2);
  42877. var _possibleConstructorReturn2 = __webpack_require__(4);
  42878. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  42879. var _inherits2 = __webpack_require__(5);
  42880. var _inherits3 = _interopRequireDefault(_inherits2);
  42881. var _BarnesHutSolver2 = __webpack_require__(120);
  42882. var _BarnesHutSolver3 = _interopRequireDefault(_BarnesHutSolver2);
  42883. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  42884. /**
  42885. * @extends BarnesHutSolver
  42886. */
  42887. var ForceAtlas2BasedRepulsionSolver = function (_BarnesHutSolver) {
  42888. (0, _inherits3["default"])(ForceAtlas2BasedRepulsionSolver, _BarnesHutSolver);
  42889. /**
  42890. * @param {Object} body
  42891. * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
  42892. * @param {Object} options
  42893. */
  42894. function ForceAtlas2BasedRepulsionSolver(body, physicsBody, options) {
  42895. (0, _classCallCheck3["default"])(this, ForceAtlas2BasedRepulsionSolver);
  42896. return (0, _possibleConstructorReturn3["default"])(this, (ForceAtlas2BasedRepulsionSolver.__proto__ || (0, _getPrototypeOf2["default"])(ForceAtlas2BasedRepulsionSolver)).call(this, body, physicsBody, options));
  42897. }
  42898. /**
  42899. * Calculate the forces based on the distance.
  42900. *
  42901. * @param {number} distance
  42902. * @param {number} dx
  42903. * @param {number} dy
  42904. * @param {Node} node
  42905. * @param {Object} parentBranch
  42906. * @private
  42907. */
  42908. (0, _createClass3["default"])(ForceAtlas2BasedRepulsionSolver, [{
  42909. key: "_calculateForces",
  42910. value: function _calculateForces(distance, dx, dy, node, parentBranch) {
  42911. if (distance === 0) {
  42912. distance = 0.1 * Math.random();
  42913. dx = distance;
  42914. }
  42915. if (this.overlapAvoidanceFactor < 1 && node.shape.radius) {
  42916. distance = Math.max(0.1 + this.overlapAvoidanceFactor * node.shape.radius, distance - node.shape.radius);
  42917. }
  42918. var degree = node.edges.length + 1;
  42919. // the dividing by the distance cubed instead of squared allows us to get the fx and fy components without sines and cosines
  42920. // it is shorthand for gravityforce with distance squared and fx = dx/distance * gravityForce
  42921. var gravityForce = this.options.gravitationalConstant * parentBranch.mass * node.options.mass * degree / Math.pow(distance, 2);
  42922. var fx = dx * gravityForce;
  42923. var fy = dy * gravityForce;
  42924. this.physicsBody.forces[node.id].x += fx;
  42925. this.physicsBody.forces[node.id].y += fy;
  42926. }
  42927. }]);
  42928. return ForceAtlas2BasedRepulsionSolver;
  42929. }(_BarnesHutSolver3["default"]);
  42930. exports["default"] = ForceAtlas2BasedRepulsionSolver;
  42931. /***/ }),
  42932. /* 226 */
  42933. /***/ (function(module, exports, __webpack_require__) {
  42934. "use strict";
  42935. Object.defineProperty(exports, "__esModule", {
  42936. value: true
  42937. });
  42938. var _getPrototypeOf = __webpack_require__(3);
  42939. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  42940. var _classCallCheck2 = __webpack_require__(0);
  42941. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  42942. var _createClass2 = __webpack_require__(1);
  42943. var _createClass3 = _interopRequireDefault(_createClass2);
  42944. var _possibleConstructorReturn2 = __webpack_require__(4);
  42945. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  42946. var _inherits2 = __webpack_require__(5);
  42947. var _inherits3 = _interopRequireDefault(_inherits2);
  42948. var _CentralGravitySolver2 = __webpack_require__(121);
  42949. var _CentralGravitySolver3 = _interopRequireDefault(_CentralGravitySolver2);
  42950. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  42951. /**
  42952. * @extends CentralGravitySolver
  42953. */
  42954. var ForceAtlas2BasedCentralGravitySolver = function (_CentralGravitySolver) {
  42955. (0, _inherits3["default"])(ForceAtlas2BasedCentralGravitySolver, _CentralGravitySolver);
  42956. /**
  42957. * @param {Object} body
  42958. * @param {{physicsNodeIndices: Array, physicsEdgeIndices: Array, forces: {}, velocities: {}}} physicsBody
  42959. * @param {Object} options
  42960. */
  42961. function ForceAtlas2BasedCentralGravitySolver(body, physicsBody, options) {
  42962. (0, _classCallCheck3["default"])(this, ForceAtlas2BasedCentralGravitySolver);
  42963. return (0, _possibleConstructorReturn3["default"])(this, (ForceAtlas2BasedCentralGravitySolver.__proto__ || (0, _getPrototypeOf2["default"])(ForceAtlas2BasedCentralGravitySolver)).call(this, body, physicsBody, options));
  42964. }
  42965. /**
  42966. * Calculate the forces based on the distance.
  42967. *
  42968. * @param {number} distance
  42969. * @param {number} dx
  42970. * @param {number} dy
  42971. * @param {Object<Node.id, Node>} forces
  42972. * @param {Node} node
  42973. * @private
  42974. */
  42975. (0, _createClass3["default"])(ForceAtlas2BasedCentralGravitySolver, [{
  42976. key: "_calculateForces",
  42977. value: function _calculateForces(distance, dx, dy, forces, node) {
  42978. if (distance > 0) {
  42979. var degree = node.edges.length + 1;
  42980. var gravityForce = this.options.centralGravity * degree * node.options.mass;
  42981. forces[node.id].x = dx * gravityForce;
  42982. forces[node.id].y = dy * gravityForce;
  42983. }
  42984. }
  42985. }]);
  42986. return ForceAtlas2BasedCentralGravitySolver;
  42987. }(_CentralGravitySolver3["default"]);
  42988. exports["default"] = ForceAtlas2BasedCentralGravitySolver;
  42989. /***/ }),
  42990. /* 227 */
  42991. /***/ (function(module, exports, __webpack_require__) {
  42992. "use strict";
  42993. Object.defineProperty(exports, "__esModule", {
  42994. value: true
  42995. });
  42996. var _keys = __webpack_require__(8);
  42997. var _keys2 = _interopRequireDefault(_keys);
  42998. var _typeof2 = __webpack_require__(6);
  42999. var _typeof3 = _interopRequireDefault(_typeof2);
  43000. var _classCallCheck2 = __webpack_require__(0);
  43001. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  43002. var _createClass2 = __webpack_require__(1);
  43003. var _createClass3 = _interopRequireDefault(_createClass2);
  43004. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  43005. /* ===========================================================================
  43006. # TODO
  43007. - `edgeReplacedById` not cleaned up yet on cluster edge removal
  43008. - allowSingleNodeCluster could be a global option as well; currently needs to always
  43009. be passed to clustering methods
  43010. ----------------------------------------------
  43011. # State Model for Clustering
  43012. The total state for clustering is non-trivial. It is useful to have a model
  43013. available as to how it works. The following documents the relevant state items.
  43014. ## Network State
  43015. The following `network`-members are relevant to clustering:
  43016. - `body.nodes` - all nodes actively participating in the network
  43017. - `body.edges` - same for edges
  43018. - `body.nodeIndices` - id's of nodes that are visible at a given moment
  43019. - `body.edgeIndices` - same for edges
  43020. This includes:
  43021. - helper nodes for dragging in `manipulation`
  43022. - helper nodes for edge type `dynamic`
  43023. - cluster nodes and edges
  43024. - there may be more than this.
  43025. A node/edge may be missing in the `Indices` member if:
  43026. - it is a helper node
  43027. - the node or edge state has option `hidden` set
  43028. - It is not visible due to clustering
  43029. ## Clustering State
  43030. For the hashes, the id's of the nodes/edges are used as key.
  43031. Member `network.clustering` contains the following items:
  43032. - `clusteredNodes` - hash with values: { clusterId: <id of cluster>, node: <node instance>}
  43033. - `clusteredEdges` - hash with values: restore information for given edge
  43034. Due to nesting of clusters, these members can contain cluster nodes and edges as well.
  43035. The important thing to note here, is that the clustered nodes and edges also
  43036. appear in the members of the cluster nodes. For data update, it is therefore
  43037. important to scan these lists as well as the cluster nodes.
  43038. ### Cluster Node
  43039. A cluster node has the following extra fields:
  43040. - `isCluster : true` - indication that this is a cluster node
  43041. - `containedNodes` - hash of nodes contained in this cluster
  43042. - `containedEdges` - same for edges
  43043. - `edges` - array of cluster edges for this node
  43044. **NOTE:**
  43045. - `containedEdges` can also contain edges which are not clustered; e.g. an edge
  43046. connecting two nodes in the same cluster.
  43047. ### Cluster Edge
  43048. These are the items in the `edges` member of a clustered node. They have the
  43049. following relevant members:
  43050. - 'clusteringEdgeReplacingIds` - array of id's of edges replaced by this edge
  43051. Note that it's possible to nest clusters, so that `clusteringEdgeReplacingIds`
  43052. can contain edge id's of other clusters.
  43053. ### Clustered Edge
  43054. This is any edge contained by a cluster edge. It gets the following additional
  43055. member:
  43056. - `edgeReplacedById` - id of the cluster edge in which current edge is clustered
  43057. =========================================================================== */
  43058. var util = __webpack_require__(2);
  43059. var NetworkUtil = __webpack_require__(76)['default'];
  43060. var Cluster = __webpack_require__(228)['default'];
  43061. var Edge = __webpack_require__(74)['default']; // Only needed for check on type!
  43062. var Node = __webpack_require__(47)['default']; // Only needed for check on type!
  43063. /**
  43064. * The clustering engine
  43065. */
  43066. var ClusterEngine = function () {
  43067. /**
  43068. * @param {Object} body
  43069. */
  43070. function ClusterEngine(body) {
  43071. var _this = this;
  43072. (0, _classCallCheck3['default'])(this, ClusterEngine);
  43073. this.body = body;
  43074. this.clusteredNodes = {}; // key: node id, value: { clusterId: <id of cluster>, node: <node instance>}
  43075. this.clusteredEdges = {}; // key: edge id, value: restore information for given edge
  43076. this.options = {};
  43077. this.defaultOptions = {};
  43078. util.extend(this.options, this.defaultOptions);
  43079. this.body.emitter.on('_resetData', function () {
  43080. _this.clusteredNodes = {};_this.clusteredEdges = {};
  43081. });
  43082. }
  43083. /**
  43084. *
  43085. * @param {number} hubsize
  43086. * @param {Object} options
  43087. */
  43088. (0, _createClass3['default'])(ClusterEngine, [{
  43089. key: 'clusterByHubsize',
  43090. value: function clusterByHubsize(hubsize, options) {
  43091. if (hubsize === undefined) {
  43092. hubsize = this._getHubSize();
  43093. } else if ((typeof hubsize === 'undefined' ? 'undefined' : (0, _typeof3['default'])(hubsize)) === "object") {
  43094. options = this._checkOptions(hubsize);
  43095. hubsize = this._getHubSize();
  43096. }
  43097. var nodesToCluster = [];
  43098. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  43099. var node = this.body.nodes[this.body.nodeIndices[i]];
  43100. if (node.edges.length >= hubsize) {
  43101. nodesToCluster.push(node.id);
  43102. }
  43103. }
  43104. for (var _i = 0; _i < nodesToCluster.length; _i++) {
  43105. this.clusterByConnection(nodesToCluster[_i], options, true);
  43106. }
  43107. this.body.emitter.emit('_dataChanged');
  43108. }
  43109. /**
  43110. * loop over all nodes, check if they adhere to the condition and cluster if needed.
  43111. * @param {Object} options
  43112. * @param {boolean} [refreshData=true]
  43113. */
  43114. }, {
  43115. key: 'cluster',
  43116. value: function cluster() {
  43117. var _this2 = this;
  43118. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  43119. var refreshData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  43120. if (options.joinCondition === undefined) {
  43121. throw new Error("Cannot call clusterByNodeData without a joinCondition function in the options.");
  43122. }
  43123. // check if the options object is fine, append if needed
  43124. options = this._checkOptions(options);
  43125. var childNodesObj = {};
  43126. var childEdgesObj = {};
  43127. // collect the nodes that will be in the cluster
  43128. util.forEach(this.body.nodes, function (node, nodeId) {
  43129. var clonedOptions = NetworkUtil.cloneOptions(node);
  43130. if (options.joinCondition(clonedOptions) === true) {
  43131. childNodesObj[nodeId] = node;
  43132. // collect the edges that will be in the cluster
  43133. util.forEach(node.edges, function (edge) {
  43134. if (_this2.clusteredEdges[edge.id] === undefined) {
  43135. childEdgesObj[edge.id] = edge;
  43136. }
  43137. });
  43138. }
  43139. });
  43140. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  43141. }
  43142. /**
  43143. * Cluster all nodes in the network that have only X edges
  43144. * @param {number} edgeCount
  43145. * @param {Object} options
  43146. * @param {boolean} [refreshData=true]
  43147. */
  43148. }, {
  43149. key: 'clusterByEdgeCount',
  43150. value: function clusterByEdgeCount(edgeCount, options) {
  43151. var _this3 = this;
  43152. var refreshData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  43153. options = this._checkOptions(options);
  43154. var clusters = [];
  43155. var usedNodes = {};
  43156. var edge = void 0,
  43157. edges = void 0,
  43158. relevantEdgeCount = void 0;
  43159. // collect the nodes that will be in the cluster
  43160. var _loop = function _loop(i) {
  43161. var childNodesObj = {};
  43162. var childEdgesObj = {};
  43163. var nodeId = _this3.body.nodeIndices[i];
  43164. var node = _this3.body.nodes[nodeId];
  43165. // if this node is already used in another cluster this session, we do not have to re-evaluate it.
  43166. if (usedNodes[nodeId] === undefined) {
  43167. relevantEdgeCount = 0;
  43168. edges = [];
  43169. for (var j = 0; j < node.edges.length; j++) {
  43170. edge = node.edges[j];
  43171. if (_this3.clusteredEdges[edge.id] === undefined) {
  43172. if (edge.toId !== edge.fromId) {
  43173. relevantEdgeCount++;
  43174. }
  43175. edges.push(edge);
  43176. }
  43177. }
  43178. // this node qualifies, we collect its neighbours to start the clustering process.
  43179. if (relevantEdgeCount === edgeCount) {
  43180. checkJoinCondition = function checkJoinCondition(node) {
  43181. if (options.joinCondition === undefined || options.joinCondition === null) {
  43182. return true;
  43183. }
  43184. var clonedOptions = NetworkUtil.cloneOptions(node);
  43185. return options.joinCondition(clonedOptions);
  43186. };
  43187. var gatheringSuccessful = true;
  43188. for (var _j = 0; _j < edges.length; _j++) {
  43189. edge = edges[_j];
  43190. var childNodeId = _this3._getConnectedId(edge, nodeId);
  43191. // add the nodes to the list by the join condition.
  43192. if (checkJoinCondition(node)) {
  43193. childEdgesObj[edge.id] = edge;
  43194. childNodesObj[nodeId] = node;
  43195. childNodesObj[childNodeId] = _this3.body.nodes[childNodeId];
  43196. usedNodes[nodeId] = true;
  43197. } else {
  43198. // this node does not qualify after all.
  43199. gatheringSuccessful = false;
  43200. break;
  43201. }
  43202. }
  43203. // add to the cluster queue
  43204. if ((0, _keys2['default'])(childNodesObj).length > 0 && (0, _keys2['default'])(childEdgesObj).length > 0 && gatheringSuccessful === true) {
  43205. /**
  43206. * Search for cluster data that contains any of the node id's
  43207. * @returns {Boolean} true if no joinCondition, otherwise return value of joinCondition
  43208. */
  43209. findClusterData = function findClusterData() {
  43210. for (var n = 0; n < clusters.length; ++n) {
  43211. // Search for a cluster containing any of the node id's
  43212. for (var m in childNodesObj) {
  43213. if (clusters[n].nodes[m] !== undefined) {
  43214. return clusters[n];
  43215. }
  43216. }
  43217. }
  43218. return undefined;
  43219. };
  43220. // If any of the found nodes is part of a cluster found in this method,
  43221. // add the current values to that cluster
  43222. foundCluster = findClusterData();
  43223. if (foundCluster !== undefined) {
  43224. // Add nodes to found cluster if not present
  43225. for (var m in childNodesObj) {
  43226. if (foundCluster.nodes[m] === undefined) {
  43227. foundCluster.nodes[m] = childNodesObj[m];
  43228. }
  43229. }
  43230. // Add edges to found cluster, if not present
  43231. for (var _m in childEdgesObj) {
  43232. if (foundCluster.edges[_m] === undefined) {
  43233. foundCluster.edges[_m] = childEdgesObj[_m];
  43234. }
  43235. }
  43236. } else {
  43237. // Create a new cluster group
  43238. clusters.push({ nodes: childNodesObj, edges: childEdgesObj });
  43239. }
  43240. }
  43241. }
  43242. }
  43243. };
  43244. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  43245. var checkJoinCondition;
  43246. var findClusterData;
  43247. var foundCluster;
  43248. _loop(i);
  43249. }
  43250. for (var i = 0; i < clusters.length; i++) {
  43251. this._cluster(clusters[i].nodes, clusters[i].edges, options, false);
  43252. }
  43253. if (refreshData === true) {
  43254. this.body.emitter.emit('_dataChanged');
  43255. }
  43256. }
  43257. /**
  43258. * Cluster all nodes in the network that have only 1 edge
  43259. * @param {Object} options
  43260. * @param {boolean} [refreshData=true]
  43261. */
  43262. }, {
  43263. key: 'clusterOutliers',
  43264. value: function clusterOutliers(options) {
  43265. var refreshData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  43266. this.clusterByEdgeCount(1, options, refreshData);
  43267. }
  43268. /**
  43269. * Cluster all nodes in the network that have only 2 edge
  43270. * @param {Object} options
  43271. * @param {boolean} [refreshData=true]
  43272. */
  43273. }, {
  43274. key: 'clusterBridges',
  43275. value: function clusterBridges(options) {
  43276. var refreshData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  43277. this.clusterByEdgeCount(2, options, refreshData);
  43278. }
  43279. /**
  43280. * suck all connected nodes of a node into the node.
  43281. * @param {Node.id} nodeId
  43282. * @param {Object} options
  43283. * @param {boolean} [refreshData=true]
  43284. */
  43285. }, {
  43286. key: 'clusterByConnection',
  43287. value: function clusterByConnection(nodeId, options) {
  43288. var refreshData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  43289. // kill conditions
  43290. if (nodeId === undefined) {
  43291. throw new Error("No nodeId supplied to clusterByConnection!");
  43292. }
  43293. if (this.body.nodes[nodeId] === undefined) {
  43294. throw new Error("The nodeId given to clusterByConnection does not exist!");
  43295. }
  43296. var node = this.body.nodes[nodeId];
  43297. options = this._checkOptions(options, node);
  43298. if (options.clusterNodeProperties.x === undefined) {
  43299. options.clusterNodeProperties.x = node.x;
  43300. }
  43301. if (options.clusterNodeProperties.y === undefined) {
  43302. options.clusterNodeProperties.y = node.y;
  43303. }
  43304. if (options.clusterNodeProperties.fixed === undefined) {
  43305. options.clusterNodeProperties.fixed = {};
  43306. options.clusterNodeProperties.fixed.x = node.options.fixed.x;
  43307. options.clusterNodeProperties.fixed.y = node.options.fixed.y;
  43308. }
  43309. var childNodesObj = {};
  43310. var childEdgesObj = {};
  43311. var parentNodeId = node.id;
  43312. var parentClonedOptions = NetworkUtil.cloneOptions(node);
  43313. childNodesObj[parentNodeId] = node;
  43314. // collect the nodes that will be in the cluster
  43315. for (var i = 0; i < node.edges.length; i++) {
  43316. var edge = node.edges[i];
  43317. if (this.clusteredEdges[edge.id] === undefined) {
  43318. var childNodeId = this._getConnectedId(edge, parentNodeId);
  43319. // if the child node is not in a cluster
  43320. if (this.clusteredNodes[childNodeId] === undefined) {
  43321. if (childNodeId !== parentNodeId) {
  43322. if (options.joinCondition === undefined) {
  43323. childEdgesObj[edge.id] = edge;
  43324. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  43325. } else {
  43326. // clone the options and insert some additional parameters that could be interesting.
  43327. var childClonedOptions = NetworkUtil.cloneOptions(this.body.nodes[childNodeId]);
  43328. if (options.joinCondition(parentClonedOptions, childClonedOptions) === true) {
  43329. childEdgesObj[edge.id] = edge;
  43330. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  43331. }
  43332. }
  43333. } else {
  43334. // swallow the edge if it is self-referencing.
  43335. childEdgesObj[edge.id] = edge;
  43336. }
  43337. }
  43338. }
  43339. }
  43340. var childNodeIDs = (0, _keys2['default'])(childNodesObj).map(function (childNode) {
  43341. return childNodesObj[childNode].id;
  43342. });
  43343. for (childNode in childNodesObj) {
  43344. if (!childNodesObj.hasOwnProperty(childNode)) continue;
  43345. var childNode = childNodesObj[childNode];
  43346. for (var y = 0; y < childNode.edges.length; y++) {
  43347. var childEdge = childNode.edges[y];
  43348. if (childNodeIDs.indexOf(this._getConnectedId(childEdge, childNode.id)) > -1) {
  43349. childEdgesObj[childEdge.id] = childEdge;
  43350. }
  43351. }
  43352. }
  43353. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  43354. }
  43355. /**
  43356. * This function creates the edges that will be attached to the cluster
  43357. * It looks for edges that are connected to the nodes from the "outside' of the cluster.
  43358. *
  43359. * @param {{Node.id: vis.Node}} childNodesObj
  43360. * @param {{vis.Edge.id: vis.Edge}} childEdgesObj
  43361. * @param {Object} clusterNodeProperties
  43362. * @param {Object} clusterEdgeProperties
  43363. * @private
  43364. */
  43365. }, {
  43366. key: '_createClusterEdges',
  43367. value: function _createClusterEdges(childNodesObj, childEdgesObj, clusterNodeProperties, clusterEdgeProperties) {
  43368. var edge = void 0,
  43369. childNodeId = void 0,
  43370. childNode = void 0,
  43371. toId = void 0,
  43372. fromId = void 0,
  43373. otherNodeId = void 0;
  43374. // loop over all child nodes and their edges to find edges going out of the cluster
  43375. // these edges will be replaced by clusterEdges.
  43376. var childKeys = (0, _keys2['default'])(childNodesObj);
  43377. var createEdges = [];
  43378. for (var i = 0; i < childKeys.length; i++) {
  43379. childNodeId = childKeys[i];
  43380. childNode = childNodesObj[childNodeId];
  43381. // construct new edges from the cluster to others
  43382. for (var j = 0; j < childNode.edges.length; j++) {
  43383. edge = childNode.edges[j];
  43384. // we only handle edges that are visible to the system, not the disabled ones from the clustering process.
  43385. if (this.clusteredEdges[edge.id] === undefined) {
  43386. // self-referencing edges will be added to the "hidden" list
  43387. if (edge.toId == edge.fromId) {
  43388. childEdgesObj[edge.id] = edge;
  43389. } else {
  43390. // set up the from and to.
  43391. if (edge.toId == childNodeId) {
  43392. // this is a double equals because ints and strings can be interchanged here.
  43393. toId = clusterNodeProperties.id;
  43394. fromId = edge.fromId;
  43395. otherNodeId = fromId;
  43396. } else {
  43397. toId = edge.toId;
  43398. fromId = clusterNodeProperties.id;
  43399. otherNodeId = toId;
  43400. }
  43401. }
  43402. // Only edges from the cluster outwards are being replaced.
  43403. if (childNodesObj[otherNodeId] === undefined) {
  43404. createEdges.push({ edge: edge, fromId: fromId, toId: toId });
  43405. }
  43406. }
  43407. }
  43408. }
  43409. //
  43410. // Here we actually create the replacement edges.
  43411. //
  43412. // We could not do this in the loop above as the creation process
  43413. // would add an edge to the edges array we are iterating over.
  43414. //
  43415. // NOTE: a clustered edge can have multiple base edges!
  43416. //
  43417. var newEdges = [];
  43418. /**
  43419. * Find a cluster edge which matches the given created edge.
  43420. * @param {vis.Edge} createdEdge
  43421. * @returns {vis.Edge}
  43422. */
  43423. var getNewEdge = function getNewEdge(createdEdge) {
  43424. for (var _j2 = 0; _j2 < newEdges.length; _j2++) {
  43425. var newEdge = newEdges[_j2];
  43426. // We replace both to and from edges with a single cluster edge
  43427. var matchToDirection = createdEdge.fromId === newEdge.fromId && createdEdge.toId === newEdge.toId;
  43428. var matchFromDirection = createdEdge.fromId === newEdge.toId && createdEdge.toId === newEdge.fromId;
  43429. if (matchToDirection || matchFromDirection) {
  43430. return newEdge;
  43431. }
  43432. }
  43433. return null;
  43434. };
  43435. for (var _j3 = 0; _j3 < createEdges.length; _j3++) {
  43436. var createdEdge = createEdges[_j3];
  43437. var _edge = createdEdge.edge;
  43438. var newEdge = getNewEdge(createdEdge);
  43439. if (newEdge === null) {
  43440. // Create a clustered edge for this connection
  43441. newEdge = this._createClusteredEdge(createdEdge.fromId, createdEdge.toId, _edge, clusterEdgeProperties);
  43442. newEdges.push(newEdge);
  43443. } else {
  43444. newEdge.clusteringEdgeReplacingIds.push(_edge.id);
  43445. }
  43446. // also reference the new edge in the old edge
  43447. this.body.edges[_edge.id].edgeReplacedById = newEdge.id;
  43448. // hide the replaced edge
  43449. this._backupEdgeOptions(_edge);
  43450. _edge.setOptions({ physics: false });
  43451. }
  43452. }
  43453. /**
  43454. * This function checks the options that can be supplied to the different cluster functions
  43455. * for certain fields and inserts defaults if needed
  43456. * @param {Object} options
  43457. * @returns {*}
  43458. * @private
  43459. */
  43460. }, {
  43461. key: '_checkOptions',
  43462. value: function _checkOptions() {
  43463. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  43464. if (options.clusterEdgeProperties === undefined) {
  43465. options.clusterEdgeProperties = {};
  43466. }
  43467. if (options.clusterNodeProperties === undefined) {
  43468. options.clusterNodeProperties = {};
  43469. }
  43470. return options;
  43471. }
  43472. /**
  43473. *
  43474. * @param {Object} childNodesObj | object with node objects, id as keys, same as childNodes except it also contains a source node
  43475. * @param {Object} childEdgesObj | object with edge objects, id as keys
  43476. * @param {Array} options | object with {clusterNodeProperties, clusterEdgeProperties, processProperties}
  43477. * @param {boolean} refreshData | when true, do not wrap up
  43478. * @private
  43479. */
  43480. }, {
  43481. key: '_cluster',
  43482. value: function _cluster(childNodesObj, childEdgesObj, options) {
  43483. var refreshData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  43484. // Remove nodes which are already clustered
  43485. var tmpNodesToRemove = [];
  43486. for (var _nodeId in childNodesObj) {
  43487. if (childNodesObj.hasOwnProperty(_nodeId)) {
  43488. if (this.clusteredNodes[_nodeId] !== undefined) {
  43489. tmpNodesToRemove.push(_nodeId);
  43490. }
  43491. }
  43492. }
  43493. for (var n = 0; n < tmpNodesToRemove.length; ++n) {
  43494. delete childNodesObj[tmpNodesToRemove[n]];
  43495. }
  43496. // kill condition: no nodes don't bother
  43497. if ((0, _keys2['default'])(childNodesObj).length == 0) {
  43498. return;
  43499. }
  43500. // allow clusters of 1 if options allow
  43501. if ((0, _keys2['default'])(childNodesObj).length == 1 && options.clusterNodeProperties.allowSingleNodeCluster != true) {
  43502. return;
  43503. }
  43504. var clusterNodeProperties = util.deepExtend({}, options.clusterNodeProperties);
  43505. // construct the clusterNodeProperties
  43506. if (options.processProperties !== undefined) {
  43507. // get the childNode options
  43508. var childNodesOptions = [];
  43509. for (var _nodeId2 in childNodesObj) {
  43510. if (childNodesObj.hasOwnProperty(_nodeId2)) {
  43511. var clonedOptions = NetworkUtil.cloneOptions(childNodesObj[_nodeId2]);
  43512. childNodesOptions.push(clonedOptions);
  43513. }
  43514. }
  43515. // get cluster properties based on childNodes
  43516. var childEdgesOptions = [];
  43517. for (var edgeId in childEdgesObj) {
  43518. if (childEdgesObj.hasOwnProperty(edgeId)) {
  43519. // these cluster edges will be removed on creation of the cluster.
  43520. if (edgeId.substr(0, 12) !== "clusterEdge:") {
  43521. var _clonedOptions = NetworkUtil.cloneOptions(childEdgesObj[edgeId], 'edge');
  43522. childEdgesOptions.push(_clonedOptions);
  43523. }
  43524. }
  43525. }
  43526. clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions);
  43527. if (!clusterNodeProperties) {
  43528. throw new Error("The processProperties function does not return properties!");
  43529. }
  43530. }
  43531. // check if we have an unique id;
  43532. if (clusterNodeProperties.id === undefined) {
  43533. clusterNodeProperties.id = 'cluster:' + util.randomUUID();
  43534. }
  43535. var clusterId = clusterNodeProperties.id;
  43536. if (clusterNodeProperties.label === undefined) {
  43537. clusterNodeProperties.label = 'cluster';
  43538. }
  43539. // give the clusterNode a position if it does not have one.
  43540. var pos = undefined;
  43541. if (clusterNodeProperties.x === undefined) {
  43542. pos = this._getClusterPosition(childNodesObj);
  43543. clusterNodeProperties.x = pos.x;
  43544. }
  43545. if (clusterNodeProperties.y === undefined) {
  43546. if (pos === undefined) {
  43547. pos = this._getClusterPosition(childNodesObj);
  43548. }
  43549. clusterNodeProperties.y = pos.y;
  43550. }
  43551. // force the ID to remain the same
  43552. clusterNodeProperties.id = clusterId;
  43553. // create the cluster Node
  43554. // Note that allowSingleNodeCluster, if present, is stored in the options as well
  43555. var clusterNode = this.body.functions.createNode(clusterNodeProperties, Cluster);
  43556. clusterNode.containedNodes = childNodesObj;
  43557. clusterNode.containedEdges = childEdgesObj;
  43558. // cache a copy from the cluster edge properties if we have to reconnect others later on
  43559. clusterNode.clusterEdgeProperties = options.clusterEdgeProperties;
  43560. // finally put the cluster node into global
  43561. this.body.nodes[clusterNodeProperties.id] = clusterNode;
  43562. this._clusterEdges(childNodesObj, childEdgesObj, clusterNodeProperties, options.clusterEdgeProperties);
  43563. // set ID to undefined so no duplicates arise
  43564. clusterNodeProperties.id = undefined;
  43565. // wrap up
  43566. if (refreshData === true) {
  43567. this.body.emitter.emit('_dataChanged');
  43568. }
  43569. }
  43570. /**
  43571. *
  43572. * @param {Edge} edge
  43573. * @private
  43574. */
  43575. }, {
  43576. key: '_backupEdgeOptions',
  43577. value: function _backupEdgeOptions(edge) {
  43578. if (this.clusteredEdges[edge.id] === undefined) {
  43579. this.clusteredEdges[edge.id] = { physics: edge.options.physics };
  43580. }
  43581. }
  43582. /**
  43583. *
  43584. * @param {Edge} edge
  43585. * @private
  43586. */
  43587. }, {
  43588. key: '_restoreEdge',
  43589. value: function _restoreEdge(edge) {
  43590. var originalOptions = this.clusteredEdges[edge.id];
  43591. if (originalOptions !== undefined) {
  43592. edge.setOptions({ physics: originalOptions.physics });
  43593. delete this.clusteredEdges[edge.id];
  43594. }
  43595. }
  43596. /**
  43597. * Check if a node is a cluster.
  43598. * @param {Node.id} nodeId
  43599. * @returns {*}
  43600. */
  43601. }, {
  43602. key: 'isCluster',
  43603. value: function isCluster(nodeId) {
  43604. if (this.body.nodes[nodeId] !== undefined) {
  43605. return this.body.nodes[nodeId].isCluster === true;
  43606. } else {
  43607. console.log("Node does not exist.");
  43608. return false;
  43609. }
  43610. }
  43611. /**
  43612. * get the position of the cluster node based on what's inside
  43613. * @param {object} childNodesObj | object with node objects, id as keys
  43614. * @returns {{x: number, y: number}}
  43615. * @private
  43616. */
  43617. }, {
  43618. key: '_getClusterPosition',
  43619. value: function _getClusterPosition(childNodesObj) {
  43620. var childKeys = (0, _keys2['default'])(childNodesObj);
  43621. var minX = childNodesObj[childKeys[0]].x;
  43622. var maxX = childNodesObj[childKeys[0]].x;
  43623. var minY = childNodesObj[childKeys[0]].y;
  43624. var maxY = childNodesObj[childKeys[0]].y;
  43625. var node = void 0;
  43626. for (var i = 1; i < childKeys.length; i++) {
  43627. node = childNodesObj[childKeys[i]];
  43628. minX = node.x < minX ? node.x : minX;
  43629. maxX = node.x > maxX ? node.x : maxX;
  43630. minY = node.y < minY ? node.y : minY;
  43631. maxY = node.y > maxY ? node.y : maxY;
  43632. }
  43633. return { x: 0.5 * (minX + maxX), y: 0.5 * (minY + maxY) };
  43634. }
  43635. /**
  43636. * Open a cluster by calling this function.
  43637. * @param {vis.Edge.id} clusterNodeId | the ID of the cluster node
  43638. * @param {Object} options
  43639. * @param {boolean} refreshData | wrap up afterwards if not true
  43640. */
  43641. }, {
  43642. key: 'openCluster',
  43643. value: function openCluster(clusterNodeId, options) {
  43644. var refreshData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  43645. // kill conditions
  43646. if (clusterNodeId === undefined) {
  43647. throw new Error("No clusterNodeId supplied to openCluster.");
  43648. }
  43649. var clusterNode = this.body.nodes[clusterNodeId];
  43650. if (clusterNode === undefined) {
  43651. throw new Error("The clusterNodeId supplied to openCluster does not exist.");
  43652. }
  43653. if (clusterNode.isCluster !== true || clusterNode.containedNodes === undefined || clusterNode.containedEdges === undefined) {
  43654. throw new Error("The node:" + clusterNodeId + " is not a valid cluster.");
  43655. }
  43656. // Check if current cluster is clustered itself
  43657. var stack = this.findNode(clusterNodeId);
  43658. var parentIndex = stack.indexOf(clusterNodeId) - 1;
  43659. if (parentIndex >= 0) {
  43660. // Current cluster is clustered; transfer contained nodes and edges to parent
  43661. var parentClusterNodeId = stack[parentIndex];
  43662. var parentClusterNode = this.body.nodes[parentClusterNodeId];
  43663. // clustering.clusteredNodes and clustering.clusteredEdges remain unchanged
  43664. parentClusterNode._openChildCluster(clusterNodeId);
  43665. // All components of child cluster node have been transferred. It can die now.
  43666. delete this.body.nodes[clusterNodeId];
  43667. if (refreshData === true) {
  43668. this.body.emitter.emit('_dataChanged');
  43669. }
  43670. return;
  43671. }
  43672. // main body
  43673. var containedNodes = clusterNode.containedNodes;
  43674. var containedEdges = clusterNode.containedEdges;
  43675. // allow the user to position the nodes after release.
  43676. if (options !== undefined && options.releaseFunction !== undefined && typeof options.releaseFunction === 'function') {
  43677. var positions = {};
  43678. var clusterPosition = { x: clusterNode.x, y: clusterNode.y };
  43679. for (var _nodeId3 in containedNodes) {
  43680. if (containedNodes.hasOwnProperty(_nodeId3)) {
  43681. var containedNode = this.body.nodes[_nodeId3];
  43682. positions[_nodeId3] = { x: containedNode.x, y: containedNode.y };
  43683. }
  43684. }
  43685. var newPositions = options.releaseFunction(clusterPosition, positions);
  43686. for (var _nodeId4 in containedNodes) {
  43687. if (containedNodes.hasOwnProperty(_nodeId4)) {
  43688. var _containedNode = this.body.nodes[_nodeId4];
  43689. if (newPositions[_nodeId4] !== undefined) {
  43690. _containedNode.x = newPositions[_nodeId4].x === undefined ? clusterNode.x : newPositions[_nodeId4].x;
  43691. _containedNode.y = newPositions[_nodeId4].y === undefined ? clusterNode.y : newPositions[_nodeId4].y;
  43692. }
  43693. }
  43694. }
  43695. } else {
  43696. // copy the position from the cluster
  43697. util.forEach(containedNodes, function (containedNode) {
  43698. // inherit position
  43699. if (containedNode.options.fixed.x === false) {
  43700. containedNode.x = clusterNode.x;
  43701. }
  43702. if (containedNode.options.fixed.y === false) {
  43703. containedNode.y = clusterNode.y;
  43704. }
  43705. });
  43706. }
  43707. // release nodes
  43708. for (var _nodeId5 in containedNodes) {
  43709. if (containedNodes.hasOwnProperty(_nodeId5)) {
  43710. var _containedNode2 = this.body.nodes[_nodeId5];
  43711. // inherit speed
  43712. _containedNode2.vx = clusterNode.vx;
  43713. _containedNode2.vy = clusterNode.vy;
  43714. _containedNode2.setOptions({ physics: true });
  43715. delete this.clusteredNodes[_nodeId5];
  43716. }
  43717. }
  43718. // copy the clusterNode edges because we cannot iterate over an object that we add or remove from.
  43719. var edgesToBeDeleted = [];
  43720. for (var i = 0; i < clusterNode.edges.length; i++) {
  43721. edgesToBeDeleted.push(clusterNode.edges[i]);
  43722. }
  43723. // actually handling the deleting.
  43724. for (var _i2 = 0; _i2 < edgesToBeDeleted.length; _i2++) {
  43725. var edge = edgesToBeDeleted[_i2];
  43726. var otherNodeId = this._getConnectedId(edge, clusterNodeId);
  43727. var otherNode = this.clusteredNodes[otherNodeId];
  43728. for (var j = 0; j < edge.clusteringEdgeReplacingIds.length; j++) {
  43729. var transferId = edge.clusteringEdgeReplacingIds[j];
  43730. var transferEdge = this.body.edges[transferId];
  43731. if (transferEdge === undefined) continue;
  43732. // if the other node is in another cluster, we transfer ownership of this edge to the other cluster
  43733. if (otherNode !== undefined) {
  43734. // transfer ownership:
  43735. var otherCluster = this.body.nodes[otherNode.clusterId];
  43736. otherCluster.containedEdges[transferEdge.id] = transferEdge;
  43737. // delete local reference
  43738. delete containedEdges[transferEdge.id];
  43739. // get to and from
  43740. var fromId = transferEdge.fromId;
  43741. var toId = transferEdge.toId;
  43742. if (transferEdge.toId == otherNodeId) {
  43743. toId = otherNode.clusterId;
  43744. } else {
  43745. fromId = otherNode.clusterId;
  43746. }
  43747. // create new cluster edge from the otherCluster
  43748. this._createClusteredEdge(fromId, toId, transferEdge, otherCluster.clusterEdgeProperties, { hidden: false, physics: true });
  43749. } else {
  43750. this._restoreEdge(transferEdge);
  43751. }
  43752. }
  43753. edge.remove();
  43754. }
  43755. // handle the releasing of the edges
  43756. for (var edgeId in containedEdges) {
  43757. if (containedEdges.hasOwnProperty(edgeId)) {
  43758. this._restoreEdge(containedEdges[edgeId]);
  43759. }
  43760. }
  43761. // remove clusterNode
  43762. delete this.body.nodes[clusterNodeId];
  43763. if (refreshData === true) {
  43764. this.body.emitter.emit('_dataChanged');
  43765. }
  43766. }
  43767. /**
  43768. *
  43769. * @param {Cluster.id} clusterId
  43770. * @returns {Array.<Node.id>}
  43771. */
  43772. }, {
  43773. key: 'getNodesInCluster',
  43774. value: function getNodesInCluster(clusterId) {
  43775. var nodesArray = [];
  43776. if (this.isCluster(clusterId) === true) {
  43777. var containedNodes = this.body.nodes[clusterId].containedNodes;
  43778. for (var _nodeId6 in containedNodes) {
  43779. if (containedNodes.hasOwnProperty(_nodeId6)) {
  43780. nodesArray.push(this.body.nodes[_nodeId6].id);
  43781. }
  43782. }
  43783. }
  43784. return nodesArray;
  43785. }
  43786. /**
  43787. * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node
  43788. *
  43789. * If a node can't be found in the chain, return an empty array.
  43790. *
  43791. * @param {string|number} nodeId
  43792. * @returns {Array}
  43793. */
  43794. }, {
  43795. key: 'findNode',
  43796. value: function findNode(nodeId) {
  43797. var stack = [];
  43798. var max = 100;
  43799. var counter = 0;
  43800. var node = void 0;
  43801. while (this.clusteredNodes[nodeId] !== undefined && counter < max) {
  43802. node = this.body.nodes[nodeId];
  43803. if (node === undefined) return [];
  43804. stack.push(node.id);
  43805. nodeId = this.clusteredNodes[nodeId].clusterId;
  43806. counter++;
  43807. }
  43808. node = this.body.nodes[nodeId];
  43809. if (node === undefined) return [];
  43810. stack.push(node.id);
  43811. stack.reverse();
  43812. return stack;
  43813. }
  43814. /**
  43815. * Using a clustered nodeId, update with the new options
  43816. * @param {vis.Edge.id} clusteredNodeId
  43817. * @param {object} newOptions
  43818. */
  43819. }, {
  43820. key: 'updateClusteredNode',
  43821. value: function updateClusteredNode(clusteredNodeId, newOptions) {
  43822. if (clusteredNodeId === undefined) {
  43823. throw new Error("No clusteredNodeId supplied to updateClusteredNode.");
  43824. }
  43825. if (newOptions === undefined) {
  43826. throw new Error("No newOptions supplied to updateClusteredNode.");
  43827. }
  43828. if (this.body.nodes[clusteredNodeId] === undefined) {
  43829. throw new Error("The clusteredNodeId supplied to updateClusteredNode does not exist.");
  43830. }
  43831. this.body.nodes[clusteredNodeId].setOptions(newOptions);
  43832. this.body.emitter.emit('_dataChanged');
  43833. }
  43834. /**
  43835. * Using a base edgeId, update all related clustered edges with the new options
  43836. * @param {vis.Edge.id} startEdgeId
  43837. * @param {object} newOptions
  43838. */
  43839. }, {
  43840. key: 'updateEdge',
  43841. value: function updateEdge(startEdgeId, newOptions) {
  43842. if (startEdgeId === undefined) {
  43843. throw new Error("No startEdgeId supplied to updateEdge.");
  43844. }
  43845. if (newOptions === undefined) {
  43846. throw new Error("No newOptions supplied to updateEdge.");
  43847. }
  43848. if (this.body.edges[startEdgeId] === undefined) {
  43849. throw new Error("The startEdgeId supplied to updateEdge does not exist.");
  43850. }
  43851. var allEdgeIds = this.getClusteredEdges(startEdgeId);
  43852. for (var i = 0; i < allEdgeIds.length; i++) {
  43853. var edge = this.body.edges[allEdgeIds[i]];
  43854. edge.setOptions(newOptions);
  43855. }
  43856. this.body.emitter.emit('_dataChanged');
  43857. }
  43858. /**
  43859. * Get a stack of clusterEdgeId's (+base edgeid) that a base edge is the same as. cluster edge C -> cluster edge B -> cluster edge A -> base edge(edgeId)
  43860. * @param {vis.Edge.id} edgeId
  43861. * @returns {Array.<vis.Edge.id>}
  43862. */
  43863. }, {
  43864. key: 'getClusteredEdges',
  43865. value: function getClusteredEdges(edgeId) {
  43866. var stack = [];
  43867. var max = 100;
  43868. var counter = 0;
  43869. while (edgeId !== undefined && this.body.edges[edgeId] !== undefined && counter < max) {
  43870. stack.push(this.body.edges[edgeId].id);
  43871. edgeId = this.body.edges[edgeId].edgeReplacedById;
  43872. counter++;
  43873. }
  43874. stack.reverse();
  43875. return stack;
  43876. }
  43877. /**
  43878. * Get the base edge id of clusterEdgeId. cluster edge (clusteredEdgeId) -> cluster edge B -> cluster edge C -> base edge
  43879. * @param {vis.Edge.id} clusteredEdgeId
  43880. * @returns {vis.Edge.id} baseEdgeId
  43881. *
  43882. * TODO: deprecate in 5.0.0. Method getBaseEdges() is the correct one to use.
  43883. */
  43884. }, {
  43885. key: 'getBaseEdge',
  43886. value: function getBaseEdge(clusteredEdgeId) {
  43887. // Just kludge this by returning the first base edge id found
  43888. return this.getBaseEdges(clusteredEdgeId)[0];
  43889. }
  43890. /**
  43891. * Get all regular edges for this clustered edge id.
  43892. *
  43893. * @param {vis.Edge.id} clusteredEdgeId
  43894. * @returns {Array.<vis.Edge.id>} all baseEdgeId's under this clustered edge
  43895. */
  43896. }, {
  43897. key: 'getBaseEdges',
  43898. value: function getBaseEdges(clusteredEdgeId) {
  43899. var IdsToHandle = [clusteredEdgeId];
  43900. var doneIds = [];
  43901. var foundIds = [];
  43902. var max = 100;
  43903. var counter = 0;
  43904. while (IdsToHandle.length > 0 && counter < max) {
  43905. var nextId = IdsToHandle.pop();
  43906. if (nextId === undefined) continue; // Paranoia here and onwards
  43907. var nextEdge = this.body.edges[nextId];
  43908. if (nextEdge === undefined) continue;
  43909. counter++;
  43910. var replacingIds = nextEdge.clusteringEdgeReplacingIds;
  43911. if (replacingIds === undefined) {
  43912. // nextId is a base id
  43913. foundIds.push(nextId);
  43914. } else {
  43915. // Another cluster edge, unravel this one as well
  43916. for (var i = 0; i < replacingIds.length; ++i) {
  43917. var replacingId = replacingIds[i];
  43918. // Don't add if already handled
  43919. // TODO: never triggers; find a test-case which does
  43920. if (IdsToHandle.indexOf(replacingIds) !== -1 || doneIds.indexOf(replacingIds) !== -1) {
  43921. continue;
  43922. }
  43923. IdsToHandle.push(replacingId);
  43924. }
  43925. }
  43926. doneIds.push(nextId);
  43927. }
  43928. return foundIds;
  43929. }
  43930. /**
  43931. * Get the Id the node is connected to
  43932. * @param {vis.Edge} edge
  43933. * @param {Node.id} nodeId
  43934. * @returns {*}
  43935. * @private
  43936. */
  43937. }, {
  43938. key: '_getConnectedId',
  43939. value: function _getConnectedId(edge, nodeId) {
  43940. if (edge.toId != nodeId) {
  43941. return edge.toId;
  43942. } else if (edge.fromId != nodeId) {
  43943. return edge.fromId;
  43944. } else {
  43945. return edge.fromId;
  43946. }
  43947. }
  43948. /**
  43949. * We determine how many connections denote an important hub.
  43950. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  43951. *
  43952. * @returns {number}
  43953. * @private
  43954. */
  43955. }, {
  43956. key: '_getHubSize',
  43957. value: function _getHubSize() {
  43958. var average = 0;
  43959. var averageSquared = 0;
  43960. var hubCounter = 0;
  43961. var largestHub = 0;
  43962. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  43963. var _node = this.body.nodes[this.body.nodeIndices[i]];
  43964. if (_node.edges.length > largestHub) {
  43965. largestHub = _node.edges.length;
  43966. }
  43967. average += _node.edges.length;
  43968. averageSquared += Math.pow(_node.edges.length, 2);
  43969. hubCounter += 1;
  43970. }
  43971. average = average / hubCounter;
  43972. averageSquared = averageSquared / hubCounter;
  43973. var variance = averageSquared - Math.pow(average, 2);
  43974. var standardDeviation = Math.sqrt(variance);
  43975. var hubThreshold = Math.floor(average + 2 * standardDeviation);
  43976. // always have at least one to cluster
  43977. if (hubThreshold > largestHub) {
  43978. hubThreshold = largestHub;
  43979. }
  43980. return hubThreshold;
  43981. }
  43982. /**
  43983. * Create an edge for the cluster representation.
  43984. *
  43985. * @param {Node.id} fromId
  43986. * @param {Node.id} toId
  43987. * @param {vis.Edge} baseEdge
  43988. * @param {Object} clusterEdgeProperties
  43989. * @param {Object} extraOptions
  43990. * @returns {Edge} newly created clustered edge
  43991. * @private
  43992. */
  43993. }, {
  43994. key: '_createClusteredEdge',
  43995. value: function _createClusteredEdge(fromId, toId, baseEdge, clusterEdgeProperties, extraOptions) {
  43996. // copy the options of the edge we will replace
  43997. var clonedOptions = NetworkUtil.cloneOptions(baseEdge, 'edge');
  43998. // make sure the properties of clusterEdges are superimposed on it
  43999. util.deepExtend(clonedOptions, clusterEdgeProperties);
  44000. // set up the edge
  44001. clonedOptions.from = fromId;
  44002. clonedOptions.to = toId;
  44003. clonedOptions.id = 'clusterEdge:' + util.randomUUID();
  44004. // apply the edge specific options to it if specified
  44005. if (extraOptions !== undefined) {
  44006. util.deepExtend(clonedOptions, extraOptions);
  44007. }
  44008. var newEdge = this.body.functions.createEdge(clonedOptions);
  44009. newEdge.clusteringEdgeReplacingIds = [baseEdge.id];
  44010. newEdge.connect();
  44011. // Register the new edge
  44012. this.body.edges[newEdge.id] = newEdge;
  44013. return newEdge;
  44014. }
  44015. /**
  44016. * Add the passed child nodes and edges to the given cluster node.
  44017. *
  44018. * @param {Object|Node} childNodes hash of nodes or single node to add in cluster
  44019. * @param {Object|Edge} childEdges hash of edges or single edge to take into account when clustering
  44020. * @param {Node} clusterNode cluster node to add nodes and edges to
  44021. * @param {Object} [clusterEdgeProperties]
  44022. * @private
  44023. */
  44024. }, {
  44025. key: '_clusterEdges',
  44026. value: function _clusterEdges(childNodes, childEdges, clusterNode, clusterEdgeProperties) {
  44027. if (childEdges instanceof Edge) {
  44028. var edge = childEdges;
  44029. var obj = {};
  44030. obj[edge.id] = edge;
  44031. childEdges = obj;
  44032. }
  44033. if (childNodes instanceof Node) {
  44034. var _node2 = childNodes;
  44035. var _obj = {};
  44036. _obj[_node2.id] = _node2;
  44037. childNodes = _obj;
  44038. }
  44039. if (clusterNode === undefined || clusterNode === null) {
  44040. throw new Error("_clusterEdges: parameter clusterNode required");
  44041. }
  44042. if (clusterEdgeProperties === undefined) {
  44043. // Take the required properties from the cluster node
  44044. clusterEdgeProperties = clusterNode.clusterEdgeProperties;
  44045. }
  44046. // create the new edges that will connect to the cluster.
  44047. // All self-referencing edges will be added to childEdges here.
  44048. this._createClusterEdges(childNodes, childEdges, clusterNode, clusterEdgeProperties);
  44049. // disable the childEdges
  44050. for (var edgeId in childEdges) {
  44051. if (childEdges.hasOwnProperty(edgeId)) {
  44052. if (this.body.edges[edgeId] !== undefined) {
  44053. var _edge2 = this.body.edges[edgeId];
  44054. // cache the options before changing
  44055. this._backupEdgeOptions(_edge2);
  44056. // disable physics and hide the edge
  44057. _edge2.setOptions({ physics: false });
  44058. }
  44059. }
  44060. }
  44061. // disable the childNodes
  44062. for (var _nodeId7 in childNodes) {
  44063. if (childNodes.hasOwnProperty(_nodeId7)) {
  44064. this.clusteredNodes[_nodeId7] = { clusterId: clusterNode.id, node: this.body.nodes[_nodeId7] };
  44065. this.body.nodes[_nodeId7].setOptions({ physics: false });
  44066. }
  44067. }
  44068. }
  44069. /**
  44070. * Determine in which cluster given nodeId resides.
  44071. *
  44072. * If not in cluster, return undefined.
  44073. *
  44074. * NOTE: If you know a cleaner way to do this, please enlighten me (wimrijnders).
  44075. *
  44076. * @param {Node.id} nodeId
  44077. * @returns {Node|undefined} Node instance for cluster, if present
  44078. * @private
  44079. */
  44080. }, {
  44081. key: '_getClusterNodeForNode',
  44082. value: function _getClusterNodeForNode(nodeId) {
  44083. if (nodeId === undefined) return undefined;
  44084. var clusteredNode = this.clusteredNodes[nodeId];
  44085. // NOTE: If no cluster info found, it should actually be an error
  44086. if (clusteredNode === undefined) return undefined;
  44087. var clusterId = clusteredNode.clusterId;
  44088. if (clusterId === undefined) return undefined;
  44089. return this.body.nodes[clusterId];
  44090. }
  44091. /**
  44092. * Internal helper function for conditionally removing items in array
  44093. *
  44094. * Done like this because Array.filter() is not fully supported by all IE's.
  44095. *
  44096. * @param {Array} arr
  44097. * @param {function} callback
  44098. * @returns {Array}
  44099. * @private
  44100. */
  44101. }, {
  44102. key: '_filter',
  44103. value: function _filter(arr, callback) {
  44104. var ret = [];
  44105. util.forEach(arr, function (item) {
  44106. if (callback(item)) {
  44107. ret.push(item);
  44108. }
  44109. });
  44110. return ret;
  44111. }
  44112. /**
  44113. * Scan all edges for changes in clustering and adjust this if necessary.
  44114. *
  44115. * Call this (internally) after there has been a change in node or edge data.
  44116. *
  44117. * Pre: States of this.body.nodes and this.body.edges consistent
  44118. * Pre: this.clusteredNodes and this.clusteredEdge consistent with containedNodes and containedEdges
  44119. * of cluster nodes.
  44120. */
  44121. }, {
  44122. key: '_updateState',
  44123. value: function _updateState() {
  44124. var _this4 = this;
  44125. var nodeId = void 0;
  44126. var deletedNodeIds = [];
  44127. var deletedEdgeIds = [];
  44128. /**
  44129. * Utility function to iterate over clustering nodes only
  44130. *
  44131. * @param {Function} callback function to call for each cluster node
  44132. */
  44133. var eachClusterNode = function eachClusterNode(callback) {
  44134. util.forEach(_this4.body.nodes, function (node) {
  44135. if (node.isCluster === true) {
  44136. callback(node);
  44137. }
  44138. });
  44139. };
  44140. //
  44141. // Remove deleted regular nodes from clustering
  44142. //
  44143. // Determine the deleted nodes
  44144. for (nodeId in this.clusteredNodes) {
  44145. if (!this.clusteredNodes.hasOwnProperty(nodeId)) continue;
  44146. var _node3 = this.body.nodes[nodeId];
  44147. if (_node3 === undefined) {
  44148. deletedNodeIds.push(nodeId);
  44149. }
  44150. }
  44151. // Remove nodes from cluster nodes
  44152. eachClusterNode(function (clusterNode) {
  44153. for (var n = 0; n < deletedNodeIds.length; n++) {
  44154. delete clusterNode.containedNodes[deletedNodeIds[n]];
  44155. }
  44156. });
  44157. // Remove nodes from cluster list
  44158. for (var n = 0; n < deletedNodeIds.length; n++) {
  44159. delete this.clusteredNodes[deletedNodeIds[n]];
  44160. }
  44161. //
  44162. // Remove deleted edges from clustering
  44163. //
  44164. // Add the deleted clustered edges to the list
  44165. util.forEach(this.clusteredEdges, function (edgeId) {
  44166. var edge = _this4.body.edges[edgeId];
  44167. if (edge === undefined || !edge.endPointsValid()) {
  44168. deletedEdgeIds.push(edgeId);
  44169. }
  44170. });
  44171. // Cluster nodes can also contain edges which are not clustered,
  44172. // i.e. nodes 1-2 within cluster with an edge in between.
  44173. // So the cluster nodes also need to be scanned for invalid edges
  44174. eachClusterNode(function (clusterNode) {
  44175. util.forEach(clusterNode.containedEdges, function (edge, edgeId) {
  44176. if (!edge.endPointsValid() && deletedEdgeIds.indexOf(edgeId) === -1) {
  44177. deletedEdgeIds.push(edgeId);
  44178. }
  44179. });
  44180. });
  44181. // Also scan for cluster edges which need to be removed in the active list.
  44182. // Regular edges have been removed beforehand, so this only picks up the cluster edges.
  44183. util.forEach(this.body.edges, function (edge, edgeId) {
  44184. // Explicitly scan the contained edges for validity
  44185. var isValid = true;
  44186. var replacedIds = edge.clusteringEdgeReplacingIds;
  44187. if (replacedIds !== undefined) {
  44188. var numValid = 0;
  44189. util.forEach(replacedIds, function (containedEdgeId) {
  44190. var containedEdge = _this4.body.edges[containedEdgeId];
  44191. if (containedEdge !== undefined && containedEdge.endPointsValid()) {
  44192. numValid += 1;
  44193. }
  44194. });
  44195. isValid = numValid > 0;
  44196. }
  44197. if (!edge.endPointsValid() || !isValid) {
  44198. deletedEdgeIds.push(edgeId);
  44199. }
  44200. });
  44201. // Remove edges from cluster nodes
  44202. eachClusterNode(function (clusterNode) {
  44203. util.forEach(deletedEdgeIds, function (deletedEdgeId) {
  44204. delete clusterNode.containedEdges[deletedEdgeId];
  44205. util.forEach(clusterNode.edges, function (edge, m) {
  44206. if (edge.id === deletedEdgeId) {
  44207. clusterNode.edges[m] = null; // Don't want to directly delete here, because in the loop
  44208. return;
  44209. }
  44210. edge.clusteringEdgeReplacingIds = _this4._filter(edge.clusteringEdgeReplacingIds, function (id) {
  44211. return deletedEdgeIds.indexOf(id) === -1;
  44212. });
  44213. });
  44214. // Clean up the nulls
  44215. clusterNode.edges = _this4._filter(clusterNode.edges, function (item) {
  44216. return item !== null;
  44217. });
  44218. });
  44219. });
  44220. // Remove from cluster list
  44221. util.forEach(deletedEdgeIds, function (edgeId) {
  44222. delete _this4.clusteredEdges[edgeId];
  44223. });
  44224. // Remove cluster edges from active list (this.body.edges).
  44225. // deletedEdgeIds still contains id of regular edges, but these should all
  44226. // be gone when you reach here.
  44227. util.forEach(deletedEdgeIds, function (edgeId) {
  44228. delete _this4.body.edges[edgeId];
  44229. });
  44230. //
  44231. // Check changed cluster state of edges
  44232. //
  44233. // Iterating over keys here, because edges may be removed in the loop
  44234. var ids = (0, _keys2['default'])(this.body.edges);
  44235. util.forEach(ids, function (edgeId) {
  44236. var edge = _this4.body.edges[edgeId];
  44237. var shouldBeClustered = _this4._isClusteredNode(edge.fromId) || _this4._isClusteredNode(edge.toId);
  44238. if (shouldBeClustered === _this4._isClusteredEdge(edge.id)) {
  44239. return; // all is well
  44240. }
  44241. if (shouldBeClustered) {
  44242. // add edge to clustering
  44243. var clusterFrom = _this4._getClusterNodeForNode(edge.fromId);
  44244. if (clusterFrom !== undefined) {
  44245. _this4._clusterEdges(_this4.body.nodes[edge.fromId], edge, clusterFrom);
  44246. }
  44247. var clusterTo = _this4._getClusterNodeForNode(edge.toId);
  44248. if (clusterTo !== undefined) {
  44249. _this4._clusterEdges(_this4.body.nodes[edge.toId], edge, clusterTo);
  44250. }
  44251. // TODO: check that it works for both edges clustered
  44252. // (This might be paranoia)
  44253. } else {
  44254. // This should not be happening, the state should
  44255. // be properly updated at this point.
  44256. //
  44257. // If it *is* reached during normal operation, then we have to implement
  44258. // undo clustering for this edge here.
  44259. throw new Error('remove edge from clustering not implemented!');
  44260. }
  44261. });
  44262. // Clusters may be nested to any level. Keep on opening until nothing to open
  44263. var changed = false;
  44264. var continueLoop = true;
  44265. var _loop2 = function _loop2() {
  44266. var clustersToOpen = [];
  44267. // Determine the id's of clusters that need opening
  44268. eachClusterNode(function (clusterNode) {
  44269. var numNodes = (0, _keys2['default'])(clusterNode.containedNodes).length;
  44270. var allowSingle = clusterNode.options.allowSingleNodeCluster === true;
  44271. if (allowSingle && numNodes < 1 || !allowSingle && numNodes < 2) {
  44272. clustersToOpen.push(clusterNode.id);
  44273. }
  44274. });
  44275. // Open them
  44276. for (var _n = 0; _n < clustersToOpen.length; ++_n) {
  44277. _this4.openCluster(clustersToOpen[_n], {}, false /* Don't refresh, we're in an refresh/update already */);
  44278. }
  44279. continueLoop = clustersToOpen.length > 0;
  44280. changed = changed || continueLoop;
  44281. };
  44282. while (continueLoop) {
  44283. _loop2();
  44284. }
  44285. if (changed) {
  44286. this._updateState(); // Redo this method (recursion possible! should be safe)
  44287. }
  44288. }
  44289. /**
  44290. * Determine if node with given id is part of a cluster.
  44291. *
  44292. * @param {Node.id} nodeId
  44293. * @return {boolean} true if part of a cluster.
  44294. */
  44295. }, {
  44296. key: '_isClusteredNode',
  44297. value: function _isClusteredNode(nodeId) {
  44298. return this.clusteredNodes[nodeId] !== undefined;
  44299. }
  44300. /**
  44301. * Determine if edge with given id is not visible due to clustering.
  44302. *
  44303. * An edge is considered clustered if:
  44304. * - it is directly replaced by a clustering edge
  44305. * - any of its connecting nodes is in a cluster
  44306. *
  44307. * @param {vis.Edge.id} edgeId
  44308. * @return {boolean} true if part of a cluster.
  44309. */
  44310. }, {
  44311. key: '_isClusteredEdge',
  44312. value: function _isClusteredEdge(edgeId) {
  44313. return this.clusteredEdges[edgeId] !== undefined;
  44314. }
  44315. }]);
  44316. return ClusterEngine;
  44317. }();
  44318. exports['default'] = ClusterEngine;
  44319. /***/ }),
  44320. /* 228 */
  44321. /***/ (function(module, exports, __webpack_require__) {
  44322. "use strict";
  44323. Object.defineProperty(exports, "__esModule", {
  44324. value: true
  44325. });
  44326. var _getPrototypeOf = __webpack_require__(3);
  44327. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  44328. var _classCallCheck2 = __webpack_require__(0);
  44329. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  44330. var _createClass2 = __webpack_require__(1);
  44331. var _createClass3 = _interopRequireDefault(_createClass2);
  44332. var _possibleConstructorReturn2 = __webpack_require__(4);
  44333. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  44334. var _inherits2 = __webpack_require__(5);
  44335. var _inherits3 = _interopRequireDefault(_inherits2);
  44336. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  44337. var util = __webpack_require__(2);
  44338. var Node = __webpack_require__(47)["default"];
  44339. /**
  44340. * A Cluster is a special Node that allows a group of Nodes positioned closely together
  44341. * to be represented by a single Cluster Node.
  44342. *
  44343. * @extends Node
  44344. */
  44345. var Cluster = function (_Node) {
  44346. (0, _inherits3["default"])(Cluster, _Node);
  44347. /**
  44348. * @param {Object} options
  44349. * @param {Object} body
  44350. * @param {Array.<HTMLImageElement>}imagelist
  44351. * @param {Array} grouplist
  44352. * @param {Object} globalOptions
  44353. * @param {Object} defaultOptions Global default options for nodes
  44354. */
  44355. function Cluster(options, body, imagelist, grouplist, globalOptions, defaultOptions) {
  44356. (0, _classCallCheck3["default"])(this, Cluster);
  44357. var _this = (0, _possibleConstructorReturn3["default"])(this, (Cluster.__proto__ || (0, _getPrototypeOf2["default"])(Cluster)).call(this, options, body, imagelist, grouplist, globalOptions, defaultOptions));
  44358. _this.isCluster = true;
  44359. _this.containedNodes = {};
  44360. _this.containedEdges = {};
  44361. return _this;
  44362. }
  44363. /**
  44364. * Transfer child cluster data to current and disconnect the child cluster.
  44365. *
  44366. * Please consult the header comment in 'Clustering.js' for the fields set here.
  44367. *
  44368. * @param {string|number} childClusterId id of child cluster to open
  44369. */
  44370. (0, _createClass3["default"])(Cluster, [{
  44371. key: "_openChildCluster",
  44372. value: function _openChildCluster(childClusterId) {
  44373. var _this2 = this;
  44374. var childCluster = this.body.nodes[childClusterId];
  44375. if (this.containedNodes[childClusterId] === undefined) {
  44376. throw new Error('node with id: ' + childClusterId + ' not in current cluster');
  44377. }
  44378. if (!childCluster.isCluster) {
  44379. throw new Error('node with id: ' + childClusterId + ' is not a cluster');
  44380. }
  44381. // Disconnect child cluster from current cluster
  44382. delete this.containedNodes[childClusterId];
  44383. util.forEach(childCluster.edges, function (edge) {
  44384. delete _this2.containedEdges[edge.id];
  44385. });
  44386. // Transfer nodes and edges
  44387. util.forEach(childCluster.containedNodes, function (node, nodeId) {
  44388. _this2.containedNodes[nodeId] = node;
  44389. });
  44390. childCluster.containedNodes = {};
  44391. util.forEach(childCluster.containedEdges, function (edge, edgeId) {
  44392. _this2.containedEdges[edgeId] = edge;
  44393. });
  44394. childCluster.containedEdges = {};
  44395. // Transfer edges within cluster edges which are clustered
  44396. util.forEach(childCluster.edges, function (clusterEdge) {
  44397. util.forEach(_this2.edges, function (parentClusterEdge) {
  44398. // Assumption: a clustered edge can only be present in a single clustering edge
  44399. // Not tested here
  44400. var index = parentClusterEdge.clusteringEdgeReplacingIds.indexOf(clusterEdge.id);
  44401. if (index === -1) return;
  44402. util.forEach(clusterEdge.clusteringEdgeReplacingIds, function (srcId) {
  44403. parentClusterEdge.clusteringEdgeReplacingIds.push(srcId);
  44404. // Maintain correct bookkeeping for transferred edge
  44405. _this2.body.edges[srcId].edgeReplacedById = parentClusterEdge.id;
  44406. });
  44407. // Remove cluster edge from parent cluster edge
  44408. parentClusterEdge.clusteringEdgeReplacingIds.splice(index, 1);
  44409. });
  44410. });
  44411. childCluster.edges = [];
  44412. }
  44413. }]);
  44414. return Cluster;
  44415. }(Node);
  44416. exports["default"] = Cluster;
  44417. /***/ }),
  44418. /* 229 */
  44419. /***/ (function(module, exports, __webpack_require__) {
  44420. "use strict";
  44421. Object.defineProperty(exports, "__esModule", {
  44422. value: true
  44423. });
  44424. var _classCallCheck2 = __webpack_require__(0);
  44425. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  44426. var _createClass2 = __webpack_require__(1);
  44427. var _createClass3 = _interopRequireDefault(_createClass2);
  44428. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  44429. /**
  44430. * Initializes window.requestAnimationFrame() to a usable form.
  44431. *
  44432. * Specifically, set up this method for the case of running on node.js with jsdom enabled.
  44433. *
  44434. * NOTES:
  44435. *
  44436. * * On node.js, when calling this directly outside of this class, `window` is not defined.
  44437. * This happens even if jsdom is used.
  44438. * * For node.js + jsdom, `window` is available at the moment the constructor is called.
  44439. * For this reason, the called is placed within the constructor.
  44440. * * Even then, `window.requestAnimationFrame()` is not defined, so it still needs to be added.
  44441. * * During unit testing, it happens that the window object is reset during execution, causing
  44442. * a runtime error due to missing `requestAnimationFrame()`. This needs to be compensated for,
  44443. * see `_requestNextFrame()`.
  44444. * * Since this is a global object, it may affect other modules besides `Network`. With normal
  44445. * usage, this does not cause any problems. During unit testing, errors may occur. These have
  44446. * been compensated for, see comment block in _requestNextFrame().
  44447. *
  44448. * @private
  44449. */
  44450. function _initRequestAnimationFrame() {
  44451. var func;
  44452. if (window !== undefined) {
  44453. func = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  44454. }
  44455. if (func === undefined) {
  44456. // window or method not present, setting mock requestAnimationFrame
  44457. window.requestAnimationFrame = function (callback) {
  44458. //console.log("Called mock requestAnimationFrame");
  44459. callback();
  44460. };
  44461. } else {
  44462. window.requestAnimationFrame = func;
  44463. }
  44464. }
  44465. var util = __webpack_require__(2);
  44466. /**
  44467. * The canvas renderer
  44468. */
  44469. var CanvasRenderer = function () {
  44470. /**
  44471. * @param {Object} body
  44472. * @param {Canvas} canvas
  44473. */
  44474. function CanvasRenderer(body, canvas) {
  44475. (0, _classCallCheck3["default"])(this, CanvasRenderer);
  44476. _initRequestAnimationFrame();
  44477. this.body = body;
  44478. this.canvas = canvas;
  44479. this.redrawRequested = false;
  44480. this.renderTimer = undefined;
  44481. this.requiresTimeout = true;
  44482. this.renderingActive = false;
  44483. this.renderRequests = 0;
  44484. this.allowRedraw = true;
  44485. this.dragging = false;
  44486. this.options = {};
  44487. this.defaultOptions = {
  44488. hideEdgesOnDrag: false,
  44489. hideNodesOnDrag: false
  44490. };
  44491. util.extend(this.options, this.defaultOptions);
  44492. this._determineBrowserMethod();
  44493. this.bindEventListeners();
  44494. }
  44495. /**
  44496. * Binds event listeners
  44497. */
  44498. (0, _createClass3["default"])(CanvasRenderer, [{
  44499. key: "bindEventListeners",
  44500. value: function bindEventListeners() {
  44501. var _this = this;
  44502. this.body.emitter.on("dragStart", function () {
  44503. _this.dragging = true;
  44504. });
  44505. this.body.emitter.on("dragEnd", function () {
  44506. _this.dragging = false;
  44507. });
  44508. this.body.emitter.on("_resizeNodes", function () {
  44509. _this._resizeNodes();
  44510. });
  44511. this.body.emitter.on("_redraw", function () {
  44512. if (_this.renderingActive === false) {
  44513. _this._redraw();
  44514. }
  44515. });
  44516. this.body.emitter.on("_blockRedraw", function () {
  44517. _this.allowRedraw = false;
  44518. });
  44519. this.body.emitter.on("_allowRedraw", function () {
  44520. _this.allowRedraw = true;_this.redrawRequested = false;
  44521. });
  44522. this.body.emitter.on("_requestRedraw", this._requestRedraw.bind(this));
  44523. this.body.emitter.on("_startRendering", function () {
  44524. _this.renderRequests += 1;
  44525. _this.renderingActive = true;
  44526. _this._startRendering();
  44527. });
  44528. this.body.emitter.on("_stopRendering", function () {
  44529. _this.renderRequests -= 1;
  44530. _this.renderingActive = _this.renderRequests > 0;
  44531. _this.renderTimer = undefined;
  44532. });
  44533. this.body.emitter.on('destroy', function () {
  44534. _this.renderRequests = 0;
  44535. _this.allowRedraw = false;
  44536. _this.renderingActive = false;
  44537. if (_this.requiresTimeout === true) {
  44538. clearTimeout(_this.renderTimer);
  44539. } else {
  44540. window.cancelAnimationFrame(_this.renderTimer);
  44541. }
  44542. _this.body.emitter.off();
  44543. });
  44544. }
  44545. /**
  44546. *
  44547. * @param {Object} options
  44548. */
  44549. }, {
  44550. key: "setOptions",
  44551. value: function setOptions(options) {
  44552. if (options !== undefined) {
  44553. var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag'];
  44554. util.selectiveDeepExtend(fields, this.options, options);
  44555. }
  44556. }
  44557. /**
  44558. * Prepare the drawing of the next frame.
  44559. *
  44560. * Calls the callback when the next frame can or will be drawn.
  44561. *
  44562. * @param {function} callback
  44563. * @param {number} delay - timeout case only, wait this number of milliseconds
  44564. * @returns {function|undefined}
  44565. * @private
  44566. */
  44567. }, {
  44568. key: "_requestNextFrame",
  44569. value: function _requestNextFrame(callback, delay) {
  44570. // During unit testing, it happens that the mock window object is reset while
  44571. // the next frame is still pending. Then, either 'window' is not present, or
  44572. // 'requestAnimationFrame()' is not present because it is not defined on the
  44573. // mock window object.
  44574. //
  44575. // As a consequence, unrelated unit tests may appear to fail, even if the problem
  44576. // described happens in the current unit test.
  44577. //
  44578. // This is not something that will happen in normal operation, but we still need
  44579. // to take it into account.
  44580. //
  44581. if (typeof window === 'undefined') return; // Doing `if (window === undefined)` does not work here!
  44582. var timer = void 0;
  44583. var myWindow = window; // Grab a reference to reduce the possibility that 'window' is reset
  44584. // while running this method.
  44585. if (this.requiresTimeout === true) {
  44586. // wait given number of milliseconds and perform the animation step function
  44587. timer = myWindow.setTimeout(callback, delay);
  44588. } else {
  44589. if (myWindow.requestAnimationFrame) {
  44590. timer = myWindow.requestAnimationFrame(callback);
  44591. }
  44592. }
  44593. return timer;
  44594. }
  44595. /**
  44596. *
  44597. * @private
  44598. */
  44599. }, {
  44600. key: "_startRendering",
  44601. value: function _startRendering() {
  44602. if (this.renderingActive === true) {
  44603. if (this.renderTimer === undefined) {
  44604. this.renderTimer = this._requestNextFrame(this._renderStep.bind(this), this.simulationInterval);
  44605. }
  44606. }
  44607. }
  44608. /**
  44609. *
  44610. * @private
  44611. */
  44612. }, {
  44613. key: "_renderStep",
  44614. value: function _renderStep() {
  44615. if (this.renderingActive === true) {
  44616. // reset the renderTimer so a new scheduled animation step can be set
  44617. this.renderTimer = undefined;
  44618. if (this.requiresTimeout === true) {
  44619. // this schedules a new simulation step
  44620. this._startRendering();
  44621. }
  44622. this._redraw();
  44623. if (this.requiresTimeout === false) {
  44624. // this schedules a new simulation step
  44625. this._startRendering();
  44626. }
  44627. }
  44628. }
  44629. /**
  44630. * Redraw the network with the current data
  44631. * chart will be resized too.
  44632. */
  44633. }, {
  44634. key: "redraw",
  44635. value: function redraw() {
  44636. this.body.emitter.emit('setSize');
  44637. this._redraw();
  44638. }
  44639. /**
  44640. * Redraw the network with the current data
  44641. * @private
  44642. */
  44643. }, {
  44644. key: "_requestRedraw",
  44645. value: function _requestRedraw() {
  44646. var _this2 = this;
  44647. if (this.redrawRequested !== true && this.renderingActive === false && this.allowRedraw === true) {
  44648. this.redrawRequested = true;
  44649. this._requestNextFrame(function () {
  44650. _this2._redraw(false);
  44651. }, 0);
  44652. }
  44653. }
  44654. /**
  44655. * Redraw the network with the current data
  44656. * @param {boolean} [hidden=false] | Used to get the first estimate of the node sizes.
  44657. * Only the nodes are drawn after which they are quickly drawn over.
  44658. * @private
  44659. */
  44660. }, {
  44661. key: "_redraw",
  44662. value: function _redraw() {
  44663. var hidden = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  44664. if (this.allowRedraw === true) {
  44665. this.body.emitter.emit("initRedraw");
  44666. this.redrawRequested = false;
  44667. // when the container div was hidden, this fixes it back up!
  44668. if (this.canvas.frame.canvas.width === 0 || this.canvas.frame.canvas.height === 0) {
  44669. this.canvas.setSize();
  44670. }
  44671. this.canvas.setTransform();
  44672. var ctx = this.canvas.getContext();
  44673. // clear the canvas
  44674. var w = this.canvas.frame.canvas.clientWidth;
  44675. var h = this.canvas.frame.canvas.clientHeight;
  44676. ctx.clearRect(0, 0, w, h);
  44677. // if the div is hidden, we stop the redraw here for performance.
  44678. if (this.canvas.frame.clientWidth === 0) {
  44679. return;
  44680. }
  44681. // set scaling and translation
  44682. ctx.save();
  44683. ctx.translate(this.body.view.translation.x, this.body.view.translation.y);
  44684. ctx.scale(this.body.view.scale, this.body.view.scale);
  44685. ctx.beginPath();
  44686. this.body.emitter.emit("beforeDrawing", ctx);
  44687. ctx.closePath();
  44688. if (hidden === false) {
  44689. if (this.dragging === false || this.dragging === true && this.options.hideEdgesOnDrag === false) {
  44690. this._drawEdges(ctx);
  44691. }
  44692. }
  44693. if (this.dragging === false || this.dragging === true && this.options.hideNodesOnDrag === false) {
  44694. this._drawNodes(ctx, hidden);
  44695. }
  44696. ctx.beginPath();
  44697. this.body.emitter.emit("afterDrawing", ctx);
  44698. ctx.closePath();
  44699. // restore original scaling and translation
  44700. ctx.restore();
  44701. if (hidden === true) {
  44702. ctx.clearRect(0, 0, w, h);
  44703. }
  44704. }
  44705. }
  44706. /**
  44707. * Redraw all nodes
  44708. *
  44709. * @param {CanvasRenderingContext2D} ctx
  44710. * @param {boolean} [alwaysShow]
  44711. * @private
  44712. */
  44713. }, {
  44714. key: "_resizeNodes",
  44715. value: function _resizeNodes() {
  44716. this.canvas.setTransform();
  44717. var ctx = this.canvas.getContext();
  44718. ctx.save();
  44719. ctx.translate(this.body.view.translation.x, this.body.view.translation.y);
  44720. ctx.scale(this.body.view.scale, this.body.view.scale);
  44721. var nodes = this.body.nodes;
  44722. var node = void 0;
  44723. // resize all nodes
  44724. for (var nodeId in nodes) {
  44725. if (nodes.hasOwnProperty(nodeId)) {
  44726. node = nodes[nodeId];
  44727. node.resize(ctx);
  44728. node.updateBoundingBox(ctx, node.selected);
  44729. }
  44730. }
  44731. // restore original scaling and translation
  44732. ctx.restore();
  44733. }
  44734. /**
  44735. * Redraw all nodes
  44736. *
  44737. * @param {CanvasRenderingContext2D} ctx 2D context of a HTML canvas
  44738. * @param {boolean} [alwaysShow]
  44739. * @private
  44740. */
  44741. }, {
  44742. key: "_drawNodes",
  44743. value: function _drawNodes(ctx) {
  44744. var alwaysShow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  44745. var nodes = this.body.nodes;
  44746. var nodeIndices = this.body.nodeIndices;
  44747. var node = void 0;
  44748. var selected = [];
  44749. var margin = 20;
  44750. var topLeft = this.canvas.DOMtoCanvas({ x: -margin, y: -margin });
  44751. var bottomRight = this.canvas.DOMtoCanvas({
  44752. x: this.canvas.frame.canvas.clientWidth + margin,
  44753. y: this.canvas.frame.canvas.clientHeight + margin
  44754. });
  44755. var viewableArea = { top: topLeft.y, left: topLeft.x, bottom: bottomRight.y, right: bottomRight.x };
  44756. // draw unselected nodes;
  44757. for (var i = 0; i < nodeIndices.length; i++) {
  44758. node = nodes[nodeIndices[i]];
  44759. // set selected nodes aside
  44760. if (node.isSelected()) {
  44761. selected.push(nodeIndices[i]);
  44762. } else {
  44763. if (alwaysShow === true) {
  44764. node.draw(ctx);
  44765. } else if (node.isBoundingBoxOverlappingWith(viewableArea) === true) {
  44766. node.draw(ctx);
  44767. } else {
  44768. node.updateBoundingBox(ctx, node.selected);
  44769. }
  44770. }
  44771. }
  44772. // draw the selected nodes on top
  44773. for (var _i = 0; _i < selected.length; _i++) {
  44774. node = nodes[selected[_i]];
  44775. node.draw(ctx);
  44776. }
  44777. }
  44778. /**
  44779. * Redraw all edges
  44780. * @param {CanvasRenderingContext2D} ctx 2D context of a HTML canvas
  44781. * @private
  44782. */
  44783. }, {
  44784. key: "_drawEdges",
  44785. value: function _drawEdges(ctx) {
  44786. var edges = this.body.edges;
  44787. var edgeIndices = this.body.edgeIndices;
  44788. var edge = void 0;
  44789. for (var i = 0; i < edgeIndices.length; i++) {
  44790. edge = edges[edgeIndices[i]];
  44791. if (edge.connected === true) {
  44792. edge.draw(ctx);
  44793. }
  44794. }
  44795. }
  44796. /**
  44797. * Determine if the browser requires a setTimeout or a requestAnimationFrame. This was required because
  44798. * some implementations (safari and IE9) did not support requestAnimationFrame
  44799. * @private
  44800. */
  44801. }, {
  44802. key: "_determineBrowserMethod",
  44803. value: function _determineBrowserMethod() {
  44804. if (typeof window !== 'undefined') {
  44805. var browserType = navigator.userAgent.toLowerCase();
  44806. this.requiresTimeout = false;
  44807. if (browserType.indexOf('msie 9.0') != -1) {
  44808. // IE 9
  44809. this.requiresTimeout = true;
  44810. } else if (browserType.indexOf('safari') != -1) {
  44811. // safari
  44812. if (browserType.indexOf('chrome') <= -1) {
  44813. this.requiresTimeout = true;
  44814. }
  44815. }
  44816. } else {
  44817. this.requiresTimeout = true;
  44818. }
  44819. }
  44820. }]);
  44821. return CanvasRenderer;
  44822. }();
  44823. exports["default"] = CanvasRenderer;
  44824. /***/ }),
  44825. /* 230 */
  44826. /***/ (function(module, exports, __webpack_require__) {
  44827. "use strict";
  44828. Object.defineProperty(exports, "__esModule", {
  44829. value: true
  44830. });
  44831. var _classCallCheck2 = __webpack_require__(0);
  44832. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  44833. var _createClass2 = __webpack_require__(1);
  44834. var _createClass3 = _interopRequireDefault(_createClass2);
  44835. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  44836. var Hammer = __webpack_require__(10);
  44837. var hammerUtil = __webpack_require__(37);
  44838. var util = __webpack_require__(2);
  44839. /**
  44840. * Create the main frame for the Network.
  44841. * This function is executed once when a Network object is created. The frame
  44842. * contains a canvas, and this canvas contains all objects like the axis and
  44843. * nodes.
  44844. */
  44845. var Canvas = function () {
  44846. /**
  44847. * @param {Object} body
  44848. */
  44849. function Canvas(body) {
  44850. (0, _classCallCheck3['default'])(this, Canvas);
  44851. this.body = body;
  44852. this.pixelRatio = 1;
  44853. this.resizeTimer = undefined;
  44854. this.resizeFunction = this._onResize.bind(this);
  44855. this.cameraState = {};
  44856. this.initialized = false;
  44857. this.canvasViewCenter = {};
  44858. this.options = {};
  44859. this.defaultOptions = {
  44860. autoResize: true,
  44861. height: '100%',
  44862. width: '100%'
  44863. };
  44864. util.extend(this.options, this.defaultOptions);
  44865. this.bindEventListeners();
  44866. }
  44867. /**
  44868. * Binds event listeners
  44869. */
  44870. (0, _createClass3['default'])(Canvas, [{
  44871. key: 'bindEventListeners',
  44872. value: function bindEventListeners() {
  44873. var _this = this;
  44874. // bind the events
  44875. this.body.emitter.once("resize", function (obj) {
  44876. if (obj.width !== 0) {
  44877. _this.body.view.translation.x = obj.width * 0.5;
  44878. }
  44879. if (obj.height !== 0) {
  44880. _this.body.view.translation.y = obj.height * 0.5;
  44881. }
  44882. });
  44883. this.body.emitter.on("setSize", this.setSize.bind(this));
  44884. this.body.emitter.on("destroy", function () {
  44885. _this.hammerFrame.destroy();
  44886. _this.hammer.destroy();
  44887. _this._cleanUp();
  44888. });
  44889. }
  44890. /**
  44891. * @param {Object} options
  44892. */
  44893. }, {
  44894. key: 'setOptions',
  44895. value: function setOptions(options) {
  44896. var _this2 = this;
  44897. if (options !== undefined) {
  44898. var fields = ['width', 'height', 'autoResize'];
  44899. util.selectiveDeepExtend(fields, this.options, options);
  44900. }
  44901. if (this.options.autoResize === true) {
  44902. // automatically adapt to a changing size of the browser.
  44903. this._cleanUp();
  44904. this.resizeTimer = setInterval(function () {
  44905. var changed = _this2.setSize();
  44906. if (changed === true) {
  44907. _this2.body.emitter.emit("_requestRedraw");
  44908. }
  44909. }, 1000);
  44910. this.resizeFunction = this._onResize.bind(this);
  44911. util.addEventListener(window, 'resize', this.resizeFunction);
  44912. }
  44913. }
  44914. /**
  44915. * @private
  44916. */
  44917. }, {
  44918. key: '_cleanUp',
  44919. value: function _cleanUp() {
  44920. // automatically adapt to a changing size of the browser.
  44921. if (this.resizeTimer !== undefined) {
  44922. clearInterval(this.resizeTimer);
  44923. }
  44924. util.removeEventListener(window, 'resize', this.resizeFunction);
  44925. this.resizeFunction = undefined;
  44926. }
  44927. /**
  44928. * @private
  44929. */
  44930. }, {
  44931. key: '_onResize',
  44932. value: function _onResize() {
  44933. this.setSize();
  44934. this.body.emitter.emit("_redraw");
  44935. }
  44936. /**
  44937. * Get and store the cameraState
  44938. *
  44939. * @param {number} [pixelRatio=this.pixelRatio]
  44940. * @private
  44941. */
  44942. }, {
  44943. key: '_getCameraState',
  44944. value: function _getCameraState() {
  44945. var pixelRatio = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.pixelRatio;
  44946. if (this.initialized === true) {
  44947. this.cameraState.previousWidth = this.frame.canvas.width / pixelRatio;
  44948. this.cameraState.previousHeight = this.frame.canvas.height / pixelRatio;
  44949. this.cameraState.scale = this.body.view.scale;
  44950. this.cameraState.position = this.DOMtoCanvas({
  44951. x: 0.5 * this.frame.canvas.width / pixelRatio,
  44952. y: 0.5 * this.frame.canvas.height / pixelRatio
  44953. });
  44954. }
  44955. }
  44956. /**
  44957. * Set the cameraState
  44958. * @private
  44959. */
  44960. }, {
  44961. key: '_setCameraState',
  44962. value: function _setCameraState() {
  44963. if (this.cameraState.scale !== undefined && this.frame.canvas.clientWidth !== 0 && this.frame.canvas.clientHeight !== 0 && this.pixelRatio !== 0 && this.cameraState.previousWidth > 0) {
  44964. var widthRatio = this.frame.canvas.width / this.pixelRatio / this.cameraState.previousWidth;
  44965. var heightRatio = this.frame.canvas.height / this.pixelRatio / this.cameraState.previousHeight;
  44966. var newScale = this.cameraState.scale;
  44967. if (widthRatio != 1 && heightRatio != 1) {
  44968. newScale = this.cameraState.scale * 0.5 * (widthRatio + heightRatio);
  44969. } else if (widthRatio != 1) {
  44970. newScale = this.cameraState.scale * widthRatio;
  44971. } else if (heightRatio != 1) {
  44972. newScale = this.cameraState.scale * heightRatio;
  44973. }
  44974. this.body.view.scale = newScale;
  44975. // this comes from the view module.
  44976. var currentViewCenter = this.DOMtoCanvas({
  44977. x: 0.5 * this.frame.canvas.clientWidth,
  44978. y: 0.5 * this.frame.canvas.clientHeight
  44979. });
  44980. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  44981. x: currentViewCenter.x - this.cameraState.position.x,
  44982. y: currentViewCenter.y - this.cameraState.position.y
  44983. };
  44984. this.body.view.translation.x += distanceFromCenter.x * this.body.view.scale;
  44985. this.body.view.translation.y += distanceFromCenter.y * this.body.view.scale;
  44986. }
  44987. }
  44988. /**
  44989. *
  44990. * @param {number|string} value
  44991. * @returns {string}
  44992. * @private
  44993. */
  44994. }, {
  44995. key: '_prepareValue',
  44996. value: function _prepareValue(value) {
  44997. if (typeof value === 'number') {
  44998. return value + 'px';
  44999. } else if (typeof value === 'string') {
  45000. if (value.indexOf('%') !== -1 || value.indexOf('px') !== -1) {
  45001. return value;
  45002. } else if (value.indexOf('%') === -1) {
  45003. return value + 'px';
  45004. }
  45005. }
  45006. throw new Error('Could not use the value supplied for width or height:' + value);
  45007. }
  45008. /**
  45009. * Create the HTML
  45010. */
  45011. }, {
  45012. key: '_create',
  45013. value: function _create() {
  45014. // remove all elements from the container element.
  45015. while (this.body.container.hasChildNodes()) {
  45016. this.body.container.removeChild(this.body.container.firstChild);
  45017. }
  45018. this.frame = document.createElement('div');
  45019. this.frame.className = 'vis-network';
  45020. this.frame.style.position = 'relative';
  45021. this.frame.style.overflow = 'hidden';
  45022. this.frame.tabIndex = 900; // tab index is required for keycharm to bind keystrokes to the div instead of the window
  45023. //////////////////////////////////////////////////////////////////
  45024. this.frame.canvas = document.createElement("canvas");
  45025. this.frame.canvas.style.position = 'relative';
  45026. this.frame.appendChild(this.frame.canvas);
  45027. if (!this.frame.canvas.getContext) {
  45028. var noCanvas = document.createElement('DIV');
  45029. noCanvas.style.color = 'red';
  45030. noCanvas.style.fontWeight = 'bold';
  45031. noCanvas.style.padding = '10px';
  45032. noCanvas.innerHTML = 'Error: your browser does not support HTML canvas';
  45033. this.frame.canvas.appendChild(noCanvas);
  45034. } else {
  45035. this._setPixelRatio();
  45036. this.setTransform();
  45037. }
  45038. // add the frame to the container element
  45039. this.body.container.appendChild(this.frame);
  45040. this.body.view.scale = 1;
  45041. this.body.view.translation = { x: 0.5 * this.frame.canvas.clientWidth, y: 0.5 * this.frame.canvas.clientHeight };
  45042. this._bindHammer();
  45043. }
  45044. /**
  45045. * This function binds hammer, it can be repeated over and over due to the uniqueness check.
  45046. * @private
  45047. */
  45048. }, {
  45049. key: '_bindHammer',
  45050. value: function _bindHammer() {
  45051. var _this3 = this;
  45052. if (this.hammer !== undefined) {
  45053. this.hammer.destroy();
  45054. }
  45055. this.drag = {};
  45056. this.pinch = {};
  45057. // init hammer
  45058. this.hammer = new Hammer(this.frame.canvas);
  45059. this.hammer.get('pinch').set({ enable: true });
  45060. // enable to get better response, todo: test on mobile.
  45061. this.hammer.get('pan').set({ threshold: 5, direction: Hammer.DIRECTION_ALL });
  45062. hammerUtil.onTouch(this.hammer, function (event) {
  45063. _this3.body.eventListeners.onTouch(event);
  45064. });
  45065. this.hammer.on('tap', function (event) {
  45066. _this3.body.eventListeners.onTap(event);
  45067. });
  45068. this.hammer.on('doubletap', function (event) {
  45069. _this3.body.eventListeners.onDoubleTap(event);
  45070. });
  45071. this.hammer.on('press', function (event) {
  45072. _this3.body.eventListeners.onHold(event);
  45073. });
  45074. this.hammer.on('panstart', function (event) {
  45075. _this3.body.eventListeners.onDragStart(event);
  45076. });
  45077. this.hammer.on('panmove', function (event) {
  45078. _this3.body.eventListeners.onDrag(event);
  45079. });
  45080. this.hammer.on('panend', function (event) {
  45081. _this3.body.eventListeners.onDragEnd(event);
  45082. });
  45083. this.hammer.on('pinch', function (event) {
  45084. _this3.body.eventListeners.onPinch(event);
  45085. });
  45086. // TODO: neatly cleanup these handlers when re-creating the Canvas, IF these are done with hammer, event.stopPropagation will not work?
  45087. this.frame.canvas.addEventListener('mousewheel', function (event) {
  45088. _this3.body.eventListeners.onMouseWheel(event);
  45089. });
  45090. this.frame.canvas.addEventListener('DOMMouseScroll', function (event) {
  45091. _this3.body.eventListeners.onMouseWheel(event);
  45092. });
  45093. this.frame.canvas.addEventListener('mousemove', function (event) {
  45094. _this3.body.eventListeners.onMouseMove(event);
  45095. });
  45096. this.frame.canvas.addEventListener('contextmenu', function (event) {
  45097. _this3.body.eventListeners.onContext(event);
  45098. });
  45099. this.hammerFrame = new Hammer(this.frame);
  45100. hammerUtil.onRelease(this.hammerFrame, function (event) {
  45101. _this3.body.eventListeners.onRelease(event);
  45102. });
  45103. }
  45104. /**
  45105. * Set a new size for the network
  45106. * @param {string} width Width in pixels or percentage (for example '800px'
  45107. * or '50%')
  45108. * @param {string} height Height in pixels or percentage (for example '400px'
  45109. * or '30%')
  45110. * @returns {boolean}
  45111. */
  45112. }, {
  45113. key: 'setSize',
  45114. value: function setSize() {
  45115. var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.options.width;
  45116. var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.options.height;
  45117. width = this._prepareValue(width);
  45118. height = this._prepareValue(height);
  45119. var emitEvent = false;
  45120. var oldWidth = this.frame.canvas.width;
  45121. var oldHeight = this.frame.canvas.height;
  45122. // update the pixel ratio
  45123. //
  45124. // NOTE: Comment in following is rather inconsistent; this is the ONLY place in the code
  45125. // where it is assumed that the pixel ratio could change at runtime.
  45126. // The only way I can think of this happening is a rotating screen or tablet; but then
  45127. // there should be a mechanism for reloading the data (TODO: check if this is present).
  45128. //
  45129. // If the assumption is true (i.e. pixel ratio can change at runtime), then *all* usage
  45130. // of pixel ratio must be overhauled for this.
  45131. //
  45132. // For the time being, I will humor the assumption here, and in the rest of the code assume it is
  45133. // constant.
  45134. var previousRatio = this.pixelRatio; // we cache this because the camera state storage needs the old value
  45135. this._setPixelRatio();
  45136. if (width != this.options.width || height != this.options.height || this.frame.style.width != width || this.frame.style.height != height) {
  45137. this._getCameraState(previousRatio);
  45138. this.frame.style.width = width;
  45139. this.frame.style.height = height;
  45140. this.frame.canvas.style.width = '100%';
  45141. this.frame.canvas.style.height = '100%';
  45142. this.frame.canvas.width = Math.round(this.frame.canvas.clientWidth * this.pixelRatio);
  45143. this.frame.canvas.height = Math.round(this.frame.canvas.clientHeight * this.pixelRatio);
  45144. this.options.width = width;
  45145. this.options.height = height;
  45146. this.canvasViewCenter = {
  45147. x: 0.5 * this.frame.clientWidth,
  45148. y: 0.5 * this.frame.clientHeight
  45149. };
  45150. emitEvent = true;
  45151. } else {
  45152. // this would adapt the width of the canvas to the width from 100% if and only if
  45153. // there is a change.
  45154. var newWidth = Math.round(this.frame.canvas.clientWidth * this.pixelRatio);
  45155. var newHeight = Math.round(this.frame.canvas.clientHeight * this.pixelRatio);
  45156. // store the camera if there is a change in size.
  45157. if (this.frame.canvas.width !== newWidth || this.frame.canvas.height !== newHeight) {
  45158. this._getCameraState(previousRatio);
  45159. }
  45160. if (this.frame.canvas.width !== newWidth) {
  45161. this.frame.canvas.width = newWidth;
  45162. emitEvent = true;
  45163. }
  45164. if (this.frame.canvas.height !== newHeight) {
  45165. this.frame.canvas.height = newHeight;
  45166. emitEvent = true;
  45167. }
  45168. }
  45169. if (emitEvent === true) {
  45170. this.body.emitter.emit('resize', {
  45171. width: Math.round(this.frame.canvas.width / this.pixelRatio),
  45172. height: Math.round(this.frame.canvas.height / this.pixelRatio),
  45173. oldWidth: Math.round(oldWidth / this.pixelRatio),
  45174. oldHeight: Math.round(oldHeight / this.pixelRatio)
  45175. });
  45176. // restore the camera on change.
  45177. this._setCameraState();
  45178. }
  45179. // set initialized so the get and set camera will work from now on.
  45180. this.initialized = true;
  45181. return emitEvent;
  45182. }
  45183. /**
  45184. *
  45185. * @returns {CanvasRenderingContext2D}
  45186. */
  45187. }, {
  45188. key: 'getContext',
  45189. value: function getContext() {
  45190. return this.frame.canvas.getContext("2d");
  45191. }
  45192. /**
  45193. * Determine the pixel ratio for various browsers.
  45194. *
  45195. * @returns {number}
  45196. * @private
  45197. */
  45198. }, {
  45199. key: '_determinePixelRatio',
  45200. value: function _determinePixelRatio() {
  45201. var ctx = this.getContext();
  45202. if (ctx === undefined) {
  45203. throw new Error("Could not get canvax context");
  45204. }
  45205. var numerator = 1;
  45206. if (typeof window !== 'undefined') {
  45207. // (window !== undefined) doesn't work here!
  45208. // Protection during unit tests, where 'window' can be missing
  45209. numerator = window.devicePixelRatio || 1;
  45210. }
  45211. var denominator = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
  45212. return numerator / denominator;
  45213. }
  45214. /**
  45215. * Lazy determination of pixel ratio.
  45216. *
  45217. * @private
  45218. */
  45219. }, {
  45220. key: '_setPixelRatio',
  45221. value: function _setPixelRatio() {
  45222. this.pixelRatio = this._determinePixelRatio();
  45223. }
  45224. /**
  45225. * Set the transform in the contained context, based on its pixelRatio
  45226. */
  45227. }, {
  45228. key: 'setTransform',
  45229. value: function setTransform() {
  45230. var ctx = this.getContext();
  45231. if (ctx === undefined) {
  45232. throw new Error("Could not get canvax context");
  45233. }
  45234. ctx.setTransform(this.pixelRatio, 0, 0, this.pixelRatio, 0, 0);
  45235. }
  45236. /**
  45237. * Convert the X coordinate in DOM-space (coordinate point in browser relative to the container div) to
  45238. * the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  45239. * @param {number} x
  45240. * @returns {number}
  45241. * @private
  45242. */
  45243. }, {
  45244. key: '_XconvertDOMtoCanvas',
  45245. value: function _XconvertDOMtoCanvas(x) {
  45246. return (x - this.body.view.translation.x) / this.body.view.scale;
  45247. }
  45248. /**
  45249. * Convert the X coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  45250. * the X coordinate in DOM-space (coordinate point in browser relative to the container div)
  45251. * @param {number} x
  45252. * @returns {number}
  45253. * @private
  45254. */
  45255. }, {
  45256. key: '_XconvertCanvasToDOM',
  45257. value: function _XconvertCanvasToDOM(x) {
  45258. return x * this.body.view.scale + this.body.view.translation.x;
  45259. }
  45260. /**
  45261. * Convert the Y coordinate in DOM-space (coordinate point in browser relative to the container div) to
  45262. * the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon)
  45263. * @param {number} y
  45264. * @returns {number}
  45265. * @private
  45266. */
  45267. }, {
  45268. key: '_YconvertDOMtoCanvas',
  45269. value: function _YconvertDOMtoCanvas(y) {
  45270. return (y - this.body.view.translation.y) / this.body.view.scale;
  45271. }
  45272. /**
  45273. * Convert the Y coordinate in canvas-space (the simulation sandbox, which the camera looks upon) to
  45274. * the Y coordinate in DOM-space (coordinate point in browser relative to the container div)
  45275. * @param {number} y
  45276. * @returns {number}
  45277. * @private
  45278. */
  45279. }, {
  45280. key: '_YconvertCanvasToDOM',
  45281. value: function _YconvertCanvasToDOM(y) {
  45282. return y * this.body.view.scale + this.body.view.translation.y;
  45283. }
  45284. /**
  45285. * @param {point} pos
  45286. * @returns {point}
  45287. */
  45288. }, {
  45289. key: 'canvasToDOM',
  45290. value: function canvasToDOM(pos) {
  45291. return { x: this._XconvertCanvasToDOM(pos.x), y: this._YconvertCanvasToDOM(pos.y) };
  45292. }
  45293. /**
  45294. *
  45295. * @param {point} pos
  45296. * @returns {point}
  45297. */
  45298. }, {
  45299. key: 'DOMtoCanvas',
  45300. value: function DOMtoCanvas(pos) {
  45301. return { x: this._XconvertDOMtoCanvas(pos.x), y: this._YconvertDOMtoCanvas(pos.y) };
  45302. }
  45303. }]);
  45304. return Canvas;
  45305. }();
  45306. exports['default'] = Canvas;
  45307. /***/ }),
  45308. /* 231 */
  45309. /***/ (function(module, exports, __webpack_require__) {
  45310. "use strict";
  45311. Object.defineProperty(exports, "__esModule", {
  45312. value: true
  45313. });
  45314. var _classCallCheck2 = __webpack_require__(0);
  45315. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  45316. var _createClass2 = __webpack_require__(1);
  45317. var _createClass3 = _interopRequireDefault(_createClass2);
  45318. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  45319. var util = __webpack_require__(2);
  45320. var NetworkUtil = __webpack_require__(76)['default'];
  45321. /**
  45322. * The view
  45323. */
  45324. var View = function () {
  45325. /**
  45326. * @param {Object} body
  45327. * @param {Canvas} canvas
  45328. */
  45329. function View(body, canvas) {
  45330. var _this = this;
  45331. (0, _classCallCheck3['default'])(this, View);
  45332. this.body = body;
  45333. this.canvas = canvas;
  45334. this.animationSpeed = 1 / this.renderRefreshRate;
  45335. this.animationEasingFunction = "easeInOutQuint";
  45336. this.easingTime = 0;
  45337. this.sourceScale = 0;
  45338. this.targetScale = 0;
  45339. this.sourceTranslation = 0;
  45340. this.targetTranslation = 0;
  45341. this.lockedOnNodeId = undefined;
  45342. this.lockedOnNodeOffset = undefined;
  45343. this.touchTime = 0;
  45344. this.viewFunction = undefined;
  45345. this.body.emitter.on("fit", this.fit.bind(this));
  45346. this.body.emitter.on("animationFinished", function () {
  45347. _this.body.emitter.emit("_stopRendering");
  45348. });
  45349. this.body.emitter.on("unlockNode", this.releaseNode.bind(this));
  45350. }
  45351. /**
  45352. *
  45353. * @param {Object} [options={}]
  45354. */
  45355. (0, _createClass3['default'])(View, [{
  45356. key: 'setOptions',
  45357. value: function setOptions() {
  45358. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  45359. this.options = options;
  45360. }
  45361. /**
  45362. * This function zooms out to fit all data on screen based on amount of nodes
  45363. * @param {Object} [options={{nodes=Array}}]
  45364. * @param {boolean} [initialZoom=false] | zoom based on fitted formula or range, true = fitted, default = false;
  45365. */
  45366. }, {
  45367. key: 'fit',
  45368. value: function fit() {
  45369. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { nodes: [] };
  45370. var initialZoom = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  45371. var range = void 0;
  45372. var zoomLevel = void 0;
  45373. if (options.nodes === undefined || options.nodes.length === 0) {
  45374. options.nodes = this.body.nodeIndices;
  45375. }
  45376. if (initialZoom === true) {
  45377. // check if more than half of the nodes have a predefined position. If so, we use the range, not the approximation.
  45378. var positionDefined = 0;
  45379. for (var nodeId in this.body.nodes) {
  45380. if (this.body.nodes.hasOwnProperty(nodeId)) {
  45381. var node = this.body.nodes[nodeId];
  45382. if (node.predefinedPosition === true) {
  45383. positionDefined += 1;
  45384. }
  45385. }
  45386. }
  45387. if (positionDefined > 0.5 * this.body.nodeIndices.length) {
  45388. this.fit(options, false);
  45389. return;
  45390. }
  45391. range = NetworkUtil.getRange(this.body.nodes, options.nodes);
  45392. var numberOfNodes = this.body.nodeIndices.length;
  45393. zoomLevel = 12.662 / (numberOfNodes + 7.4147) + 0.0964822; // this is obtained from fitting a dataset from 5 points with scale levels that looked good.
  45394. // correct for larger canvasses.
  45395. var factor = Math.min(this.canvas.frame.canvas.clientWidth / 600, this.canvas.frame.canvas.clientHeight / 600);
  45396. zoomLevel *= factor;
  45397. } else {
  45398. this.body.emitter.emit("_resizeNodes");
  45399. range = NetworkUtil.getRange(this.body.nodes, options.nodes);
  45400. var xDistance = Math.abs(range.maxX - range.minX) * 1.1;
  45401. var yDistance = Math.abs(range.maxY - range.minY) * 1.1;
  45402. var xZoomLevel = this.canvas.frame.canvas.clientWidth / xDistance;
  45403. var yZoomLevel = this.canvas.frame.canvas.clientHeight / yDistance;
  45404. zoomLevel = xZoomLevel <= yZoomLevel ? xZoomLevel : yZoomLevel;
  45405. }
  45406. if (zoomLevel > 1.0) {
  45407. zoomLevel = 1.0;
  45408. } else if (zoomLevel === 0) {
  45409. zoomLevel = 1.0;
  45410. }
  45411. var center = NetworkUtil.findCenter(range);
  45412. var animationOptions = { position: center, scale: zoomLevel, animation: options.animation };
  45413. this.moveTo(animationOptions);
  45414. }
  45415. // animation
  45416. /**
  45417. * Center a node in view.
  45418. *
  45419. * @param {number} nodeId
  45420. * @param {number} [options]
  45421. */
  45422. }, {
  45423. key: 'focus',
  45424. value: function focus(nodeId) {
  45425. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  45426. if (this.body.nodes[nodeId] !== undefined) {
  45427. var nodePosition = { x: this.body.nodes[nodeId].x, y: this.body.nodes[nodeId].y };
  45428. options.position = nodePosition;
  45429. options.lockedOnNode = nodeId;
  45430. this.moveTo(options);
  45431. } else {
  45432. console.log("Node: " + nodeId + " cannot be found.");
  45433. }
  45434. }
  45435. /**
  45436. *
  45437. * @param {Object} options | options.offset = {x:number, y:number} // offset from the center in DOM pixels
  45438. * | options.scale = number // scale to move to
  45439. * | options.position = {x:number, y:number} // position to move to
  45440. * | options.animation = {duration:number, easingFunction:String} || Boolean // position to move to
  45441. */
  45442. }, {
  45443. key: 'moveTo',
  45444. value: function moveTo(options) {
  45445. if (options === undefined) {
  45446. options = {};
  45447. return;
  45448. }
  45449. if (options.offset === undefined) {
  45450. options.offset = { x: 0, y: 0 };
  45451. }
  45452. if (options.offset.x === undefined) {
  45453. options.offset.x = 0;
  45454. }
  45455. if (options.offset.y === undefined) {
  45456. options.offset.y = 0;
  45457. }
  45458. if (options.scale === undefined) {
  45459. options.scale = this.body.view.scale;
  45460. }
  45461. if (options.position === undefined) {
  45462. options.position = this.getViewPosition();
  45463. }
  45464. if (options.animation === undefined) {
  45465. options.animation = { duration: 0 };
  45466. }
  45467. if (options.animation === false) {
  45468. options.animation = { duration: 0 };
  45469. }
  45470. if (options.animation === true) {
  45471. options.animation = {};
  45472. }
  45473. if (options.animation.duration === undefined) {
  45474. options.animation.duration = 1000;
  45475. } // default duration
  45476. if (options.animation.easingFunction === undefined) {
  45477. options.animation.easingFunction = "easeInOutQuad";
  45478. } // default easing function
  45479. this.animateView(options);
  45480. }
  45481. /**
  45482. *
  45483. * @param {Object} options | options.offset = {x:number, y:number} // offset from the center in DOM pixels
  45484. * | options.time = number // animation time in milliseconds
  45485. * | options.scale = number // scale to animate to
  45486. * | options.position = {x:number, y:number} // position to animate to
  45487. * | options.easingFunction = String // linear, easeInQuad, easeOutQuad, easeInOutQuad,
  45488. * // easeInCubic, easeOutCubic, easeInOutCubic,
  45489. * // easeInQuart, easeOutQuart, easeInOutQuart,
  45490. * // easeInQuint, easeOutQuint, easeInOutQuint
  45491. */
  45492. }, {
  45493. key: 'animateView',
  45494. value: function animateView(options) {
  45495. if (options === undefined) {
  45496. return;
  45497. }
  45498. this.animationEasingFunction = options.animation.easingFunction;
  45499. // release if something focussed on the node
  45500. this.releaseNode();
  45501. if (options.locked === true) {
  45502. this.lockedOnNodeId = options.lockedOnNode;
  45503. this.lockedOnNodeOffset = options.offset;
  45504. }
  45505. // forcefully complete the old animation if it was still running
  45506. if (this.easingTime != 0) {
  45507. this._transitionRedraw(true); // by setting easingtime to 1, we finish the animation.
  45508. }
  45509. this.sourceScale = this.body.view.scale;
  45510. this.sourceTranslation = this.body.view.translation;
  45511. this.targetScale = options.scale;
  45512. // set the scale so the viewCenter is based on the correct zoom level. This is overridden in the transitionRedraw
  45513. // but at least then we'll have the target transition
  45514. this.body.view.scale = this.targetScale;
  45515. var viewCenter = this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight });
  45516. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  45517. x: viewCenter.x - options.position.x,
  45518. y: viewCenter.y - options.position.y
  45519. };
  45520. this.targetTranslation = {
  45521. x: this.sourceTranslation.x + distanceFromCenter.x * this.targetScale + options.offset.x,
  45522. y: this.sourceTranslation.y + distanceFromCenter.y * this.targetScale + options.offset.y
  45523. };
  45524. // if the time is set to 0, don't do an animation
  45525. if (options.animation.duration === 0) {
  45526. if (this.lockedOnNodeId != undefined) {
  45527. this.viewFunction = this._lockedRedraw.bind(this);
  45528. this.body.emitter.on("initRedraw", this.viewFunction);
  45529. } else {
  45530. this.body.view.scale = this.targetScale;
  45531. this.body.view.translation = this.targetTranslation;
  45532. this.body.emitter.emit("_requestRedraw");
  45533. }
  45534. } else {
  45535. this.animationSpeed = 1 / (60 * options.animation.duration * 0.001) || 1 / 60; // 60 for 60 seconds, 0.001 for milli's
  45536. this.animationEasingFunction = options.animation.easingFunction;
  45537. this.viewFunction = this._transitionRedraw.bind(this);
  45538. this.body.emitter.on("initRedraw", this.viewFunction);
  45539. this.body.emitter.emit("_startRendering");
  45540. }
  45541. }
  45542. /**
  45543. * used to animate smoothly by hijacking the redraw function.
  45544. * @private
  45545. */
  45546. }, {
  45547. key: '_lockedRedraw',
  45548. value: function _lockedRedraw() {
  45549. var nodePosition = { x: this.body.nodes[this.lockedOnNodeId].x, y: this.body.nodes[this.lockedOnNodeId].y };
  45550. var viewCenter = this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight });
  45551. var distanceFromCenter = { // offset from view, distance view has to change by these x and y to center the node
  45552. x: viewCenter.x - nodePosition.x,
  45553. y: viewCenter.y - nodePosition.y
  45554. };
  45555. var sourceTranslation = this.body.view.translation;
  45556. var targetTranslation = {
  45557. x: sourceTranslation.x + distanceFromCenter.x * this.body.view.scale + this.lockedOnNodeOffset.x,
  45558. y: sourceTranslation.y + distanceFromCenter.y * this.body.view.scale + this.lockedOnNodeOffset.y
  45559. };
  45560. this.body.view.translation = targetTranslation;
  45561. }
  45562. /**
  45563. * Resets state of a locked on Node
  45564. */
  45565. }, {
  45566. key: 'releaseNode',
  45567. value: function releaseNode() {
  45568. if (this.lockedOnNodeId !== undefined && this.viewFunction !== undefined) {
  45569. this.body.emitter.off("initRedraw", this.viewFunction);
  45570. this.lockedOnNodeId = undefined;
  45571. this.lockedOnNodeOffset = undefined;
  45572. }
  45573. }
  45574. /**
  45575. * @param {boolean} [finished=false]
  45576. * @private
  45577. */
  45578. }, {
  45579. key: '_transitionRedraw',
  45580. value: function _transitionRedraw() {
  45581. var finished = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  45582. this.easingTime += this.animationSpeed;
  45583. this.easingTime = finished === true ? 1.0 : this.easingTime;
  45584. var progress = util.easingFunctions[this.animationEasingFunction](this.easingTime);
  45585. this.body.view.scale = this.sourceScale + (this.targetScale - this.sourceScale) * progress;
  45586. this.body.view.translation = {
  45587. x: this.sourceTranslation.x + (this.targetTranslation.x - this.sourceTranslation.x) * progress,
  45588. y: this.sourceTranslation.y + (this.targetTranslation.y - this.sourceTranslation.y) * progress
  45589. };
  45590. // cleanup
  45591. if (this.easingTime >= 1.0) {
  45592. this.body.emitter.off("initRedraw", this.viewFunction);
  45593. this.easingTime = 0;
  45594. if (this.lockedOnNodeId != undefined) {
  45595. this.viewFunction = this._lockedRedraw.bind(this);
  45596. this.body.emitter.on("initRedraw", this.viewFunction);
  45597. }
  45598. this.body.emitter.emit("animationFinished");
  45599. }
  45600. }
  45601. /**
  45602. *
  45603. * @returns {number}
  45604. */
  45605. }, {
  45606. key: 'getScale',
  45607. value: function getScale() {
  45608. return this.body.view.scale;
  45609. }
  45610. /**
  45611. *
  45612. * @returns {{x: number, y: number}}
  45613. */
  45614. }, {
  45615. key: 'getViewPosition',
  45616. value: function getViewPosition() {
  45617. return this.canvas.DOMtoCanvas({ x: 0.5 * this.canvas.frame.canvas.clientWidth, y: 0.5 * this.canvas.frame.canvas.clientHeight });
  45618. }
  45619. }]);
  45620. return View;
  45621. }();
  45622. exports['default'] = View;
  45623. /***/ }),
  45624. /* 232 */
  45625. /***/ (function(module, exports, __webpack_require__) {
  45626. "use strict";
  45627. Object.defineProperty(exports, "__esModule", {
  45628. value: true
  45629. });
  45630. var _classCallCheck2 = __webpack_require__(0);
  45631. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  45632. var _createClass2 = __webpack_require__(1);
  45633. var _createClass3 = _interopRequireDefault(_createClass2);
  45634. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  45635. var util = __webpack_require__(2);
  45636. var NavigationHandler = __webpack_require__(233)['default'];
  45637. var Popup = __webpack_require__(104)['default'];
  45638. /**
  45639. * Handler for interactions
  45640. */
  45641. var InteractionHandler = function () {
  45642. /**
  45643. * @param {Object} body
  45644. * @param {Canvas} canvas
  45645. * @param {SelectionHandler} selectionHandler
  45646. */
  45647. function InteractionHandler(body, canvas, selectionHandler) {
  45648. (0, _classCallCheck3['default'])(this, InteractionHandler);
  45649. this.body = body;
  45650. this.canvas = canvas;
  45651. this.selectionHandler = selectionHandler;
  45652. this.navigationHandler = new NavigationHandler(body, canvas);
  45653. // bind the events from hammer to functions in this object
  45654. this.body.eventListeners.onTap = this.onTap.bind(this);
  45655. this.body.eventListeners.onTouch = this.onTouch.bind(this);
  45656. this.body.eventListeners.onDoubleTap = this.onDoubleTap.bind(this);
  45657. this.body.eventListeners.onHold = this.onHold.bind(this);
  45658. this.body.eventListeners.onDragStart = this.onDragStart.bind(this);
  45659. this.body.eventListeners.onDrag = this.onDrag.bind(this);
  45660. this.body.eventListeners.onDragEnd = this.onDragEnd.bind(this);
  45661. this.body.eventListeners.onMouseWheel = this.onMouseWheel.bind(this);
  45662. this.body.eventListeners.onPinch = this.onPinch.bind(this);
  45663. this.body.eventListeners.onMouseMove = this.onMouseMove.bind(this);
  45664. this.body.eventListeners.onRelease = this.onRelease.bind(this);
  45665. this.body.eventListeners.onContext = this.onContext.bind(this);
  45666. this.touchTime = 0;
  45667. this.drag = {};
  45668. this.pinch = {};
  45669. this.popup = undefined;
  45670. this.popupObj = undefined;
  45671. this.popupTimer = undefined;
  45672. this.body.functions.getPointer = this.getPointer.bind(this);
  45673. this.options = {};
  45674. this.defaultOptions = {
  45675. dragNodes: true,
  45676. dragView: true,
  45677. hover: false,
  45678. keyboard: {
  45679. enabled: false,
  45680. speed: { x: 10, y: 10, zoom: 0.02 },
  45681. bindToWindow: true
  45682. },
  45683. navigationButtons: false,
  45684. tooltipDelay: 300,
  45685. zoomView: true
  45686. };
  45687. util.extend(this.options, this.defaultOptions);
  45688. this.bindEventListeners();
  45689. }
  45690. /**
  45691. * Binds event listeners
  45692. */
  45693. (0, _createClass3['default'])(InteractionHandler, [{
  45694. key: 'bindEventListeners',
  45695. value: function bindEventListeners() {
  45696. var _this = this;
  45697. this.body.emitter.on('destroy', function () {
  45698. clearTimeout(_this.popupTimer);
  45699. delete _this.body.functions.getPointer;
  45700. });
  45701. }
  45702. /**
  45703. *
  45704. * @param {Object} options
  45705. */
  45706. }, {
  45707. key: 'setOptions',
  45708. value: function setOptions(options) {
  45709. if (options !== undefined) {
  45710. // extend all but the values in fields
  45711. var fields = ['hideEdgesOnDrag', 'hideNodesOnDrag', 'keyboard', 'multiselect', 'selectable', 'selectConnectedEdges'];
  45712. util.selectiveNotDeepExtend(fields, this.options, options);
  45713. // merge the keyboard options in.
  45714. util.mergeOptions(this.options, options, 'keyboard');
  45715. if (options.tooltip) {
  45716. util.extend(this.options.tooltip, options.tooltip);
  45717. if (options.tooltip.color) {
  45718. this.options.tooltip.color = util.parseColor(options.tooltip.color);
  45719. }
  45720. }
  45721. }
  45722. this.navigationHandler.setOptions(this.options);
  45723. }
  45724. /**
  45725. * Get the pointer location from a touch location
  45726. * @param {{x: number, y: number}} touch
  45727. * @return {{x: number, y: number}} pointer
  45728. * @private
  45729. */
  45730. }, {
  45731. key: 'getPointer',
  45732. value: function getPointer(touch) {
  45733. return {
  45734. x: touch.x - util.getAbsoluteLeft(this.canvas.frame.canvas),
  45735. y: touch.y - util.getAbsoluteTop(this.canvas.frame.canvas)
  45736. };
  45737. }
  45738. /**
  45739. * On start of a touch gesture, store the pointer
  45740. * @param {Event} event The event
  45741. * @private
  45742. */
  45743. }, {
  45744. key: 'onTouch',
  45745. value: function onTouch(event) {
  45746. if (new Date().valueOf() - this.touchTime > 50) {
  45747. this.drag.pointer = this.getPointer(event.center);
  45748. this.drag.pinched = false;
  45749. this.pinch.scale = this.body.view.scale;
  45750. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  45751. this.touchTime = new Date().valueOf();
  45752. }
  45753. }
  45754. /**
  45755. * handle tap/click event: select/unselect a node
  45756. * @param {Event} event
  45757. * @private
  45758. */
  45759. }, {
  45760. key: 'onTap',
  45761. value: function onTap(event) {
  45762. var pointer = this.getPointer(event.center);
  45763. var multiselect = this.selectionHandler.options.multiselect && (event.changedPointers[0].ctrlKey || event.changedPointers[0].metaKey);
  45764. this.checkSelectionChanges(pointer, event, multiselect);
  45765. this.selectionHandler._generateClickEvent('click', event, pointer);
  45766. }
  45767. /**
  45768. * handle doubletap event
  45769. * @param {Event} event
  45770. * @private
  45771. */
  45772. }, {
  45773. key: 'onDoubleTap',
  45774. value: function onDoubleTap(event) {
  45775. var pointer = this.getPointer(event.center);
  45776. this.selectionHandler._generateClickEvent('doubleClick', event, pointer);
  45777. }
  45778. /**
  45779. * handle long tap event: multi select nodes
  45780. * @param {Event} event
  45781. * @private
  45782. */
  45783. }, {
  45784. key: 'onHold',
  45785. value: function onHold(event) {
  45786. var pointer = this.getPointer(event.center);
  45787. var multiselect = this.selectionHandler.options.multiselect;
  45788. this.checkSelectionChanges(pointer, event, multiselect);
  45789. this.selectionHandler._generateClickEvent('click', event, pointer);
  45790. this.selectionHandler._generateClickEvent('hold', event, pointer);
  45791. }
  45792. /**
  45793. * handle the release of the screen
  45794. *
  45795. * @param {Event} event
  45796. * @private
  45797. */
  45798. }, {
  45799. key: 'onRelease',
  45800. value: function onRelease(event) {
  45801. if (new Date().valueOf() - this.touchTime > 10) {
  45802. var pointer = this.getPointer(event.center);
  45803. this.selectionHandler._generateClickEvent('release', event, pointer);
  45804. // to avoid double fireing of this event because we have two hammer instances. (on canvas and on frame)
  45805. this.touchTime = new Date().valueOf();
  45806. }
  45807. }
  45808. /**
  45809. *
  45810. * @param {Event} event
  45811. */
  45812. }, {
  45813. key: 'onContext',
  45814. value: function onContext(event) {
  45815. var pointer = this.getPointer({ x: event.clientX, y: event.clientY });
  45816. this.selectionHandler._generateClickEvent('oncontext', event, pointer);
  45817. }
  45818. /**
  45819. * Select and deselect nodes depending current selection change.
  45820. *
  45821. * For changing nodes, select/deselect events are fired.
  45822. *
  45823. * NOTE: For a given edge, if one connecting node is deselected and with the same
  45824. * click the other node is selected, no events for the edge will fire.
  45825. * It was selected and it will remain selected.
  45826. *
  45827. * TODO: This is all SelectionHandler calls; the method should be moved to there.
  45828. *
  45829. * @param {{x: number, y: number}} pointer
  45830. * @param {Event} event
  45831. * @param {boolean} [add=false]
  45832. */
  45833. }, {
  45834. key: 'checkSelectionChanges',
  45835. value: function checkSelectionChanges(pointer, event) {
  45836. var add = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  45837. var previousSelection = this.selectionHandler.getSelection();
  45838. var selected = false;
  45839. if (add === true) {
  45840. selected = this.selectionHandler.selectAdditionalOnPoint(pointer);
  45841. } else {
  45842. selected = this.selectionHandler.selectOnPoint(pointer);
  45843. }
  45844. var currentSelection = this.selectionHandler.getSelection();
  45845. // See NOTE in method comment for the reason to do it like this
  45846. var deselectedItems = this._determineDifference(previousSelection, currentSelection);
  45847. var selectedItems = this._determineDifference(currentSelection, previousSelection);
  45848. if (deselectedItems.edges.length > 0) {
  45849. this.selectionHandler._generateClickEvent('deselectEdge', event, pointer, previousSelection);
  45850. selected = true;
  45851. }
  45852. if (deselectedItems.nodes.length > 0) {
  45853. this.selectionHandler._generateClickEvent('deselectNode', event, pointer, previousSelection);
  45854. selected = true;
  45855. }
  45856. if (selectedItems.nodes.length > 0) {
  45857. this.selectionHandler._generateClickEvent('selectNode', event, pointer);
  45858. selected = true;
  45859. }
  45860. if (selectedItems.edges.length > 0) {
  45861. this.selectionHandler._generateClickEvent('selectEdge', event, pointer);
  45862. selected = true;
  45863. }
  45864. // fire the select event if anything has been selected or deselected
  45865. if (selected === true) {
  45866. // select or unselect
  45867. this.selectionHandler._generateClickEvent('select', event, pointer);
  45868. }
  45869. }
  45870. /**
  45871. * Remove all node and edge id's from the first set that are present in the second one.
  45872. *
  45873. * @param {{nodes: Array.<Node>, edges: Array.<vis.Edge>}} firstSet
  45874. * @param {{nodes: Array.<Node>, edges: Array.<vis.Edge>}} secondSet
  45875. * @returns {{nodes: Array.<Node>, edges: Array.<vis.Edge>}}
  45876. * @private
  45877. */
  45878. }, {
  45879. key: '_determineDifference',
  45880. value: function _determineDifference(firstSet, secondSet) {
  45881. var arrayDiff = function arrayDiff(firstArr, secondArr) {
  45882. var result = [];
  45883. for (var i = 0; i < firstArr.length; i++) {
  45884. var value = firstArr[i];
  45885. if (secondArr.indexOf(value) === -1) {
  45886. result.push(value);
  45887. }
  45888. }
  45889. return result;
  45890. };
  45891. return {
  45892. nodes: arrayDiff(firstSet.nodes, secondSet.nodes),
  45893. edges: arrayDiff(firstSet.edges, secondSet.edges)
  45894. };
  45895. }
  45896. /**
  45897. * This function is called by onDragStart.
  45898. * It is separated out because we can then overload it for the datamanipulation system.
  45899. *
  45900. * @param {Event} event
  45901. * @private
  45902. */
  45903. }, {
  45904. key: 'onDragStart',
  45905. value: function onDragStart(event) {
  45906. //in case the touch event was triggered on an external div, do the initial touch now.
  45907. if (this.drag.pointer === undefined) {
  45908. this.onTouch(event);
  45909. }
  45910. // note: drag.pointer is set in onTouch to get the initial touch location
  45911. var node = this.selectionHandler.getNodeAt(this.drag.pointer);
  45912. this.drag.dragging = true;
  45913. this.drag.selection = [];
  45914. this.drag.translation = util.extend({}, this.body.view.translation); // copy the object
  45915. this.drag.nodeId = undefined;
  45916. if (node !== undefined && this.options.dragNodes === true) {
  45917. this.drag.nodeId = node.id;
  45918. // select the clicked node if not yet selected
  45919. if (node.isSelected() === false) {
  45920. this.selectionHandler.unselectAll();
  45921. this.selectionHandler.selectObject(node);
  45922. }
  45923. // after select to contain the node
  45924. this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer);
  45925. var selection = this.selectionHandler.selectionObj.nodes;
  45926. // create an array with the selected nodes and their original location and status
  45927. for (var nodeId in selection) {
  45928. if (selection.hasOwnProperty(nodeId)) {
  45929. var object = selection[nodeId];
  45930. var s = {
  45931. id: object.id,
  45932. node: object,
  45933. // store original x, y, xFixed and yFixed, make the node temporarily Fixed
  45934. x: object.x,
  45935. y: object.y,
  45936. xFixed: object.options.fixed.x,
  45937. yFixed: object.options.fixed.y
  45938. };
  45939. object.options.fixed.x = true;
  45940. object.options.fixed.y = true;
  45941. this.drag.selection.push(s);
  45942. }
  45943. }
  45944. } else {
  45945. // fallback if no node is selected and thus the view is dragged.
  45946. this.selectionHandler._generateClickEvent('dragStart', event, this.drag.pointer, undefined, true);
  45947. }
  45948. }
  45949. /**
  45950. * handle drag event
  45951. * @param {Event} event
  45952. * @private
  45953. */
  45954. }, {
  45955. key: 'onDrag',
  45956. value: function onDrag(event) {
  45957. var _this2 = this;
  45958. if (this.drag.pinched === true) {
  45959. return;
  45960. }
  45961. // remove the focus on node if it is focussed on by the focusOnNode
  45962. this.body.emitter.emit('unlockNode');
  45963. var pointer = this.getPointer(event.center);
  45964. var selection = this.drag.selection;
  45965. if (selection && selection.length && this.options.dragNodes === true) {
  45966. this.selectionHandler._generateClickEvent('dragging', event, pointer);
  45967. // calculate delta's and new location
  45968. var deltaX = pointer.x - this.drag.pointer.x;
  45969. var deltaY = pointer.y - this.drag.pointer.y;
  45970. // update position of all selected nodes
  45971. selection.forEach(function (selection) {
  45972. var node = selection.node;
  45973. // only move the node if it was not fixed initially
  45974. if (selection.xFixed === false) {
  45975. node.x = _this2.canvas._XconvertDOMtoCanvas(_this2.canvas._XconvertCanvasToDOM(selection.x) + deltaX);
  45976. }
  45977. // only move the node if it was not fixed initially
  45978. if (selection.yFixed === false) {
  45979. node.y = _this2.canvas._YconvertDOMtoCanvas(_this2.canvas._YconvertCanvasToDOM(selection.y) + deltaY);
  45980. }
  45981. });
  45982. // start the simulation of the physics
  45983. this.body.emitter.emit('startSimulation');
  45984. } else {
  45985. // move the network
  45986. if (this.options.dragView === true) {
  45987. this.selectionHandler._generateClickEvent('dragging', event, pointer, undefined, true);
  45988. // if the drag was not started properly because the click started outside the network div, start it now.
  45989. if (this.drag.pointer === undefined) {
  45990. this.onDragStart(event);
  45991. return;
  45992. }
  45993. var diffX = pointer.x - this.drag.pointer.x;
  45994. var diffY = pointer.y - this.drag.pointer.y;
  45995. this.body.view.translation = { x: this.drag.translation.x + diffX, y: this.drag.translation.y + diffY };
  45996. this.body.emitter.emit('_requestRedraw');
  45997. }
  45998. }
  45999. }
  46000. /**
  46001. * handle drag start event
  46002. * @param {Event} event
  46003. * @private
  46004. */
  46005. }, {
  46006. key: 'onDragEnd',
  46007. value: function onDragEnd(event) {
  46008. this.drag.dragging = false;
  46009. var selection = this.drag.selection;
  46010. if (selection && selection.length) {
  46011. selection.forEach(function (s) {
  46012. // restore original xFixed and yFixed
  46013. s.node.options.fixed.x = s.xFixed;
  46014. s.node.options.fixed.y = s.yFixed;
  46015. });
  46016. this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center));
  46017. this.body.emitter.emit('startSimulation');
  46018. } else {
  46019. this.selectionHandler._generateClickEvent('dragEnd', event, this.getPointer(event.center), undefined, true);
  46020. this.body.emitter.emit('_requestRedraw');
  46021. }
  46022. }
  46023. /**
  46024. * Handle pinch event
  46025. * @param {Event} event The event
  46026. * @private
  46027. */
  46028. }, {
  46029. key: 'onPinch',
  46030. value: function onPinch(event) {
  46031. var pointer = this.getPointer(event.center);
  46032. this.drag.pinched = true;
  46033. if (this.pinch['scale'] === undefined) {
  46034. this.pinch.scale = 1;
  46035. }
  46036. // TODO: enabled moving while pinching?
  46037. var scale = this.pinch.scale * event.scale;
  46038. this.zoom(scale, pointer);
  46039. }
  46040. /**
  46041. * Zoom the network in or out
  46042. * @param {number} scale a number around 1, and between 0.01 and 10
  46043. * @param {{x: number, y: number}} pointer Position on screen
  46044. * @private
  46045. */
  46046. }, {
  46047. key: 'zoom',
  46048. value: function zoom(scale, pointer) {
  46049. if (this.options.zoomView === true) {
  46050. var scaleOld = this.body.view.scale;
  46051. if (scale < 0.00001) {
  46052. scale = 0.00001;
  46053. }
  46054. if (scale > 10) {
  46055. scale = 10;
  46056. }
  46057. var preScaleDragPointer = undefined;
  46058. if (this.drag !== undefined) {
  46059. if (this.drag.dragging === true) {
  46060. preScaleDragPointer = this.canvas.DOMtoCanvas(this.drag.pointer);
  46061. }
  46062. }
  46063. // + this.canvas.frame.canvas.clientHeight / 2
  46064. var translation = this.body.view.translation;
  46065. var scaleFrac = scale / scaleOld;
  46066. var tx = (1 - scaleFrac) * pointer.x + translation.x * scaleFrac;
  46067. var ty = (1 - scaleFrac) * pointer.y + translation.y * scaleFrac;
  46068. this.body.view.scale = scale;
  46069. this.body.view.translation = { x: tx, y: ty };
  46070. if (preScaleDragPointer != undefined) {
  46071. var postScaleDragPointer = this.canvas.canvasToDOM(preScaleDragPointer);
  46072. this.drag.pointer.x = postScaleDragPointer.x;
  46073. this.drag.pointer.y = postScaleDragPointer.y;
  46074. }
  46075. this.body.emitter.emit('_requestRedraw');
  46076. if (scaleOld < scale) {
  46077. this.body.emitter.emit('zoom', { direction: '+', scale: this.body.view.scale, pointer: pointer });
  46078. } else {
  46079. this.body.emitter.emit('zoom', { direction: '-', scale: this.body.view.scale, pointer: pointer });
  46080. }
  46081. }
  46082. }
  46083. /**
  46084. * Event handler for mouse wheel event, used to zoom the timeline
  46085. * See http://adomas.org/javascript-mouse-wheel/
  46086. * https://github.com/EightMedia/hammer.js/issues/256
  46087. * @param {MouseEvent} event
  46088. * @private
  46089. */
  46090. }, {
  46091. key: 'onMouseWheel',
  46092. value: function onMouseWheel(event) {
  46093. if (this.options.zoomView === true) {
  46094. // retrieve delta
  46095. var delta = 0;
  46096. if (event.wheelDelta) {
  46097. /* IE/Opera. */
  46098. delta = event.wheelDelta / 120;
  46099. } else if (event.detail) {
  46100. /* Mozilla case. */
  46101. // In Mozilla, sign of delta is different than in IE.
  46102. // Also, delta is multiple of 3.
  46103. delta = -event.detail / 3;
  46104. }
  46105. // If delta is nonzero, handle it.
  46106. // Basically, delta is now positive if wheel was scrolled up,
  46107. // and negative, if wheel was scrolled down.
  46108. if (delta !== 0) {
  46109. // calculate the new scale
  46110. var scale = this.body.view.scale;
  46111. var zoom = delta / 10;
  46112. if (delta < 0) {
  46113. zoom = zoom / (1 - zoom);
  46114. }
  46115. scale *= 1 + zoom;
  46116. // calculate the pointer location
  46117. var pointer = this.getPointer({ x: event.clientX, y: event.clientY });
  46118. // apply the new scale
  46119. this.zoom(scale, pointer);
  46120. }
  46121. // Prevent default actions caused by mouse wheel.
  46122. event.preventDefault();
  46123. }
  46124. }
  46125. /**
  46126. * Mouse move handler for checking whether the title moves over a node with a title.
  46127. * @param {Event} event
  46128. * @private
  46129. */
  46130. }, {
  46131. key: 'onMouseMove',
  46132. value: function onMouseMove(event) {
  46133. var _this3 = this;
  46134. var pointer = this.getPointer({ x: event.clientX, y: event.clientY });
  46135. var popupVisible = false;
  46136. // check if the previously selected node is still selected
  46137. if (this.popup !== undefined) {
  46138. if (this.popup.hidden === false) {
  46139. this._checkHidePopup(pointer);
  46140. }
  46141. // if the popup was not hidden above
  46142. if (this.popup.hidden === false) {
  46143. popupVisible = true;
  46144. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  46145. this.popup.show();
  46146. }
  46147. }
  46148. // if we bind the keyboard to the div, we have to highlight it to use it. This highlights it on mouse over.
  46149. if (this.options.keyboard.bindToWindow === false && this.options.keyboard.enabled === true) {
  46150. this.canvas.frame.focus();
  46151. }
  46152. // start a timeout that will check if the mouse is positioned above an element
  46153. if (popupVisible === false) {
  46154. if (this.popupTimer !== undefined) {
  46155. clearInterval(this.popupTimer); // stop any running calculationTimer
  46156. this.popupTimer = undefined;
  46157. }
  46158. if (!this.drag.dragging) {
  46159. this.popupTimer = setTimeout(function () {
  46160. return _this3._checkShowPopup(pointer);
  46161. }, this.options.tooltipDelay);
  46162. }
  46163. }
  46164. // adding hover highlights
  46165. if (this.options.hover === true) {
  46166. this.selectionHandler.hoverObject(event, pointer);
  46167. }
  46168. }
  46169. /**
  46170. * Check if there is an element on the given position in the network
  46171. * (a node or edge). If so, and if this element has a title,
  46172. * show a popup window with its title.
  46173. *
  46174. * @param {{x:number, y:number}} pointer
  46175. * @private
  46176. */
  46177. }, {
  46178. key: '_checkShowPopup',
  46179. value: function _checkShowPopup(pointer) {
  46180. var x = this.canvas._XconvertDOMtoCanvas(pointer.x);
  46181. var y = this.canvas._YconvertDOMtoCanvas(pointer.y);
  46182. var pointerObj = {
  46183. left: x,
  46184. top: y,
  46185. right: x,
  46186. bottom: y
  46187. };
  46188. var previousPopupObjId = this.popupObj === undefined ? undefined : this.popupObj.id;
  46189. var nodeUnderCursor = false;
  46190. var popupType = 'node';
  46191. // check if a node is under the cursor.
  46192. if (this.popupObj === undefined) {
  46193. // search the nodes for overlap, select the top one in case of multiple nodes
  46194. var nodeIndices = this.body.nodeIndices;
  46195. var nodes = this.body.nodes;
  46196. var node = void 0;
  46197. var overlappingNodes = [];
  46198. for (var i = 0; i < nodeIndices.length; i++) {
  46199. node = nodes[nodeIndices[i]];
  46200. if (node.isOverlappingWith(pointerObj) === true) {
  46201. if (node.getTitle() !== undefined) {
  46202. overlappingNodes.push(nodeIndices[i]);
  46203. }
  46204. }
  46205. }
  46206. if (overlappingNodes.length > 0) {
  46207. // if there are overlapping nodes, select the last one, this is the one which is drawn on top of the others
  46208. this.popupObj = nodes[overlappingNodes[overlappingNodes.length - 1]];
  46209. // if you hover over a node, the title of the edge is not supposed to be shown.
  46210. nodeUnderCursor = true;
  46211. }
  46212. }
  46213. if (this.popupObj === undefined && nodeUnderCursor === false) {
  46214. // search the edges for overlap
  46215. var edgeIndices = this.body.edgeIndices;
  46216. var edges = this.body.edges;
  46217. var edge = void 0;
  46218. var overlappingEdges = [];
  46219. for (var _i = 0; _i < edgeIndices.length; _i++) {
  46220. edge = edges[edgeIndices[_i]];
  46221. if (edge.isOverlappingWith(pointerObj) === true) {
  46222. if (edge.connected === true && edge.getTitle() !== undefined) {
  46223. overlappingEdges.push(edgeIndices[_i]);
  46224. }
  46225. }
  46226. }
  46227. if (overlappingEdges.length > 0) {
  46228. this.popupObj = edges[overlappingEdges[overlappingEdges.length - 1]];
  46229. popupType = 'edge';
  46230. }
  46231. }
  46232. if (this.popupObj !== undefined) {
  46233. // show popup message window
  46234. if (this.popupObj.id !== previousPopupObjId) {
  46235. if (this.popup === undefined) {
  46236. this.popup = new Popup(this.canvas.frame);
  46237. }
  46238. this.popup.popupTargetType = popupType;
  46239. this.popup.popupTargetId = this.popupObj.id;
  46240. // adjust a small offset such that the mouse cursor is located in the
  46241. // bottom left location of the popup, and you can easily move over the
  46242. // popup area
  46243. this.popup.setPosition(pointer.x + 3, pointer.y - 5);
  46244. this.popup.setText(this.popupObj.getTitle());
  46245. this.popup.show();
  46246. this.body.emitter.emit('showPopup', this.popupObj.id);
  46247. }
  46248. } else {
  46249. if (this.popup !== undefined) {
  46250. this.popup.hide();
  46251. this.body.emitter.emit('hidePopup');
  46252. }
  46253. }
  46254. }
  46255. /**
  46256. * Check if the popup must be hidden, which is the case when the mouse is no
  46257. * longer hovering on the object
  46258. * @param {{x:number, y:number}} pointer
  46259. * @private
  46260. */
  46261. }, {
  46262. key: '_checkHidePopup',
  46263. value: function _checkHidePopup(pointer) {
  46264. var pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  46265. var stillOnObj = false;
  46266. if (this.popup.popupTargetType === 'node') {
  46267. if (this.body.nodes[this.popup.popupTargetId] !== undefined) {
  46268. stillOnObj = this.body.nodes[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  46269. // 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.
  46270. // we initially only check stillOnObj because this is much faster.
  46271. if (stillOnObj === true) {
  46272. var overNode = this.selectionHandler.getNodeAt(pointer);
  46273. stillOnObj = overNode === undefined ? false : overNode.id === this.popup.popupTargetId;
  46274. }
  46275. }
  46276. } else {
  46277. if (this.selectionHandler.getNodeAt(pointer) === undefined) {
  46278. if (this.body.edges[this.popup.popupTargetId] !== undefined) {
  46279. stillOnObj = this.body.edges[this.popup.popupTargetId].isOverlappingWith(pointerObj);
  46280. }
  46281. }
  46282. }
  46283. if (stillOnObj === false) {
  46284. this.popupObj = undefined;
  46285. this.popup.hide();
  46286. this.body.emitter.emit('hidePopup');
  46287. }
  46288. }
  46289. }]);
  46290. return InteractionHandler;
  46291. }();
  46292. exports['default'] = InteractionHandler;
  46293. /***/ }),
  46294. /* 233 */
  46295. /***/ (function(module, exports, __webpack_require__) {
  46296. "use strict";
  46297. Object.defineProperty(exports, "__esModule", {
  46298. value: true
  46299. });
  46300. var _classCallCheck2 = __webpack_require__(0);
  46301. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  46302. var _createClass2 = __webpack_require__(1);
  46303. var _createClass3 = _interopRequireDefault(_createClass2);
  46304. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  46305. var Hammer = __webpack_require__(10);
  46306. var hammerUtil = __webpack_require__(37);
  46307. var keycharm = __webpack_require__(35);
  46308. /**
  46309. * Navigation Handler
  46310. */
  46311. var NavigationHandler = function () {
  46312. /**
  46313. * @param {Object} body
  46314. * @param {Canvas} canvas
  46315. */
  46316. function NavigationHandler(body, canvas) {
  46317. var _this = this;
  46318. (0, _classCallCheck3['default'])(this, NavigationHandler);
  46319. this.body = body;
  46320. this.canvas = canvas;
  46321. this.iconsCreated = false;
  46322. this.navigationHammers = [];
  46323. this.boundFunctions = {};
  46324. this.touchTime = 0;
  46325. this.activated = false;
  46326. this.body.emitter.on("activate", function () {
  46327. _this.activated = true;_this.configureKeyboardBindings();
  46328. });
  46329. this.body.emitter.on("deactivate", function () {
  46330. _this.activated = false;_this.configureKeyboardBindings();
  46331. });
  46332. this.body.emitter.on("destroy", function () {
  46333. if (_this.keycharm !== undefined) {
  46334. _this.keycharm.destroy();
  46335. }
  46336. });
  46337. this.options = {};
  46338. }
  46339. /**
  46340. *
  46341. * @param {Object} options
  46342. */
  46343. (0, _createClass3['default'])(NavigationHandler, [{
  46344. key: 'setOptions',
  46345. value: function setOptions(options) {
  46346. if (options !== undefined) {
  46347. this.options = options;
  46348. this.create();
  46349. }
  46350. }
  46351. /**
  46352. * Creates or refreshes navigation and sets key bindings
  46353. */
  46354. }, {
  46355. key: 'create',
  46356. value: function create() {
  46357. if (this.options.navigationButtons === true) {
  46358. if (this.iconsCreated === false) {
  46359. this.loadNavigationElements();
  46360. }
  46361. } else if (this.iconsCreated === true) {
  46362. this.cleanNavigation();
  46363. }
  46364. this.configureKeyboardBindings();
  46365. }
  46366. /**
  46367. * Cleans up previous navigation items
  46368. */
  46369. }, {
  46370. key: 'cleanNavigation',
  46371. value: function cleanNavigation() {
  46372. // clean hammer bindings
  46373. if (this.navigationHammers.length != 0) {
  46374. for (var i = 0; i < this.navigationHammers.length; i++) {
  46375. this.navigationHammers[i].destroy();
  46376. }
  46377. this.navigationHammers = [];
  46378. }
  46379. // clean up previous navigation items
  46380. if (this.navigationDOM && this.navigationDOM['wrapper'] && this.navigationDOM['wrapper'].parentNode) {
  46381. this.navigationDOM['wrapper'].parentNode.removeChild(this.navigationDOM['wrapper']);
  46382. }
  46383. this.iconsCreated = false;
  46384. }
  46385. /**
  46386. * Creation of the navigation controls nodes. They are drawn over the rest of the nodes and are not affected by scale and translation
  46387. * they have a triggerFunction which is called on click. If the position of the navigation controls is dependent
  46388. * on this.frame.canvas.clientWidth or this.frame.canvas.clientHeight, we flag horizontalAlignLeft and verticalAlignTop false.
  46389. * This means that the location will be corrected by the _relocateNavigation function on a size change of the canvas.
  46390. *
  46391. * @private
  46392. */
  46393. }, {
  46394. key: 'loadNavigationElements',
  46395. value: function loadNavigationElements() {
  46396. var _this2 = this;
  46397. this.cleanNavigation();
  46398. this.navigationDOM = {};
  46399. var navigationDivs = ['up', 'down', 'left', 'right', 'zoomIn', 'zoomOut', 'zoomExtends'];
  46400. var navigationDivActions = ['_moveUp', '_moveDown', '_moveLeft', '_moveRight', '_zoomIn', '_zoomOut', '_fit'];
  46401. this.navigationDOM['wrapper'] = document.createElement('div');
  46402. this.navigationDOM['wrapper'].className = 'vis-navigation';
  46403. this.canvas.frame.appendChild(this.navigationDOM['wrapper']);
  46404. for (var i = 0; i < navigationDivs.length; i++) {
  46405. this.navigationDOM[navigationDivs[i]] = document.createElement('div');
  46406. this.navigationDOM[navigationDivs[i]].className = 'vis-button vis-' + navigationDivs[i];
  46407. this.navigationDOM['wrapper'].appendChild(this.navigationDOM[navigationDivs[i]]);
  46408. var hammer = new Hammer(this.navigationDOM[navigationDivs[i]]);
  46409. if (navigationDivActions[i] === "_fit") {
  46410. hammerUtil.onTouch(hammer, this._fit.bind(this));
  46411. } else {
  46412. hammerUtil.onTouch(hammer, this.bindToRedraw.bind(this, navigationDivActions[i]));
  46413. }
  46414. this.navigationHammers.push(hammer);
  46415. }
  46416. // use a hammer for the release so we do not require the one used in the rest of the network
  46417. // the one the rest uses can be overloaded by the manipulation system.
  46418. var hammerFrame = new Hammer(this.canvas.frame);
  46419. hammerUtil.onRelease(hammerFrame, function () {
  46420. _this2._stopMovement();
  46421. });
  46422. this.navigationHammers.push(hammerFrame);
  46423. this.iconsCreated = true;
  46424. }
  46425. /**
  46426. *
  46427. * @param {string} action
  46428. */
  46429. }, {
  46430. key: 'bindToRedraw',
  46431. value: function bindToRedraw(action) {
  46432. if (this.boundFunctions[action] === undefined) {
  46433. this.boundFunctions[action] = this[action].bind(this);
  46434. this.body.emitter.on("initRedraw", this.boundFunctions[action]);
  46435. this.body.emitter.emit("_startRendering");
  46436. }
  46437. }
  46438. /**
  46439. *
  46440. * @param {string} action
  46441. */
  46442. }, {
  46443. key: 'unbindFromRedraw',
  46444. value: function unbindFromRedraw(action) {
  46445. if (this.boundFunctions[action] !== undefined) {
  46446. this.body.emitter.off("initRedraw", this.boundFunctions[action]);
  46447. this.body.emitter.emit("_stopRendering");
  46448. delete this.boundFunctions[action];
  46449. }
  46450. }
  46451. /**
  46452. * this stops all movement induced by the navigation buttons
  46453. *
  46454. * @private
  46455. */
  46456. }, {
  46457. key: '_fit',
  46458. value: function _fit() {
  46459. if (new Date().valueOf() - this.touchTime > 700) {
  46460. // TODO: fix ugly hack to avoid hammer's double fireing of event (because we use release?)
  46461. this.body.emitter.emit("fit", { duration: 700 });
  46462. this.touchTime = new Date().valueOf();
  46463. }
  46464. }
  46465. /**
  46466. * this stops all movement induced by the navigation buttons
  46467. *
  46468. * @private
  46469. */
  46470. }, {
  46471. key: '_stopMovement',
  46472. value: function _stopMovement() {
  46473. for (var boundAction in this.boundFunctions) {
  46474. if (this.boundFunctions.hasOwnProperty(boundAction)) {
  46475. this.body.emitter.off("initRedraw", this.boundFunctions[boundAction]);
  46476. this.body.emitter.emit("_stopRendering");
  46477. }
  46478. }
  46479. this.boundFunctions = {};
  46480. }
  46481. /**
  46482. *
  46483. * @private
  46484. */
  46485. }, {
  46486. key: '_moveUp',
  46487. value: function _moveUp() {
  46488. this.body.view.translation.y += this.options.keyboard.speed.y;
  46489. }
  46490. /**
  46491. *
  46492. * @private
  46493. */
  46494. }, {
  46495. key: '_moveDown',
  46496. value: function _moveDown() {
  46497. this.body.view.translation.y -= this.options.keyboard.speed.y;
  46498. }
  46499. /**
  46500. *
  46501. * @private
  46502. */
  46503. }, {
  46504. key: '_moveLeft',
  46505. value: function _moveLeft() {
  46506. this.body.view.translation.x += this.options.keyboard.speed.x;
  46507. }
  46508. /**
  46509. *
  46510. * @private
  46511. */
  46512. }, {
  46513. key: '_moveRight',
  46514. value: function _moveRight() {
  46515. this.body.view.translation.x -= this.options.keyboard.speed.x;
  46516. }
  46517. /**
  46518. *
  46519. * @private
  46520. */
  46521. }, {
  46522. key: '_zoomIn',
  46523. value: function _zoomIn() {
  46524. var scaleOld = this.body.view.scale;
  46525. var scale = this.body.view.scale * (1 + this.options.keyboard.speed.zoom);
  46526. var translation = this.body.view.translation;
  46527. var scaleFrac = scale / scaleOld;
  46528. var tx = (1 - scaleFrac) * this.canvas.canvasViewCenter.x + translation.x * scaleFrac;
  46529. var ty = (1 - scaleFrac) * this.canvas.canvasViewCenter.y + translation.y * scaleFrac;
  46530. this.body.view.scale = scale;
  46531. this.body.view.translation = { x: tx, y: ty };
  46532. this.body.emitter.emit('zoom', { direction: '+', scale: this.body.view.scale, pointer: null });
  46533. }
  46534. /**
  46535. *
  46536. * @private
  46537. */
  46538. }, {
  46539. key: '_zoomOut',
  46540. value: function _zoomOut() {
  46541. var scaleOld = this.body.view.scale;
  46542. var scale = this.body.view.scale / (1 + this.options.keyboard.speed.zoom);
  46543. var translation = this.body.view.translation;
  46544. var scaleFrac = scale / scaleOld;
  46545. var tx = (1 - scaleFrac) * this.canvas.canvasViewCenter.x + translation.x * scaleFrac;
  46546. var ty = (1 - scaleFrac) * this.canvas.canvasViewCenter.y + translation.y * scaleFrac;
  46547. this.body.view.scale = scale;
  46548. this.body.view.translation = { x: tx, y: ty };
  46549. this.body.emitter.emit('zoom', { direction: '-', scale: this.body.view.scale, pointer: null });
  46550. }
  46551. /**
  46552. * bind all keys using keycharm.
  46553. */
  46554. }, {
  46555. key: 'configureKeyboardBindings',
  46556. value: function configureKeyboardBindings() {
  46557. var _this3 = this;
  46558. if (this.keycharm !== undefined) {
  46559. this.keycharm.destroy();
  46560. }
  46561. if (this.options.keyboard.enabled === true) {
  46562. if (this.options.keyboard.bindToWindow === true) {
  46563. this.keycharm = keycharm({ container: window, preventDefault: true });
  46564. } else {
  46565. this.keycharm = keycharm({ container: this.canvas.frame, preventDefault: true });
  46566. }
  46567. this.keycharm.reset();
  46568. if (this.activated === true) {
  46569. this.keycharm.bind("up", function () {
  46570. _this3.bindToRedraw("_moveUp");
  46571. }, "keydown");
  46572. this.keycharm.bind("down", function () {
  46573. _this3.bindToRedraw("_moveDown");
  46574. }, "keydown");
  46575. this.keycharm.bind("left", function () {
  46576. _this3.bindToRedraw("_moveLeft");
  46577. }, "keydown");
  46578. this.keycharm.bind("right", function () {
  46579. _this3.bindToRedraw("_moveRight");
  46580. }, "keydown");
  46581. this.keycharm.bind("=", function () {
  46582. _this3.bindToRedraw("_zoomIn");
  46583. }, "keydown");
  46584. this.keycharm.bind("num+", function () {
  46585. _this3.bindToRedraw("_zoomIn");
  46586. }, "keydown");
  46587. this.keycharm.bind("num-", function () {
  46588. _this3.bindToRedraw("_zoomOut");
  46589. }, "keydown");
  46590. this.keycharm.bind("-", function () {
  46591. _this3.bindToRedraw("_zoomOut");
  46592. }, "keydown");
  46593. this.keycharm.bind("[", function () {
  46594. _this3.bindToRedraw("_zoomOut");
  46595. }, "keydown");
  46596. this.keycharm.bind("]", function () {
  46597. _this3.bindToRedraw("_zoomIn");
  46598. }, "keydown");
  46599. this.keycharm.bind("pageup", function () {
  46600. _this3.bindToRedraw("_zoomIn");
  46601. }, "keydown");
  46602. this.keycharm.bind("pagedown", function () {
  46603. _this3.bindToRedraw("_zoomOut");
  46604. }, "keydown");
  46605. this.keycharm.bind("up", function () {
  46606. _this3.unbindFromRedraw("_moveUp");
  46607. }, "keyup");
  46608. this.keycharm.bind("down", function () {
  46609. _this3.unbindFromRedraw("_moveDown");
  46610. }, "keyup");
  46611. this.keycharm.bind("left", function () {
  46612. _this3.unbindFromRedraw("_moveLeft");
  46613. }, "keyup");
  46614. this.keycharm.bind("right", function () {
  46615. _this3.unbindFromRedraw("_moveRight");
  46616. }, "keyup");
  46617. this.keycharm.bind("=", function () {
  46618. _this3.unbindFromRedraw("_zoomIn");
  46619. }, "keyup");
  46620. this.keycharm.bind("num+", function () {
  46621. _this3.unbindFromRedraw("_zoomIn");
  46622. }, "keyup");
  46623. this.keycharm.bind("num-", function () {
  46624. _this3.unbindFromRedraw("_zoomOut");
  46625. }, "keyup");
  46626. this.keycharm.bind("-", function () {
  46627. _this3.unbindFromRedraw("_zoomOut");
  46628. }, "keyup");
  46629. this.keycharm.bind("[", function () {
  46630. _this3.unbindFromRedraw("_zoomOut");
  46631. }, "keyup");
  46632. this.keycharm.bind("]", function () {
  46633. _this3.unbindFromRedraw("_zoomIn");
  46634. }, "keyup");
  46635. this.keycharm.bind("pageup", function () {
  46636. _this3.unbindFromRedraw("_zoomIn");
  46637. }, "keyup");
  46638. this.keycharm.bind("pagedown", function () {
  46639. _this3.unbindFromRedraw("_zoomOut");
  46640. }, "keyup");
  46641. }
  46642. }
  46643. }
  46644. }]);
  46645. return NavigationHandler;
  46646. }();
  46647. exports['default'] = NavigationHandler;
  46648. /***/ }),
  46649. /* 234 */
  46650. /***/ (function(module, exports, __webpack_require__) {
  46651. "use strict";
  46652. Object.defineProperty(exports, "__esModule", {
  46653. value: true
  46654. });
  46655. var _classCallCheck2 = __webpack_require__(0);
  46656. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  46657. var _createClass2 = __webpack_require__(1);
  46658. var _createClass3 = _interopRequireDefault(_createClass2);
  46659. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  46660. var Node = __webpack_require__(47)['default'];
  46661. var Edge = __webpack_require__(74)['default'];
  46662. var util = __webpack_require__(2);
  46663. /**
  46664. * The handler for selections
  46665. */
  46666. var SelectionHandler = function () {
  46667. /**
  46668. * @param {Object} body
  46669. * @param {Canvas} canvas
  46670. */
  46671. function SelectionHandler(body, canvas) {
  46672. var _this = this;
  46673. (0, _classCallCheck3['default'])(this, SelectionHandler);
  46674. this.body = body;
  46675. this.canvas = canvas;
  46676. this.selectionObj = { nodes: [], edges: [] };
  46677. this.hoverObj = { nodes: {}, edges: {} };
  46678. this.options = {};
  46679. this.defaultOptions = {
  46680. multiselect: false,
  46681. selectable: true,
  46682. selectConnectedEdges: true,
  46683. hoverConnectedEdges: true
  46684. };
  46685. util.extend(this.options, this.defaultOptions);
  46686. this.body.emitter.on("_dataChanged", function () {
  46687. _this.updateSelection();
  46688. });
  46689. }
  46690. /**
  46691. *
  46692. * @param {Object} [options]
  46693. */
  46694. (0, _createClass3['default'])(SelectionHandler, [{
  46695. key: 'setOptions',
  46696. value: function setOptions(options) {
  46697. if (options !== undefined) {
  46698. var fields = ['multiselect', 'hoverConnectedEdges', 'selectable', 'selectConnectedEdges'];
  46699. util.selectiveDeepExtend(fields, this.options, options);
  46700. }
  46701. }
  46702. /**
  46703. * handles the selection part of the tap;
  46704. *
  46705. * @param {{x: number, y: number}} pointer
  46706. * @returns {boolean}
  46707. */
  46708. }, {
  46709. key: 'selectOnPoint',
  46710. value: function selectOnPoint(pointer) {
  46711. var selected = false;
  46712. if (this.options.selectable === true) {
  46713. var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer);
  46714. // unselect after getting the objects in order to restore width and height.
  46715. this.unselectAll();
  46716. if (obj !== undefined) {
  46717. selected = this.selectObject(obj);
  46718. }
  46719. this.body.emitter.emit("_requestRedraw");
  46720. }
  46721. return selected;
  46722. }
  46723. /**
  46724. *
  46725. * @param {{x: number, y: number}} pointer
  46726. * @returns {boolean}
  46727. */
  46728. }, {
  46729. key: 'selectAdditionalOnPoint',
  46730. value: function selectAdditionalOnPoint(pointer) {
  46731. var selectionChanged = false;
  46732. if (this.options.selectable === true) {
  46733. var obj = this.getNodeAt(pointer) || this.getEdgeAt(pointer);
  46734. if (obj !== undefined) {
  46735. selectionChanged = true;
  46736. if (obj.isSelected() === true) {
  46737. this.deselectObject(obj);
  46738. } else {
  46739. this.selectObject(obj);
  46740. }
  46741. this.body.emitter.emit("_requestRedraw");
  46742. }
  46743. }
  46744. return selectionChanged;
  46745. }
  46746. /**
  46747. * Create an object containing the standard fields for an event.
  46748. *
  46749. * @param {Event} event
  46750. * @param {{x: number, y: number}} pointer Object with the x and y screen coordinates of the mouse
  46751. * @returns {{}}
  46752. * @private
  46753. */
  46754. }, {
  46755. key: '_initBaseEvent',
  46756. value: function _initBaseEvent(event, pointer) {
  46757. var properties = {};
  46758. properties['pointer'] = {
  46759. DOM: { x: pointer.x, y: pointer.y },
  46760. canvas: this.canvas.DOMtoCanvas(pointer)
  46761. };
  46762. properties['event'] = event;
  46763. return properties;
  46764. }
  46765. /**
  46766. * Generate an event which the user can catch.
  46767. *
  46768. * This adds some extra data to the event with respect to cursor position and
  46769. * selected nodes and edges.
  46770. *
  46771. * @param {string} eventType Name of event to send
  46772. * @param {Event} event
  46773. * @param {{x: number, y: number}} pointer Object with the x and y screen coordinates of the mouse
  46774. * @param {Object|undefined} oldSelection If present, selection state before event occured
  46775. * @param {boolean|undefined} [emptySelection=false] Indicate if selection data should be passed
  46776. */
  46777. }, {
  46778. key: '_generateClickEvent',
  46779. value: function _generateClickEvent(eventType, event, pointer, oldSelection) {
  46780. var emptySelection = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  46781. var properties = this._initBaseEvent(event, pointer);
  46782. if (emptySelection === true) {
  46783. properties.nodes = [];
  46784. properties.edges = [];
  46785. } else {
  46786. var tmp = this.getSelection();
  46787. properties.nodes = tmp.nodes;
  46788. properties.edges = tmp.edges;
  46789. }
  46790. if (oldSelection !== undefined) {
  46791. properties['previousSelection'] = oldSelection;
  46792. }
  46793. if (eventType == 'click') {
  46794. // For the time being, restrict this functionality to
  46795. // just the click event.
  46796. properties.items = this.getClickedItems(pointer);
  46797. }
  46798. this.body.emitter.emit(eventType, properties);
  46799. }
  46800. /**
  46801. *
  46802. * @param {Object} obj
  46803. * @param {boolean} [highlightEdges=this.options.selectConnectedEdges]
  46804. * @returns {boolean}
  46805. */
  46806. }, {
  46807. key: 'selectObject',
  46808. value: function selectObject(obj) {
  46809. var highlightEdges = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.options.selectConnectedEdges;
  46810. if (obj !== undefined) {
  46811. if (obj instanceof Node) {
  46812. if (highlightEdges === true) {
  46813. this._selectConnectedEdges(obj);
  46814. }
  46815. }
  46816. obj.select();
  46817. this._addToSelection(obj);
  46818. return true;
  46819. }
  46820. return false;
  46821. }
  46822. /**
  46823. *
  46824. * @param {Object} obj
  46825. */
  46826. }, {
  46827. key: 'deselectObject',
  46828. value: function deselectObject(obj) {
  46829. if (obj.isSelected() === true) {
  46830. obj.selected = false;
  46831. this._removeFromSelection(obj);
  46832. }
  46833. }
  46834. /**
  46835. * retrieve all nodes overlapping with given object
  46836. * @param {Object} object An object with parameters left, top, right, bottom
  46837. * @return {number[]} An array with id's of the overlapping nodes
  46838. * @private
  46839. */
  46840. }, {
  46841. key: '_getAllNodesOverlappingWith',
  46842. value: function _getAllNodesOverlappingWith(object) {
  46843. var overlappingNodes = [];
  46844. var nodes = this.body.nodes;
  46845. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  46846. var nodeId = this.body.nodeIndices[i];
  46847. if (nodes[nodeId].isOverlappingWith(object)) {
  46848. overlappingNodes.push(nodeId);
  46849. }
  46850. }
  46851. return overlappingNodes;
  46852. }
  46853. /**
  46854. * Return a position object in canvasspace from a single point in screenspace
  46855. *
  46856. * @param {{x: number, y: number}} pointer
  46857. * @returns {{left: number, top: number, right: number, bottom: number}}
  46858. * @private
  46859. */
  46860. }, {
  46861. key: '_pointerToPositionObject',
  46862. value: function _pointerToPositionObject(pointer) {
  46863. var canvasPos = this.canvas.DOMtoCanvas(pointer);
  46864. return {
  46865. left: canvasPos.x - 1,
  46866. top: canvasPos.y + 1,
  46867. right: canvasPos.x + 1,
  46868. bottom: canvasPos.y - 1
  46869. };
  46870. }
  46871. /**
  46872. * Get the top node at the passed point (like a click)
  46873. *
  46874. * @param {{x: number, y: number}} pointer
  46875. * @param {boolean} [returnNode=true]
  46876. * @return {Node | undefined} node
  46877. */
  46878. }, {
  46879. key: 'getNodeAt',
  46880. value: function getNodeAt(pointer) {
  46881. var returnNode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  46882. // we first check if this is an navigation controls element
  46883. var positionObject = this._pointerToPositionObject(pointer);
  46884. var overlappingNodes = this._getAllNodesOverlappingWith(positionObject);
  46885. // if there are overlapping nodes, select the last one, this is the
  46886. // one which is drawn on top of the others
  46887. if (overlappingNodes.length > 0) {
  46888. if (returnNode === true) {
  46889. return this.body.nodes[overlappingNodes[overlappingNodes.length - 1]];
  46890. } else {
  46891. return overlappingNodes[overlappingNodes.length - 1];
  46892. }
  46893. } else {
  46894. return undefined;
  46895. }
  46896. }
  46897. /**
  46898. * retrieve all edges overlapping with given object, selector is around center
  46899. * @param {Object} object An object with parameters left, top, right, bottom
  46900. * @param {number[]} overlappingEdges An array with id's of the overlapping nodes
  46901. * @private
  46902. */
  46903. }, {
  46904. key: '_getEdgesOverlappingWith',
  46905. value: function _getEdgesOverlappingWith(object, overlappingEdges) {
  46906. var edges = this.body.edges;
  46907. for (var i = 0; i < this.body.edgeIndices.length; i++) {
  46908. var edgeId = this.body.edgeIndices[i];
  46909. if (edges[edgeId].isOverlappingWith(object)) {
  46910. overlappingEdges.push(edgeId);
  46911. }
  46912. }
  46913. }
  46914. /**
  46915. * retrieve all nodes overlapping with given object
  46916. * @param {Object} object An object with parameters left, top, right, bottom
  46917. * @return {number[]} An array with id's of the overlapping nodes
  46918. * @private
  46919. */
  46920. }, {
  46921. key: '_getAllEdgesOverlappingWith',
  46922. value: function _getAllEdgesOverlappingWith(object) {
  46923. var overlappingEdges = [];
  46924. this._getEdgesOverlappingWith(object, overlappingEdges);
  46925. return overlappingEdges;
  46926. }
  46927. /**
  46928. * Get the edges nearest to the passed point (like a click)
  46929. *
  46930. * @param {{x: number, y: number}} pointer
  46931. * @param {boolean} [returnEdge=true]
  46932. * @return {Edge | undefined} node
  46933. */
  46934. }, {
  46935. key: 'getEdgeAt',
  46936. value: function getEdgeAt(pointer) {
  46937. var returnEdge = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  46938. // Iterate over edges, pick closest within 10
  46939. var canvasPos = this.canvas.DOMtoCanvas(pointer);
  46940. var mindist = 10;
  46941. var overlappingEdge = null;
  46942. var edges = this.body.edges;
  46943. for (var i = 0; i < this.body.edgeIndices.length; i++) {
  46944. var edgeId = this.body.edgeIndices[i];
  46945. var edge = edges[edgeId];
  46946. if (edge.connected) {
  46947. var xFrom = edge.from.x;
  46948. var yFrom = edge.from.y;
  46949. var xTo = edge.to.x;
  46950. var yTo = edge.to.y;
  46951. var dist = edge.edgeType.getDistanceToEdge(xFrom, yFrom, xTo, yTo, canvasPos.x, canvasPos.y);
  46952. if (dist < mindist) {
  46953. overlappingEdge = edgeId;
  46954. mindist = dist;
  46955. }
  46956. }
  46957. }
  46958. if (overlappingEdge !== null) {
  46959. if (returnEdge === true) {
  46960. return this.body.edges[overlappingEdge];
  46961. } else {
  46962. return overlappingEdge;
  46963. }
  46964. } else {
  46965. return undefined;
  46966. }
  46967. }
  46968. /**
  46969. * Add object to the selection array.
  46970. *
  46971. * @param {Object} obj
  46972. * @private
  46973. */
  46974. }, {
  46975. key: '_addToSelection',
  46976. value: function _addToSelection(obj) {
  46977. if (obj instanceof Node) {
  46978. this.selectionObj.nodes[obj.id] = obj;
  46979. } else {
  46980. this.selectionObj.edges[obj.id] = obj;
  46981. }
  46982. }
  46983. /**
  46984. * Add object to the selection array.
  46985. *
  46986. * @param {Object} obj
  46987. * @private
  46988. */
  46989. }, {
  46990. key: '_addToHover',
  46991. value: function _addToHover(obj) {
  46992. if (obj instanceof Node) {
  46993. this.hoverObj.nodes[obj.id] = obj;
  46994. } else {
  46995. this.hoverObj.edges[obj.id] = obj;
  46996. }
  46997. }
  46998. /**
  46999. * Remove a single option from selection.
  47000. *
  47001. * @param {Object} obj
  47002. * @private
  47003. */
  47004. }, {
  47005. key: '_removeFromSelection',
  47006. value: function _removeFromSelection(obj) {
  47007. if (obj instanceof Node) {
  47008. delete this.selectionObj.nodes[obj.id];
  47009. this._unselectConnectedEdges(obj);
  47010. } else {
  47011. delete this.selectionObj.edges[obj.id];
  47012. }
  47013. }
  47014. /**
  47015. * Unselect all. The selectionObj is useful for this.
  47016. */
  47017. }, {
  47018. key: 'unselectAll',
  47019. value: function unselectAll() {
  47020. for (var nodeId in this.selectionObj.nodes) {
  47021. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  47022. this.selectionObj.nodes[nodeId].unselect();
  47023. }
  47024. }
  47025. for (var edgeId in this.selectionObj.edges) {
  47026. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  47027. this.selectionObj.edges[edgeId].unselect();
  47028. }
  47029. }
  47030. this.selectionObj = { nodes: {}, edges: {} };
  47031. }
  47032. /**
  47033. * return the number of selected nodes
  47034. *
  47035. * @returns {number}
  47036. * @private
  47037. */
  47038. }, {
  47039. key: '_getSelectedNodeCount',
  47040. value: function _getSelectedNodeCount() {
  47041. var count = 0;
  47042. for (var nodeId in this.selectionObj.nodes) {
  47043. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  47044. count += 1;
  47045. }
  47046. }
  47047. return count;
  47048. }
  47049. /**
  47050. * return the selected node
  47051. *
  47052. * @returns {number}
  47053. * @private
  47054. */
  47055. }, {
  47056. key: '_getSelectedNode',
  47057. value: function _getSelectedNode() {
  47058. for (var nodeId in this.selectionObj.nodes) {
  47059. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  47060. return this.selectionObj.nodes[nodeId];
  47061. }
  47062. }
  47063. return undefined;
  47064. }
  47065. /**
  47066. * return the selected edge
  47067. *
  47068. * @returns {number}
  47069. * @private
  47070. */
  47071. }, {
  47072. key: '_getSelectedEdge',
  47073. value: function _getSelectedEdge() {
  47074. for (var edgeId in this.selectionObj.edges) {
  47075. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  47076. return this.selectionObj.edges[edgeId];
  47077. }
  47078. }
  47079. return undefined;
  47080. }
  47081. /**
  47082. * return the number of selected edges
  47083. *
  47084. * @returns {number}
  47085. * @private
  47086. */
  47087. }, {
  47088. key: '_getSelectedEdgeCount',
  47089. value: function _getSelectedEdgeCount() {
  47090. var count = 0;
  47091. for (var edgeId in this.selectionObj.edges) {
  47092. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  47093. count += 1;
  47094. }
  47095. }
  47096. return count;
  47097. }
  47098. /**
  47099. * return the number of selected objects.
  47100. *
  47101. * @returns {number}
  47102. * @private
  47103. */
  47104. }, {
  47105. key: '_getSelectedObjectCount',
  47106. value: function _getSelectedObjectCount() {
  47107. var count = 0;
  47108. for (var nodeId in this.selectionObj.nodes) {
  47109. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  47110. count += 1;
  47111. }
  47112. }
  47113. for (var edgeId in this.selectionObj.edges) {
  47114. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  47115. count += 1;
  47116. }
  47117. }
  47118. return count;
  47119. }
  47120. /**
  47121. * Check if anything is selected
  47122. *
  47123. * @returns {boolean}
  47124. * @private
  47125. */
  47126. }, {
  47127. key: '_selectionIsEmpty',
  47128. value: function _selectionIsEmpty() {
  47129. for (var nodeId in this.selectionObj.nodes) {
  47130. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  47131. return false;
  47132. }
  47133. }
  47134. for (var edgeId in this.selectionObj.edges) {
  47135. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  47136. return false;
  47137. }
  47138. }
  47139. return true;
  47140. }
  47141. /**
  47142. * check if one of the selected nodes is a cluster.
  47143. *
  47144. * @returns {boolean}
  47145. * @private
  47146. */
  47147. }, {
  47148. key: '_clusterInSelection',
  47149. value: function _clusterInSelection() {
  47150. for (var nodeId in this.selectionObj.nodes) {
  47151. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  47152. if (this.selectionObj.nodes[nodeId].clusterSize > 1) {
  47153. return true;
  47154. }
  47155. }
  47156. }
  47157. return false;
  47158. }
  47159. /**
  47160. * select the edges connected to the node that is being selected
  47161. *
  47162. * @param {Node} node
  47163. * @private
  47164. */
  47165. }, {
  47166. key: '_selectConnectedEdges',
  47167. value: function _selectConnectedEdges(node) {
  47168. for (var i = 0; i < node.edges.length; i++) {
  47169. var edge = node.edges[i];
  47170. edge.select();
  47171. this._addToSelection(edge);
  47172. }
  47173. }
  47174. /**
  47175. * select the edges connected to the node that is being selected
  47176. *
  47177. * @param {Node} node
  47178. * @private
  47179. */
  47180. }, {
  47181. key: '_hoverConnectedEdges',
  47182. value: function _hoverConnectedEdges(node) {
  47183. for (var i = 0; i < node.edges.length; i++) {
  47184. var edge = node.edges[i];
  47185. edge.hover = true;
  47186. this._addToHover(edge);
  47187. }
  47188. }
  47189. /**
  47190. * unselect the edges connected to the node that is being selected
  47191. *
  47192. * @param {Node} node
  47193. * @private
  47194. */
  47195. }, {
  47196. key: '_unselectConnectedEdges',
  47197. value: function _unselectConnectedEdges(node) {
  47198. for (var i = 0; i < node.edges.length; i++) {
  47199. var edge = node.edges[i];
  47200. edge.unselect();
  47201. this._removeFromSelection(edge);
  47202. }
  47203. }
  47204. /**
  47205. * Remove the highlight from a node or edge, in response to mouse movement
  47206. *
  47207. * @param {Event} event
  47208. * @param {{x: number, y: number}} pointer object with the x and y screen coordinates of the mouse
  47209. * @param {Node|vis.Edge} object
  47210. * @private
  47211. */
  47212. }, {
  47213. key: 'emitBlurEvent',
  47214. value: function emitBlurEvent(event, pointer, object) {
  47215. var properties = this._initBaseEvent(event, pointer);
  47216. if (object.hover === true) {
  47217. object.hover = false;
  47218. if (object instanceof Node) {
  47219. properties.node = object.id;
  47220. this.body.emitter.emit("blurNode", properties);
  47221. } else {
  47222. properties.edge = object.id;
  47223. this.body.emitter.emit("blurEdge", properties);
  47224. }
  47225. }
  47226. }
  47227. /**
  47228. * Create the highlight for a node or edge, in response to mouse movement
  47229. *
  47230. * @param {Event} event
  47231. * @param {{x: number, y: number}} pointer object with the x and y screen coordinates of the mouse
  47232. * @param {Node|vis.Edge} object
  47233. * @returns {boolean} hoverChanged
  47234. * @private
  47235. */
  47236. }, {
  47237. key: 'emitHoverEvent',
  47238. value: function emitHoverEvent(event, pointer, object) {
  47239. var properties = this._initBaseEvent(event, pointer);
  47240. var hoverChanged = false;
  47241. if (object.hover === false) {
  47242. object.hover = true;
  47243. this._addToHover(object);
  47244. hoverChanged = true;
  47245. if (object instanceof Node) {
  47246. properties.node = object.id;
  47247. this.body.emitter.emit("hoverNode", properties);
  47248. } else {
  47249. properties.edge = object.id;
  47250. this.body.emitter.emit("hoverEdge", properties);
  47251. }
  47252. }
  47253. return hoverChanged;
  47254. }
  47255. /**
  47256. * Perform actions in response to a mouse movement.
  47257. *
  47258. * @param {Event} event
  47259. * @param {{x: number, y: number}} pointer | object with the x and y screen coordinates of the mouse
  47260. */
  47261. }, {
  47262. key: 'hoverObject',
  47263. value: function hoverObject(event, pointer) {
  47264. var object = this.getNodeAt(pointer);
  47265. if (object === undefined) {
  47266. object = this.getEdgeAt(pointer);
  47267. }
  47268. var hoverChanged = false;
  47269. // remove all node hover highlights
  47270. for (var nodeId in this.hoverObj.nodes) {
  47271. if (this.hoverObj.nodes.hasOwnProperty(nodeId)) {
  47272. if (object === undefined || object instanceof Node && object.id != nodeId || object instanceof Edge) {
  47273. this.emitBlurEvent(event, pointer, this.hoverObj.nodes[nodeId]);
  47274. delete this.hoverObj.nodes[nodeId];
  47275. hoverChanged = true;
  47276. }
  47277. }
  47278. }
  47279. // removing all edge hover highlights
  47280. for (var edgeId in this.hoverObj.edges) {
  47281. if (this.hoverObj.edges.hasOwnProperty(edgeId)) {
  47282. // if the hover has been changed here it means that the node has been hovered over or off
  47283. // we then do not use the emitBlurEvent method here.
  47284. if (hoverChanged === true) {
  47285. this.hoverObj.edges[edgeId].hover = false;
  47286. delete this.hoverObj.edges[edgeId];
  47287. }
  47288. // if the blur remains the same and the object is undefined (mouse off) or another
  47289. // edge has been hovered, or another node has been hovered we blur the edge.
  47290. else if (object === undefined || object instanceof Edge && object.id != edgeId || object instanceof Node && !object.hover) {
  47291. this.emitBlurEvent(event, pointer, this.hoverObj.edges[edgeId]);
  47292. delete this.hoverObj.edges[edgeId];
  47293. hoverChanged = true;
  47294. }
  47295. }
  47296. }
  47297. if (object !== undefined) {
  47298. hoverChanged = hoverChanged || this.emitHoverEvent(event, pointer, object);
  47299. if (object instanceof Node && this.options.hoverConnectedEdges === true) {
  47300. this._hoverConnectedEdges(object);
  47301. }
  47302. }
  47303. if (hoverChanged === true) {
  47304. this.body.emitter.emit('_requestRedraw');
  47305. }
  47306. }
  47307. /**
  47308. *
  47309. * retrieve the currently selected objects
  47310. * @return {{nodes: Array.<string>, edges: Array.<string>}} selection
  47311. */
  47312. }, {
  47313. key: 'getSelection',
  47314. value: function getSelection() {
  47315. var nodeIds = this.getSelectedNodes();
  47316. var edgeIds = this.getSelectedEdges();
  47317. return { nodes: nodeIds, edges: edgeIds };
  47318. }
  47319. /**
  47320. *
  47321. * retrieve the currently selected nodes
  47322. * @return {string[]} selection An array with the ids of the
  47323. * selected nodes.
  47324. */
  47325. }, {
  47326. key: 'getSelectedNodes',
  47327. value: function getSelectedNodes() {
  47328. var idArray = [];
  47329. if (this.options.selectable === true) {
  47330. for (var nodeId in this.selectionObj.nodes) {
  47331. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  47332. idArray.push(this.selectionObj.nodes[nodeId].id);
  47333. }
  47334. }
  47335. }
  47336. return idArray;
  47337. }
  47338. /**
  47339. *
  47340. * retrieve the currently selected edges
  47341. * @return {Array} selection An array with the ids of the
  47342. * selected nodes.
  47343. */
  47344. }, {
  47345. key: 'getSelectedEdges',
  47346. value: function getSelectedEdges() {
  47347. var idArray = [];
  47348. if (this.options.selectable === true) {
  47349. for (var edgeId in this.selectionObj.edges) {
  47350. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  47351. idArray.push(this.selectionObj.edges[edgeId].id);
  47352. }
  47353. }
  47354. }
  47355. return idArray;
  47356. }
  47357. /**
  47358. * Updates the current selection
  47359. * @param {{nodes: Array.<string>, edges: Array.<string>}} selection
  47360. * @param {Object} options Options
  47361. */
  47362. }, {
  47363. key: 'setSelection',
  47364. value: function setSelection(selection) {
  47365. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  47366. var i = void 0,
  47367. id = void 0;
  47368. if (!selection || !selection.nodes && !selection.edges) throw 'Selection must be an object with nodes and/or edges properties';
  47369. // first unselect any selected node, if option is true or undefined
  47370. if (options.unselectAll || options.unselectAll === undefined) {
  47371. this.unselectAll();
  47372. }
  47373. if (selection.nodes) {
  47374. for (i = 0; i < selection.nodes.length; i++) {
  47375. id = selection.nodes[i];
  47376. var node = this.body.nodes[id];
  47377. if (!node) {
  47378. throw new RangeError('Node with id "' + id + '" not found');
  47379. }
  47380. // don't select edges with it
  47381. this.selectObject(node, options.highlightEdges);
  47382. }
  47383. }
  47384. if (selection.edges) {
  47385. for (i = 0; i < selection.edges.length; i++) {
  47386. id = selection.edges[i];
  47387. var edge = this.body.edges[id];
  47388. if (!edge) {
  47389. throw new RangeError('Edge with id "' + id + '" not found');
  47390. }
  47391. this.selectObject(edge);
  47392. }
  47393. }
  47394. this.body.emitter.emit('_requestRedraw');
  47395. }
  47396. /**
  47397. * select zero or more nodes with the option to highlight edges
  47398. * @param {number[] | string[]} selection An array with the ids of the
  47399. * selected nodes.
  47400. * @param {boolean} [highlightEdges]
  47401. */
  47402. }, {
  47403. key: 'selectNodes',
  47404. value: function selectNodes(selection) {
  47405. var highlightEdges = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  47406. if (!selection || selection.length === undefined) throw 'Selection must be an array with ids';
  47407. this.setSelection({ nodes: selection }, { highlightEdges: highlightEdges });
  47408. }
  47409. /**
  47410. * select zero or more edges
  47411. * @param {number[] | string[]} selection An array with the ids of the
  47412. * selected nodes.
  47413. */
  47414. }, {
  47415. key: 'selectEdges',
  47416. value: function selectEdges(selection) {
  47417. if (!selection || selection.length === undefined) throw 'Selection must be an array with ids';
  47418. this.setSelection({ edges: selection });
  47419. }
  47420. /**
  47421. * Validate the selection: remove ids of nodes which no longer exist
  47422. * @private
  47423. */
  47424. }, {
  47425. key: 'updateSelection',
  47426. value: function updateSelection() {
  47427. for (var nodeId in this.selectionObj.nodes) {
  47428. if (this.selectionObj.nodes.hasOwnProperty(nodeId)) {
  47429. if (!this.body.nodes.hasOwnProperty(nodeId)) {
  47430. delete this.selectionObj.nodes[nodeId];
  47431. }
  47432. }
  47433. }
  47434. for (var edgeId in this.selectionObj.edges) {
  47435. if (this.selectionObj.edges.hasOwnProperty(edgeId)) {
  47436. if (!this.body.edges.hasOwnProperty(edgeId)) {
  47437. delete this.selectionObj.edges[edgeId];
  47438. }
  47439. }
  47440. }
  47441. }
  47442. /**
  47443. * Determine all the visual elements clicked which are on the given point.
  47444. *
  47445. * All elements are returned; this includes nodes, edges and their labels.
  47446. * The order returned is from highest to lowest, i.e. element 0 of the return
  47447. * value is the topmost item clicked on.
  47448. *
  47449. * The return value consists of an array of the following possible elements:
  47450. *
  47451. * - `{nodeId:number}` - node with given id clicked on
  47452. * - `{nodeId:number, labelId:0}` - label of node with given id clicked on
  47453. * - `{edgeId:number}` - edge with given id clicked on
  47454. * - `{edge:number, labelId:0}` - label of edge with given id clicked on
  47455. *
  47456. * ## NOTES
  47457. *
  47458. * - Currently, there is only one label associated with a node or an edge,
  47459. * but this is expected to change somewhere in the future.
  47460. * - Since there is no z-indexing yet, it is not really possible to set the nodes and
  47461. * edges in the correct order. For the time being, nodes come first.
  47462. *
  47463. * @param {point} pointer mouse position in screen coordinates
  47464. * @returns {Array.<nodeClickItem|nodeLabelClickItem|edgeClickItem|edgeLabelClickItem>}
  47465. * @private
  47466. */
  47467. }, {
  47468. key: 'getClickedItems',
  47469. value: function getClickedItems(pointer) {
  47470. var point = this.canvas.DOMtoCanvas(pointer);
  47471. var items = [];
  47472. // Note reverse order; we want the topmost clicked items to be first in the array
  47473. // Also note that selected nodes are disregarded here; these normally display on top
  47474. var nodeIndices = this.body.nodeIndices;
  47475. var nodes = this.body.nodes;
  47476. for (var i = nodeIndices.length - 1; i >= 0; i--) {
  47477. var node = nodes[nodeIndices[i]];
  47478. var ret = node.getItemsOnPoint(point);
  47479. items.push.apply(items, ret); // Append the return value to the running list.
  47480. }
  47481. var edgeIndices = this.body.edgeIndices;
  47482. var edges = this.body.edges;
  47483. for (var _i = edgeIndices.length - 1; _i >= 0; _i--) {
  47484. var edge = edges[edgeIndices[_i]];
  47485. var _ret = edge.getItemsOnPoint(point);
  47486. items.push.apply(items, _ret); // Append the return value to the running list.
  47487. }
  47488. return items;
  47489. }
  47490. }]);
  47491. return SelectionHandler;
  47492. }();
  47493. exports['default'] = SelectionHandler;
  47494. /***/ }),
  47495. /* 235 */
  47496. /***/ (function(module, exports, __webpack_require__) {
  47497. "use strict";
  47498. /**
  47499. * There's a mix-up with terms in the code. Following are the formal definitions:
  47500. *
  47501. * tree - a strict hierarchical network, i.e. every node has at most one parent
  47502. * forest - a collection of trees. These distinct trees are thus not connected.
  47503. *
  47504. * So:
  47505. * - in a network that is not a tree, there exist nodes with multiple parents.
  47506. * - a network consisting of unconnected sub-networks, of which at least one
  47507. * is not a tree, is not a forest.
  47508. *
  47509. * In the code, the definitions are:
  47510. *
  47511. * tree - any disconnected sub-network, strict hierarchical or not.
  47512. * forest - a bunch of these sub-networks
  47513. *
  47514. * The difference between tree and not-tree is important in the code, notably within
  47515. * to the block-shifting algorithm. The algorithm assumes formal trees and fails
  47516. * for not-trees, often in a spectacular manner (search for 'exploding network' in the issues).
  47517. *
  47518. * In order to distinguish the definitions in the following code, the adjective 'formal' is
  47519. * used. If 'formal' is absent, you must assume the non-formal definition.
  47520. *
  47521. * ----------------------------------------------------------------------------------
  47522. * NOTES
  47523. * =====
  47524. *
  47525. * A hierarchical layout is a different thing from a hierarchical network.
  47526. * The layout is a way to arrange the nodes in the view; this can be done
  47527. * on non-hierarchical networks as well. The converse is also possible.
  47528. */
  47529. Object.defineProperty(exports, "__esModule", {
  47530. value: true
  47531. });
  47532. var _slicedToArray2 = __webpack_require__(30);
  47533. var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
  47534. var _typeof2 = __webpack_require__(6);
  47535. var _typeof3 = _interopRequireDefault(_typeof2);
  47536. var _keys = __webpack_require__(8);
  47537. var _keys2 = _interopRequireDefault(_keys);
  47538. var _classCallCheck2 = __webpack_require__(0);
  47539. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  47540. var _createClass2 = __webpack_require__(1);
  47541. var _createClass3 = _interopRequireDefault(_createClass2);
  47542. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  47543. var util = __webpack_require__(2);
  47544. var NetworkUtil = __webpack_require__(76)['default'];
  47545. var _require = __webpack_require__(236),
  47546. HorizontalStrategy = _require.HorizontalStrategy,
  47547. VerticalStrategy = _require.VerticalStrategy;
  47548. /**
  47549. * Container for derived data on current network, relating to hierarchy.
  47550. *
  47551. * @private
  47552. */
  47553. var HierarchicalStatus = function () {
  47554. /**
  47555. * @ignore
  47556. */
  47557. function HierarchicalStatus() {
  47558. (0, _classCallCheck3['default'])(this, HierarchicalStatus);
  47559. this.childrenReference = {}; // child id's per node id
  47560. this.parentReference = {}; // parent id's per node id
  47561. this.trees = {}; // tree id per node id; i.e. to which tree does given node id belong
  47562. this.distributionOrdering = {}; // The nodes per level, in the display order
  47563. this.levels = {}; // hierarchy level per node id
  47564. this.distributionIndex = {}; // The position of the node in the level sorting order, per node id.
  47565. this.isTree = false; // True if current network is a formal tree
  47566. this.treeIndex = -1; // Highest tree id in current network.
  47567. }
  47568. /**
  47569. * Add the relation between given nodes to the current state.
  47570. *
  47571. * @param {Node.id} parentNodeId
  47572. * @param {Node.id} childNodeId
  47573. */
  47574. (0, _createClass3['default'])(HierarchicalStatus, [{
  47575. key: 'addRelation',
  47576. value: function addRelation(parentNodeId, childNodeId) {
  47577. if (this.childrenReference[parentNodeId] === undefined) {
  47578. this.childrenReference[parentNodeId] = [];
  47579. }
  47580. this.childrenReference[parentNodeId].push(childNodeId);
  47581. if (this.parentReference[childNodeId] === undefined) {
  47582. this.parentReference[childNodeId] = [];
  47583. }
  47584. this.parentReference[childNodeId].push(parentNodeId);
  47585. }
  47586. /**
  47587. * Check if the current state is for a formal tree or formal forest.
  47588. *
  47589. * This is the case if every node has at most one parent.
  47590. *
  47591. * Pre: parentReference init'ed properly for current network
  47592. */
  47593. }, {
  47594. key: 'checkIfTree',
  47595. value: function checkIfTree() {
  47596. for (var i in this.parentReference) {
  47597. if (this.parentReference[i].length > 1) {
  47598. this.isTree = false;
  47599. return;
  47600. }
  47601. }
  47602. this.isTree = true;
  47603. }
  47604. /**
  47605. * Return the number of separate trees in the current network.
  47606. * @returns {number}
  47607. */
  47608. }, {
  47609. key: 'numTrees',
  47610. value: function numTrees() {
  47611. return this.treeIndex + 1; // This assumes the indexes are assigned consecitively
  47612. }
  47613. /**
  47614. * Assign a tree id to a node
  47615. * @param {Node} node
  47616. * @param {string|number} treeId
  47617. */
  47618. }, {
  47619. key: 'setTreeIndex',
  47620. value: function setTreeIndex(node, treeId) {
  47621. if (treeId === undefined) return; // Don't bother
  47622. if (this.trees[node.id] === undefined) {
  47623. this.trees[node.id] = treeId;
  47624. this.treeIndex = Math.max(treeId, this.treeIndex);
  47625. }
  47626. }
  47627. /**
  47628. * Ensure level for given id is defined.
  47629. *
  47630. * Sets level to zero for given node id if not already present
  47631. *
  47632. * @param {Node.id} nodeId
  47633. */
  47634. }, {
  47635. key: 'ensureLevel',
  47636. value: function ensureLevel(nodeId) {
  47637. if (this.levels[nodeId] === undefined) {
  47638. this.levels[nodeId] = 0;
  47639. }
  47640. }
  47641. /**
  47642. * get the maximum level of a branch.
  47643. *
  47644. * TODO: Never entered; find a test case to test this!
  47645. * @param {Node.id} nodeId
  47646. * @returns {number}
  47647. */
  47648. }, {
  47649. key: 'getMaxLevel',
  47650. value: function getMaxLevel(nodeId) {
  47651. var _this = this;
  47652. var accumulator = {};
  47653. var _getMaxLevel = function _getMaxLevel(nodeId) {
  47654. if (accumulator[nodeId] !== undefined) {
  47655. return accumulator[nodeId];
  47656. }
  47657. var level = _this.levels[nodeId];
  47658. if (_this.childrenReference[nodeId]) {
  47659. var children = _this.childrenReference[nodeId];
  47660. if (children.length > 0) {
  47661. for (var i = 0; i < children.length; i++) {
  47662. level = Math.max(level, _getMaxLevel(children[i]));
  47663. }
  47664. }
  47665. }
  47666. accumulator[nodeId] = level;
  47667. return level;
  47668. };
  47669. return _getMaxLevel(nodeId);
  47670. }
  47671. /**
  47672. *
  47673. * @param {Node} nodeA
  47674. * @param {Node} nodeB
  47675. */
  47676. }, {
  47677. key: 'levelDownstream',
  47678. value: function levelDownstream(nodeA, nodeB) {
  47679. if (this.levels[nodeB.id] === undefined) {
  47680. // set initial level
  47681. if (this.levels[nodeA.id] === undefined) {
  47682. this.levels[nodeA.id] = 0;
  47683. }
  47684. // set level
  47685. this.levels[nodeB.id] = this.levels[nodeA.id] + 1;
  47686. }
  47687. }
  47688. /**
  47689. * Small util method to set the minimum levels of the nodes to zero.
  47690. *
  47691. * @param {Array.<Node>} nodes
  47692. */
  47693. }, {
  47694. key: 'setMinLevelToZero',
  47695. value: function setMinLevelToZero(nodes) {
  47696. var minLevel = 1e9;
  47697. // get the minimum level
  47698. for (var nodeId in nodes) {
  47699. if (nodes.hasOwnProperty(nodeId)) {
  47700. if (this.levels[nodeId] !== undefined) {
  47701. minLevel = Math.min(this.levels[nodeId], minLevel);
  47702. }
  47703. }
  47704. }
  47705. // subtract the minimum from the set so we have a range starting from 0
  47706. for (var _nodeId in nodes) {
  47707. if (nodes.hasOwnProperty(_nodeId)) {
  47708. if (this.levels[_nodeId] !== undefined) {
  47709. this.levels[_nodeId] -= minLevel;
  47710. }
  47711. }
  47712. }
  47713. }
  47714. /**
  47715. * Get the min and max xy-coordinates of a given tree
  47716. *
  47717. * @param {Array.<Node>} nodes
  47718. * @param {number} index
  47719. * @returns {{min_x: number, max_x: number, min_y: number, max_y: number}}
  47720. */
  47721. }, {
  47722. key: 'getTreeSize',
  47723. value: function getTreeSize(nodes, index) {
  47724. var min_x = 1e9;
  47725. var max_x = -1e9;
  47726. var min_y = 1e9;
  47727. var max_y = -1e9;
  47728. for (var nodeId in this.trees) {
  47729. if (this.trees.hasOwnProperty(nodeId)) {
  47730. if (this.trees[nodeId] === index) {
  47731. var node = nodes[nodeId];
  47732. min_x = Math.min(node.x, min_x);
  47733. max_x = Math.max(node.x, max_x);
  47734. min_y = Math.min(node.y, min_y);
  47735. max_y = Math.max(node.y, max_y);
  47736. }
  47737. }
  47738. }
  47739. return {
  47740. min_x: min_x,
  47741. max_x: max_x,
  47742. min_y: min_y,
  47743. max_y: max_y
  47744. };
  47745. }
  47746. /**
  47747. * Check if two nodes have the same parent(s)
  47748. *
  47749. * @param {Node} node1
  47750. * @param {Node} node2
  47751. * @return {boolean} true if the two nodes have a same ancestor node, false otherwise
  47752. */
  47753. }, {
  47754. key: 'hasSameParent',
  47755. value: function hasSameParent(node1, node2) {
  47756. var parents1 = this.parentReference[node1.id];
  47757. var parents2 = this.parentReference[node2.id];
  47758. if (parents1 === undefined || parents2 === undefined) {
  47759. return false;
  47760. }
  47761. for (var i = 0; i < parents1.length; i++) {
  47762. for (var j = 0; j < parents2.length; j++) {
  47763. if (parents1[i] == parents2[j]) {
  47764. return true;
  47765. }
  47766. }
  47767. }
  47768. return false;
  47769. }
  47770. /**
  47771. * Check if two nodes are in the same tree.
  47772. *
  47773. * @param {Node} node1
  47774. * @param {Node} node2
  47775. * @return {Boolean} true if this is so, false otherwise
  47776. */
  47777. }, {
  47778. key: 'inSameSubNetwork',
  47779. value: function inSameSubNetwork(node1, node2) {
  47780. return this.trees[node1.id] === this.trees[node2.id];
  47781. }
  47782. /**
  47783. * Get a list of the distinct levels in the current network
  47784. *
  47785. * @returns {Array}
  47786. */
  47787. }, {
  47788. key: 'getLevels',
  47789. value: function getLevels() {
  47790. return (0, _keys2['default'])(this.distributionOrdering);
  47791. }
  47792. /**
  47793. * Add a node to the ordering per level
  47794. *
  47795. * @param {Node} node
  47796. * @param {number} level
  47797. */
  47798. }, {
  47799. key: 'addToOrdering',
  47800. value: function addToOrdering(node, level) {
  47801. if (this.distributionOrdering[level] === undefined) {
  47802. this.distributionOrdering[level] = [];
  47803. }
  47804. var isPresent = false;
  47805. var curLevel = this.distributionOrdering[level];
  47806. for (var n in curLevel) {
  47807. //if (curLevel[n].id === node.id) {
  47808. if (curLevel[n] === node) {
  47809. isPresent = true;
  47810. break;
  47811. }
  47812. }
  47813. if (!isPresent) {
  47814. this.distributionOrdering[level].push(node);
  47815. this.distributionIndex[node.id] = this.distributionOrdering[level].length - 1;
  47816. }
  47817. }
  47818. }]);
  47819. return HierarchicalStatus;
  47820. }();
  47821. /**
  47822. * The Layout Engine
  47823. */
  47824. var LayoutEngine = function () {
  47825. /**
  47826. * @param {Object} body
  47827. */
  47828. function LayoutEngine(body) {
  47829. (0, _classCallCheck3['default'])(this, LayoutEngine);
  47830. this.body = body;
  47831. this.initialRandomSeed = Math.round(Math.random() * 1000000);
  47832. this.randomSeed = this.initialRandomSeed;
  47833. this.setPhysics = false;
  47834. this.options = {};
  47835. this.optionsBackup = { physics: {} };
  47836. this.defaultOptions = {
  47837. randomSeed: undefined,
  47838. improvedLayout: true,
  47839. hierarchical: {
  47840. enabled: false,
  47841. levelSeparation: 150,
  47842. nodeSpacing: 100,
  47843. treeSpacing: 200,
  47844. blockShifting: true,
  47845. edgeMinimization: true,
  47846. parentCentralization: true,
  47847. direction: 'UD', // UD, DU, LR, RL
  47848. sortMethod: 'hubsize' // hubsize, directed
  47849. }
  47850. };
  47851. util.extend(this.options, this.defaultOptions);
  47852. this.bindEventListeners();
  47853. }
  47854. /**
  47855. * Binds event listeners
  47856. */
  47857. (0, _createClass3['default'])(LayoutEngine, [{
  47858. key: 'bindEventListeners',
  47859. value: function bindEventListeners() {
  47860. var _this2 = this;
  47861. this.body.emitter.on('_dataChanged', function () {
  47862. _this2.setupHierarchicalLayout();
  47863. });
  47864. this.body.emitter.on('_dataLoaded', function () {
  47865. _this2.layoutNetwork();
  47866. });
  47867. this.body.emitter.on('_resetHierarchicalLayout', function () {
  47868. _this2.setupHierarchicalLayout();
  47869. });
  47870. this.body.emitter.on('_adjustEdgesForHierarchicalLayout', function () {
  47871. if (_this2.options.hierarchical.enabled !== true) {
  47872. return;
  47873. }
  47874. // get the type of static smooth curve in case it is required
  47875. var type = _this2.direction.curveType();
  47876. // force all edges into static smooth curves.
  47877. _this2.body.emitter.emit('_forceDisableDynamicCurves', type, false);
  47878. });
  47879. }
  47880. /**
  47881. *
  47882. * @param {Object} options
  47883. * @param {Object} allOptions
  47884. * @returns {Object}
  47885. */
  47886. }, {
  47887. key: 'setOptions',
  47888. value: function setOptions(options, allOptions) {
  47889. if (options !== undefined) {
  47890. var hierarchical = this.options.hierarchical;
  47891. var prevHierarchicalState = hierarchical.enabled;
  47892. util.selectiveDeepExtend(["randomSeed", "improvedLayout"], this.options, options);
  47893. util.mergeOptions(this.options, options, 'hierarchical');
  47894. if (options.randomSeed !== undefined) {
  47895. this.initialRandomSeed = options.randomSeed;
  47896. }
  47897. if (hierarchical.enabled === true) {
  47898. if (prevHierarchicalState === true) {
  47899. // refresh the overridden options for nodes and edges.
  47900. this.body.emitter.emit('refresh', true);
  47901. }
  47902. // make sure the level separation is the right way up
  47903. if (hierarchical.direction === 'RL' || hierarchical.direction === 'DU') {
  47904. if (hierarchical.levelSeparation > 0) {
  47905. hierarchical.levelSeparation *= -1;
  47906. }
  47907. } else {
  47908. if (hierarchical.levelSeparation < 0) {
  47909. hierarchical.levelSeparation *= -1;
  47910. }
  47911. }
  47912. this.setDirectionStrategy();
  47913. this.body.emitter.emit('_resetHierarchicalLayout');
  47914. // because the hierarchical system needs it's own physics and smooth curve settings,
  47915. // we adapt the other options if needed.
  47916. return this.adaptAllOptionsForHierarchicalLayout(allOptions);
  47917. } else {
  47918. if (prevHierarchicalState === true) {
  47919. // refresh the overridden options for nodes and edges.
  47920. this.body.emitter.emit('refresh');
  47921. return util.deepExtend(allOptions, this.optionsBackup);
  47922. }
  47923. }
  47924. }
  47925. return allOptions;
  47926. }
  47927. /**
  47928. *
  47929. * @param {Object} allOptions
  47930. * @returns {Object}
  47931. */
  47932. }, {
  47933. key: 'adaptAllOptionsForHierarchicalLayout',
  47934. value: function adaptAllOptionsForHierarchicalLayout(allOptions) {
  47935. if (this.options.hierarchical.enabled === true) {
  47936. var backupPhysics = this.optionsBackup.physics;
  47937. // set the physics
  47938. if (allOptions.physics === undefined || allOptions.physics === true) {
  47939. allOptions.physics = {
  47940. enabled: backupPhysics.enabled === undefined ? true : backupPhysics.enabled,
  47941. solver: 'hierarchicalRepulsion'
  47942. };
  47943. backupPhysics.enabled = backupPhysics.enabled === undefined ? true : backupPhysics.enabled;
  47944. backupPhysics.solver = backupPhysics.solver || 'barnesHut';
  47945. } else if ((0, _typeof3['default'])(allOptions.physics) === 'object') {
  47946. backupPhysics.enabled = allOptions.physics.enabled === undefined ? true : allOptions.physics.enabled;
  47947. backupPhysics.solver = allOptions.physics.solver || 'barnesHut';
  47948. allOptions.physics.solver = 'hierarchicalRepulsion';
  47949. } else if (allOptions.physics !== false) {
  47950. backupPhysics.solver = 'barnesHut';
  47951. allOptions.physics = { solver: 'hierarchicalRepulsion' };
  47952. }
  47953. // get the type of static smooth curve in case it is required
  47954. var type = this.direction.curveType();
  47955. // disable smooth curves if nothing is defined. If smooth curves have been turned on,
  47956. // turn them into static smooth curves.
  47957. if (allOptions.edges === undefined) {
  47958. this.optionsBackup.edges = { smooth: { enabled: true, type: 'dynamic' } };
  47959. allOptions.edges = { smooth: false };
  47960. } else if (allOptions.edges.smooth === undefined) {
  47961. this.optionsBackup.edges = { smooth: { enabled: true, type: 'dynamic' } };
  47962. allOptions.edges.smooth = false;
  47963. } else {
  47964. if (typeof allOptions.edges.smooth === 'boolean') {
  47965. this.optionsBackup.edges = { smooth: allOptions.edges.smooth };
  47966. allOptions.edges.smooth = { enabled: allOptions.edges.smooth, type: type };
  47967. } else {
  47968. var smooth = allOptions.edges.smooth;
  47969. // allow custom types except for dynamic
  47970. if (smooth.type !== undefined && smooth.type !== 'dynamic') {
  47971. type = smooth.type;
  47972. }
  47973. // TODO: this is options merging; see if the standard routines can be used here.
  47974. this.optionsBackup.edges = {
  47975. smooth: smooth.enabled === undefined ? true : smooth.enabled,
  47976. type: smooth.type === undefined ? 'dynamic' : smooth.type,
  47977. roundness: smooth.roundness === undefined ? 0.5 : smooth.roundness,
  47978. forceDirection: smooth.forceDirection === undefined ? false : smooth.forceDirection
  47979. };
  47980. // NOTE: Copying an object to self; this is basically setting defaults for undefined variables
  47981. allOptions.edges.smooth = {
  47982. enabled: smooth.enabled === undefined ? true : smooth.enabled,
  47983. type: type,
  47984. roundness: smooth.roundness === undefined ? 0.5 : smooth.roundness,
  47985. forceDirection: smooth.forceDirection === undefined ? false : smooth.forceDirection
  47986. };
  47987. }
  47988. }
  47989. // Force all edges into static smooth curves.
  47990. // Only applies to edges that do not use the global options for smooth.
  47991. this.body.emitter.emit('_forceDisableDynamicCurves', type);
  47992. }
  47993. return allOptions;
  47994. }
  47995. /**
  47996. *
  47997. * @returns {number}
  47998. */
  47999. }, {
  48000. key: 'seededRandom',
  48001. value: function seededRandom() {
  48002. var x = Math.sin(this.randomSeed++) * 10000;
  48003. return x - Math.floor(x);
  48004. }
  48005. /**
  48006. *
  48007. * @param {Array.<Node>} nodesArray
  48008. */
  48009. }, {
  48010. key: 'positionInitially',
  48011. value: function positionInitially(nodesArray) {
  48012. if (this.options.hierarchical.enabled !== true) {
  48013. this.randomSeed = this.initialRandomSeed;
  48014. var radius = nodesArray.length + 50;
  48015. for (var i = 0; i < nodesArray.length; i++) {
  48016. var node = nodesArray[i];
  48017. var angle = 2 * Math.PI * this.seededRandom();
  48018. if (node.x === undefined) {
  48019. node.x = radius * Math.cos(angle);
  48020. }
  48021. if (node.y === undefined) {
  48022. node.y = radius * Math.sin(angle);
  48023. }
  48024. }
  48025. }
  48026. }
  48027. /**
  48028. * Use Kamada Kawai to position nodes. This is quite a heavy algorithm so if there are a lot of nodes we
  48029. * cluster them first to reduce the amount.
  48030. */
  48031. }, {
  48032. key: 'layoutNetwork',
  48033. value: function layoutNetwork() {
  48034. if (this.options.hierarchical.enabled !== true && this.options.improvedLayout === true) {
  48035. var indices = this.body.nodeIndices;
  48036. // first check if we should Kamada Kawai to layout. The threshold is if less than half of the visible
  48037. // nodes have predefined positions we use this.
  48038. var positionDefined = 0;
  48039. for (var i = 0; i < indices.length; i++) {
  48040. var node = this.body.nodes[indices[i]];
  48041. if (node.predefinedPosition === true) {
  48042. positionDefined += 1;
  48043. }
  48044. }
  48045. // if less than half of the nodes have a predefined position we continue
  48046. if (positionDefined < 0.5 * indices.length) {
  48047. var MAX_LEVELS = 10;
  48048. var level = 0;
  48049. var clusterThreshold = 150; // TODO add this to options
  48050. //
  48051. // Define the options for the hidden cluster nodes
  48052. // These options don't propagate outside the clustering phase.
  48053. //
  48054. // Some options are explicitly disabled, because they may be set in group or default node options.
  48055. // The clusters are never displayed, so most explicit settings here serve as performance optimizations.
  48056. //
  48057. // The explicit setting of 'shape' is to avoid `shape: 'image'`; images are not passed to the hidden
  48058. // cluster nodes, leading to an exception on creation.
  48059. //
  48060. // All settings here are performance related, except when noted otherwise.
  48061. //
  48062. var clusterOptions = {
  48063. clusterNodeProperties: {
  48064. shape: 'ellipse', // Bugfix: avoid type 'image', no images supplied
  48065. label: '', // avoid label handling
  48066. group: '', // avoid group handling
  48067. font: { multi: false } // avoid font propagation
  48068. },
  48069. clusterEdgeProperties: {
  48070. label: '', // avoid label handling
  48071. font: { multi: false }, // avoid font propagation
  48072. smooth: {
  48073. enabled: false // avoid drawing penalty for complex edges
  48074. }
  48075. }
  48076. };
  48077. // if there are a lot of nodes, we cluster before we run the algorithm.
  48078. // NOTE: this part fails to find clusters for large scale-free networks, which should
  48079. // be easily clusterable.
  48080. // TODO: examine why this is so
  48081. if (indices.length > clusterThreshold) {
  48082. var startLength = indices.length;
  48083. while (indices.length > clusterThreshold && level <= MAX_LEVELS) {
  48084. //console.time("clustering")
  48085. level += 1;
  48086. var before = indices.length;
  48087. // if there are many nodes we do a hubsize cluster
  48088. if (level % 3 === 0) {
  48089. this.body.modules.clustering.clusterBridges(clusterOptions);
  48090. } else {
  48091. this.body.modules.clustering.clusterOutliers(clusterOptions);
  48092. }
  48093. var after = indices.length;
  48094. if (before == after && level % 3 !== 0) {
  48095. this._declusterAll();
  48096. this.body.emitter.emit("_layoutFailed");
  48097. console.info("This network could not be positioned by this version of the improved layout algorithm." + " Please disable improvedLayout for better performance.");
  48098. return;
  48099. }
  48100. //console.timeEnd("clustering")
  48101. //console.log(before,level,after);
  48102. }
  48103. // increase the size of the edges
  48104. this.body.modules.kamadaKawai.setOptions({ springLength: Math.max(150, 2 * startLength) });
  48105. }
  48106. if (level > MAX_LEVELS) {
  48107. console.info("The clustering didn't succeed within the amount of interations allowed," + " progressing with partial result.");
  48108. }
  48109. // position the system for these nodes and edges
  48110. this.body.modules.kamadaKawai.solve(indices, this.body.edgeIndices, true);
  48111. // shift to center point
  48112. this._shiftToCenter();
  48113. // perturb the nodes a little bit to force the physics to kick in
  48114. var offset = 70;
  48115. for (var _i = 0; _i < indices.length; _i++) {
  48116. // Only perturb the nodes that aren't fixed
  48117. var _node = this.body.nodes[indices[_i]];
  48118. if (_node.predefinedPosition === false) {
  48119. _node.x += (0.5 - this.seededRandom()) * offset;
  48120. _node.y += (0.5 - this.seededRandom()) * offset;
  48121. }
  48122. }
  48123. // uncluster all clusters
  48124. this._declusterAll();
  48125. // reposition all bezier nodes.
  48126. this.body.emitter.emit("_repositionBezierNodes");
  48127. }
  48128. }
  48129. }
  48130. /**
  48131. * Move all the nodes towards to the center so gravitational pull wil not move the nodes away from view
  48132. * @private
  48133. */
  48134. }, {
  48135. key: '_shiftToCenter',
  48136. value: function _shiftToCenter() {
  48137. var range = NetworkUtil.getRangeCore(this.body.nodes, this.body.nodeIndices);
  48138. var center = NetworkUtil.findCenter(range);
  48139. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  48140. var node = this.body.nodes[this.body.nodeIndices[i]];
  48141. node.x -= center.x;
  48142. node.y -= center.y;
  48143. }
  48144. }
  48145. /**
  48146. * Expands all clusters
  48147. * @private
  48148. */
  48149. }, {
  48150. key: '_declusterAll',
  48151. value: function _declusterAll() {
  48152. var clustersPresent = true;
  48153. while (clustersPresent === true) {
  48154. clustersPresent = false;
  48155. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  48156. if (this.body.nodes[this.body.nodeIndices[i]].isCluster === true) {
  48157. clustersPresent = true;
  48158. this.body.modules.clustering.openCluster(this.body.nodeIndices[i], {}, false);
  48159. }
  48160. }
  48161. if (clustersPresent === true) {
  48162. this.body.emitter.emit('_dataChanged');
  48163. }
  48164. }
  48165. }
  48166. /**
  48167. *
  48168. * @returns {number|*}
  48169. */
  48170. }, {
  48171. key: 'getSeed',
  48172. value: function getSeed() {
  48173. return this.initialRandomSeed;
  48174. }
  48175. /**
  48176. * This is the main function to layout the nodes in a hierarchical way.
  48177. * It checks if the node details are supplied correctly
  48178. *
  48179. * @private
  48180. */
  48181. }, {
  48182. key: 'setupHierarchicalLayout',
  48183. value: function setupHierarchicalLayout() {
  48184. if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) {
  48185. // get the size of the largest hubs and check if the user has defined a level for a node.
  48186. var node = void 0,
  48187. nodeId = void 0;
  48188. var definedLevel = false;
  48189. var undefinedLevel = false;
  48190. this.lastNodeOnLevel = {};
  48191. this.hierarchical = new HierarchicalStatus();
  48192. for (nodeId in this.body.nodes) {
  48193. if (this.body.nodes.hasOwnProperty(nodeId)) {
  48194. node = this.body.nodes[nodeId];
  48195. if (node.options.level !== undefined) {
  48196. definedLevel = true;
  48197. this.hierarchical.levels[nodeId] = node.options.level;
  48198. } else {
  48199. undefinedLevel = true;
  48200. }
  48201. }
  48202. }
  48203. // if the user defined some levels but not all, alert and run without hierarchical layout
  48204. if (undefinedLevel === true && definedLevel === true) {
  48205. throw new Error('To use the hierarchical layout, nodes require either no predefined levels' + ' or levels have to be defined for all nodes.');
  48206. } else {
  48207. // define levels if undefined by the users. Based on hubsize.
  48208. if (undefinedLevel === true) {
  48209. var sortMethod = this.options.hierarchical.sortMethod;
  48210. if (sortMethod === 'hubsize') {
  48211. this._determineLevelsByHubsize();
  48212. } else if (sortMethod === 'directed') {
  48213. this._determineLevelsDirected();
  48214. } else if (sortMethod === 'custom') {
  48215. this._determineLevelsCustomCallback();
  48216. }
  48217. }
  48218. // fallback for cases where there are nodes but no edges
  48219. for (var _nodeId2 in this.body.nodes) {
  48220. if (this.body.nodes.hasOwnProperty(_nodeId2)) {
  48221. this.hierarchical.ensureLevel(_nodeId2);
  48222. }
  48223. }
  48224. // check the distribution of the nodes per level.
  48225. var distribution = this._getDistribution();
  48226. // get the parent children relations.
  48227. this._generateMap();
  48228. // place the nodes on the canvas.
  48229. this._placeNodesByHierarchy(distribution);
  48230. // condense the whitespace.
  48231. this._condenseHierarchy();
  48232. // shift to center so gravity does not have to do much
  48233. this._shiftToCenter();
  48234. }
  48235. }
  48236. }
  48237. /**
  48238. * @private
  48239. */
  48240. }, {
  48241. key: '_condenseHierarchy',
  48242. value: function _condenseHierarchy() {
  48243. var _this3 = this;
  48244. // Global var in this scope to define when the movement has stopped.
  48245. var stillShifting = false;
  48246. var branches = {};
  48247. // first we have some methods to help shifting trees around.
  48248. // the main method to shift the trees
  48249. var shiftTrees = function shiftTrees() {
  48250. var treeSizes = getTreeSizes();
  48251. var shiftBy = 0;
  48252. for (var i = 0; i < treeSizes.length - 1; i++) {
  48253. var diff = treeSizes[i].max - treeSizes[i + 1].min;
  48254. shiftBy += diff + _this3.options.hierarchical.treeSpacing;
  48255. shiftTree(i + 1, shiftBy);
  48256. }
  48257. };
  48258. // shift a single tree by an offset
  48259. var shiftTree = function shiftTree(index, offset) {
  48260. var trees = _this3.hierarchical.trees;
  48261. for (var nodeId in trees) {
  48262. if (trees.hasOwnProperty(nodeId)) {
  48263. if (trees[nodeId] === index) {
  48264. _this3.direction.shift(nodeId, offset);
  48265. }
  48266. }
  48267. }
  48268. };
  48269. // get the width of all trees
  48270. var getTreeSizes = function getTreeSizes() {
  48271. var treeWidths = [];
  48272. for (var i = 0; i < _this3.hierarchical.numTrees(); i++) {
  48273. treeWidths.push(_this3.direction.getTreeSize(i));
  48274. }
  48275. return treeWidths;
  48276. };
  48277. // get a map of all nodes in this branch
  48278. var getBranchNodes = function getBranchNodes(source, map) {
  48279. if (map[source.id]) {
  48280. return;
  48281. }
  48282. map[source.id] = true;
  48283. if (_this3.hierarchical.childrenReference[source.id]) {
  48284. var children = _this3.hierarchical.childrenReference[source.id];
  48285. if (children.length > 0) {
  48286. for (var i = 0; i < children.length; i++) {
  48287. getBranchNodes(_this3.body.nodes[children[i]], map);
  48288. }
  48289. }
  48290. }
  48291. };
  48292. // get a min max width as well as the maximum movement space it has on either sides
  48293. // we use min max terminology because width and height can interchange depending on the direction of the layout
  48294. var getBranchBoundary = function getBranchBoundary(branchMap) {
  48295. var maxLevel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1e9;
  48296. var minSpace = 1e9;
  48297. var maxSpace = 1e9;
  48298. var min = 1e9;
  48299. var max = -1e9;
  48300. for (var branchNode in branchMap) {
  48301. if (branchMap.hasOwnProperty(branchNode)) {
  48302. var node = _this3.body.nodes[branchNode];
  48303. var level = _this3.hierarchical.levels[node.id];
  48304. var position = _this3.direction.getPosition(node);
  48305. // get the space around the node.
  48306. var _getSpaceAroundNode2 = _this3._getSpaceAroundNode(node, branchMap),
  48307. _getSpaceAroundNode3 = (0, _slicedToArray3['default'])(_getSpaceAroundNode2, 2),
  48308. minSpaceNode = _getSpaceAroundNode3[0],
  48309. maxSpaceNode = _getSpaceAroundNode3[1];
  48310. minSpace = Math.min(minSpaceNode, minSpace);
  48311. maxSpace = Math.min(maxSpaceNode, maxSpace);
  48312. // the width is only relevant for the levels two nodes have in common. This is why we filter on this.
  48313. if (level <= maxLevel) {
  48314. min = Math.min(position, min);
  48315. max = Math.max(position, max);
  48316. }
  48317. }
  48318. }
  48319. return [min, max, minSpace, maxSpace];
  48320. };
  48321. // check what the maximum level is these nodes have in common.
  48322. var getCollisionLevel = function getCollisionLevel(node1, node2) {
  48323. var maxLevel1 = _this3.hierarchical.getMaxLevel(node1.id);
  48324. var maxLevel2 = _this3.hierarchical.getMaxLevel(node2.id);
  48325. return Math.min(maxLevel1, maxLevel2);
  48326. };
  48327. /**
  48328. * Condense elements. These can be nodes or branches depending on the callback.
  48329. *
  48330. * @param {function} callback
  48331. * @param {Array.<number>} levels
  48332. * @param {*} centerParents
  48333. */
  48334. var shiftElementsCloser = function shiftElementsCloser(callback, levels, centerParents) {
  48335. var hier = _this3.hierarchical;
  48336. for (var i = 0; i < levels.length; i++) {
  48337. var level = levels[i];
  48338. var levelNodes = hier.distributionOrdering[level];
  48339. if (levelNodes.length > 1) {
  48340. for (var j = 0; j < levelNodes.length - 1; j++) {
  48341. var node1 = levelNodes[j];
  48342. var node2 = levelNodes[j + 1];
  48343. // NOTE: logic maintained as it was; if nodes have same ancestor,
  48344. // then of course they are in the same sub-network.
  48345. if (hier.hasSameParent(node1, node2) && hier.inSameSubNetwork(node1, node2)) {
  48346. callback(node1, node2, centerParents);
  48347. }
  48348. }
  48349. }
  48350. }
  48351. };
  48352. // callback for shifting branches
  48353. var branchShiftCallback = function branchShiftCallback(node1, node2) {
  48354. var centerParent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  48355. //window.CALLBACKS.push(() => {
  48356. var pos1 = _this3.direction.getPosition(node1);
  48357. var pos2 = _this3.direction.getPosition(node2);
  48358. var diffAbs = Math.abs(pos2 - pos1);
  48359. var nodeSpacing = _this3.options.hierarchical.nodeSpacing;
  48360. //console.log("NOW CHECKING:", node1.id, node2.id, diffAbs);
  48361. if (diffAbs > nodeSpacing) {
  48362. var branchNodes1 = {};
  48363. var branchNodes2 = {};
  48364. getBranchNodes(node1, branchNodes1);
  48365. getBranchNodes(node2, branchNodes2);
  48366. // check the largest distance between the branches
  48367. var maxLevel = getCollisionLevel(node1, node2);
  48368. var branchNodeBoundary1 = getBranchBoundary(branchNodes1, maxLevel);
  48369. var branchNodeBoundary2 = getBranchBoundary(branchNodes2, maxLevel);
  48370. var max1 = branchNodeBoundary1[1];
  48371. var min2 = branchNodeBoundary2[0];
  48372. var minSpace2 = branchNodeBoundary2[2];
  48373. //console.log(node1.id, getBranchBoundary(branchNodes1, maxLevel), node2.id,
  48374. // getBranchBoundary(branchNodes2, maxLevel), maxLevel);
  48375. var diffBranch = Math.abs(max1 - min2);
  48376. if (diffBranch > nodeSpacing) {
  48377. var offset = max1 - min2 + nodeSpacing;
  48378. if (offset < -minSpace2 + nodeSpacing) {
  48379. offset = -minSpace2 + nodeSpacing;
  48380. //console.log("RESETTING OFFSET", max1 - min2 + this.options.hierarchical.nodeSpacing, -minSpace2, offset);
  48381. }
  48382. if (offset < 0) {
  48383. //console.log("SHIFTING", node2.id, offset);
  48384. _this3._shiftBlock(node2.id, offset);
  48385. stillShifting = true;
  48386. if (centerParent === true) _this3._centerParent(node2);
  48387. }
  48388. }
  48389. }
  48390. //this.body.emitter.emit("_redraw");})
  48391. };
  48392. var minimizeEdgeLength = function minimizeEdgeLength(iterations, node) {
  48393. //window.CALLBACKS.push(() => {
  48394. // console.log("ts",node.id);
  48395. var nodeId = node.id;
  48396. var allEdges = node.edges;
  48397. var nodeLevel = _this3.hierarchical.levels[node.id];
  48398. // gather constants
  48399. var C2 = _this3.options.hierarchical.levelSeparation * _this3.options.hierarchical.levelSeparation;
  48400. var referenceNodes = {};
  48401. var aboveEdges = [];
  48402. for (var i = 0; i < allEdges.length; i++) {
  48403. var edge = allEdges[i];
  48404. if (edge.toId != edge.fromId) {
  48405. var otherNode = edge.toId == nodeId ? edge.from : edge.to;
  48406. referenceNodes[allEdges[i].id] = otherNode;
  48407. if (_this3.hierarchical.levels[otherNode.id] < nodeLevel) {
  48408. aboveEdges.push(edge);
  48409. }
  48410. }
  48411. }
  48412. // differentiated sum of lengths based on only moving one node over one axis
  48413. var getFx = function getFx(point, edges) {
  48414. var sum = 0;
  48415. for (var _i2 = 0; _i2 < edges.length; _i2++) {
  48416. if (referenceNodes[edges[_i2].id] !== undefined) {
  48417. var a = _this3.direction.getPosition(referenceNodes[edges[_i2].id]) - point;
  48418. sum += a / Math.sqrt(a * a + C2);
  48419. }
  48420. }
  48421. return sum;
  48422. };
  48423. // doubly differentiated sum of lengths based on only moving one node over one axis
  48424. var getDFx = function getDFx(point, edges) {
  48425. var sum = 0;
  48426. for (var _i3 = 0; _i3 < edges.length; _i3++) {
  48427. if (referenceNodes[edges[_i3].id] !== undefined) {
  48428. var a = _this3.direction.getPosition(referenceNodes[edges[_i3].id]) - point;
  48429. sum -= C2 * Math.pow(a * a + C2, -1.5);
  48430. }
  48431. }
  48432. return sum;
  48433. };
  48434. var getGuess = function getGuess(iterations, edges) {
  48435. var guess = _this3.direction.getPosition(node);
  48436. // Newton's method for optimization
  48437. var guessMap = {};
  48438. for (var _i4 = 0; _i4 < iterations; _i4++) {
  48439. var fx = getFx(guess, edges);
  48440. var dfx = getDFx(guess, edges);
  48441. // we limit the movement to avoid instability.
  48442. var limit = 40;
  48443. var ratio = Math.max(-limit, Math.min(limit, Math.round(fx / dfx)));
  48444. guess = guess - ratio;
  48445. // reduce duplicates
  48446. if (guessMap[guess] !== undefined) {
  48447. break;
  48448. }
  48449. guessMap[guess] = _i4;
  48450. }
  48451. return guess;
  48452. };
  48453. var moveBranch = function moveBranch(guess) {
  48454. // position node if there is space
  48455. var nodePosition = _this3.direction.getPosition(node);
  48456. // check movable area of the branch
  48457. if (branches[node.id] === undefined) {
  48458. var branchNodes = {};
  48459. getBranchNodes(node, branchNodes);
  48460. branches[node.id] = branchNodes;
  48461. }
  48462. var branchBoundary = getBranchBoundary(branches[node.id]);
  48463. var minSpaceBranch = branchBoundary[2];
  48464. var maxSpaceBranch = branchBoundary[3];
  48465. var diff = guess - nodePosition;
  48466. // check if we are allowed to move the node:
  48467. var branchOffset = 0;
  48468. if (diff > 0) {
  48469. branchOffset = Math.min(diff, maxSpaceBranch - _this3.options.hierarchical.nodeSpacing);
  48470. } else if (diff < 0) {
  48471. branchOffset = -Math.min(-diff, minSpaceBranch - _this3.options.hierarchical.nodeSpacing);
  48472. }
  48473. if (branchOffset != 0) {
  48474. //console.log("moving branch:",branchOffset, maxSpaceBranch, minSpaceBranch)
  48475. _this3._shiftBlock(node.id, branchOffset);
  48476. //this.body.emitter.emit("_redraw");
  48477. stillShifting = true;
  48478. }
  48479. };
  48480. var moveNode = function moveNode(guess) {
  48481. var nodePosition = _this3.direction.getPosition(node);
  48482. // position node if there is space
  48483. var _getSpaceAroundNode4 = _this3._getSpaceAroundNode(node),
  48484. _getSpaceAroundNode5 = (0, _slicedToArray3['default'])(_getSpaceAroundNode4, 2),
  48485. minSpace = _getSpaceAroundNode5[0],
  48486. maxSpace = _getSpaceAroundNode5[1];
  48487. var diff = guess - nodePosition;
  48488. // check if we are allowed to move the node:
  48489. var newPosition = nodePosition;
  48490. if (diff > 0) {
  48491. newPosition = Math.min(nodePosition + (maxSpace - _this3.options.hierarchical.nodeSpacing), guess);
  48492. } else if (diff < 0) {
  48493. newPosition = Math.max(nodePosition - (minSpace - _this3.options.hierarchical.nodeSpacing), guess);
  48494. }
  48495. if (newPosition !== nodePosition) {
  48496. //console.log("moving Node:",diff, minSpace, maxSpace);
  48497. _this3.direction.setPosition(node, newPosition);
  48498. //this.body.emitter.emit("_redraw");
  48499. stillShifting = true;
  48500. }
  48501. };
  48502. var guess = getGuess(iterations, aboveEdges);
  48503. moveBranch(guess);
  48504. guess = getGuess(iterations, allEdges);
  48505. moveNode(guess);
  48506. //})
  48507. };
  48508. // method to remove whitespace between branches. Because we do bottom up, we can center the parents.
  48509. var minimizeEdgeLengthBottomUp = function minimizeEdgeLengthBottomUp(iterations) {
  48510. var levels = _this3.hierarchical.getLevels();
  48511. levels = levels.reverse();
  48512. for (var i = 0; i < iterations; i++) {
  48513. stillShifting = false;
  48514. for (var j = 0; j < levels.length; j++) {
  48515. var level = levels[j];
  48516. var levelNodes = _this3.hierarchical.distributionOrdering[level];
  48517. for (var k = 0; k < levelNodes.length; k++) {
  48518. minimizeEdgeLength(1000, levelNodes[k]);
  48519. }
  48520. }
  48521. if (stillShifting !== true) {
  48522. //console.log("FINISHED minimizeEdgeLengthBottomUp IN " + i);
  48523. break;
  48524. }
  48525. }
  48526. };
  48527. // method to remove whitespace between branches. Because we do bottom up, we can center the parents.
  48528. var shiftBranchesCloserBottomUp = function shiftBranchesCloserBottomUp(iterations) {
  48529. var levels = _this3.hierarchical.getLevels();
  48530. levels = levels.reverse();
  48531. for (var i = 0; i < iterations; i++) {
  48532. stillShifting = false;
  48533. shiftElementsCloser(branchShiftCallback, levels, true);
  48534. if (stillShifting !== true) {
  48535. //console.log("FINISHED shiftBranchesCloserBottomUp IN " + (i+1));
  48536. break;
  48537. }
  48538. }
  48539. };
  48540. // center all parents
  48541. var centerAllParents = function centerAllParents() {
  48542. for (var nodeId in _this3.body.nodes) {
  48543. if (_this3.body.nodes.hasOwnProperty(nodeId)) _this3._centerParent(_this3.body.nodes[nodeId]);
  48544. }
  48545. };
  48546. // center all parents
  48547. var centerAllParentsBottomUp = function centerAllParentsBottomUp() {
  48548. var levels = _this3.hierarchical.getLevels();
  48549. levels = levels.reverse();
  48550. for (var i = 0; i < levels.length; i++) {
  48551. var level = levels[i];
  48552. var levelNodes = _this3.hierarchical.distributionOrdering[level];
  48553. for (var j = 0; j < levelNodes.length; j++) {
  48554. _this3._centerParent(levelNodes[j]);
  48555. }
  48556. }
  48557. };
  48558. // the actual work is done here.
  48559. if (this.options.hierarchical.blockShifting === true) {
  48560. shiftBranchesCloserBottomUp(5);
  48561. centerAllParents();
  48562. }
  48563. // minimize edge length
  48564. if (this.options.hierarchical.edgeMinimization === true) {
  48565. minimizeEdgeLengthBottomUp(20);
  48566. }
  48567. if (this.options.hierarchical.parentCentralization === true) {
  48568. centerAllParentsBottomUp();
  48569. }
  48570. shiftTrees();
  48571. }
  48572. /**
  48573. * This gives the space around the node. IF a map is supplied, it will only check against nodes NOT in the map.
  48574. * This is used to only get the distances to nodes outside of a branch.
  48575. * @param {Node} node
  48576. * @param {{Node.id: vis.Node}} map
  48577. * @returns {number[]}
  48578. * @private
  48579. */
  48580. }, {
  48581. key: '_getSpaceAroundNode',
  48582. value: function _getSpaceAroundNode(node, map) {
  48583. var useMap = true;
  48584. if (map === undefined) {
  48585. useMap = false;
  48586. }
  48587. var level = this.hierarchical.levels[node.id];
  48588. if (level !== undefined) {
  48589. var index = this.hierarchical.distributionIndex[node.id];
  48590. var position = this.direction.getPosition(node);
  48591. var ordering = this.hierarchical.distributionOrdering[level];
  48592. var minSpace = 1e9;
  48593. var maxSpace = 1e9;
  48594. if (index !== 0) {
  48595. var prevNode = ordering[index - 1];
  48596. if (useMap === true && map[prevNode.id] === undefined || useMap === false) {
  48597. var prevPos = this.direction.getPosition(prevNode);
  48598. minSpace = position - prevPos;
  48599. }
  48600. }
  48601. if (index != ordering.length - 1) {
  48602. var nextNode = ordering[index + 1];
  48603. if (useMap === true && map[nextNode.id] === undefined || useMap === false) {
  48604. var nextPos = this.direction.getPosition(nextNode);
  48605. maxSpace = Math.min(maxSpace, nextPos - position);
  48606. }
  48607. }
  48608. return [minSpace, maxSpace];
  48609. } else {
  48610. return [0, 0];
  48611. }
  48612. }
  48613. /**
  48614. * We use this method to center a parent node and check if it does not cross other nodes when it does.
  48615. * @param {Node} node
  48616. * @private
  48617. */
  48618. }, {
  48619. key: '_centerParent',
  48620. value: function _centerParent(node) {
  48621. if (this.hierarchical.parentReference[node.id]) {
  48622. var parents = this.hierarchical.parentReference[node.id];
  48623. for (var i = 0; i < parents.length; i++) {
  48624. var parentId = parents[i];
  48625. var parentNode = this.body.nodes[parentId];
  48626. var children = this.hierarchical.childrenReference[parentId];
  48627. if (children !== undefined) {
  48628. // get the range of the children
  48629. var newPosition = this._getCenterPosition(children);
  48630. var position = this.direction.getPosition(parentNode);
  48631. var _getSpaceAroundNode6 = this._getSpaceAroundNode(parentNode),
  48632. _getSpaceAroundNode7 = (0, _slicedToArray3['default'])(_getSpaceAroundNode6, 2),
  48633. minSpace = _getSpaceAroundNode7[0],
  48634. maxSpace = _getSpaceAroundNode7[1];
  48635. var diff = position - newPosition;
  48636. if (diff < 0 && Math.abs(diff) < maxSpace - this.options.hierarchical.nodeSpacing || diff > 0 && Math.abs(diff) < minSpace - this.options.hierarchical.nodeSpacing) {
  48637. this.direction.setPosition(parentNode, newPosition);
  48638. }
  48639. }
  48640. }
  48641. }
  48642. }
  48643. /**
  48644. * This function places the nodes on the canvas based on the hierarchial distribution.
  48645. *
  48646. * @param {Object} distribution | obtained by the function this._getDistribution()
  48647. * @private
  48648. */
  48649. }, {
  48650. key: '_placeNodesByHierarchy',
  48651. value: function _placeNodesByHierarchy(distribution) {
  48652. this.positionedNodes = {};
  48653. // start placing all the level 0 nodes first. Then recursively position their branches.
  48654. for (var level in distribution) {
  48655. if (distribution.hasOwnProperty(level)) {
  48656. // sort nodes in level by position:
  48657. var nodeArray = (0, _keys2['default'])(distribution[level]);
  48658. nodeArray = this._indexArrayToNodes(nodeArray);
  48659. this.direction.sort(nodeArray);
  48660. var handledNodeCount = 0;
  48661. for (var i = 0; i < nodeArray.length; i++) {
  48662. var node = nodeArray[i];
  48663. if (this.positionedNodes[node.id] === undefined) {
  48664. var spacing = this.options.hierarchical.nodeSpacing;
  48665. var pos = spacing * handledNodeCount;
  48666. // We get the X or Y values we need and store them in pos and previousPos.
  48667. // The get and set make sure we get X or Y
  48668. if (handledNodeCount > 0) {
  48669. pos = this.direction.getPosition(nodeArray[i - 1]) + spacing;
  48670. }
  48671. this.direction.setPosition(node, pos, level);
  48672. this._validatePositionAndContinue(node, level, pos);
  48673. handledNodeCount++;
  48674. }
  48675. }
  48676. }
  48677. }
  48678. }
  48679. /**
  48680. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  48681. * on a X position that ensures there will be no overlap.
  48682. *
  48683. * @param {Node.id} parentId
  48684. * @param {number} parentLevel
  48685. * @private
  48686. */
  48687. }, {
  48688. key: '_placeBranchNodes',
  48689. value: function _placeBranchNodes(parentId, parentLevel) {
  48690. var childRef = this.hierarchical.childrenReference[parentId];
  48691. // if this is not a parent, cancel the placing. This can happen with multiple parents to one child.
  48692. if (childRef === undefined) {
  48693. return;
  48694. }
  48695. // get a list of childNodes
  48696. var childNodes = [];
  48697. for (var i = 0; i < childRef.length; i++) {
  48698. childNodes.push(this.body.nodes[childRef[i]]);
  48699. }
  48700. // use the positions to order the nodes.
  48701. this.direction.sort(childNodes);
  48702. // position the childNodes
  48703. for (var _i5 = 0; _i5 < childNodes.length; _i5++) {
  48704. var childNode = childNodes[_i5];
  48705. var childNodeLevel = this.hierarchical.levels[childNode.id];
  48706. // check if the child node is below the parent node and if it has already been positioned.
  48707. if (childNodeLevel > parentLevel && this.positionedNodes[childNode.id] === undefined) {
  48708. // get the amount of space required for this node. If parent the width is based on the amount of children.
  48709. var spacing = this.options.hierarchical.nodeSpacing;
  48710. var pos = void 0;
  48711. // we get the X or Y values we need and store them in pos and previousPos.
  48712. // The get and set make sure we get X or Y
  48713. if (_i5 === 0) {
  48714. pos = this.direction.getPosition(this.body.nodes[parentId]);
  48715. } else {
  48716. pos = this.direction.getPosition(childNodes[_i5 - 1]) + spacing;
  48717. }
  48718. this.direction.setPosition(childNode, pos, childNodeLevel);
  48719. this._validatePositionAndContinue(childNode, childNodeLevel, pos);
  48720. } else {
  48721. return;
  48722. }
  48723. }
  48724. // center the parent nodes.
  48725. var center = this._getCenterPosition(childNodes);
  48726. this.direction.setPosition(this.body.nodes[parentId], center, parentLevel);
  48727. }
  48728. /**
  48729. * This method checks for overlap and if required shifts the branch. It also keeps records of positioned nodes.
  48730. * Finally it will call _placeBranchNodes to place the branch nodes.
  48731. * @param {Node} node
  48732. * @param {number} level
  48733. * @param {number} pos
  48734. * @private
  48735. */
  48736. }, {
  48737. key: '_validatePositionAndContinue',
  48738. value: function _validatePositionAndContinue(node, level, pos) {
  48739. // This method only works for formal trees and formal forests
  48740. // Early exit if this is not the case
  48741. if (!this.hierarchical.isTree) return;
  48742. // if overlap has been detected, we shift the branch
  48743. if (this.lastNodeOnLevel[level] !== undefined) {
  48744. var previousPos = this.direction.getPosition(this.body.nodes[this.lastNodeOnLevel[level]]);
  48745. if (pos - previousPos < this.options.hierarchical.nodeSpacing) {
  48746. var diff = previousPos + this.options.hierarchical.nodeSpacing - pos;
  48747. var sharedParent = this._findCommonParent(this.lastNodeOnLevel[level], node.id);
  48748. this._shiftBlock(sharedParent.withChild, diff);
  48749. }
  48750. }
  48751. this.lastNodeOnLevel[level] = node.id; // store change in position.
  48752. this.positionedNodes[node.id] = true;
  48753. this._placeBranchNodes(node.id, level);
  48754. }
  48755. /**
  48756. * Receives an array with node indices and returns an array with the actual node references.
  48757. * Used for sorting based on node properties.
  48758. * @param {Array.<Node.id>} idArray
  48759. * @returns {Array.<Node>}
  48760. */
  48761. }, {
  48762. key: '_indexArrayToNodes',
  48763. value: function _indexArrayToNodes(idArray) {
  48764. var array = [];
  48765. for (var i = 0; i < idArray.length; i++) {
  48766. array.push(this.body.nodes[idArray[i]]);
  48767. }
  48768. return array;
  48769. }
  48770. /**
  48771. * This function get the distribution of levels based on hubsize
  48772. *
  48773. * @returns {Object}
  48774. * @private
  48775. */
  48776. }, {
  48777. key: '_getDistribution',
  48778. value: function _getDistribution() {
  48779. var distribution = {};
  48780. var nodeId = void 0,
  48781. node = void 0;
  48782. // we fix Y because the hierarchy is vertical,
  48783. // we fix X so we do not give a node an x position for a second time.
  48784. // the fix of X is removed after the x value has been set.
  48785. for (nodeId in this.body.nodes) {
  48786. if (this.body.nodes.hasOwnProperty(nodeId)) {
  48787. node = this.body.nodes[nodeId];
  48788. var level = this.hierarchical.levels[nodeId] === undefined ? 0 : this.hierarchical.levels[nodeId];
  48789. this.direction.fix(node, level);
  48790. if (distribution[level] === undefined) {
  48791. distribution[level] = {};
  48792. }
  48793. distribution[level][nodeId] = node;
  48794. }
  48795. }
  48796. return distribution;
  48797. }
  48798. /**
  48799. * Return the active (i.e. visible) edges for this node
  48800. *
  48801. * @param {Node} node
  48802. * @returns {Array.<vis.Edge>} Array of edge instances
  48803. * @private
  48804. */
  48805. }, {
  48806. key: '_getActiveEdges',
  48807. value: function _getActiveEdges(node) {
  48808. var _this4 = this;
  48809. var result = [];
  48810. util.forEach(node.edges, function (edge) {
  48811. if (_this4.body.edgeIndices.indexOf(edge.id) !== -1) {
  48812. result.push(edge);
  48813. }
  48814. });
  48815. return result;
  48816. }
  48817. /**
  48818. * Get the hubsizes for all active nodes.
  48819. *
  48820. * @returns {number}
  48821. * @private
  48822. */
  48823. }, {
  48824. key: '_getHubSizes',
  48825. value: function _getHubSizes() {
  48826. var _this5 = this;
  48827. var hubSizes = {};
  48828. var nodeIds = this.body.nodeIndices;
  48829. util.forEach(nodeIds, function (nodeId) {
  48830. var node = _this5.body.nodes[nodeId];
  48831. var hubSize = _this5._getActiveEdges(node).length;
  48832. hubSizes[hubSize] = true;
  48833. });
  48834. // Make an array of the size sorted descending
  48835. var result = [];
  48836. util.forEach(hubSizes, function (size) {
  48837. result.push(Number(size));
  48838. });
  48839. result.sort(function (a, b) {
  48840. return b - a;
  48841. });
  48842. return result;
  48843. }
  48844. /**
  48845. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  48846. *
  48847. * @private
  48848. */
  48849. }, {
  48850. key: '_determineLevelsByHubsize',
  48851. value: function _determineLevelsByHubsize() {
  48852. var _this6 = this;
  48853. var levelDownstream = function levelDownstream(nodeA, nodeB) {
  48854. _this6.hierarchical.levelDownstream(nodeA, nodeB);
  48855. };
  48856. var hubSizes = this._getHubSizes();
  48857. var _loop = function _loop(i) {
  48858. var hubSize = hubSizes[i];
  48859. if (hubSize === 0) return 'break';
  48860. util.forEach(_this6.body.nodeIndices, function (nodeId) {
  48861. var node = _this6.body.nodes[nodeId];
  48862. if (hubSize === _this6._getActiveEdges(node).length) {
  48863. _this6._crawlNetwork(levelDownstream, nodeId);
  48864. }
  48865. });
  48866. };
  48867. for (var i = 0; i < hubSizes.length; ++i) {
  48868. var _ret = _loop(i);
  48869. if (_ret === 'break') break;
  48870. }
  48871. }
  48872. /**
  48873. * TODO: release feature
  48874. * TODO: Determine if this feature is needed at all
  48875. *
  48876. * @private
  48877. */
  48878. }, {
  48879. key: '_determineLevelsCustomCallback',
  48880. value: function _determineLevelsCustomCallback() {
  48881. var _this7 = this;
  48882. var minLevel = 100000;
  48883. // TODO: this should come from options.
  48884. var customCallback = function customCallback(nodeA, nodeB, edge) {// eslint-disable-line no-unused-vars
  48885. };
  48886. // TODO: perhaps move to HierarchicalStatus.
  48887. // But I currently don't see the point, this method is not used.
  48888. var levelByDirection = function levelByDirection(nodeA, nodeB, edge) {
  48889. var levelA = _this7.hierarchical.levels[nodeA.id];
  48890. // set initial level
  48891. if (levelA === undefined) {
  48892. levelA = _this7.hierarchical.levels[nodeA.id] = minLevel;
  48893. }
  48894. var diff = customCallback(NetworkUtil.cloneOptions(nodeA, 'node'), NetworkUtil.cloneOptions(nodeB, 'node'), NetworkUtil.cloneOptions(edge, 'edge'));
  48895. _this7.hierarchical.levels[nodeB.id] = levelA + diff;
  48896. };
  48897. this._crawlNetwork(levelByDirection);
  48898. this.hierarchical.setMinLevelToZero(this.body.nodes);
  48899. }
  48900. /**
  48901. * Allocate nodes in levels based on the direction of the edges.
  48902. *
  48903. * @private
  48904. */
  48905. }, {
  48906. key: '_determineLevelsDirected',
  48907. value: function _determineLevelsDirected() {
  48908. var _this8 = this;
  48909. var minLevel = 10000;
  48910. /**
  48911. * Check if there is an edge going the opposite direction for given edge
  48912. *
  48913. * @param {Edge} edge edge to check
  48914. * @returns {boolean} true if there's another edge going into the opposite direction
  48915. */
  48916. var isBidirectional = function isBidirectional(edge) {
  48917. util.forEach(_this8.body.edges, function (otherEdge) {
  48918. if (otherEdge.toId === edge.fromId && otherEdge.fromId === edge.toId) {
  48919. return true;
  48920. }
  48921. });
  48922. return false;
  48923. };
  48924. var levelByDirection = function levelByDirection(nodeA, nodeB, edge) {
  48925. var levelA = _this8.hierarchical.levels[nodeA.id];
  48926. var levelB = _this8.hierarchical.levels[nodeB.id];
  48927. if (isBidirectional(edge) && levelA !== undefined && levelB !== undefined) {
  48928. // Don't redo the level determination if already done in this case.
  48929. return;
  48930. }
  48931. // set initial level
  48932. if (levelA === undefined) {
  48933. levelA = _this8.hierarchical.levels[nodeA.id] = minLevel;
  48934. }
  48935. if (edge.toId == nodeB.id) {
  48936. _this8.hierarchical.levels[nodeB.id] = levelA + 1;
  48937. } else {
  48938. _this8.hierarchical.levels[nodeB.id] = levelA - 1;
  48939. }
  48940. };
  48941. this._crawlNetwork(levelByDirection);
  48942. this.hierarchical.setMinLevelToZero(this.body.nodes);
  48943. }
  48944. /**
  48945. * Update the bookkeeping of parent and child.
  48946. * @private
  48947. */
  48948. }, {
  48949. key: '_generateMap',
  48950. value: function _generateMap() {
  48951. var _this9 = this;
  48952. var fillInRelations = function fillInRelations(parentNode, childNode) {
  48953. if (_this9.hierarchical.levels[childNode.id] > _this9.hierarchical.levels[parentNode.id]) {
  48954. _this9.hierarchical.addRelation(parentNode.id, childNode.id);
  48955. }
  48956. };
  48957. this._crawlNetwork(fillInRelations);
  48958. this.hierarchical.checkIfTree();
  48959. }
  48960. /**
  48961. * Crawl over the entire network and use a callback on each node couple that is connected to each other.
  48962. * @param {function} [callback=function(){}] | will receive nodeA, nodeB and the connecting edge. A and B are distinct.
  48963. * @param {Node.id} startingNodeId
  48964. * @private
  48965. */
  48966. }, {
  48967. key: '_crawlNetwork',
  48968. value: function _crawlNetwork() {
  48969. var _this10 = this;
  48970. var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {};
  48971. var startingNodeId = arguments[1];
  48972. var progress = {};
  48973. var crawler = function crawler(node, tree) {
  48974. if (progress[node.id] === undefined) {
  48975. _this10.hierarchical.setTreeIndex(node, tree);
  48976. progress[node.id] = true;
  48977. var childNode = void 0;
  48978. var edges = _this10._getActiveEdges(node);
  48979. for (var i = 0; i < edges.length; i++) {
  48980. var edge = edges[i];
  48981. if (edge.connected === true) {
  48982. if (edge.toId == node.id) {
  48983. // Not '===' because id's can be string and numeric
  48984. childNode = edge.from;
  48985. } else {
  48986. childNode = edge.to;
  48987. }
  48988. if (node.id != childNode.id) {
  48989. // Not '!==' because id's can be string and numeric
  48990. callback(node, childNode, edge);
  48991. crawler(childNode, tree);
  48992. }
  48993. }
  48994. }
  48995. }
  48996. };
  48997. if (startingNodeId === undefined) {
  48998. // Crawl over all nodes
  48999. var treeIndex = 0; // Serves to pass a unique id for the current distinct tree
  49000. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  49001. var nodeId = this.body.nodeIndices[i];
  49002. if (progress[nodeId] === undefined) {
  49003. var node = this.body.nodes[nodeId];
  49004. crawler(node, treeIndex);
  49005. treeIndex += 1;
  49006. }
  49007. }
  49008. } else {
  49009. // Crawl from the given starting node
  49010. var _node2 = this.body.nodes[startingNodeId];
  49011. if (_node2 === undefined) {
  49012. console.error("Node not found:", startingNodeId);
  49013. return;
  49014. }
  49015. crawler(_node2);
  49016. }
  49017. }
  49018. /**
  49019. * Shift a branch a certain distance
  49020. * @param {Node.id} parentId
  49021. * @param {number} diff
  49022. * @private
  49023. */
  49024. }, {
  49025. key: '_shiftBlock',
  49026. value: function _shiftBlock(parentId, diff) {
  49027. var _this11 = this;
  49028. var progress = {};
  49029. var shifter = function shifter(parentId) {
  49030. if (progress[parentId]) {
  49031. return;
  49032. }
  49033. progress[parentId] = true;
  49034. _this11.direction.shift(parentId, diff);
  49035. var childRef = _this11.hierarchical.childrenReference[parentId];
  49036. if (childRef !== undefined) {
  49037. for (var i = 0; i < childRef.length; i++) {
  49038. shifter(childRef[i]);
  49039. }
  49040. }
  49041. };
  49042. shifter(parentId);
  49043. }
  49044. /**
  49045. * Find a common parent between branches.
  49046. * @param {Node.id} childA
  49047. * @param {Node.id} childB
  49048. * @returns {{foundParent, withChild}}
  49049. * @private
  49050. */
  49051. }, {
  49052. key: '_findCommonParent',
  49053. value: function _findCommonParent(childA, childB) {
  49054. var _this12 = this;
  49055. var parents = {};
  49056. var iterateParents = function iterateParents(parents, child) {
  49057. var parentRef = _this12.hierarchical.parentReference[child];
  49058. if (parentRef !== undefined) {
  49059. for (var i = 0; i < parentRef.length; i++) {
  49060. var parent = parentRef[i];
  49061. parents[parent] = true;
  49062. iterateParents(parents, parent);
  49063. }
  49064. }
  49065. };
  49066. var findParent = function findParent(parents, child) {
  49067. var parentRef = _this12.hierarchical.parentReference[child];
  49068. if (parentRef !== undefined) {
  49069. for (var i = 0; i < parentRef.length; i++) {
  49070. var parent = parentRef[i];
  49071. if (parents[parent] !== undefined) {
  49072. return { foundParent: parent, withChild: child };
  49073. }
  49074. var branch = findParent(parents, parent);
  49075. if (branch.foundParent !== null) {
  49076. return branch;
  49077. }
  49078. }
  49079. }
  49080. return { foundParent: null, withChild: child };
  49081. };
  49082. iterateParents(parents, childA);
  49083. return findParent(parents, childB);
  49084. }
  49085. /**
  49086. * Set the strategy pattern for handling the coordinates given the current direction.
  49087. *
  49088. * The individual instances contain all the operations and data specific to a layout direction.
  49089. *
  49090. * @param {Node} node
  49091. * @param {{x: number, y: number}} position
  49092. * @param {number} level
  49093. * @param {boolean} [doNotUpdate=false]
  49094. * @private
  49095. */
  49096. }, {
  49097. key: 'setDirectionStrategy',
  49098. value: function setDirectionStrategy() {
  49099. var isVertical = this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU';
  49100. if (isVertical) {
  49101. this.direction = new VerticalStrategy(this);
  49102. } else {
  49103. this.direction = new HorizontalStrategy(this);
  49104. }
  49105. }
  49106. /**
  49107. * Determine the center position of a branch from the passed list of child nodes
  49108. *
  49109. * This takes into account the positions of all the child nodes.
  49110. * @param {Array.<Node|vis.Node.id>} childNodes Array of either child nodes or node id's
  49111. * @return {number}
  49112. * @private
  49113. */
  49114. }, {
  49115. key: '_getCenterPosition',
  49116. value: function _getCenterPosition(childNodes) {
  49117. var minPos = 1e9;
  49118. var maxPos = -1e9;
  49119. for (var i = 0; i < childNodes.length; i++) {
  49120. var childNode = void 0;
  49121. if (childNodes[i].id !== undefined) {
  49122. childNode = childNodes[i];
  49123. } else {
  49124. var childNodeId = childNodes[i];
  49125. childNode = this.body.nodes[childNodeId];
  49126. }
  49127. var position = this.direction.getPosition(childNode);
  49128. minPos = Math.min(minPos, position);
  49129. maxPos = Math.max(maxPos, position);
  49130. }
  49131. return 0.5 * (minPos + maxPos);
  49132. }
  49133. }]);
  49134. return LayoutEngine;
  49135. }();
  49136. exports['default'] = LayoutEngine;
  49137. /***/ }),
  49138. /* 236 */
  49139. /***/ (function(module, exports, __webpack_require__) {
  49140. "use strict";
  49141. Object.defineProperty(exports, "__esModule", {
  49142. value: true
  49143. });
  49144. exports.VerticalStrategy = exports.HorizontalStrategy = undefined;
  49145. var _getPrototypeOf = __webpack_require__(3);
  49146. var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
  49147. var _possibleConstructorReturn2 = __webpack_require__(4);
  49148. var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
  49149. var _inherits2 = __webpack_require__(5);
  49150. var _inherits3 = _interopRequireDefault(_inherits2);
  49151. var _classCallCheck2 = __webpack_require__(0);
  49152. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  49153. var _createClass2 = __webpack_require__(1);
  49154. var _createClass3 = _interopRequireDefault(_createClass2);
  49155. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  49156. /**
  49157. * Helper classes for LayoutEngine.
  49158. *
  49159. * Strategy pattern for usage of direction methods for hierarchical layouts.
  49160. */
  49161. /**
  49162. * Interface definition for direction strategy classes.
  49163. *
  49164. * This class describes the interface for the Strategy
  49165. * pattern classes used to differentiate horizontal and vertical
  49166. * direction of hierarchical results.
  49167. *
  49168. * For a given direction, one coordinate will be 'fixed', meaning that it is
  49169. * determined by level.
  49170. * The other coordinate is 'unfixed', meaning that the nodes on a given level
  49171. * can still move along that coordinate. So:
  49172. *
  49173. * - `vertical` layout: `x` unfixed, `y` fixed per level
  49174. * - `horizontal` layout: `x` fixed per level, `y` unfixed
  49175. *
  49176. * The local methods are stubs and should be regarded as abstract.
  49177. * Derived classes **must** implement all the methods themselves.
  49178. *
  49179. * @private
  49180. */
  49181. var DirectionInterface = function () {
  49182. function DirectionInterface() {
  49183. (0, _classCallCheck3['default'])(this, DirectionInterface);
  49184. }
  49185. (0, _createClass3['default'])(DirectionInterface, [{
  49186. key: 'abstract',
  49187. /** @ignore **/
  49188. value: function abstract() {
  49189. throw new Error("Can't instantiate abstract class!");
  49190. }
  49191. /**
  49192. * This is a dummy call which is used to suppress the jsdoc errors of type:
  49193. *
  49194. * "'param' is assigned a value but never used"
  49195. *
  49196. * @ignore
  49197. **/
  49198. }, {
  49199. key: 'fake_use',
  49200. value: function fake_use() {}
  49201. // Do nothing special
  49202. /**
  49203. * Type to use to translate dynamic curves to, in the case of hierarchical layout.
  49204. * Dynamic curves do not work for these.
  49205. *
  49206. * The value should be perpendicular to the actual direction of the layout.
  49207. *
  49208. * @return {string} Direction, either 'vertical' or 'horizontal'
  49209. */
  49210. }, {
  49211. key: 'curveType',
  49212. value: function curveType() {
  49213. return this.abstract();
  49214. }
  49215. /**
  49216. * Return the value of the coordinate that is not fixed for this direction.
  49217. *
  49218. * @param {Node} node The node to read
  49219. * @return {number} Value of the unfixed coordinate
  49220. */
  49221. }, {
  49222. key: 'getPosition',
  49223. value: function getPosition(node) {
  49224. this.fake_use(node);return this.abstract();
  49225. }
  49226. /**
  49227. * Set the value of the coordinate that is not fixed for this direction.
  49228. *
  49229. * @param {Node} node The node to adjust
  49230. * @param {number} position
  49231. * @param {number} [level] if specified, the hierarchy level that this node should be fixed to
  49232. */
  49233. }, {
  49234. key: 'setPosition',
  49235. value: function setPosition(node, position) {
  49236. var level = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
  49237. this.fake_use(node, position, level);this.abstract();
  49238. }
  49239. /**
  49240. * Get the width of a tree.
  49241. *
  49242. * A `tree` here is a subset of nodes within the network which are not connected to other nodes,
  49243. * only among themselves. In essence, it is a sub-network.
  49244. *
  49245. * @param {number} index The index number of a tree
  49246. * @return {number} the width of a tree in the view coordinates
  49247. */
  49248. }, {
  49249. key: 'getTreeSize',
  49250. value: function getTreeSize(index) {
  49251. this.fake_use(index);return this.abstract();
  49252. }
  49253. /**
  49254. * Sort array of nodes on the unfixed coordinates.
  49255. *
  49256. * @param {Array.<Node>} nodeArray array of nodes to sort
  49257. */
  49258. }, {
  49259. key: 'sort',
  49260. value: function sort(nodeArray) {
  49261. this.fake_use(nodeArray);this.abstract();
  49262. }
  49263. /**
  49264. * Assign the fixed coordinate of the node to the given level
  49265. *
  49266. * @param {Node} node The node to adjust
  49267. * @param {number} level The level to fix to
  49268. */
  49269. }, {
  49270. key: 'fix',
  49271. value: function fix(node, level) {
  49272. this.fake_use(node, level);this.abstract();
  49273. }
  49274. /**
  49275. * Add an offset to the unfixed coordinate of the given node.
  49276. *
  49277. * @param {NodeId} nodeId Id of the node to adjust
  49278. * @param {number} diff Offset to add to the unfixed coordinate
  49279. */
  49280. }, {
  49281. key: 'shift',
  49282. value: function shift(nodeId, diff) {
  49283. this.fake_use(nodeId, diff);this.abstract();
  49284. }
  49285. }]);
  49286. return DirectionInterface;
  49287. }();
  49288. /**
  49289. * Vertical Strategy
  49290. *
  49291. * Coordinate `y` is fixed on levels, coordinate `x` is unfixed.
  49292. *
  49293. * @extends DirectionInterface
  49294. * @private
  49295. */
  49296. var VerticalStrategy = function (_DirectionInterface) {
  49297. (0, _inherits3['default'])(VerticalStrategy, _DirectionInterface);
  49298. /**
  49299. * Constructor
  49300. *
  49301. * @param {Object} layout reference to the parent LayoutEngine instance.
  49302. */
  49303. function VerticalStrategy(layout) {
  49304. (0, _classCallCheck3['default'])(this, VerticalStrategy);
  49305. var _this = (0, _possibleConstructorReturn3['default'])(this, (VerticalStrategy.__proto__ || (0, _getPrototypeOf2['default'])(VerticalStrategy)).call(this));
  49306. _this.layout = layout;
  49307. return _this;
  49308. }
  49309. /** @inheritdoc */
  49310. (0, _createClass3['default'])(VerticalStrategy, [{
  49311. key: 'curveType',
  49312. value: function curveType() {
  49313. return 'horizontal';
  49314. }
  49315. /** @inheritdoc */
  49316. }, {
  49317. key: 'getPosition',
  49318. value: function getPosition(node) {
  49319. return node.x;
  49320. }
  49321. /** @inheritdoc */
  49322. }, {
  49323. key: 'setPosition',
  49324. value: function setPosition(node, position) {
  49325. var level = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
  49326. if (level !== undefined) {
  49327. this.layout.hierarchical.addToOrdering(node, level);
  49328. }
  49329. node.x = position;
  49330. }
  49331. /** @inheritdoc */
  49332. }, {
  49333. key: 'getTreeSize',
  49334. value: function getTreeSize(index) {
  49335. var res = this.layout.hierarchical.getTreeSize(this.layout.body.nodes, index);
  49336. return { min: res.min_x, max: res.max_x };
  49337. }
  49338. /** @inheritdoc */
  49339. }, {
  49340. key: 'sort',
  49341. value: function sort(nodeArray) {
  49342. nodeArray.sort(function (a, b) {
  49343. // Test on 'undefined' takes care of divergent behaviour in chrome
  49344. if (a.x === undefined || b.x === undefined) return 0; // THIS HAPPENS
  49345. return a.x - b.x;
  49346. });
  49347. }
  49348. /** @inheritdoc */
  49349. }, {
  49350. key: 'fix',
  49351. value: function fix(node, level) {
  49352. node.y = this.layout.options.hierarchical.levelSeparation * level;
  49353. node.options.fixed.y = true;
  49354. }
  49355. /** @inheritdoc */
  49356. }, {
  49357. key: 'shift',
  49358. value: function shift(nodeId, diff) {
  49359. this.layout.body.nodes[nodeId].x += diff;
  49360. }
  49361. }]);
  49362. return VerticalStrategy;
  49363. }(DirectionInterface);
  49364. /**
  49365. * Horizontal Strategy
  49366. *
  49367. * Coordinate `x` is fixed on levels, coordinate `y` is unfixed.
  49368. *
  49369. * @extends DirectionInterface
  49370. * @private
  49371. */
  49372. var HorizontalStrategy = function (_DirectionInterface2) {
  49373. (0, _inherits3['default'])(HorizontalStrategy, _DirectionInterface2);
  49374. /**
  49375. * Constructor
  49376. *
  49377. * @param {Object} layout reference to the parent LayoutEngine instance.
  49378. */
  49379. function HorizontalStrategy(layout) {
  49380. (0, _classCallCheck3['default'])(this, HorizontalStrategy);
  49381. var _this2 = (0, _possibleConstructorReturn3['default'])(this, (HorizontalStrategy.__proto__ || (0, _getPrototypeOf2['default'])(HorizontalStrategy)).call(this));
  49382. _this2.layout = layout;
  49383. return _this2;
  49384. }
  49385. /** @inheritdoc */
  49386. (0, _createClass3['default'])(HorizontalStrategy, [{
  49387. key: 'curveType',
  49388. value: function curveType() {
  49389. return 'vertical';
  49390. }
  49391. /** @inheritdoc */
  49392. }, {
  49393. key: 'getPosition',
  49394. value: function getPosition(node) {
  49395. return node.y;
  49396. }
  49397. /** @inheritdoc */
  49398. }, {
  49399. key: 'setPosition',
  49400. value: function setPosition(node, position) {
  49401. var level = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
  49402. if (level !== undefined) {
  49403. this.layout.hierarchical.addToOrdering(node, level);
  49404. }
  49405. node.y = position;
  49406. }
  49407. /** @inheritdoc */
  49408. }, {
  49409. key: 'getTreeSize',
  49410. value: function getTreeSize(index) {
  49411. var res = this.layout.hierarchical.getTreeSize(this.layout.body.nodes, index);
  49412. return { min: res.min_y, max: res.max_y };
  49413. }
  49414. /** @inheritdoc */
  49415. }, {
  49416. key: 'sort',
  49417. value: function sort(nodeArray) {
  49418. nodeArray.sort(function (a, b) {
  49419. // Test on 'undefined' takes care of divergent behaviour in chrome
  49420. if (a.y === undefined || b.y === undefined) return 0; // THIS HAPPENS
  49421. return a.y - b.y;
  49422. });
  49423. }
  49424. /** @inheritdoc */
  49425. }, {
  49426. key: 'fix',
  49427. value: function fix(node, level) {
  49428. node.x = this.layout.options.hierarchical.levelSeparation * level;
  49429. node.options.fixed.x = true;
  49430. }
  49431. /** @inheritdoc */
  49432. }, {
  49433. key: 'shift',
  49434. value: function shift(nodeId, diff) {
  49435. this.layout.body.nodes[nodeId].y += diff;
  49436. }
  49437. }]);
  49438. return HorizontalStrategy;
  49439. }(DirectionInterface);
  49440. exports.HorizontalStrategy = HorizontalStrategy;
  49441. exports.VerticalStrategy = VerticalStrategy;
  49442. /***/ }),
  49443. /* 237 */
  49444. /***/ (function(module, exports, __webpack_require__) {
  49445. "use strict";
  49446. Object.defineProperty(exports, "__esModule", {
  49447. value: true
  49448. });
  49449. var _keys = __webpack_require__(8);
  49450. var _keys2 = _interopRequireDefault(_keys);
  49451. var _stringify = __webpack_require__(19);
  49452. var _stringify2 = _interopRequireDefault(_stringify);
  49453. var _typeof2 = __webpack_require__(6);
  49454. var _typeof3 = _interopRequireDefault(_typeof2);
  49455. var _classCallCheck2 = __webpack_require__(0);
  49456. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  49457. var _createClass2 = __webpack_require__(1);
  49458. var _createClass3 = _interopRequireDefault(_createClass2);
  49459. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
  49460. var util = __webpack_require__(2);
  49461. var Hammer = __webpack_require__(10);
  49462. var hammerUtil = __webpack_require__(37);
  49463. /**
  49464. * Clears the toolbar div element of children
  49465. *
  49466. * @private
  49467. */
  49468. var ManipulationSystem = function () {
  49469. /**
  49470. * @param {Object} body
  49471. * @param {Canvas} canvas
  49472. * @param {SelectionHandler} selectionHandler
  49473. */
  49474. function ManipulationSystem(body, canvas, selectionHandler) {
  49475. var _this = this;
  49476. (0, _classCallCheck3['default'])(this, ManipulationSystem);
  49477. this.body = body;
  49478. this.canvas = canvas;
  49479. this.selectionHandler = selectionHandler;
  49480. this.editMode = false;
  49481. this.manipulationDiv = undefined;
  49482. this.editModeDiv = undefined;
  49483. this.closeDiv = undefined;
  49484. this.manipulationHammers = [];
  49485. this.temporaryUIFunctions = {};
  49486. this.temporaryEventFunctions = [];
  49487. this.touchTime = 0;
  49488. this.temporaryIds = { nodes: [], edges: [] };
  49489. this.guiEnabled = false;
  49490. this.inMode = false;
  49491. this.selectedControlNode = undefined;
  49492. this.options = {};
  49493. this.defaultOptions = {
  49494. enabled: false,
  49495. initiallyActive: false,
  49496. addNode: true,
  49497. addEdge: true,
  49498. editNode: undefined,
  49499. editEdge: true,
  49500. deleteNode: true,
  49501. deleteEdge: true,
  49502. controlNodeStyle: {
  49503. shape: 'dot',
  49504. size: 6,
  49505. color: { background: '#ff0000', border: '#3c3c3c', highlight: { background: '#07f968', border: '#3c3c3c' } },
  49506. borderWidth: 2,
  49507. borderWidthSelected: 2
  49508. }
  49509. };
  49510. util.extend(this.options, this.defaultOptions);
  49511. this.body.emitter.on('destroy', function () {
  49512. _this._clean();
  49513. });
  49514. this.body.emitter.on('_dataChanged', this._restore.bind(this));
  49515. this.body.emitter.on('_resetData', this._restore.bind(this));
  49516. }
  49517. /**
  49518. * If something changes in the data during editing, switch back to the initial datamanipulation state and close all edit modes.
  49519. * @private
  49520. */
  49521. (0, _createClass3['default'])(ManipulationSystem, [{
  49522. key: '_restore',
  49523. value: function _restore() {
  49524. if (this.inMode !== false) {
  49525. if (this.options.initiallyActive === true) {
  49526. this.enableEditMode();
  49527. } else {
  49528. this.disableEditMode();
  49529. }
  49530. }
  49531. }
  49532. /**
  49533. * Set the Options
  49534. *
  49535. * @param {Object} options
  49536. * @param {Object} allOptions
  49537. * @param {Object} globalOptions
  49538. */
  49539. }, {
  49540. key: 'setOptions',
  49541. value: function setOptions(options, allOptions, globalOptions) {
  49542. if (allOptions !== undefined) {
  49543. if (allOptions.locale !== undefined) {
  49544. this.options.locale = allOptions.locale;
  49545. } else {
  49546. this.options.locale = globalOptions.locale;
  49547. }
  49548. if (allOptions.locales !== undefined) {
  49549. this.options.locales = allOptions.locales;
  49550. } else {
  49551. this.options.locales = globalOptions.locales;
  49552. }
  49553. }
  49554. if (options !== undefined) {
  49555. if (typeof options === 'boolean') {
  49556. this.options.enabled = options;
  49557. } else {
  49558. this.options.enabled = true;
  49559. util.deepExtend(this.options, options);
  49560. }
  49561. if (this.options.initiallyActive === true) {
  49562. this.editMode = true;
  49563. }
  49564. this._setup();
  49565. }
  49566. }
  49567. /**
  49568. * Enable or disable edit-mode. Draws the DOM required and cleans up after itself.
  49569. *
  49570. * @private
  49571. */
  49572. }, {
  49573. key: 'toggleEditMode',
  49574. value: function toggleEditMode() {
  49575. if (this.editMode === true) {
  49576. this.disableEditMode();
  49577. } else {
  49578. this.enableEditMode();
  49579. }
  49580. }
  49581. /**
  49582. * Enables Edit Mode
  49583. */
  49584. }, {
  49585. key: 'enableEditMode',
  49586. value: function enableEditMode() {
  49587. this.editMode = true;
  49588. this._clean();
  49589. if (this.guiEnabled === true) {
  49590. this.manipulationDiv.style.display = 'block';
  49591. this.closeDiv.style.display = 'block';
  49592. this.editModeDiv.style.display = 'none';
  49593. this.showManipulatorToolbar();
  49594. }
  49595. }
  49596. /**
  49597. * Disables Edit Mode
  49598. */
  49599. }, {
  49600. key: 'disableEditMode',
  49601. value: function disableEditMode() {
  49602. this.editMode = false;
  49603. this._clean();
  49604. if (this.guiEnabled === true) {
  49605. this.manipulationDiv.style.display = 'none';
  49606. this.closeDiv.style.display = 'none';
  49607. this.editModeDiv.style.display = 'block';
  49608. this._createEditButton();
  49609. }
  49610. }
  49611. /**
  49612. * Creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
  49613. *
  49614. * @private
  49615. */
  49616. }, {
  49617. key: 'showManipulatorToolbar',
  49618. value: function showManipulatorToolbar() {
  49619. // restore the state of any bound functions or events, remove control nodes, restore physics
  49620. this._clean();
  49621. // reset global variables
  49622. this.manipulationDOM = {};
  49623. // if the gui is enabled, draw all elements.
  49624. if (this.guiEnabled === true) {
  49625. // a _restore will hide these menus
  49626. this.editMode = true;
  49627. this.manipulationDiv.style.display = 'block';
  49628. this.closeDiv.style.display = 'block';
  49629. var selectedNodeCount = this.selectionHandler._getSelectedNodeCount();
  49630. var selectedEdgeCount = this.selectionHandler._getSelectedEdgeCount();
  49631. var selectedTotalCount = selectedNodeCount + selectedEdgeCount;
  49632. var locale = this.options.locales[this.options.locale];
  49633. var needSeperator = false;
  49634. if (this.options.addNode !== false) {
  49635. this._createAddNodeButton(locale);
  49636. needSeperator = true;
  49637. }
  49638. if (this.options.addEdge !== false) {
  49639. if (needSeperator === true) {
  49640. this._createSeperator(1);
  49641. } else {
  49642. needSeperator = true;
  49643. }
  49644. this._createAddEdgeButton(locale);
  49645. }
  49646. if (selectedNodeCount === 1 && typeof this.options.editNode === 'function') {
  49647. if (needSeperator === true) {
  49648. this._createSeperator(2);
  49649. } else {
  49650. needSeperator = true;
  49651. }
  49652. this._createEditNodeButton(locale);
  49653. } else if (selectedEdgeCount === 1 && selectedNodeCount === 0 && this.options.editEdge !== false) {
  49654. if (needSeperator === true) {
  49655. this._createSeperator(3);
  49656. } else {
  49657. needSeperator = true;
  49658. }
  49659. this._createEditEdgeButton(locale);
  49660. }
  49661. // remove buttons
  49662. if (selectedTotalCount !== 0) {
  49663. if (selectedNodeCount > 0 && this.options.deleteNode !== false) {
  49664. if (needSeperator === true) {
  49665. this._createSeperator(4);
  49666. }
  49667. this._createDeleteButton(locale);
  49668. } else if (selectedNodeCount === 0 && this.options.deleteEdge !== false) {
  49669. if (needSeperator === true) {
  49670. this._createSeperator(4);
  49671. }
  49672. this._createDeleteButton(locale);
  49673. }
  49674. }
  49675. // bind the close button
  49676. this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
  49677. // refresh this bar based on what has been selected
  49678. this._temporaryBindEvent('select', this.showManipulatorToolbar.bind(this));
  49679. }
  49680. // redraw to show any possible changes
  49681. this.body.emitter.emit('_redraw');
  49682. }
  49683. /**
  49684. * Create the toolbar for adding Nodes
  49685. */
  49686. }, {
  49687. key: 'addNodeMode',
  49688. value: function addNodeMode() {
  49689. // when using the gui, enable edit mode if it wasnt already.
  49690. if (this.editMode !== true) {
  49691. this.enableEditMode();
  49692. }
  49693. // restore the state of any bound functions or events, remove control nodes, restore physics
  49694. this._clean();
  49695. this.inMode = 'addNode';
  49696. if (this.guiEnabled === true) {
  49697. var locale = this.options.locales[this.options.locale];
  49698. this.manipulationDOM = {};
  49699. this._createBackButton(locale);
  49700. this._createSeperator();
  49701. this._createDescription(locale['addDescription'] || this.options.locales['en']['addDescription']);
  49702. // bind the close button
  49703. this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
  49704. }
  49705. this._temporaryBindEvent('click', this._performAddNode.bind(this));
  49706. }
  49707. /**
  49708. * call the bound function to handle the editing of the node. The node has to be selected.
  49709. */
  49710. }, {
  49711. key: 'editNode',
  49712. value: function editNode() {
  49713. var _this2 = this;
  49714. // when using the gui, enable edit mode if it wasnt already.
  49715. if (this.editMode !== true) {
  49716. this.enableEditMode();
  49717. }
  49718. // restore the state of any bound functions or events, remove control nodes, restore physics
  49719. this._clean();
  49720. var node = this.selectionHandler._getSelectedNode();
  49721. if (node !== undefined) {
  49722. this.inMode = 'editNode';
  49723. if (typeof this.options.editNode === 'function') {
  49724. if (node.isCluster !== true) {
  49725. var data = util.deepExtend({}, node.options, false);
  49726. data.x = node.x;
  49727. data.y = node.y;
  49728. if (this.options.editNode.length === 2) {
  49729. this.options.editNode(data, function (finalizedData) {
  49730. if (finalizedData !== null && finalizedData !== undefined && _this2.inMode === 'editNode') {
  49731. // if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
  49732. _this2.body.data.nodes.getDataSet().update(finalizedData);
  49733. }
  49734. _this2.showManipulatorToolbar();
  49735. });
  49736. } else {
  49737. throw new Error('The function for edit does not support two arguments (data, callback)');
  49738. }
  49739. } else {
  49740. alert(this.options.locales[this.options.locale]['editClusterError'] || this.options.locales['en']['editClusterError']);
  49741. }
  49742. } else {
  49743. throw new Error('No function has been configured to handle the editing of nodes.');
  49744. }
  49745. } else {
  49746. this.showManipulatorToolbar();
  49747. }
  49748. }
  49749. /**
  49750. * create the toolbar to connect nodes
  49751. */
  49752. }, {
  49753. key: 'addEdgeMode',
  49754. value: function addEdgeMode() {
  49755. // when using the gui, enable edit mode if it wasnt already.
  49756. if (this.editMode !== true) {
  49757. this.enableEditMode();
  49758. }
  49759. // restore the state of any bound functions or events, remove control nodes, restore physics
  49760. this._clean();
  49761. this.inMode = 'addEdge';
  49762. if (this.guiEnabled === true) {
  49763. var locale = this.options.locales[this.options.locale];
  49764. this.manipulationDOM = {};
  49765. this._createBackButton(locale);
  49766. this._createSeperator();
  49767. this._createDescription(locale['edgeDescription'] || this.options.locales['en']['edgeDescription']);
  49768. // bind the close button
  49769. this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
  49770. }
  49771. // temporarily overload functions
  49772. this._temporaryBindUI('onTouch', this._handleConnect.bind(this));
  49773. this._temporaryBindUI('onDragEnd', this._finishConnect.bind(this));
  49774. this._temporaryBindUI('onDrag', this._dragControlNode.bind(this));
  49775. this._temporaryBindUI('onRelease', this._finishConnect.bind(this));
  49776. this._temporaryBindUI('onDragStart', this._dragStartEdge.bind(this));
  49777. this._temporaryBindUI('onHold', function () {});
  49778. }
  49779. /**
  49780. * create the toolbar to edit edges
  49781. */
  49782. }, {
  49783. key: 'editEdgeMode',
  49784. value: function editEdgeMode() {
  49785. // when using the gui, enable edit mode if it wasn't already.
  49786. if (this.editMode !== true) {
  49787. this.enableEditMode();
  49788. }
  49789. // restore the state of any bound functions or events, remove control nodes, restore physics
  49790. this._clean();
  49791. this.inMode = 'editEdge';
  49792. if ((0, _typeof3['default'])(this.options.editEdge) === 'object' && typeof this.options.editEdge.editWithoutDrag === "function") {
  49793. this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0];
  49794. if (this.edgeBeingEditedId !== undefined) {
  49795. var edge = this.body.edges[this.edgeBeingEditedId];
  49796. this._performEditEdge(edge.from, edge.to);
  49797. return;
  49798. }
  49799. }
  49800. if (this.guiEnabled === true) {
  49801. var locale = this.options.locales[this.options.locale];
  49802. this.manipulationDOM = {};
  49803. this._createBackButton(locale);
  49804. this._createSeperator();
  49805. this._createDescription(locale['editEdgeDescription'] || this.options.locales['en']['editEdgeDescription']);
  49806. // bind the close button
  49807. this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
  49808. }
  49809. this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0];
  49810. if (this.edgeBeingEditedId !== undefined) {
  49811. var _edge = this.body.edges[this.edgeBeingEditedId];
  49812. // create control nodes
  49813. var controlNodeFrom = this._getNewTargetNode(_edge.from.x, _edge.from.y);
  49814. var controlNodeTo = this._getNewTargetNode(_edge.to.x, _edge.to.y);
  49815. this.temporaryIds.nodes.push(controlNodeFrom.id);
  49816. this.temporaryIds.nodes.push(controlNodeTo.id);
  49817. this.body.nodes[controlNodeFrom.id] = controlNodeFrom;
  49818. this.body.nodeIndices.push(controlNodeFrom.id);
  49819. this.body.nodes[controlNodeTo.id] = controlNodeTo;
  49820. this.body.nodeIndices.push(controlNodeTo.id);
  49821. // temporarily overload UI functions, cleaned up automatically because of _temporaryBindUI
  49822. this._temporaryBindUI('onTouch', this._controlNodeTouch.bind(this)); // used to get the position
  49823. this._temporaryBindUI('onTap', function () {}); // disabled
  49824. this._temporaryBindUI('onHold', function () {}); // disabled
  49825. this._temporaryBindUI('onDragStart', this._controlNodeDragStart.bind(this)); // used to select control node
  49826. this._temporaryBindUI('onDrag', this._controlNodeDrag.bind(this)); // used to drag control node
  49827. this._temporaryBindUI('onDragEnd', this._controlNodeDragEnd.bind(this)); // used to connect or revert control nodes
  49828. this._temporaryBindUI('onMouseMove', function () {}); // disabled
  49829. // create function to position control nodes correctly on movement
  49830. // automatically cleaned up because we use the temporary bind
  49831. this._temporaryBindEvent('beforeDrawing', function (ctx) {
  49832. var positions = _edge.edgeType.findBorderPositions(ctx);
  49833. if (controlNodeFrom.selected === false) {
  49834. controlNodeFrom.x = positions.from.x;
  49835. controlNodeFrom.y = positions.from.y;
  49836. }
  49837. if (controlNodeTo.selected === false) {
  49838. controlNodeTo.x = positions.to.x;
  49839. controlNodeTo.y = positions.to.y;
  49840. }
  49841. });
  49842. this.body.emitter.emit('_redraw');
  49843. } else {
  49844. this.showManipulatorToolbar();
  49845. }
  49846. }
  49847. /**
  49848. * delete everything in the selection
  49849. */
  49850. }, {
  49851. key: 'deleteSelected',
  49852. value: function deleteSelected() {
  49853. var _this3 = this;
  49854. // when using the gui, enable edit mode if it wasnt already.
  49855. if (this.editMode !== true) {
  49856. this.enableEditMode();
  49857. }
  49858. // restore the state of any bound functions or events, remove control nodes, restore physics
  49859. this._clean();
  49860. this.inMode = 'delete';
  49861. var selectedNodes = this.selectionHandler.getSelectedNodes();
  49862. var selectedEdges = this.selectionHandler.getSelectedEdges();
  49863. var deleteFunction = undefined;
  49864. if (selectedNodes.length > 0) {
  49865. for (var i = 0; i < selectedNodes.length; i++) {
  49866. if (this.body.nodes[selectedNodes[i]].isCluster === true) {
  49867. alert(this.options.locales[this.options.locale]['deleteClusterError'] || this.options.locales['en']['deleteClusterError']);
  49868. return;
  49869. }
  49870. }
  49871. if (typeof this.options.deleteNode === 'function') {
  49872. deleteFunction = this.options.deleteNode;
  49873. }
  49874. } else if (selectedEdges.length > 0) {
  49875. if (typeof this.options.deleteEdge === 'function') {
  49876. deleteFunction = this.options.deleteEdge;
  49877. }
  49878. }
  49879. if (typeof deleteFunction === 'function') {
  49880. var data = { nodes: selectedNodes, edges: selectedEdges };
  49881. if (deleteFunction.length === 2) {
  49882. deleteFunction(data, function (finalizedData) {
  49883. if (finalizedData !== null && finalizedData !== undefined && _this3.inMode === 'delete') {
  49884. // if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
  49885. _this3.body.data.edges.getDataSet().remove(finalizedData.edges);
  49886. _this3.body.data.nodes.getDataSet().remove(finalizedData.nodes);
  49887. _this3.body.emitter.emit('startSimulation');
  49888. _this3.showManipulatorToolbar();
  49889. } else {
  49890. _this3.body.emitter.emit('startSimulation');
  49891. _this3.showManipulatorToolbar();
  49892. }
  49893. });
  49894. } else {
  49895. throw new Error('The function for delete does not support two arguments (data, callback)');
  49896. }
  49897. } else {
  49898. this.body.data.edges.getDataSet().remove(selectedEdges);
  49899. this.body.data.nodes.getDataSet().remove(selectedNodes);
  49900. this.body.emitter.emit('startSimulation');
  49901. this.showManipulatorToolbar();
  49902. }
  49903. }
  49904. //********************************************** PRIVATE ***************************************//
  49905. /**
  49906. * draw or remove the DOM
  49907. * @private
  49908. */
  49909. }, {
  49910. key: '_setup',
  49911. value: function _setup() {
  49912. if (this.options.enabled === true) {
  49913. // Enable the GUI
  49914. this.guiEnabled = true;
  49915. this._createWrappers();
  49916. if (this.editMode === false) {
  49917. this._createEditButton();
  49918. } else {
  49919. this.showManipulatorToolbar();
  49920. }
  49921. } else {
  49922. this._removeManipulationDOM();
  49923. // disable the gui
  49924. this.guiEnabled = false;
  49925. }
  49926. }
  49927. /**
  49928. * create the div overlays that contain the DOM
  49929. * @private
  49930. */
  49931. }, {
  49932. key: '_createWrappers',
  49933. value: function _createWrappers() {
  49934. // load the manipulator HTML elements. All styling done in css.
  49935. if (this.manipulationDiv === undefined) {
  49936. this.manipulationDiv = document.createElement('div');
  49937. this.manipulationDiv.className = 'vis-manipulation';
  49938. if (this.editMode === true) {
  49939. this.manipulationDiv.style.display = 'block';
  49940. } else {
  49941. this.manipulationDiv.style.display = 'none';
  49942. }
  49943. this.canvas.frame.appendChild(this.manipulationDiv);
  49944. }
  49945. // container for the edit button.
  49946. if (this.editModeDiv === undefined) {
  49947. this.editModeDiv = document.createElement('div');
  49948. this.editModeDiv.className = 'vis-edit-mode';
  49949. if (this.editMode === true) {
  49950. this.editModeDiv.style.display = 'none';
  49951. } else {
  49952. this.editModeDiv.style.display = 'block';
  49953. }
  49954. this.canvas.frame.appendChild(this.editModeDiv);
  49955. }
  49956. // container for the close div button
  49957. if (this.closeDiv === undefined) {
  49958. this.closeDiv = document.createElement('div');
  49959. this.closeDiv.className = 'vis-close';
  49960. this.closeDiv.style.display = this.manipulationDiv.style.display;
  49961. this.canvas.frame.appendChild(this.closeDiv);
  49962. }
  49963. }
  49964. /**
  49965. * generate a new target node. Used for creating new edges and editing edges
  49966. *
  49967. * @param {number} x
  49968. * @param {number} y
  49969. * @returns {Node}
  49970. * @private
  49971. */
  49972. }, {
  49973. key: '_getNewTargetNode',
  49974. value: function _getNewTargetNode(x, y) {
  49975. var controlNodeStyle = util.deepExtend({}, this.options.controlNodeStyle);
  49976. controlNodeStyle.id = 'targetNode' + util.randomUUID();
  49977. controlNodeStyle.hidden = false;
  49978. controlNodeStyle.physics = false;
  49979. controlNodeStyle.x = x;
  49980. controlNodeStyle.y = y;
  49981. // we have to define the bounding box in order for the nodes to be drawn immediately
  49982. var node = this.body.functions.createNode(controlNodeStyle);
  49983. node.shape.boundingBox = { left: x, right: x, top: y, bottom: y };
  49984. return node;
  49985. }
  49986. /**
  49987. * Create the edit button
  49988. */
  49989. }, {
  49990. key: '_createEditButton',
  49991. value: function _createEditButton() {
  49992. // restore everything to it's original state (if applicable)
  49993. this._clean();
  49994. // reset the manipulationDOM
  49995. this.manipulationDOM = {};
  49996. // empty the editModeDiv
  49997. util.recursiveDOMDelete(this.editModeDiv);
  49998. // create the contents for the editMode button
  49999. var locale = this.options.locales[this.options.locale];
  50000. var button = this._createButton('editMode', 'vis-button vis-edit vis-edit-mode', locale['edit'] || this.options.locales['en']['edit']);
  50001. this.editModeDiv.appendChild(button);
  50002. // bind a hammer listener to the button, calling the function toggleEditMode.
  50003. this._bindHammerToDiv(button, this.toggleEditMode.bind(this));
  50004. }
  50005. /**
  50006. * this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed.
  50007. * @private
  50008. */
  50009. }, {
  50010. key: '_clean',
  50011. value: function _clean() {
  50012. // not in mode
  50013. this.inMode = false;
  50014. // _clean the divs
  50015. if (this.guiEnabled === true) {
  50016. util.recursiveDOMDelete(this.editModeDiv);
  50017. util.recursiveDOMDelete(this.manipulationDiv);
  50018. // removes all the bindings and overloads
  50019. this._cleanManipulatorHammers();
  50020. }
  50021. // remove temporary nodes and edges
  50022. this._cleanupTemporaryNodesAndEdges();
  50023. // restore overloaded UI functions
  50024. this._unbindTemporaryUIs();
  50025. // remove the temporaryEventFunctions
  50026. this._unbindTemporaryEvents();
  50027. // restore the physics if required
  50028. this.body.emitter.emit('restorePhysics');
  50029. }
  50030. /**
  50031. * Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up.
  50032. * @private
  50033. */
  50034. }, {
  50035. key: '_cleanManipulatorHammers',
  50036. value: function _cleanManipulatorHammers() {
  50037. // _clean hammer bindings
  50038. if (this.manipulationHammers.length != 0) {
  50039. for (var i = 0; i < this.manipulationHammers.length; i++) {
  50040. this.manipulationHammers[i].destroy();
  50041. }
  50042. this.manipulationHammers = [];
  50043. }
  50044. }
  50045. /**
  50046. * Remove all DOM elements created by this module.
  50047. * @private
  50048. */
  50049. }, {
  50050. key: '_removeManipulationDOM',
  50051. value: function _removeManipulationDOM() {
  50052. // removes all the bindings and overloads
  50053. this._clean();
  50054. // empty the manipulation divs
  50055. util.recursiveDOMDelete(this.manipulationDiv);
  50056. util.recursiveDOMDelete(this.editModeDiv);
  50057. util.recursiveDOMDelete(this.closeDiv);
  50058. // remove the manipulation divs
  50059. if (this.manipulationDiv) {
  50060. this.canvas.frame.removeChild(this.manipulationDiv);
  50061. }
  50062. if (this.editModeDiv) {
  50063. this.canvas.frame.removeChild(this.editModeDiv);
  50064. }
  50065. if (this.closeDiv) {
  50066. this.canvas.frame.removeChild(this.closeDiv);
  50067. }
  50068. // set the references to undefined
  50069. this.manipulationDiv = undefined;
  50070. this.editModeDiv = undefined;
  50071. this.closeDiv = undefined;
  50072. }
  50073. /**
  50074. * create a seperator line. the index is to differentiate in the manipulation dom
  50075. * @param {number} [index=1]
  50076. * @private
  50077. */
  50078. }, {
  50079. key: '_createSeperator',
  50080. value: function _createSeperator() {
  50081. var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
  50082. this.manipulationDOM['seperatorLineDiv' + index] = document.createElement('div');
  50083. this.manipulationDOM['seperatorLineDiv' + index].className = 'vis-separator-line';
  50084. this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv' + index]);
  50085. }
  50086. // ---------------------- DOM functions for buttons --------------------------//
  50087. /**
  50088. *
  50089. * @param {Locale} locale
  50090. * @private
  50091. */
  50092. }, {
  50093. key: '_createAddNodeButton',
  50094. value: function _createAddNodeButton(locale) {
  50095. var button = this._createButton('addNode', 'vis-button vis-add', locale['addNode'] || this.options.locales['en']['addNode']);
  50096. this.manipulationDiv.appendChild(button);
  50097. this._bindHammerToDiv(button, this.addNodeMode.bind(this));
  50098. }
  50099. /**
  50100. *
  50101. * @param {Locale} locale
  50102. * @private
  50103. */
  50104. }, {
  50105. key: '_createAddEdgeButton',
  50106. value: function _createAddEdgeButton(locale) {
  50107. var button = this._createButton('addEdge', 'vis-button vis-connect', locale['addEdge'] || this.options.locales['en']['addEdge']);
  50108. this.manipulationDiv.appendChild(button);
  50109. this._bindHammerToDiv(button, this.addEdgeMode.bind(this));
  50110. }
  50111. /**
  50112. *
  50113. * @param {Locale} locale
  50114. * @private
  50115. */
  50116. }, {
  50117. key: '_createEditNodeButton',
  50118. value: function _createEditNodeButton(locale) {
  50119. var button = this._createButton('editNode', 'vis-button vis-edit', locale['editNode'] || this.options.locales['en']['editNode']);
  50120. this.manipulationDiv.appendChild(button);
  50121. this._bindHammerToDiv(button, this.editNode.bind(this));
  50122. }
  50123. /**
  50124. *
  50125. * @param {Locale} locale
  50126. * @private
  50127. */
  50128. }, {
  50129. key: '_createEditEdgeButton',
  50130. value: function _createEditEdgeButton(locale) {
  50131. var button = this._createButton('editEdge', 'vis-button vis-edit', locale['editEdge'] || this.options.locales['en']['editEdge']);
  50132. this.manipulationDiv.appendChild(button);
  50133. this._bindHammerToDiv(button, this.editEdgeMode.bind(this));
  50134. }
  50135. /**
  50136. *
  50137. * @param {Locale} locale
  50138. * @private
  50139. */
  50140. }, {
  50141. key: '_createDeleteButton',
  50142. value: function _createDeleteButton(locale) {
  50143. var deleteBtnClass;
  50144. if (this.options.rtl) {
  50145. deleteBtnClass = 'vis-button vis-delete-rtl';
  50146. } else {
  50147. deleteBtnClass = 'vis-button vis-delete';
  50148. }
  50149. var button = this._createButton('delete', deleteBtnClass, locale['del'] || this.options.locales['en']['del']);
  50150. this.manipulationDiv.appendChild(button);
  50151. this._bindHammerToDiv(button, this.deleteSelected.bind(this));
  50152. }
  50153. /**
  50154. *
  50155. * @param {Locale} locale
  50156. * @private
  50157. */
  50158. }, {
  50159. key: '_createBackButton',
  50160. value: function _createBackButton(locale) {
  50161. var button = this._createButton('back', 'vis-button vis-back', locale['back'] || this.options.locales['en']['back']);
  50162. this.manipulationDiv.appendChild(button);
  50163. this._bindHammerToDiv(button, this.showManipulatorToolbar.bind(this));
  50164. }
  50165. /**
  50166. *
  50167. * @param {number|string} id
  50168. * @param {string} className
  50169. * @param {label} label
  50170. * @param {string} labelClassName
  50171. * @returns {HTMLElement}
  50172. * @private
  50173. */
  50174. }, {
  50175. key: '_createButton',
  50176. value: function _createButton(id, className, label) {
  50177. var labelClassName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'vis-label';
  50178. this.manipulationDOM[id + 'Div'] = document.createElement('div');
  50179. this.manipulationDOM[id + 'Div'].className = className;
  50180. this.manipulationDOM[id + 'Label'] = document.createElement('div');
  50181. this.manipulationDOM[id + 'Label'].className = labelClassName;
  50182. this.manipulationDOM[id + 'Label'].innerHTML = label;
  50183. this.manipulationDOM[id + 'Div'].appendChild(this.manipulationDOM[id + 'Label']);
  50184. return this.manipulationDOM[id + 'Div'];
  50185. }
  50186. /**
  50187. *
  50188. * @param {Label} label
  50189. * @private
  50190. */
  50191. }, {
  50192. key: '_createDescription',
  50193. value: function _createDescription(label) {
  50194. this.manipulationDiv.appendChild(this._createButton('description', 'vis-button vis-none', label));
  50195. }
  50196. // -------------------------- End of DOM functions for buttons ------------------------------//
  50197. /**
  50198. * this binds an event until cleanup by the clean functions.
  50199. * @param {Event} event The event
  50200. * @param {function} newFunction
  50201. * @private
  50202. */
  50203. }, {
  50204. key: '_temporaryBindEvent',
  50205. value: function _temporaryBindEvent(event, newFunction) {
  50206. this.temporaryEventFunctions.push({ event: event, boundFunction: newFunction });
  50207. this.body.emitter.on(event, newFunction);
  50208. }
  50209. /**
  50210. * this overrides an UI function until cleanup by the clean function
  50211. * @param {string} UIfunctionName
  50212. * @param {function} newFunction
  50213. * @private
  50214. */
  50215. }, {
  50216. key: '_temporaryBindUI',
  50217. value: function _temporaryBindUI(UIfunctionName, newFunction) {
  50218. if (this.body.eventListeners[UIfunctionName] !== undefined) {
  50219. this.temporaryUIFunctions[UIfunctionName] = this.body.eventListeners[UIfunctionName];
  50220. this.body.eventListeners[UIfunctionName] = newFunction;
  50221. } else {
  50222. throw new Error('This UI function does not exist. Typo? You tried: ' + UIfunctionName + ' possible are: ' + (0, _stringify2['default'])((0, _keys2['default'])(this.body.eventListeners)));
  50223. }
  50224. }
  50225. /**
  50226. * Restore the overridden UI functions to their original state.
  50227. *
  50228. * @private
  50229. */
  50230. }, {
  50231. key: '_unbindTemporaryUIs',
  50232. value: function _unbindTemporaryUIs() {
  50233. for (var functionName in this.temporaryUIFunctions) {
  50234. if (this.temporaryUIFunctions.hasOwnProperty(functionName)) {
  50235. this.body.eventListeners[functionName] = this.temporaryUIFunctions[functionName];
  50236. delete this.temporaryUIFunctions[functionName];
  50237. }
  50238. }
  50239. this.temporaryUIFunctions = {};
  50240. }
  50241. /**
  50242. * Unbind the events created by _temporaryBindEvent
  50243. * @private
  50244. */
  50245. }, {
  50246. key: '_unbindTemporaryEvents',
  50247. value: function _unbindTemporaryEvents() {
  50248. for (var i = 0; i < this.temporaryEventFunctions.length; i++) {
  50249. var eventName = this.temporaryEventFunctions[i].event;
  50250. var boundFunction = this.temporaryEventFunctions[i].boundFunction;
  50251. this.body.emitter.off(eventName, boundFunction);
  50252. }
  50253. this.temporaryEventFunctions = [];
  50254. }
  50255. /**
  50256. * Bind an hammer instance to a DOM element.
  50257. *
  50258. * @param {Element} domElement
  50259. * @param {function} boundFunction
  50260. */
  50261. }, {
  50262. key: '_bindHammerToDiv',
  50263. value: function _bindHammerToDiv(domElement, boundFunction) {
  50264. var hammer = new Hammer(domElement, {});
  50265. hammerUtil.onTouch(hammer, boundFunction);
  50266. this.manipulationHammers.push(hammer);
  50267. }
  50268. /**
  50269. * Neatly clean up temporary edges and nodes
  50270. * @private
  50271. */
  50272. }, {
  50273. key: '_cleanupTemporaryNodesAndEdges',
  50274. value: function _cleanupTemporaryNodesAndEdges() {
  50275. // _clean temporary edges
  50276. for (var i = 0; i < this.temporaryIds.edges.length; i++) {
  50277. this.body.edges[this.temporaryIds.edges[i]].disconnect();
  50278. delete this.body.edges[this.temporaryIds.edges[i]];
  50279. var indexTempEdge = this.body.edgeIndices.indexOf(this.temporaryIds.edges[i]);
  50280. if (indexTempEdge !== -1) {
  50281. this.body.edgeIndices.splice(indexTempEdge, 1);
  50282. }
  50283. }
  50284. // _clean temporary nodes
  50285. for (var _i = 0; _i < this.temporaryIds.nodes.length; _i++) {
  50286. delete this.body.nodes[this.temporaryIds.nodes[_i]];
  50287. var indexTempNode = this.body.nodeIndices.indexOf(this.temporaryIds.nodes[_i]);
  50288. if (indexTempNode !== -1) {
  50289. this.body.nodeIndices.splice(indexTempNode, 1);
  50290. }
  50291. }
  50292. this.temporaryIds = { nodes: [], edges: [] };
  50293. }
  50294. // ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------//
  50295. /**
  50296. * the touch is used to get the position of the initial click
  50297. * @param {Event} event The event
  50298. * @private
  50299. */
  50300. }, {
  50301. key: '_controlNodeTouch',
  50302. value: function _controlNodeTouch(event) {
  50303. this.selectionHandler.unselectAll();
  50304. this.lastTouch = this.body.functions.getPointer(event.center);
  50305. this.lastTouch.translation = util.extend({}, this.body.view.translation); // copy the object
  50306. }
  50307. /**
  50308. * the drag start is used to mark one of the control nodes as selected.
  50309. * @param {Event} event The event
  50310. * @private
  50311. */
  50312. }, {
  50313. key: '_controlNodeDragStart',
  50314. value: function _controlNodeDragStart(event) {
  50315. // eslint-disable-line no-unused-vars
  50316. var pointer = this.lastTouch;
  50317. var pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  50318. var from = this.body.nodes[this.temporaryIds.nodes[0]];
  50319. var to = this.body.nodes[this.temporaryIds.nodes[1]];
  50320. var edge = this.body.edges[this.edgeBeingEditedId];
  50321. this.selectedControlNode = undefined;
  50322. var fromSelect = from.isOverlappingWith(pointerObj);
  50323. var toSelect = to.isOverlappingWith(pointerObj);
  50324. if (fromSelect === true) {
  50325. this.selectedControlNode = from;
  50326. edge.edgeType.from = from;
  50327. } else if (toSelect === true) {
  50328. this.selectedControlNode = to;
  50329. edge.edgeType.to = to;
  50330. }
  50331. // we use the selection to find the node that is being dragged. We explicitly select it here.
  50332. if (this.selectedControlNode !== undefined) {
  50333. this.selectionHandler.selectObject(this.selectedControlNode);
  50334. }
  50335. this.body.emitter.emit('_redraw');
  50336. }
  50337. /**
  50338. * dragging the control nodes or the canvas
  50339. * @param {Event} event The event
  50340. * @private
  50341. */
  50342. }, {
  50343. key: '_controlNodeDrag',
  50344. value: function _controlNodeDrag(event) {
  50345. this.body.emitter.emit('disablePhysics');
  50346. var pointer = this.body.functions.getPointer(event.center);
  50347. var pos = this.canvas.DOMtoCanvas(pointer);
  50348. if (this.selectedControlNode !== undefined) {
  50349. this.selectedControlNode.x = pos.x;
  50350. this.selectedControlNode.y = pos.y;
  50351. } else {
  50352. // if the drag was not started properly because the click started outside the network div, start it now.
  50353. var diffX = pointer.x - this.lastTouch.x;
  50354. var diffY = pointer.y - this.lastTouch.y;
  50355. this.body.view.translation = { x: this.lastTouch.translation.x + diffX, y: this.lastTouch.translation.y + diffY };
  50356. }
  50357. this.body.emitter.emit('_redraw');
  50358. }
  50359. /**
  50360. * connecting or restoring the control nodes.
  50361. * @param {Event} event The event
  50362. * @private
  50363. */
  50364. }, {
  50365. key: '_controlNodeDragEnd',
  50366. value: function _controlNodeDragEnd(event) {
  50367. var pointer = this.body.functions.getPointer(event.center);
  50368. var pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  50369. var edge = this.body.edges[this.edgeBeingEditedId];
  50370. // if the node that was dragged is not a control node, return
  50371. if (this.selectedControlNode === undefined) {
  50372. return;
  50373. }
  50374. // we use the selection to find the node that is being dragged. We explicitly DEselect the control node here.
  50375. this.selectionHandler.unselectAll();
  50376. var overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj);
  50377. var node = undefined;
  50378. for (var i = overlappingNodeIds.length - 1; i >= 0; i--) {
  50379. if (overlappingNodeIds[i] !== this.selectedControlNode.id) {
  50380. node = this.body.nodes[overlappingNodeIds[i]];
  50381. break;
  50382. }
  50383. }
  50384. // perform the connection
  50385. if (node !== undefined && this.selectedControlNode !== undefined) {
  50386. if (node.isCluster === true) {
  50387. alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']);
  50388. } else {
  50389. var from = this.body.nodes[this.temporaryIds.nodes[0]];
  50390. if (this.selectedControlNode.id === from.id) {
  50391. this._performEditEdge(node.id, edge.to.id);
  50392. } else {
  50393. this._performEditEdge(edge.from.id, node.id);
  50394. }
  50395. }
  50396. } else {
  50397. edge.updateEdgeType();
  50398. this.body.emitter.emit('restorePhysics');
  50399. }
  50400. this.body.emitter.emit('_redraw');
  50401. }
  50402. // ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------//
  50403. // ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------//
  50404. /**
  50405. * the function bound to the selection event. It checks if you want to connect a cluster and changes the description
  50406. * to walk the user through the process.
  50407. *
  50408. * @param {Event} event
  50409. * @private
  50410. */
  50411. }, {
  50412. key: '_handleConnect',
  50413. value: function _handleConnect(event) {
  50414. // check to avoid double fireing of this function.
  50415. if (new Date().valueOf() - this.touchTime > 100) {
  50416. this.lastTouch = this.body.functions.getPointer(event.center);
  50417. this.lastTouch.translation = util.extend({}, this.body.view.translation); // copy the object
  50418. var pointer = this.lastTouch;
  50419. var node = this.selectionHandler.getNodeAt(pointer);
  50420. if (node !== undefined) {
  50421. if (node.isCluster === true) {
  50422. alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']);
  50423. } else {
  50424. // create a node the temporary line can look at
  50425. var targetNode = this._getNewTargetNode(node.x, node.y);
  50426. this.body.nodes[targetNode.id] = targetNode;
  50427. this.body.nodeIndices.push(targetNode.id);
  50428. // create a temporary edge
  50429. var connectionEdge = this.body.functions.createEdge({
  50430. id: 'connectionEdge' + util.randomUUID(),
  50431. from: node.id,
  50432. to: targetNode.id,
  50433. physics: false,
  50434. smooth: {
  50435. enabled: true,
  50436. type: 'continuous',
  50437. roundness: 0.5
  50438. }
  50439. });
  50440. this.body.edges[connectionEdge.id] = connectionEdge;
  50441. this.body.edgeIndices.push(connectionEdge.id);
  50442. this.temporaryIds.nodes.push(targetNode.id);
  50443. this.temporaryIds.edges.push(connectionEdge.id);
  50444. }
  50445. }
  50446. this.touchTime = new Date().valueOf();
  50447. }
  50448. }
  50449. /**
  50450. *
  50451. * @param {Event} event
  50452. * @private
  50453. */
  50454. }, {
  50455. key: '_dragControlNode',
  50456. value: function _dragControlNode(event) {
  50457. var pointer = this.body.functions.getPointer(event.center);
  50458. if (this.temporaryIds.nodes[0] !== undefined) {
  50459. var targetNode = this.body.nodes[this.temporaryIds.nodes[0]]; // there is only one temp node in the add edge mode.
  50460. targetNode.x = this.canvas._XconvertDOMtoCanvas(pointer.x);
  50461. targetNode.y = this.canvas._YconvertDOMtoCanvas(pointer.y);
  50462. this.body.emitter.emit('_redraw');
  50463. } else {
  50464. var diffX = pointer.x - this.lastTouch.x;
  50465. var diffY = pointer.y - this.lastTouch.y;
  50466. this.body.view.translation = { x: this.lastTouch.translation.x + diffX, y: this.lastTouch.translation.y + diffY };
  50467. }
  50468. }
  50469. /**
  50470. * Connect the new edge to the target if one exists, otherwise remove temp line
  50471. * @param {Event} event The event
  50472. * @private
  50473. */
  50474. }, {
  50475. key: '_finishConnect',
  50476. value: function _finishConnect(event) {
  50477. var pointer = this.body.functions.getPointer(event.center);
  50478. var pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
  50479. // remember the edge id
  50480. var connectFromId = undefined;
  50481. if (this.temporaryIds.edges[0] !== undefined) {
  50482. connectFromId = this.body.edges[this.temporaryIds.edges[0]].fromId;
  50483. }
  50484. // get the overlapping node but NOT the temporary node;
  50485. var overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj);
  50486. var node = undefined;
  50487. for (var i = overlappingNodeIds.length - 1; i >= 0; i--) {
  50488. // if the node id is NOT a temporary node, accept the node.
  50489. if (this.temporaryIds.nodes.indexOf(overlappingNodeIds[i]) === -1) {
  50490. node = this.body.nodes[overlappingNodeIds[i]];
  50491. break;
  50492. }
  50493. }
  50494. // clean temporary nodes and edges.
  50495. this._cleanupTemporaryNodesAndEdges();
  50496. // perform the connection
  50497. if (node !== undefined) {
  50498. if (node.isCluster === true) {
  50499. alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']);
  50500. } else {
  50501. if (this.body.nodes[connectFromId] !== undefined && this.body.nodes[node.id] !== undefined) {
  50502. this._performAddEdge(connectFromId, node.id);
  50503. }
  50504. }
  50505. }
  50506. // No need to do _generateclickevent('dragEnd') here, the regular dragEnd event fires.
  50507. this.body.emitter.emit('_redraw');
  50508. }
  50509. /**
  50510. *
  50511. * @param {Event} event
  50512. * @private
  50513. */
  50514. }, {
  50515. key: '_dragStartEdge',
  50516. value: function _dragStartEdge(event) {
  50517. var pointer = this.lastTouch;
  50518. this.selectionHandler._generateClickEvent('dragStart', event, pointer, undefined, true);
  50519. }
  50520. // --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------//
  50521. // ------------------------------ Performing all the actual data manipulation ------------------------//
  50522. /**
  50523. * Adds a node on the specified location
  50524. *
  50525. * @param {Object} clickData
  50526. * @private
  50527. */
  50528. }, {
  50529. key: '_performAddNode',
  50530. value: function _performAddNode(clickData) {
  50531. var _this4 = this;
  50532. var defaultData = {
  50533. id: util.randomUUID(),
  50534. x: clickData.pointer.canvas.x,
  50535. y: clickData.pointer.canvas.y,
  50536. label: 'new'
  50537. };
  50538. if (typeof this.options.addNode === 'function') {
  50539. if (this.options.addNode.length === 2) {
  50540. this.options.addNode(defaultData, function (finalizedData) {
  50541. if (finalizedData !== null && finalizedData !== undefined && _this4.inMode === 'addNode') {
  50542. // if for whatever reason the mode has changes (due to dataset change) disregard the callback
  50543. _this4.body.data.nodes.getDataSet().add(finalizedData);
  50544. _this4.showManipulatorToolbar();
  50545. }
  50546. });
  50547. } else {
  50548. this.showManipulatorToolbar();
  50549. throw new Error('The function for add does not support two arguments (data,callback)');
  50550. }
  50551. } else {
  50552. this.body.data.nodes.getDataSet().add(defaultData);
  50553. this.showManipulatorToolbar();
  50554. }
  50555. }
  50556. /**
  50557. * connect two nodes with a new edge.
  50558. *
  50559. * @param {Node.id} sourceNodeId
  50560. * @param {Node.id} targetNodeId
  50561. * @private
  50562. */
  50563. }, {
  50564. key: '_performAddEdge',
  50565. value: function _performAddEdge(sourceNodeId, targetNodeId) {
  50566. var _this5 = this;
  50567. var defaultData = { from: sourceNodeId, to: targetNodeId };
  50568. if (typeof this.options.addEdge === 'function') {
  50569. if (this.options.addEdge.length === 2) {
  50570. this.options.addEdge(defaultData, function (finalizedData) {
  50571. if (finalizedData !== null && finalizedData !== undefined && _this5.inMode === 'addEdge') {
  50572. // if for whatever reason the mode has changes (due to dataset change) disregard the callback
  50573. _this5.body.data.edges.getDataSet().add(finalizedData);
  50574. _this5.selectionHandler.unselectAll();
  50575. _this5.showManipulatorToolbar();
  50576. }
  50577. });
  50578. } else {
  50579. throw new Error('The function for connect does not support two arguments (data,callback)');
  50580. }
  50581. } else {
  50582. this.body.data.edges.getDataSet().add(defaultData);
  50583. this.selectionHandler.unselectAll();
  50584. this.showManipulatorToolbar();
  50585. }
  50586. }
  50587. /**
  50588. * connect two nodes with a new edge.
  50589. *
  50590. * @param {Node.id} sourceNodeId
  50591. * @param {Node.id} targetNodeId
  50592. * @private
  50593. */
  50594. }, {
  50595. key: '_performEditEdge',
  50596. value: function _performEditEdge(sourceNodeId, targetNodeId) {
  50597. var _this6 = this;
  50598. var defaultData = { id: this.edgeBeingEditedId, from: sourceNodeId, to: targetNodeId, label: this.body.data.edges._data[this.edgeBeingEditedId].label };
  50599. var eeFunct = this.options.editEdge;
  50600. if ((typeof eeFunct === 'undefined' ? 'undefined' : (0, _typeof3['default'])(eeFunct)) === 'object') {
  50601. eeFunct = eeFunct.editWithoutDrag;
  50602. }
  50603. if (typeof eeFunct === 'function') {
  50604. if (eeFunct.length === 2) {
  50605. eeFunct(defaultData, function (finalizedData) {
  50606. if (finalizedData === null || finalizedData === undefined || _this6.inMode !== 'editEdge') {
  50607. // if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
  50608. _this6.body.edges[defaultData.id].updateEdgeType();
  50609. _this6.body.emitter.emit('_redraw');
  50610. _this6.showManipulatorToolbar();
  50611. } else {
  50612. _this6.body.data.edges.getDataSet().update(finalizedData);
  50613. _this6.selectionHandler.unselectAll();
  50614. _this6.showManipulatorToolbar();
  50615. }
  50616. });
  50617. } else {
  50618. throw new Error('The function for edit does not support two arguments (data, callback)');
  50619. }
  50620. } else {
  50621. this.body.data.edges.getDataSet().update(defaultData);
  50622. this.selectionHandler.unselectAll();
  50623. this.showManipulatorToolbar();
  50624. }
  50625. }
  50626. }]);
  50627. return ManipulationSystem;
  50628. }();
  50629. exports['default'] = ManipulationSystem;
  50630. /***/ }),
  50631. /* 238 */
  50632. /***/ (function(module, exports, __webpack_require__) {
  50633. "use strict";
  50634. Object.defineProperty(exports, "__esModule", {
  50635. value: true
  50636. });
  50637. var _slicedToArray2 = __webpack_require__(30);
  50638. var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
  50639. var _classCallCheck2 = __webpack_require__(0);
  50640. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  50641. var _createClass2 = __webpack_require__(1);
  50642. var _createClass3 = _interopRequireDefault(_createClass2);
  50643. var _FloydWarshall = __webpack_require__(239);
  50644. var _FloydWarshall2 = _interopRequireDefault(_FloydWarshall);
  50645. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  50646. /**
  50647. * KamadaKawai positions the nodes initially based on
  50648. *
  50649. * "AN ALGORITHM FOR DRAWING GENERAL UNDIRECTED GRAPHS"
  50650. * -- Tomihisa KAMADA and Satoru KAWAI in 1989
  50651. *
  50652. * Possible optimizations in the distance calculation can be implemented.
  50653. */
  50654. var KamadaKawai = function () {
  50655. /**
  50656. * @param {Object} body
  50657. * @param {number} edgeLength
  50658. * @param {number} edgeStrength
  50659. */
  50660. function KamadaKawai(body, edgeLength, edgeStrength) {
  50661. (0, _classCallCheck3["default"])(this, KamadaKawai);
  50662. this.body = body;
  50663. this.springLength = edgeLength;
  50664. this.springConstant = edgeStrength;
  50665. this.distanceSolver = new _FloydWarshall2["default"]();
  50666. }
  50667. /**
  50668. * Not sure if needed but can be used to update the spring length and spring constant
  50669. * @param {Object} options
  50670. */
  50671. (0, _createClass3["default"])(KamadaKawai, [{
  50672. key: "setOptions",
  50673. value: function setOptions(options) {
  50674. if (options) {
  50675. if (options.springLength) {
  50676. this.springLength = options.springLength;
  50677. }
  50678. if (options.springConstant) {
  50679. this.springConstant = options.springConstant;
  50680. }
  50681. }
  50682. }
  50683. /**
  50684. * Position the system
  50685. * @param {Array.<Node>} nodesArray
  50686. * @param {Array.<vis.Edge>} edgesArray
  50687. * @param {boolean} [ignoreClusters=false]
  50688. */
  50689. }, {
  50690. key: "solve",
  50691. value: function solve(nodesArray, edgesArray) {
  50692. var ignoreClusters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  50693. // get distance matrix
  50694. var D_matrix = this.distanceSolver.getDistances(this.body, nodesArray, edgesArray); // distance matrix
  50695. // get the L Matrix
  50696. this._createL_matrix(D_matrix);
  50697. // get the K Matrix
  50698. this._createK_matrix(D_matrix);
  50699. // initial E Matrix
  50700. this._createE_matrix();
  50701. // calculate positions
  50702. var threshold = 0.01;
  50703. var innerThreshold = 1;
  50704. var iterations = 0;
  50705. var maxIterations = Math.max(1000, Math.min(10 * this.body.nodeIndices.length, 6000));
  50706. var maxInnerIterations = 5;
  50707. var maxEnergy = 1e9;
  50708. var highE_nodeId = 0,
  50709. dE_dx = 0,
  50710. dE_dy = 0,
  50711. delta_m = 0,
  50712. subIterations = 0;
  50713. while (maxEnergy > threshold && iterations < maxIterations) {
  50714. iterations += 1;
  50715. var _getHighestEnergyNode2 = this._getHighestEnergyNode(ignoreClusters);
  50716. var _getHighestEnergyNode3 = (0, _slicedToArray3["default"])(_getHighestEnergyNode2, 4);
  50717. highE_nodeId = _getHighestEnergyNode3[0];
  50718. maxEnergy = _getHighestEnergyNode3[1];
  50719. dE_dx = _getHighestEnergyNode3[2];
  50720. dE_dy = _getHighestEnergyNode3[3];
  50721. delta_m = maxEnergy;
  50722. subIterations = 0;
  50723. while (delta_m > innerThreshold && subIterations < maxInnerIterations) {
  50724. subIterations += 1;
  50725. this._moveNode(highE_nodeId, dE_dx, dE_dy);
  50726. var _getEnergy2 = this._getEnergy(highE_nodeId);
  50727. var _getEnergy3 = (0, _slicedToArray3["default"])(_getEnergy2, 3);
  50728. delta_m = _getEnergy3[0];
  50729. dE_dx = _getEnergy3[1];
  50730. dE_dy = _getEnergy3[2];
  50731. }
  50732. }
  50733. }
  50734. /**
  50735. * get the node with the highest energy
  50736. * @param {boolean} ignoreClusters
  50737. * @returns {number[]}
  50738. * @private
  50739. */
  50740. }, {
  50741. key: "_getHighestEnergyNode",
  50742. value: function _getHighestEnergyNode(ignoreClusters) {
  50743. var nodesArray = this.body.nodeIndices;
  50744. var nodes = this.body.nodes;
  50745. var maxEnergy = 0;
  50746. var maxEnergyNodeId = nodesArray[0];
  50747. var dE_dx_max = 0,
  50748. dE_dy_max = 0;
  50749. for (var nodeIdx = 0; nodeIdx < nodesArray.length; nodeIdx++) {
  50750. var m = nodesArray[nodeIdx];
  50751. // by not evaluating nodes with predefined positions we should only move nodes that have no positions.
  50752. if (nodes[m].predefinedPosition === false || nodes[m].isCluster === true && ignoreClusters === true || nodes[m].options.fixed.x === true || nodes[m].options.fixed.y === true) {
  50753. var _getEnergy4 = this._getEnergy(m),
  50754. _getEnergy5 = (0, _slicedToArray3["default"])(_getEnergy4, 3),
  50755. delta_m = _getEnergy5[0],
  50756. dE_dx = _getEnergy5[1],
  50757. dE_dy = _getEnergy5[2];
  50758. if (maxEnergy < delta_m) {
  50759. maxEnergy = delta_m;
  50760. maxEnergyNodeId = m;
  50761. dE_dx_max = dE_dx;
  50762. dE_dy_max = dE_dy;
  50763. }
  50764. }
  50765. }
  50766. return [maxEnergyNodeId, maxEnergy, dE_dx_max, dE_dy_max];
  50767. }
  50768. /**
  50769. * calculate the energy of a single node
  50770. * @param {Node.id} m
  50771. * @returns {number[]}
  50772. * @private
  50773. */
  50774. }, {
  50775. key: "_getEnergy",
  50776. value: function _getEnergy(m) {
  50777. var _E_sums$m = (0, _slicedToArray3["default"])(this.E_sums[m], 2),
  50778. dE_dx = _E_sums$m[0],
  50779. dE_dy = _E_sums$m[1];
  50780. var delta_m = Math.sqrt(Math.pow(dE_dx, 2) + Math.pow(dE_dy, 2));
  50781. return [delta_m, dE_dx, dE_dy];
  50782. }
  50783. /**
  50784. * move the node based on it's energy
  50785. * the dx and dy are calculated from the linear system proposed by Kamada and Kawai
  50786. * @param {number} m
  50787. * @param {number} dE_dx
  50788. * @param {number} dE_dy
  50789. * @private
  50790. */
  50791. }, {
  50792. key: "_moveNode",
  50793. value: function _moveNode(m, dE_dx, dE_dy) {
  50794. var nodesArray = this.body.nodeIndices;
  50795. var nodes = this.body.nodes;
  50796. var d2E_dx2 = 0;
  50797. var d2E_dxdy = 0;
  50798. var d2E_dy2 = 0;
  50799. var x_m = nodes[m].x;
  50800. var y_m = nodes[m].y;
  50801. var km = this.K_matrix[m];
  50802. var lm = this.L_matrix[m];
  50803. for (var iIdx = 0; iIdx < nodesArray.length; iIdx++) {
  50804. var i = nodesArray[iIdx];
  50805. if (i !== m) {
  50806. var x_i = nodes[i].x;
  50807. var y_i = nodes[i].y;
  50808. var kmat = km[i];
  50809. var lmat = lm[i];
  50810. var denominator = 1.0 / Math.pow(Math.pow(x_m - x_i, 2) + Math.pow(y_m - y_i, 2), 1.5);
  50811. d2E_dx2 += kmat * (1 - lmat * Math.pow(y_m - y_i, 2) * denominator);
  50812. d2E_dxdy += kmat * (lmat * (x_m - x_i) * (y_m - y_i) * denominator);
  50813. d2E_dy2 += kmat * (1 - lmat * Math.pow(x_m - x_i, 2) * denominator);
  50814. }
  50815. }
  50816. // make the variable names easier to make the solving of the linear system easier to read
  50817. var A = d2E_dx2,
  50818. B = d2E_dxdy,
  50819. C = dE_dx,
  50820. D = d2E_dy2,
  50821. E = dE_dy;
  50822. // solve the linear system for dx and dy
  50823. var dy = (C / A + E / B) / (B / A - D / B);
  50824. var dx = -(B * dy + C) / A;
  50825. // move the node
  50826. nodes[m].x += dx;
  50827. nodes[m].y += dy;
  50828. // Recalculate E_matrix (should be incremental)
  50829. this._updateE_matrix(m);
  50830. }
  50831. /**
  50832. * Create the L matrix: edge length times shortest path
  50833. * @param {Object} D_matrix
  50834. * @private
  50835. */
  50836. }, {
  50837. key: "_createL_matrix",
  50838. value: function _createL_matrix(D_matrix) {
  50839. var nodesArray = this.body.nodeIndices;
  50840. var edgeLength = this.springLength;
  50841. this.L_matrix = [];
  50842. for (var i = 0; i < nodesArray.length; i++) {
  50843. this.L_matrix[nodesArray[i]] = {};
  50844. for (var j = 0; j < nodesArray.length; j++) {
  50845. this.L_matrix[nodesArray[i]][nodesArray[j]] = edgeLength * D_matrix[nodesArray[i]][nodesArray[j]];
  50846. }
  50847. }
  50848. }
  50849. /**
  50850. * Create the K matrix: spring constants times shortest path
  50851. * @param {Object} D_matrix
  50852. * @private
  50853. */
  50854. }, {
  50855. key: "_createK_matrix",
  50856. value: function _createK_matrix(D_matrix) {
  50857. var nodesArray = this.body.nodeIndices;
  50858. var edgeStrength = this.springConstant;
  50859. this.K_matrix = [];
  50860. for (var i = 0; i < nodesArray.length; i++) {
  50861. this.K_matrix[nodesArray[i]] = {};
  50862. for (var j = 0; j < nodesArray.length; j++) {
  50863. this.K_matrix[nodesArray[i]][nodesArray[j]] = edgeStrength * Math.pow(D_matrix[nodesArray[i]][nodesArray[j]], -2);
  50864. }
  50865. }
  50866. }
  50867. /**
  50868. * Create matrix with all energies between nodes
  50869. * @private
  50870. */
  50871. }, {
  50872. key: "_createE_matrix",
  50873. value: function _createE_matrix() {
  50874. var nodesArray = this.body.nodeIndices;
  50875. var nodes = this.body.nodes;
  50876. this.E_matrix = {};
  50877. this.E_sums = {};
  50878. for (var mIdx = 0; mIdx < nodesArray.length; mIdx++) {
  50879. this.E_matrix[nodesArray[mIdx]] = [];
  50880. }
  50881. for (var _mIdx = 0; _mIdx < nodesArray.length; _mIdx++) {
  50882. var m = nodesArray[_mIdx];
  50883. var x_m = nodes[m].x;
  50884. var y_m = nodes[m].y;
  50885. var dE_dx = 0;
  50886. var dE_dy = 0;
  50887. for (var iIdx = _mIdx; iIdx < nodesArray.length; iIdx++) {
  50888. var i = nodesArray[iIdx];
  50889. if (i !== m) {
  50890. var x_i = nodes[i].x;
  50891. var y_i = nodes[i].y;
  50892. var denominator = 1.0 / Math.sqrt(Math.pow(x_m - x_i, 2) + Math.pow(y_m - y_i, 2));
  50893. this.E_matrix[m][iIdx] = [this.K_matrix[m][i] * (x_m - x_i - this.L_matrix[m][i] * (x_m - x_i) * denominator), this.K_matrix[m][i] * (y_m - y_i - this.L_matrix[m][i] * (y_m - y_i) * denominator)];
  50894. this.E_matrix[i][_mIdx] = this.E_matrix[m][iIdx];
  50895. dE_dx += this.E_matrix[m][iIdx][0];
  50896. dE_dy += this.E_matrix[m][iIdx][1];
  50897. }
  50898. }
  50899. //Store sum
  50900. this.E_sums[m] = [dE_dx, dE_dy];
  50901. }
  50902. }
  50903. /**
  50904. * Update method, just doing single column (rows are auto-updated) (update all sums)
  50905. *
  50906. * @param {number} m
  50907. * @private
  50908. */
  50909. }, {
  50910. key: "_updateE_matrix",
  50911. value: function _updateE_matrix(m) {
  50912. var nodesArray = this.body.nodeIndices;
  50913. var nodes = this.body.nodes;
  50914. var colm = this.E_matrix[m];
  50915. var kcolm = this.K_matrix[m];
  50916. var lcolm = this.L_matrix[m];
  50917. var x_m = nodes[m].x;
  50918. var y_m = nodes[m].y;
  50919. var dE_dx = 0;
  50920. var dE_dy = 0;
  50921. for (var iIdx = 0; iIdx < nodesArray.length; iIdx++) {
  50922. var i = nodesArray[iIdx];
  50923. if (i !== m) {
  50924. //Keep old energy value for sum modification below
  50925. var cell = colm[iIdx];
  50926. var oldDx = cell[0];
  50927. var oldDy = cell[1];
  50928. //Calc new energy:
  50929. var x_i = nodes[i].x;
  50930. var y_i = nodes[i].y;
  50931. var denominator = 1.0 / Math.sqrt(Math.pow(x_m - x_i, 2) + Math.pow(y_m - y_i, 2));
  50932. var dx = kcolm[i] * (x_m - x_i - lcolm[i] * (x_m - x_i) * denominator);
  50933. var dy = kcolm[i] * (y_m - y_i - lcolm[i] * (y_m - y_i) * denominator);
  50934. colm[iIdx] = [dx, dy];
  50935. dE_dx += dx;
  50936. dE_dy += dy;
  50937. //add new energy to sum of each column
  50938. var sum = this.E_sums[i];
  50939. sum[0] += dx - oldDx;
  50940. sum[1] += dy - oldDy;
  50941. }
  50942. }
  50943. //Store sum at -1 index
  50944. this.E_sums[m] = [dE_dx, dE_dy];
  50945. }
  50946. }]);
  50947. return KamadaKawai;
  50948. }(); // distance finding algorithm
  50949. exports["default"] = KamadaKawai;
  50950. /***/ }),
  50951. /* 239 */
  50952. /***/ (function(module, exports, __webpack_require__) {
  50953. "use strict";
  50954. Object.defineProperty(exports, "__esModule", {
  50955. value: true
  50956. });
  50957. var _classCallCheck2 = __webpack_require__(0);
  50958. var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
  50959. var _createClass2 = __webpack_require__(1);
  50960. var _createClass3 = _interopRequireDefault(_createClass2);
  50961. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  50962. /**
  50963. * The Floyd–Warshall algorithm is an algorithm for finding shortest paths in
  50964. * a weighted graph with positive or negative edge weights (but with no negative
  50965. * cycles). - https://en.wikipedia.org/wiki/Floyd–Warshall_algorithm
  50966. */
  50967. var FloydWarshall = function () {
  50968. /**
  50969. * @ignore
  50970. */
  50971. function FloydWarshall() {
  50972. (0, _classCallCheck3["default"])(this, FloydWarshall);
  50973. }
  50974. /**
  50975. *
  50976. * @param {Object} body
  50977. * @param {Array.<Node>} nodesArray
  50978. * @param {Array.<Edge>} edgesArray
  50979. * @returns {{}}
  50980. */
  50981. (0, _createClass3["default"])(FloydWarshall, [{
  50982. key: "getDistances",
  50983. value: function getDistances(body, nodesArray, edgesArray) {
  50984. var D_matrix = {};
  50985. var edges = body.edges;
  50986. // prepare matrix with large numbers
  50987. for (var i = 0; i < nodesArray.length; i++) {
  50988. var node = nodesArray[i];
  50989. var cell = {};
  50990. D_matrix[node] = cell;
  50991. for (var j = 0; j < nodesArray.length; j++) {
  50992. cell[nodesArray[j]] = i == j ? 0 : 1e9;
  50993. }
  50994. }
  50995. // put the weights for the edges in. This assumes unidirectionality.
  50996. for (var _i = 0; _i < edgesArray.length; _i++) {
  50997. var edge = edges[edgesArray[_i]];
  50998. // 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
  50999. if (edge.connected === true && D_matrix[edge.fromId] !== undefined && D_matrix[edge.toId] !== undefined) {
  51000. D_matrix[edge.fromId][edge.toId] = 1;
  51001. D_matrix[edge.toId][edge.fromId] = 1;
  51002. }
  51003. }
  51004. var nodeCount = nodesArray.length;
  51005. // Adapted FloydWarshall based on unidirectionality to greatly reduce complexity.
  51006. for (var k = 0; k < nodeCount; k++) {
  51007. var knode = nodesArray[k];
  51008. var kcolm = D_matrix[knode];
  51009. for (var _i2 = 0; _i2 < nodeCount - 1; _i2++) {
  51010. var inode = nodesArray[_i2];
  51011. var icolm = D_matrix[inode];
  51012. for (var _j = _i2 + 1; _j < nodeCount; _j++) {
  51013. var jnode = nodesArray[_j];
  51014. var jcolm = D_matrix[jnode];
  51015. var val = Math.min(icolm[jnode], icolm[knode] + kcolm[jnode]);
  51016. icolm[jnode] = val;
  51017. jcolm[inode] = val;
  51018. }
  51019. }
  51020. }
  51021. return D_matrix;
  51022. }
  51023. }]);
  51024. return FloydWarshall;
  51025. }();
  51026. exports["default"] = FloydWarshall;
  51027. /***/ })
  51028. /******/ ]);
  51029. });