You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225
  1. /*!
  2. * Chart.js v2.9.4
  3. * https://www.chartjs.org
  4. * (c) 2020 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(function () {
  9. try {
  10. return require('moment');
  11. } catch (e) {
  12. }
  13. }()) :
  14. typeof define === 'function' && define.amd ? define(['require'], function (require) {
  15. return factory(function () {
  16. try {
  17. return require('moment');
  18. } catch (e) {
  19. }
  20. }());
  21. }) :
  22. (global = global || self, global.Chart = factory(global.moment));
  23. }(this, (function (moment) {
  24. 'use strict';
  25. moment = moment && moment.hasOwnProperty('default') ? moment['default'] : moment;
  26. function createCommonjsModule(fn, module) {
  27. return module = {exports: {}}, fn(module, module.exports), module.exports;
  28. }
  29. function getCjsExportFromNamespace(n) {
  30. return n && n['default'] || n;
  31. }
  32. var colorName = {
  33. "aliceblue": [240, 248, 255],
  34. "antiquewhite": [250, 235, 215],
  35. "aqua": [0, 255, 255],
  36. "aquamarine": [127, 255, 212],
  37. "azure": [240, 255, 255],
  38. "beige": [245, 245, 220],
  39. "bisque": [255, 228, 196],
  40. "black": [0, 0, 0],
  41. "blanchedalmond": [255, 235, 205],
  42. "blue": [0, 0, 255],
  43. "blueviolet": [138, 43, 226],
  44. "brown": [165, 42, 42],
  45. "burlywood": [222, 184, 135],
  46. "cadetblue": [95, 158, 160],
  47. "chartreuse": [127, 255, 0],
  48. "chocolate": [210, 105, 30],
  49. "coral": [255, 127, 80],
  50. "cornflowerblue": [100, 149, 237],
  51. "cornsilk": [255, 248, 220],
  52. "crimson": [220, 20, 60],
  53. "cyan": [0, 255, 255],
  54. "darkblue": [0, 0, 139],
  55. "darkcyan": [0, 139, 139],
  56. "darkgoldenrod": [184, 134, 11],
  57. "darkgray": [169, 169, 169],
  58. "darkgreen": [0, 100, 0],
  59. "darkgrey": [169, 169, 169],
  60. "darkkhaki": [189, 183, 107],
  61. "darkmagenta": [139, 0, 139],
  62. "darkolivegreen": [85, 107, 47],
  63. "darkorange": [255, 140, 0],
  64. "darkorchid": [153, 50, 204],
  65. "darkred": [139, 0, 0],
  66. "darksalmon": [233, 150, 122],
  67. "darkseagreen": [143, 188, 143],
  68. "darkslateblue": [72, 61, 139],
  69. "darkslategray": [47, 79, 79],
  70. "darkslategrey": [47, 79, 79],
  71. "darkturquoise": [0, 206, 209],
  72. "darkviolet": [148, 0, 211],
  73. "deeppink": [255, 20, 147],
  74. "deepskyblue": [0, 191, 255],
  75. "dimgray": [105, 105, 105],
  76. "dimgrey": [105, 105, 105],
  77. "dodgerblue": [30, 144, 255],
  78. "firebrick": [178, 34, 34],
  79. "floralwhite": [255, 250, 240],
  80. "forestgreen": [34, 139, 34],
  81. "fuchsia": [255, 0, 255],
  82. "gainsboro": [220, 220, 220],
  83. "ghostwhite": [248, 248, 255],
  84. "gold": [255, 215, 0],
  85. "goldenrod": [218, 165, 32],
  86. "gray": [128, 128, 128],
  87. "green": [0, 128, 0],
  88. "greenyellow": [173, 255, 47],
  89. "grey": [128, 128, 128],
  90. "honeydew": [240, 255, 240],
  91. "hotpink": [255, 105, 180],
  92. "indianred": [205, 92, 92],
  93. "indigo": [75, 0, 130],
  94. "ivory": [255, 255, 240],
  95. "khaki": [240, 230, 140],
  96. "lavender": [230, 230, 250],
  97. "lavenderblush": [255, 240, 245],
  98. "lawngreen": [124, 252, 0],
  99. "lemonchiffon": [255, 250, 205],
  100. "lightblue": [173, 216, 230],
  101. "lightcoral": [240, 128, 128],
  102. "lightcyan": [224, 255, 255],
  103. "lightgoldenrodyellow": [250, 250, 210],
  104. "lightgray": [211, 211, 211],
  105. "lightgreen": [144, 238, 144],
  106. "lightgrey": [211, 211, 211],
  107. "lightpink": [255, 182, 193],
  108. "lightsalmon": [255, 160, 122],
  109. "lightseagreen": [32, 178, 170],
  110. "lightskyblue": [135, 206, 250],
  111. "lightslategray": [119, 136, 153],
  112. "lightslategrey": [119, 136, 153],
  113. "lightsteelblue": [176, 196, 222],
  114. "lightyellow": [255, 255, 224],
  115. "lime": [0, 255, 0],
  116. "limegreen": [50, 205, 50],
  117. "linen": [250, 240, 230],
  118. "magenta": [255, 0, 255],
  119. "maroon": [128, 0, 0],
  120. "mediumaquamarine": [102, 205, 170],
  121. "mediumblue": [0, 0, 205],
  122. "mediumorchid": [186, 85, 211],
  123. "mediumpurple": [147, 112, 219],
  124. "mediumseagreen": [60, 179, 113],
  125. "mediumslateblue": [123, 104, 238],
  126. "mediumspringgreen": [0, 250, 154],
  127. "mediumturquoise": [72, 209, 204],
  128. "mediumvioletred": [199, 21, 133],
  129. "midnightblue": [25, 25, 112],
  130. "mintcream": [245, 255, 250],
  131. "mistyrose": [255, 228, 225],
  132. "moccasin": [255, 228, 181],
  133. "navajowhite": [255, 222, 173],
  134. "navy": [0, 0, 128],
  135. "oldlace": [253, 245, 230],
  136. "olive": [128, 128, 0],
  137. "olivedrab": [107, 142, 35],
  138. "orange": [255, 165, 0],
  139. "orangered": [255, 69, 0],
  140. "orchid": [218, 112, 214],
  141. "palegoldenrod": [238, 232, 170],
  142. "palegreen": [152, 251, 152],
  143. "paleturquoise": [175, 238, 238],
  144. "palevioletred": [219, 112, 147],
  145. "papayawhip": [255, 239, 213],
  146. "peachpuff": [255, 218, 185],
  147. "peru": [205, 133, 63],
  148. "pink": [255, 192, 203],
  149. "plum": [221, 160, 221],
  150. "powderblue": [176, 224, 230],
  151. "purple": [128, 0, 128],
  152. "rebeccapurple": [102, 51, 153],
  153. "red": [255, 0, 0],
  154. "rosybrown": [188, 143, 143],
  155. "royalblue": [65, 105, 225],
  156. "saddlebrown": [139, 69, 19],
  157. "salmon": [250, 128, 114],
  158. "sandybrown": [244, 164, 96],
  159. "seagreen": [46, 139, 87],
  160. "seashell": [255, 245, 238],
  161. "sienna": [160, 82, 45],
  162. "silver": [192, 192, 192],
  163. "skyblue": [135, 206, 235],
  164. "slateblue": [106, 90, 205],
  165. "slategray": [112, 128, 144],
  166. "slategrey": [112, 128, 144],
  167. "snow": [255, 250, 250],
  168. "springgreen": [0, 255, 127],
  169. "steelblue": [70, 130, 180],
  170. "tan": [210, 180, 140],
  171. "teal": [0, 128, 128],
  172. "thistle": [216, 191, 216],
  173. "tomato": [255, 99, 71],
  174. "turquoise": [64, 224, 208],
  175. "violet": [238, 130, 238],
  176. "wheat": [245, 222, 179],
  177. "white": [255, 255, 255],
  178. "whitesmoke": [245, 245, 245],
  179. "yellow": [255, 255, 0],
  180. "yellowgreen": [154, 205, 50]
  181. };
  182. var conversions = createCommonjsModule(function (module) {
  183. /* MIT license */
  184. // NOTE: conversions should only return primitive values (i.e. arrays, or
  185. // values that give correct `typeof` results).
  186. // do not use box values types (i.e. Number(), String(), etc.)
  187. var reverseKeywords = {};
  188. for (var key in colorName) {
  189. if (colorName.hasOwnProperty(key)) {
  190. reverseKeywords[colorName[key]] = key;
  191. }
  192. }
  193. var convert = module.exports = {
  194. rgb: {channels: 3, labels: 'rgb'},
  195. hsl: {channels: 3, labels: 'hsl'},
  196. hsv: {channels: 3, labels: 'hsv'},
  197. hwb: {channels: 3, labels: 'hwb'},
  198. cmyk: {channels: 4, labels: 'cmyk'},
  199. xyz: {channels: 3, labels: 'xyz'},
  200. lab: {channels: 3, labels: 'lab'},
  201. lch: {channels: 3, labels: 'lch'},
  202. hex: {channels: 1, labels: ['hex']},
  203. keyword: {channels: 1, labels: ['keyword']},
  204. ansi16: {channels: 1, labels: ['ansi16']},
  205. ansi256: {channels: 1, labels: ['ansi256']},
  206. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  207. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  208. gray: {channels: 1, labels: ['gray']}
  209. };
  210. // hide .channels and .labels properties
  211. for (var model in convert) {
  212. if (convert.hasOwnProperty(model)) {
  213. if (!('channels' in convert[model])) {
  214. throw new Error('missing channels property: ' + model);
  215. }
  216. if (!('labels' in convert[model])) {
  217. throw new Error('missing channel labels property: ' + model);
  218. }
  219. if (convert[model].labels.length !== convert[model].channels) {
  220. throw new Error('channel and label counts mismatch: ' + model);
  221. }
  222. var channels = convert[model].channels;
  223. var labels = convert[model].labels;
  224. delete convert[model].channels;
  225. delete convert[model].labels;
  226. Object.defineProperty(convert[model], 'channels', {value: channels});
  227. Object.defineProperty(convert[model], 'labels', {value: labels});
  228. }
  229. }
  230. convert.rgb.hsl = function (rgb) {
  231. var r = rgb[0] / 255;
  232. var g = rgb[1] / 255;
  233. var b = rgb[2] / 255;
  234. var min = Math.min(r, g, b);
  235. var max = Math.max(r, g, b);
  236. var delta = max - min;
  237. var h;
  238. var s;
  239. var l;
  240. if (max === min) {
  241. h = 0;
  242. } else if (r === max) {
  243. h = (g - b) / delta;
  244. } else if (g === max) {
  245. h = 2 + (b - r) / delta;
  246. } else if (b === max) {
  247. h = 4 + (r - g) / delta;
  248. }
  249. h = Math.min(h * 60, 360);
  250. if (h < 0) {
  251. h += 360;
  252. }
  253. l = (min + max) / 2;
  254. if (max === min) {
  255. s = 0;
  256. } else if (l <= 0.5) {
  257. s = delta / (max + min);
  258. } else {
  259. s = delta / (2 - max - min);
  260. }
  261. return [h, s * 100, l * 100];
  262. };
  263. convert.rgb.hsv = function (rgb) {
  264. var rdif;
  265. var gdif;
  266. var bdif;
  267. var h;
  268. var s;
  269. var r = rgb[0] / 255;
  270. var g = rgb[1] / 255;
  271. var b = rgb[2] / 255;
  272. var v = Math.max(r, g, b);
  273. var diff = v - Math.min(r, g, b);
  274. var diffc = function (c) {
  275. return (v - c) / 6 / diff + 1 / 2;
  276. };
  277. if (diff === 0) {
  278. h = s = 0;
  279. } else {
  280. s = diff / v;
  281. rdif = diffc(r);
  282. gdif = diffc(g);
  283. bdif = diffc(b);
  284. if (r === v) {
  285. h = bdif - gdif;
  286. } else if (g === v) {
  287. h = (1 / 3) + rdif - bdif;
  288. } else if (b === v) {
  289. h = (2 / 3) + gdif - rdif;
  290. }
  291. if (h < 0) {
  292. h += 1;
  293. } else if (h > 1) {
  294. h -= 1;
  295. }
  296. }
  297. return [
  298. h * 360,
  299. s * 100,
  300. v * 100
  301. ];
  302. };
  303. convert.rgb.hwb = function (rgb) {
  304. var r = rgb[0];
  305. var g = rgb[1];
  306. var b = rgb[2];
  307. var h = convert.rgb.hsl(rgb)[0];
  308. var w = 1 / 255 * Math.min(r, Math.min(g, b));
  309. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  310. return [h, w * 100, b * 100];
  311. };
  312. convert.rgb.cmyk = function (rgb) {
  313. var r = rgb[0] / 255;
  314. var g = rgb[1] / 255;
  315. var b = rgb[2] / 255;
  316. var c;
  317. var m;
  318. var y;
  319. var k;
  320. k = Math.min(1 - r, 1 - g, 1 - b);
  321. c = (1 - r - k) / (1 - k) || 0;
  322. m = (1 - g - k) / (1 - k) || 0;
  323. y = (1 - b - k) / (1 - k) || 0;
  324. return [c * 100, m * 100, y * 100, k * 100];
  325. };
  326. /**
  327. * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  328. * */
  329. function comparativeDistance(x, y) {
  330. return (
  331. Math.pow(x[0] - y[0], 2) +
  332. Math.pow(x[1] - y[1], 2) +
  333. Math.pow(x[2] - y[2], 2)
  334. );
  335. }
  336. convert.rgb.keyword = function (rgb) {
  337. var reversed = reverseKeywords[rgb];
  338. if (reversed) {
  339. return reversed;
  340. }
  341. var currentClosestDistance = Infinity;
  342. var currentClosestKeyword;
  343. for (var keyword in colorName) {
  344. if (colorName.hasOwnProperty(keyword)) {
  345. var value = colorName[keyword];
  346. // Compute comparative distance
  347. var distance = comparativeDistance(rgb, value);
  348. // Check if its less, if so set as closest
  349. if (distance < currentClosestDistance) {
  350. currentClosestDistance = distance;
  351. currentClosestKeyword = keyword;
  352. }
  353. }
  354. }
  355. return currentClosestKeyword;
  356. };
  357. convert.keyword.rgb = function (keyword) {
  358. return colorName[keyword];
  359. };
  360. convert.rgb.xyz = function (rgb) {
  361. var r = rgb[0] / 255;
  362. var g = rgb[1] / 255;
  363. var b = rgb[2] / 255;
  364. // assume sRGB
  365. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  366. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  367. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  368. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  369. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  370. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  371. return [x * 100, y * 100, z * 100];
  372. };
  373. convert.rgb.lab = function (rgb) {
  374. var xyz = convert.rgb.xyz(rgb);
  375. var x = xyz[0];
  376. var y = xyz[1];
  377. var z = xyz[2];
  378. var l;
  379. var a;
  380. var b;
  381. x /= 95.047;
  382. y /= 100;
  383. z /= 108.883;
  384. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  385. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  386. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  387. l = (116 * y) - 16;
  388. a = 500 * (x - y);
  389. b = 200 * (y - z);
  390. return [l, a, b];
  391. };
  392. convert.hsl.rgb = function (hsl) {
  393. var h = hsl[0] / 360;
  394. var s = hsl[1] / 100;
  395. var l = hsl[2] / 100;
  396. var t1;
  397. var t2;
  398. var t3;
  399. var rgb;
  400. var val;
  401. if (s === 0) {
  402. val = l * 255;
  403. return [val, val, val];
  404. }
  405. if (l < 0.5) {
  406. t2 = l * (1 + s);
  407. } else {
  408. t2 = l + s - l * s;
  409. }
  410. t1 = 2 * l - t2;
  411. rgb = [0, 0, 0];
  412. for (var i = 0; i < 3; i++) {
  413. t3 = h + 1 / 3 * -(i - 1);
  414. if (t3 < 0) {
  415. t3++;
  416. }
  417. if (t3 > 1) {
  418. t3--;
  419. }
  420. if (6 * t3 < 1) {
  421. val = t1 + (t2 - t1) * 6 * t3;
  422. } else if (2 * t3 < 1) {
  423. val = t2;
  424. } else if (3 * t3 < 2) {
  425. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  426. } else {
  427. val = t1;
  428. }
  429. rgb[i] = val * 255;
  430. }
  431. return rgb;
  432. };
  433. convert.hsl.hsv = function (hsl) {
  434. var h = hsl[0];
  435. var s = hsl[1] / 100;
  436. var l = hsl[2] / 100;
  437. var smin = s;
  438. var lmin = Math.max(l, 0.01);
  439. var sv;
  440. var v;
  441. l *= 2;
  442. s *= (l <= 1) ? l : 2 - l;
  443. smin *= lmin <= 1 ? lmin : 2 - lmin;
  444. v = (l + s) / 2;
  445. sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  446. return [h, sv * 100, v * 100];
  447. };
  448. convert.hsv.rgb = function (hsv) {
  449. var h = hsv[0] / 60;
  450. var s = hsv[1] / 100;
  451. var v = hsv[2] / 100;
  452. var hi = Math.floor(h) % 6;
  453. var f = h - Math.floor(h);
  454. var p = 255 * v * (1 - s);
  455. var q = 255 * v * (1 - (s * f));
  456. var t = 255 * v * (1 - (s * (1 - f)));
  457. v *= 255;
  458. switch (hi) {
  459. case 0:
  460. return [v, t, p];
  461. case 1:
  462. return [q, v, p];
  463. case 2:
  464. return [p, v, t];
  465. case 3:
  466. return [p, q, v];
  467. case 4:
  468. return [t, p, v];
  469. case 5:
  470. return [v, p, q];
  471. }
  472. };
  473. convert.hsv.hsl = function (hsv) {
  474. var h = hsv[0];
  475. var s = hsv[1] / 100;
  476. var v = hsv[2] / 100;
  477. var vmin = Math.max(v, 0.01);
  478. var lmin;
  479. var sl;
  480. var l;
  481. l = (2 - s) * v;
  482. lmin = (2 - s) * vmin;
  483. sl = s * vmin;
  484. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  485. sl = sl || 0;
  486. l /= 2;
  487. return [h, sl * 100, l * 100];
  488. };
  489. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  490. convert.hwb.rgb = function (hwb) {
  491. var h = hwb[0] / 360;
  492. var wh = hwb[1] / 100;
  493. var bl = hwb[2] / 100;
  494. var ratio = wh + bl;
  495. var i;
  496. var v;
  497. var f;
  498. var n;
  499. // wh + bl cant be > 1
  500. if (ratio > 1) {
  501. wh /= ratio;
  502. bl /= ratio;
  503. }
  504. i = Math.floor(6 * h);
  505. v = 1 - bl;
  506. f = 6 * h - i;
  507. if ((i & 0x01) !== 0) {
  508. f = 1 - f;
  509. }
  510. n = wh + f * (v - wh); // linear interpolation
  511. var r;
  512. var g;
  513. var b;
  514. switch (i) {
  515. default:
  516. case 6:
  517. case 0:
  518. r = v;
  519. g = n;
  520. b = wh;
  521. break;
  522. case 1:
  523. r = n;
  524. g = v;
  525. b = wh;
  526. break;
  527. case 2:
  528. r = wh;
  529. g = v;
  530. b = n;
  531. break;
  532. case 3:
  533. r = wh;
  534. g = n;
  535. b = v;
  536. break;
  537. case 4:
  538. r = n;
  539. g = wh;
  540. b = v;
  541. break;
  542. case 5:
  543. r = v;
  544. g = wh;
  545. b = n;
  546. break;
  547. }
  548. return [r * 255, g * 255, b * 255];
  549. };
  550. convert.cmyk.rgb = function (cmyk) {
  551. var c = cmyk[0] / 100;
  552. var m = cmyk[1] / 100;
  553. var y = cmyk[2] / 100;
  554. var k = cmyk[3] / 100;
  555. var r;
  556. var g;
  557. var b;
  558. r = 1 - Math.min(1, c * (1 - k) + k);
  559. g = 1 - Math.min(1, m * (1 - k) + k);
  560. b = 1 - Math.min(1, y * (1 - k) + k);
  561. return [r * 255, g * 255, b * 255];
  562. };
  563. convert.xyz.rgb = function (xyz) {
  564. var x = xyz[0] / 100;
  565. var y = xyz[1] / 100;
  566. var z = xyz[2] / 100;
  567. var r;
  568. var g;
  569. var b;
  570. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  571. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  572. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  573. // assume sRGB
  574. r = r > 0.0031308
  575. ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  576. : r * 12.92;
  577. g = g > 0.0031308
  578. ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  579. : g * 12.92;
  580. b = b > 0.0031308
  581. ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  582. : b * 12.92;
  583. r = Math.min(Math.max(0, r), 1);
  584. g = Math.min(Math.max(0, g), 1);
  585. b = Math.min(Math.max(0, b), 1);
  586. return [r * 255, g * 255, b * 255];
  587. };
  588. convert.xyz.lab = function (xyz) {
  589. var x = xyz[0];
  590. var y = xyz[1];
  591. var z = xyz[2];
  592. var l;
  593. var a;
  594. var b;
  595. x /= 95.047;
  596. y /= 100;
  597. z /= 108.883;
  598. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  599. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  600. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  601. l = (116 * y) - 16;
  602. a = 500 * (x - y);
  603. b = 200 * (y - z);
  604. return [l, a, b];
  605. };
  606. convert.lab.xyz = function (lab) {
  607. var l = lab[0];
  608. var a = lab[1];
  609. var b = lab[2];
  610. var x;
  611. var y;
  612. var z;
  613. y = (l + 16) / 116;
  614. x = a / 500 + y;
  615. z = y - b / 200;
  616. var y2 = Math.pow(y, 3);
  617. var x2 = Math.pow(x, 3);
  618. var z2 = Math.pow(z, 3);
  619. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  620. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  621. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  622. x *= 95.047;
  623. y *= 100;
  624. z *= 108.883;
  625. return [x, y, z];
  626. };
  627. convert.lab.lch = function (lab) {
  628. var l = lab[0];
  629. var a = lab[1];
  630. var b = lab[2];
  631. var hr;
  632. var h;
  633. var c;
  634. hr = Math.atan2(b, a);
  635. h = hr * 360 / 2 / Math.PI;
  636. if (h < 0) {
  637. h += 360;
  638. }
  639. c = Math.sqrt(a * a + b * b);
  640. return [l, c, h];
  641. };
  642. convert.lch.lab = function (lch) {
  643. var l = lch[0];
  644. var c = lch[1];
  645. var h = lch[2];
  646. var a;
  647. var b;
  648. var hr;
  649. hr = h / 360 * 2 * Math.PI;
  650. a = c * Math.cos(hr);
  651. b = c * Math.sin(hr);
  652. return [l, a, b];
  653. };
  654. convert.rgb.ansi16 = function (args) {
  655. var r = args[0];
  656. var g = args[1];
  657. var b = args[2];
  658. var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
  659. value = Math.round(value / 50);
  660. if (value === 0) {
  661. return 30;
  662. }
  663. var ansi = 30
  664. + ((Math.round(b / 255) << 2)
  665. | (Math.round(g / 255) << 1)
  666. | Math.round(r / 255));
  667. if (value === 2) {
  668. ansi += 60;
  669. }
  670. return ansi;
  671. };
  672. convert.hsv.ansi16 = function (args) {
  673. // optimization here; we already know the value and don't need to get
  674. // it converted for us.
  675. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
  676. };
  677. convert.rgb.ansi256 = function (args) {
  678. var r = args[0];
  679. var g = args[1];
  680. var b = args[2];
  681. // we use the extended greyscale palette here, with the exception of
  682. // black and white. normal palette only has 4 greyscale shades.
  683. if (r === g && g === b) {
  684. if (r < 8) {
  685. return 16;
  686. }
  687. if (r > 248) {
  688. return 231;
  689. }
  690. return Math.round(((r - 8) / 247) * 24) + 232;
  691. }
  692. var ansi = 16
  693. + (36 * Math.round(r / 255 * 5))
  694. + (6 * Math.round(g / 255 * 5))
  695. + Math.round(b / 255 * 5);
  696. return ansi;
  697. };
  698. convert.ansi16.rgb = function (args) {
  699. var color = args % 10;
  700. // handle greyscale
  701. if (color === 0 || color === 7) {
  702. if (args > 50) {
  703. color += 3.5;
  704. }
  705. color = color / 10.5 * 255;
  706. return [color, color, color];
  707. }
  708. var mult = (~~(args > 50) + 1) * 0.5;
  709. var r = ((color & 1) * mult) * 255;
  710. var g = (((color >> 1) & 1) * mult) * 255;
  711. var b = (((color >> 2) & 1) * mult) * 255;
  712. return [r, g, b];
  713. };
  714. convert.ansi256.rgb = function (args) {
  715. // handle greyscale
  716. if (args >= 232) {
  717. var c = (args - 232) * 10 + 8;
  718. return [c, c, c];
  719. }
  720. args -= 16;
  721. var rem;
  722. var r = Math.floor(args / 36) / 5 * 255;
  723. var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  724. var b = (rem % 6) / 5 * 255;
  725. return [r, g, b];
  726. };
  727. convert.rgb.hex = function (args) {
  728. var integer = ((Math.round(args[0]) & 0xFF) << 16)
  729. + ((Math.round(args[1]) & 0xFF) << 8)
  730. + (Math.round(args[2]) & 0xFF);
  731. var string = integer.toString(16).toUpperCase();
  732. return '000000'.substring(string.length) + string;
  733. };
  734. convert.hex.rgb = function (args) {
  735. var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  736. if (!match) {
  737. return [0, 0, 0];
  738. }
  739. var colorString = match[0];
  740. if (match[0].length === 3) {
  741. colorString = colorString.split('').map(function (char) {
  742. return char + char;
  743. }).join('');
  744. }
  745. var integer = parseInt(colorString, 16);
  746. var r = (integer >> 16) & 0xFF;
  747. var g = (integer >> 8) & 0xFF;
  748. var b = integer & 0xFF;
  749. return [r, g, b];
  750. };
  751. convert.rgb.hcg = function (rgb) {
  752. var r = rgb[0] / 255;
  753. var g = rgb[1] / 255;
  754. var b = rgb[2] / 255;
  755. var max = Math.max(Math.max(r, g), b);
  756. var min = Math.min(Math.min(r, g), b);
  757. var chroma = (max - min);
  758. var grayscale;
  759. var hue;
  760. if (chroma < 1) {
  761. grayscale = min / (1 - chroma);
  762. } else {
  763. grayscale = 0;
  764. }
  765. if (chroma <= 0) {
  766. hue = 0;
  767. } else if (max === r) {
  768. hue = ((g - b) / chroma) % 6;
  769. } else if (max === g) {
  770. hue = 2 + (b - r) / chroma;
  771. } else {
  772. hue = 4 + (r - g) / chroma + 4;
  773. }
  774. hue /= 6;
  775. hue %= 1;
  776. return [hue * 360, chroma * 100, grayscale * 100];
  777. };
  778. convert.hsl.hcg = function (hsl) {
  779. var s = hsl[1] / 100;
  780. var l = hsl[2] / 100;
  781. var c = 1;
  782. var f = 0;
  783. if (l < 0.5) {
  784. c = 2.0 * s * l;
  785. } else {
  786. c = 2.0 * s * (1.0 - l);
  787. }
  788. if (c < 1.0) {
  789. f = (l - 0.5 * c) / (1.0 - c);
  790. }
  791. return [hsl[0], c * 100, f * 100];
  792. };
  793. convert.hsv.hcg = function (hsv) {
  794. var s = hsv[1] / 100;
  795. var v = hsv[2] / 100;
  796. var c = s * v;
  797. var f = 0;
  798. if (c < 1.0) {
  799. f = (v - c) / (1 - c);
  800. }
  801. return [hsv[0], c * 100, f * 100];
  802. };
  803. convert.hcg.rgb = function (hcg) {
  804. var h = hcg[0] / 360;
  805. var c = hcg[1] / 100;
  806. var g = hcg[2] / 100;
  807. if (c === 0.0) {
  808. return [g * 255, g * 255, g * 255];
  809. }
  810. var pure = [0, 0, 0];
  811. var hi = (h % 1) * 6;
  812. var v = hi % 1;
  813. var w = 1 - v;
  814. var mg = 0;
  815. switch (Math.floor(hi)) {
  816. case 0:
  817. pure[0] = 1;
  818. pure[1] = v;
  819. pure[2] = 0;
  820. break;
  821. case 1:
  822. pure[0] = w;
  823. pure[1] = 1;
  824. pure[2] = 0;
  825. break;
  826. case 2:
  827. pure[0] = 0;
  828. pure[1] = 1;
  829. pure[2] = v;
  830. break;
  831. case 3:
  832. pure[0] = 0;
  833. pure[1] = w;
  834. pure[2] = 1;
  835. break;
  836. case 4:
  837. pure[0] = v;
  838. pure[1] = 0;
  839. pure[2] = 1;
  840. break;
  841. default:
  842. pure[0] = 1;
  843. pure[1] = 0;
  844. pure[2] = w;
  845. }
  846. mg = (1.0 - c) * g;
  847. return [
  848. (c * pure[0] + mg) * 255,
  849. (c * pure[1] + mg) * 255,
  850. (c * pure[2] + mg) * 255
  851. ];
  852. };
  853. convert.hcg.hsv = function (hcg) {
  854. var c = hcg[1] / 100;
  855. var g = hcg[2] / 100;
  856. var v = c + g * (1.0 - c);
  857. var f = 0;
  858. if (v > 0.0) {
  859. f = c / v;
  860. }
  861. return [hcg[0], f * 100, v * 100];
  862. };
  863. convert.hcg.hsl = function (hcg) {
  864. var c = hcg[1] / 100;
  865. var g = hcg[2] / 100;
  866. var l = g * (1.0 - c) + 0.5 * c;
  867. var s = 0;
  868. if (l > 0.0 && l < 0.5) {
  869. s = c / (2 * l);
  870. } else if (l >= 0.5 && l < 1.0) {
  871. s = c / (2 * (1 - l));
  872. }
  873. return [hcg[0], s * 100, l * 100];
  874. };
  875. convert.hcg.hwb = function (hcg) {
  876. var c = hcg[1] / 100;
  877. var g = hcg[2] / 100;
  878. var v = c + g * (1.0 - c);
  879. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  880. };
  881. convert.hwb.hcg = function (hwb) {
  882. var w = hwb[1] / 100;
  883. var b = hwb[2] / 100;
  884. var v = 1 - b;
  885. var c = v - w;
  886. var g = 0;
  887. if (c < 1) {
  888. g = (v - c) / (1 - c);
  889. }
  890. return [hwb[0], c * 100, g * 100];
  891. };
  892. convert.apple.rgb = function (apple) {
  893. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  894. };
  895. convert.rgb.apple = function (rgb) {
  896. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  897. };
  898. convert.gray.rgb = function (args) {
  899. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  900. };
  901. convert.gray.hsl = convert.gray.hsv = function (args) {
  902. return [0, 0, args[0]];
  903. };
  904. convert.gray.hwb = function (gray) {
  905. return [0, 100, gray[0]];
  906. };
  907. convert.gray.cmyk = function (gray) {
  908. return [0, 0, 0, gray[0]];
  909. };
  910. convert.gray.lab = function (gray) {
  911. return [gray[0], 0, 0];
  912. };
  913. convert.gray.hex = function (gray) {
  914. var val = Math.round(gray[0] / 100 * 255) & 0xFF;
  915. var integer = (val << 16) + (val << 8) + val;
  916. var string = integer.toString(16).toUpperCase();
  917. return '000000'.substring(string.length) + string;
  918. };
  919. convert.rgb.gray = function (rgb) {
  920. var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  921. return [val / 255 * 100];
  922. };
  923. });
  924. var conversions_1 = conversions.rgb;
  925. var conversions_2 = conversions.hsl;
  926. var conversions_3 = conversions.hsv;
  927. var conversions_4 = conversions.hwb;
  928. var conversions_5 = conversions.cmyk;
  929. var conversions_6 = conversions.xyz;
  930. var conversions_7 = conversions.lab;
  931. var conversions_8 = conversions.lch;
  932. var conversions_9 = conversions.hex;
  933. var conversions_10 = conversions.keyword;
  934. var conversions_11 = conversions.ansi16;
  935. var conversions_12 = conversions.ansi256;
  936. var conversions_13 = conversions.hcg;
  937. var conversions_14 = conversions.apple;
  938. var conversions_15 = conversions.gray;
  939. /*
  940. this function routes a model to all other models.
  941. all functions that are routed have a property `.conversion` attached
  942. to the returned synthetic function. This property is an array
  943. of strings, each with the steps in between the 'from' and 'to'
  944. color models (inclusive).
  945. conversions that are not possible simply are not included.
  946. */
  947. function buildGraph() {
  948. var graph = {};
  949. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  950. var models = Object.keys(conversions);
  951. for (var len = models.length, i = 0; i < len; i++) {
  952. graph[models[i]] = {
  953. // http://jsperf.com/1-vs-infinity
  954. // micro-opt, but this is simple.
  955. distance: -1,
  956. parent: null
  957. };
  958. }
  959. return graph;
  960. }
  961. // https://en.wikipedia.org/wiki/Breadth-first_search
  962. function deriveBFS(fromModel) {
  963. var graph = buildGraph();
  964. var queue = [fromModel]; // unshift -> queue -> pop
  965. graph[fromModel].distance = 0;
  966. while (queue.length) {
  967. var current = queue.pop();
  968. var adjacents = Object.keys(conversions[current]);
  969. for (var len = adjacents.length, i = 0; i < len; i++) {
  970. var adjacent = adjacents[i];
  971. var node = graph[adjacent];
  972. if (node.distance === -1) {
  973. node.distance = graph[current].distance + 1;
  974. node.parent = current;
  975. queue.unshift(adjacent);
  976. }
  977. }
  978. }
  979. return graph;
  980. }
  981. function link(from, to) {
  982. return function (args) {
  983. return to(from(args));
  984. };
  985. }
  986. function wrapConversion(toModel, graph) {
  987. var path = [graph[toModel].parent, toModel];
  988. var fn = conversions[graph[toModel].parent][toModel];
  989. var cur = graph[toModel].parent;
  990. while (graph[cur].parent) {
  991. path.unshift(graph[cur].parent);
  992. fn = link(conversions[graph[cur].parent][cur], fn);
  993. cur = graph[cur].parent;
  994. }
  995. fn.conversion = path;
  996. return fn;
  997. }
  998. var route = function (fromModel) {
  999. var graph = deriveBFS(fromModel);
  1000. var conversion = {};
  1001. var models = Object.keys(graph);
  1002. for (var len = models.length, i = 0; i < len; i++) {
  1003. var toModel = models[i];
  1004. var node = graph[toModel];
  1005. if (node.parent === null) {
  1006. // no possible conversion, or this node is the source model.
  1007. continue;
  1008. }
  1009. conversion[toModel] = wrapConversion(toModel, graph);
  1010. }
  1011. return conversion;
  1012. };
  1013. var convert = {};
  1014. var models = Object.keys(conversions);
  1015. function wrapRaw(fn) {
  1016. var wrappedFn = function (args) {
  1017. if (args === undefined || args === null) {
  1018. return args;
  1019. }
  1020. if (arguments.length > 1) {
  1021. args = Array.prototype.slice.call(arguments);
  1022. }
  1023. return fn(args);
  1024. };
  1025. // preserve .conversion property if there is one
  1026. if ('conversion' in fn) {
  1027. wrappedFn.conversion = fn.conversion;
  1028. }
  1029. return wrappedFn;
  1030. }
  1031. function wrapRounded(fn) {
  1032. var wrappedFn = function (args) {
  1033. if (args === undefined || args === null) {
  1034. return args;
  1035. }
  1036. if (arguments.length > 1) {
  1037. args = Array.prototype.slice.call(arguments);
  1038. }
  1039. var result = fn(args);
  1040. // we're assuming the result is an array here.
  1041. // see notice in conversions.js; don't use box types
  1042. // in conversion functions.
  1043. if (typeof result === 'object') {
  1044. for (var len = result.length, i = 0; i < len; i++) {
  1045. result[i] = Math.round(result[i]);
  1046. }
  1047. }
  1048. return result;
  1049. };
  1050. // preserve .conversion property if there is one
  1051. if ('conversion' in fn) {
  1052. wrappedFn.conversion = fn.conversion;
  1053. }
  1054. return wrappedFn;
  1055. }
  1056. models.forEach(function (fromModel) {
  1057. convert[fromModel] = {};
  1058. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  1059. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  1060. var routes = route(fromModel);
  1061. var routeModels = Object.keys(routes);
  1062. routeModels.forEach(function (toModel) {
  1063. var fn = routes[toModel];
  1064. convert[fromModel][toModel] = wrapRounded(fn);
  1065. convert[fromModel][toModel].raw = wrapRaw(fn);
  1066. });
  1067. });
  1068. var colorConvert = convert;
  1069. var colorName$1 = {
  1070. "aliceblue": [240, 248, 255],
  1071. "antiquewhite": [250, 235, 215],
  1072. "aqua": [0, 255, 255],
  1073. "aquamarine": [127, 255, 212],
  1074. "azure": [240, 255, 255],
  1075. "beige": [245, 245, 220],
  1076. "bisque": [255, 228, 196],
  1077. "black": [0, 0, 0],
  1078. "blanchedalmond": [255, 235, 205],
  1079. "blue": [0, 0, 255],
  1080. "blueviolet": [138, 43, 226],
  1081. "brown": [165, 42, 42],
  1082. "burlywood": [222, 184, 135],
  1083. "cadetblue": [95, 158, 160],
  1084. "chartreuse": [127, 255, 0],
  1085. "chocolate": [210, 105, 30],
  1086. "coral": [255, 127, 80],
  1087. "cornflowerblue": [100, 149, 237],
  1088. "cornsilk": [255, 248, 220],
  1089. "crimson": [220, 20, 60],
  1090. "cyan": [0, 255, 255],
  1091. "darkblue": [0, 0, 139],
  1092. "darkcyan": [0, 139, 139],
  1093. "darkgoldenrod": [184, 134, 11],
  1094. "darkgray": [169, 169, 169],
  1095. "darkgreen": [0, 100, 0],
  1096. "darkgrey": [169, 169, 169],
  1097. "darkkhaki": [189, 183, 107],
  1098. "darkmagenta": [139, 0, 139],
  1099. "darkolivegreen": [85, 107, 47],
  1100. "darkorange": [255, 140, 0],
  1101. "darkorchid": [153, 50, 204],
  1102. "darkred": [139, 0, 0],
  1103. "darksalmon": [233, 150, 122],
  1104. "darkseagreen": [143, 188, 143],
  1105. "darkslateblue": [72, 61, 139],
  1106. "darkslategray": [47, 79, 79],
  1107. "darkslategrey": [47, 79, 79],
  1108. "darkturquoise": [0, 206, 209],
  1109. "darkviolet": [148, 0, 211],
  1110. "deeppink": [255, 20, 147],
  1111. "deepskyblue": [0, 191, 255],
  1112. "dimgray": [105, 105, 105],
  1113. "dimgrey": [105, 105, 105],
  1114. "dodgerblue": [30, 144, 255],
  1115. "firebrick": [178, 34, 34],
  1116. "floralwhite": [255, 250, 240],
  1117. "forestgreen": [34, 139, 34],
  1118. "fuchsia": [255, 0, 255],
  1119. "gainsboro": [220, 220, 220],
  1120. "ghostwhite": [248, 248, 255],
  1121. "gold": [255, 215, 0],
  1122. "goldenrod": [218, 165, 32],
  1123. "gray": [128, 128, 128],
  1124. "green": [0, 128, 0],
  1125. "greenyellow": [173, 255, 47],
  1126. "grey": [128, 128, 128],
  1127. "honeydew": [240, 255, 240],
  1128. "hotpink": [255, 105, 180],
  1129. "indianred": [205, 92, 92],
  1130. "indigo": [75, 0, 130],
  1131. "ivory": [255, 255, 240],
  1132. "khaki": [240, 230, 140],
  1133. "lavender": [230, 230, 250],
  1134. "lavenderblush": [255, 240, 245],
  1135. "lawngreen": [124, 252, 0],
  1136. "lemonchiffon": [255, 250, 205],
  1137. "lightblue": [173, 216, 230],
  1138. "lightcoral": [240, 128, 128],
  1139. "lightcyan": [224, 255, 255],
  1140. "lightgoldenrodyellow": [250, 250, 210],
  1141. "lightgray": [211, 211, 211],
  1142. "lightgreen": [144, 238, 144],
  1143. "lightgrey": [211, 211, 211],
  1144. "lightpink": [255, 182, 193],
  1145. "lightsalmon": [255, 160, 122],
  1146. "lightseagreen": [32, 178, 170],
  1147. "lightskyblue": [135, 206, 250],
  1148. "lightslategray": [119, 136, 153],
  1149. "lightslategrey": [119, 136, 153],
  1150. "lightsteelblue": [176, 196, 222],
  1151. "lightyellow": [255, 255, 224],
  1152. "lime": [0, 255, 0],
  1153. "limegreen": [50, 205, 50],
  1154. "linen": [250, 240, 230],
  1155. "magenta": [255, 0, 255],
  1156. "maroon": [128, 0, 0],
  1157. "mediumaquamarine": [102, 205, 170],
  1158. "mediumblue": [0, 0, 205],
  1159. "mediumorchid": [186, 85, 211],
  1160. "mediumpurple": [147, 112, 219],
  1161. "mediumseagreen": [60, 179, 113],
  1162. "mediumslateblue": [123, 104, 238],
  1163. "mediumspringgreen": [0, 250, 154],
  1164. "mediumturquoise": [72, 209, 204],
  1165. "mediumvioletred": [199, 21, 133],
  1166. "midnightblue": [25, 25, 112],
  1167. "mintcream": [245, 255, 250],
  1168. "mistyrose": [255, 228, 225],
  1169. "moccasin": [255, 228, 181],
  1170. "navajowhite": [255, 222, 173],
  1171. "navy": [0, 0, 128],
  1172. "oldlace": [253, 245, 230],
  1173. "olive": [128, 128, 0],
  1174. "olivedrab": [107, 142, 35],
  1175. "orange": [255, 165, 0],
  1176. "orangered": [255, 69, 0],
  1177. "orchid": [218, 112, 214],
  1178. "palegoldenrod": [238, 232, 170],
  1179. "palegreen": [152, 251, 152],
  1180. "paleturquoise": [175, 238, 238],
  1181. "palevioletred": [219, 112, 147],
  1182. "papayawhip": [255, 239, 213],
  1183. "peachpuff": [255, 218, 185],
  1184. "peru": [205, 133, 63],
  1185. "pink": [255, 192, 203],
  1186. "plum": [221, 160, 221],
  1187. "powderblue": [176, 224, 230],
  1188. "purple": [128, 0, 128],
  1189. "rebeccapurple": [102, 51, 153],
  1190. "red": [255, 0, 0],
  1191. "rosybrown": [188, 143, 143],
  1192. "royalblue": [65, 105, 225],
  1193. "saddlebrown": [139, 69, 19],
  1194. "salmon": [250, 128, 114],
  1195. "sandybrown": [244, 164, 96],
  1196. "seagreen": [46, 139, 87],
  1197. "seashell": [255, 245, 238],
  1198. "sienna": [160, 82, 45],
  1199. "silver": [192, 192, 192],
  1200. "skyblue": [135, 206, 235],
  1201. "slateblue": [106, 90, 205],
  1202. "slategray": [112, 128, 144],
  1203. "slategrey": [112, 128, 144],
  1204. "snow": [255, 250, 250],
  1205. "springgreen": [0, 255, 127],
  1206. "steelblue": [70, 130, 180],
  1207. "tan": [210, 180, 140],
  1208. "teal": [0, 128, 128],
  1209. "thistle": [216, 191, 216],
  1210. "tomato": [255, 99, 71],
  1211. "turquoise": [64, 224, 208],
  1212. "violet": [238, 130, 238],
  1213. "wheat": [245, 222, 179],
  1214. "white": [255, 255, 255],
  1215. "whitesmoke": [245, 245, 245],
  1216. "yellow": [255, 255, 0],
  1217. "yellowgreen": [154, 205, 50]
  1218. };
  1219. /* MIT license */
  1220. var colorString = {
  1221. getRgba: getRgba,
  1222. getHsla: getHsla,
  1223. getRgb: getRgb,
  1224. getHsl: getHsl,
  1225. getHwb: getHwb,
  1226. getAlpha: getAlpha,
  1227. hexString: hexString,
  1228. rgbString: rgbString,
  1229. rgbaString: rgbaString,
  1230. percentString: percentString,
  1231. percentaString: percentaString,
  1232. hslString: hslString,
  1233. hslaString: hslaString,
  1234. hwbString: hwbString,
  1235. keyword: keyword
  1236. };
  1237. function getRgba(string) {
  1238. if (!string) {
  1239. return;
  1240. }
  1241. var abbr = /^#([a-fA-F0-9]{3,4})$/i,
  1242. hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
  1243. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1244. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1245. keyword = /(\w+)/;
  1246. var rgb = [0, 0, 0],
  1247. a = 1,
  1248. match = string.match(abbr),
  1249. hexAlpha = "";
  1250. if (match) {
  1251. match = match[1];
  1252. hexAlpha = match[3];
  1253. for (var i = 0; i < rgb.length; i++) {
  1254. rgb[i] = parseInt(match[i] + match[i], 16);
  1255. }
  1256. if (hexAlpha) {
  1257. a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
  1258. }
  1259. } else if (match = string.match(hex)) {
  1260. hexAlpha = match[2];
  1261. match = match[1];
  1262. for (var i = 0; i < rgb.length; i++) {
  1263. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  1264. }
  1265. if (hexAlpha) {
  1266. a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
  1267. }
  1268. } else if (match = string.match(rgba)) {
  1269. for (var i = 0; i < rgb.length; i++) {
  1270. rgb[i] = parseInt(match[i + 1]);
  1271. }
  1272. a = parseFloat(match[4]);
  1273. } else if (match = string.match(per)) {
  1274. for (var i = 0; i < rgb.length; i++) {
  1275. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  1276. }
  1277. a = parseFloat(match[4]);
  1278. } else if (match = string.match(keyword)) {
  1279. if (match[1] == "transparent") {
  1280. return [0, 0, 0, 0];
  1281. }
  1282. rgb = colorName$1[match[1]];
  1283. if (!rgb) {
  1284. return;
  1285. }
  1286. }
  1287. for (var i = 0; i < rgb.length; i++) {
  1288. rgb[i] = scale(rgb[i], 0, 255);
  1289. }
  1290. if (!a && a != 0) {
  1291. a = 1;
  1292. } else {
  1293. a = scale(a, 0, 1);
  1294. }
  1295. rgb[3] = a;
  1296. return rgb;
  1297. }
  1298. function getHsla(string) {
  1299. if (!string) {
  1300. return;
  1301. }
  1302. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1303. var match = string.match(hsl);
  1304. if (match) {
  1305. var alpha = parseFloat(match[4]);
  1306. var h = scale(parseInt(match[1]), 0, 360),
  1307. s = scale(parseFloat(match[2]), 0, 100),
  1308. l = scale(parseFloat(match[3]), 0, 100),
  1309. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1310. return [h, s, l, a];
  1311. }
  1312. }
  1313. function getHwb(string) {
  1314. if (!string) {
  1315. return;
  1316. }
  1317. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1318. var match = string.match(hwb);
  1319. if (match) {
  1320. var alpha = parseFloat(match[4]);
  1321. var h = scale(parseInt(match[1]), 0, 360),
  1322. w = scale(parseFloat(match[2]), 0, 100),
  1323. b = scale(parseFloat(match[3]), 0, 100),
  1324. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1325. return [h, w, b, a];
  1326. }
  1327. }
  1328. function getRgb(string) {
  1329. var rgba = getRgba(string);
  1330. return rgba && rgba.slice(0, 3);
  1331. }
  1332. function getHsl(string) {
  1333. var hsla = getHsla(string);
  1334. return hsla && hsla.slice(0, 3);
  1335. }
  1336. function getAlpha(string) {
  1337. var vals = getRgba(string);
  1338. if (vals) {
  1339. return vals[3];
  1340. } else if (vals = getHsla(string)) {
  1341. return vals[3];
  1342. } else if (vals = getHwb(string)) {
  1343. return vals[3];
  1344. }
  1345. }
  1346. // generators
  1347. function hexString(rgba, a) {
  1348. var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
  1349. return "#" + hexDouble(rgba[0])
  1350. + hexDouble(rgba[1])
  1351. + hexDouble(rgba[2])
  1352. + (
  1353. (a >= 0 && a < 1)
  1354. ? hexDouble(Math.round(a * 255))
  1355. : ""
  1356. );
  1357. }
  1358. function rgbString(rgba, alpha) {
  1359. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1360. return rgbaString(rgba, alpha);
  1361. }
  1362. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  1363. }
  1364. function rgbaString(rgba, alpha) {
  1365. if (alpha === undefined) {
  1366. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  1367. }
  1368. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  1369. + ", " + alpha + ")";
  1370. }
  1371. function percentString(rgba, alpha) {
  1372. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1373. return percentaString(rgba, alpha);
  1374. }
  1375. var r = Math.round(rgba[0] / 255 * 100),
  1376. g = Math.round(rgba[1] / 255 * 100),
  1377. b = Math.round(rgba[2] / 255 * 100);
  1378. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  1379. }
  1380. function percentaString(rgba, alpha) {
  1381. var r = Math.round(rgba[0] / 255 * 100),
  1382. g = Math.round(rgba[1] / 255 * 100),
  1383. b = Math.round(rgba[2] / 255 * 100);
  1384. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  1385. }
  1386. function hslString(hsla, alpha) {
  1387. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  1388. return hslaString(hsla, alpha);
  1389. }
  1390. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  1391. }
  1392. function hslaString(hsla, alpha) {
  1393. if (alpha === undefined) {
  1394. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  1395. }
  1396. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  1397. + alpha + ")";
  1398. }
  1399. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  1400. // (hwb have alpha optional & 1 is default value)
  1401. function hwbString(hwb, alpha) {
  1402. if (alpha === undefined) {
  1403. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  1404. }
  1405. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  1406. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  1407. }
  1408. function keyword(rgb) {
  1409. return reverseNames[rgb.slice(0, 3)];
  1410. }
  1411. // helpers
  1412. function scale(num, min, max) {
  1413. return Math.min(Math.max(min, num), max);
  1414. }
  1415. function hexDouble(num) {
  1416. var str = num.toString(16).toUpperCase();
  1417. return (str.length < 2) ? "0" + str : str;
  1418. }
  1419. //create a list of reverse color names
  1420. var reverseNames = {};
  1421. for (var name in colorName$1) {
  1422. reverseNames[colorName$1[name]] = name;
  1423. }
  1424. /* MIT license */
  1425. var Color = function (obj) {
  1426. if (obj instanceof Color) {
  1427. return obj;
  1428. }
  1429. if (!(this instanceof Color)) {
  1430. return new Color(obj);
  1431. }
  1432. this.valid = false;
  1433. this.values = {
  1434. rgb: [0, 0, 0],
  1435. hsl: [0, 0, 0],
  1436. hsv: [0, 0, 0],
  1437. hwb: [0, 0, 0],
  1438. cmyk: [0, 0, 0, 0],
  1439. alpha: 1
  1440. };
  1441. // parse Color() argument
  1442. var vals;
  1443. if (typeof obj === 'string') {
  1444. vals = colorString.getRgba(obj);
  1445. if (vals) {
  1446. this.setValues('rgb', vals);
  1447. } else if (vals = colorString.getHsla(obj)) {
  1448. this.setValues('hsl', vals);
  1449. } else if (vals = colorString.getHwb(obj)) {
  1450. this.setValues('hwb', vals);
  1451. }
  1452. } else if (typeof obj === 'object') {
  1453. vals = obj;
  1454. if (vals.r !== undefined || vals.red !== undefined) {
  1455. this.setValues('rgb', vals);
  1456. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  1457. this.setValues('hsl', vals);
  1458. } else if (vals.v !== undefined || vals.value !== undefined) {
  1459. this.setValues('hsv', vals);
  1460. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  1461. this.setValues('hwb', vals);
  1462. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  1463. this.setValues('cmyk', vals);
  1464. }
  1465. }
  1466. };
  1467. Color.prototype = {
  1468. isValid: function () {
  1469. return this.valid;
  1470. },
  1471. rgb: function () {
  1472. return this.setSpace('rgb', arguments);
  1473. },
  1474. hsl: function () {
  1475. return this.setSpace('hsl', arguments);
  1476. },
  1477. hsv: function () {
  1478. return this.setSpace('hsv', arguments);
  1479. },
  1480. hwb: function () {
  1481. return this.setSpace('hwb', arguments);
  1482. },
  1483. cmyk: function () {
  1484. return this.setSpace('cmyk', arguments);
  1485. },
  1486. rgbArray: function () {
  1487. return this.values.rgb;
  1488. },
  1489. hslArray: function () {
  1490. return this.values.hsl;
  1491. },
  1492. hsvArray: function () {
  1493. return this.values.hsv;
  1494. },
  1495. hwbArray: function () {
  1496. var values = this.values;
  1497. if (values.alpha !== 1) {
  1498. return values.hwb.concat([values.alpha]);
  1499. }
  1500. return values.hwb;
  1501. },
  1502. cmykArray: function () {
  1503. return this.values.cmyk;
  1504. },
  1505. rgbaArray: function () {
  1506. var values = this.values;
  1507. return values.rgb.concat([values.alpha]);
  1508. },
  1509. hslaArray: function () {
  1510. var values = this.values;
  1511. return values.hsl.concat([values.alpha]);
  1512. },
  1513. alpha: function (val) {
  1514. if (val === undefined) {
  1515. return this.values.alpha;
  1516. }
  1517. this.setValues('alpha', val);
  1518. return this;
  1519. },
  1520. red: function (val) {
  1521. return this.setChannel('rgb', 0, val);
  1522. },
  1523. green: function (val) {
  1524. return this.setChannel('rgb', 1, val);
  1525. },
  1526. blue: function (val) {
  1527. return this.setChannel('rgb', 2, val);
  1528. },
  1529. hue: function (val) {
  1530. if (val) {
  1531. val %= 360;
  1532. val = val < 0 ? 360 + val : val;
  1533. }
  1534. return this.setChannel('hsl', 0, val);
  1535. },
  1536. saturation: function (val) {
  1537. return this.setChannel('hsl', 1, val);
  1538. },
  1539. lightness: function (val) {
  1540. return this.setChannel('hsl', 2, val);
  1541. },
  1542. saturationv: function (val) {
  1543. return this.setChannel('hsv', 1, val);
  1544. },
  1545. whiteness: function (val) {
  1546. return this.setChannel('hwb', 1, val);
  1547. },
  1548. blackness: function (val) {
  1549. return this.setChannel('hwb', 2, val);
  1550. },
  1551. value: function (val) {
  1552. return this.setChannel('hsv', 2, val);
  1553. },
  1554. cyan: function (val) {
  1555. return this.setChannel('cmyk', 0, val);
  1556. },
  1557. magenta: function (val) {
  1558. return this.setChannel('cmyk', 1, val);
  1559. },
  1560. yellow: function (val) {
  1561. return this.setChannel('cmyk', 2, val);
  1562. },
  1563. black: function (val) {
  1564. return this.setChannel('cmyk', 3, val);
  1565. },
  1566. hexString: function () {
  1567. return colorString.hexString(this.values.rgb);
  1568. },
  1569. rgbString: function () {
  1570. return colorString.rgbString(this.values.rgb, this.values.alpha);
  1571. },
  1572. rgbaString: function () {
  1573. return colorString.rgbaString(this.values.rgb, this.values.alpha);
  1574. },
  1575. percentString: function () {
  1576. return colorString.percentString(this.values.rgb, this.values.alpha);
  1577. },
  1578. hslString: function () {
  1579. return colorString.hslString(this.values.hsl, this.values.alpha);
  1580. },
  1581. hslaString: function () {
  1582. return colorString.hslaString(this.values.hsl, this.values.alpha);
  1583. },
  1584. hwbString: function () {
  1585. return colorString.hwbString(this.values.hwb, this.values.alpha);
  1586. },
  1587. keyword: function () {
  1588. return colorString.keyword(this.values.rgb, this.values.alpha);
  1589. },
  1590. rgbNumber: function () {
  1591. var rgb = this.values.rgb;
  1592. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  1593. },
  1594. luminosity: function () {
  1595. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  1596. var rgb = this.values.rgb;
  1597. var lum = [];
  1598. for (var i = 0; i < rgb.length; i++) {
  1599. var chan = rgb[i] / 255;
  1600. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  1601. }
  1602. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  1603. },
  1604. contrast: function (color2) {
  1605. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  1606. var lum1 = this.luminosity();
  1607. var lum2 = color2.luminosity();
  1608. if (lum1 > lum2) {
  1609. return (lum1 + 0.05) / (lum2 + 0.05);
  1610. }
  1611. return (lum2 + 0.05) / (lum1 + 0.05);
  1612. },
  1613. level: function (color2) {
  1614. var contrastRatio = this.contrast(color2);
  1615. if (contrastRatio >= 7.1) {
  1616. return 'AAA';
  1617. }
  1618. return (contrastRatio >= 4.5) ? 'AA' : '';
  1619. },
  1620. dark: function () {
  1621. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  1622. var rgb = this.values.rgb;
  1623. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  1624. return yiq < 128;
  1625. },
  1626. light: function () {
  1627. return !this.dark();
  1628. },
  1629. negate: function () {
  1630. var rgb = [];
  1631. for (var i = 0; i < 3; i++) {
  1632. rgb[i] = 255 - this.values.rgb[i];
  1633. }
  1634. this.setValues('rgb', rgb);
  1635. return this;
  1636. },
  1637. lighten: function (ratio) {
  1638. var hsl = this.values.hsl;
  1639. hsl[2] += hsl[2] * ratio;
  1640. this.setValues('hsl', hsl);
  1641. return this;
  1642. },
  1643. darken: function (ratio) {
  1644. var hsl = this.values.hsl;
  1645. hsl[2] -= hsl[2] * ratio;
  1646. this.setValues('hsl', hsl);
  1647. return this;
  1648. },
  1649. saturate: function (ratio) {
  1650. var hsl = this.values.hsl;
  1651. hsl[1] += hsl[1] * ratio;
  1652. this.setValues('hsl', hsl);
  1653. return this;
  1654. },
  1655. desaturate: function (ratio) {
  1656. var hsl = this.values.hsl;
  1657. hsl[1] -= hsl[1] * ratio;
  1658. this.setValues('hsl', hsl);
  1659. return this;
  1660. },
  1661. whiten: function (ratio) {
  1662. var hwb = this.values.hwb;
  1663. hwb[1] += hwb[1] * ratio;
  1664. this.setValues('hwb', hwb);
  1665. return this;
  1666. },
  1667. blacken: function (ratio) {
  1668. var hwb = this.values.hwb;
  1669. hwb[2] += hwb[2] * ratio;
  1670. this.setValues('hwb', hwb);
  1671. return this;
  1672. },
  1673. greyscale: function () {
  1674. var rgb = this.values.rgb;
  1675. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  1676. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  1677. this.setValues('rgb', [val, val, val]);
  1678. return this;
  1679. },
  1680. clearer: function (ratio) {
  1681. var alpha = this.values.alpha;
  1682. this.setValues('alpha', alpha - (alpha * ratio));
  1683. return this;
  1684. },
  1685. opaquer: function (ratio) {
  1686. var alpha = this.values.alpha;
  1687. this.setValues('alpha', alpha + (alpha * ratio));
  1688. return this;
  1689. },
  1690. rotate: function (degrees) {
  1691. var hsl = this.values.hsl;
  1692. var hue = (hsl[0] + degrees) % 360;
  1693. hsl[0] = hue < 0 ? 360 + hue : hue;
  1694. this.setValues('hsl', hsl);
  1695. return this;
  1696. },
  1697. /**
  1698. * Ported from sass implementation in C
  1699. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  1700. */
  1701. mix: function (mixinColor, weight) {
  1702. var color1 = this;
  1703. var color2 = mixinColor;
  1704. var p = weight === undefined ? 0.5 : weight;
  1705. var w = 2 * p - 1;
  1706. var a = color1.alpha() - color2.alpha();
  1707. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  1708. var w2 = 1 - w1;
  1709. return this
  1710. .rgb(
  1711. w1 * color1.red() + w2 * color2.red(),
  1712. w1 * color1.green() + w2 * color2.green(),
  1713. w1 * color1.blue() + w2 * color2.blue()
  1714. )
  1715. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  1716. },
  1717. toJSON: function () {
  1718. return this.rgb();
  1719. },
  1720. clone: function () {
  1721. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  1722. // making the final build way to big to embed in Chart.js. So let's do it manually,
  1723. // assuming that values to clone are 1 dimension arrays containing only numbers,
  1724. // except 'alpha' which is a number.
  1725. var result = new Color();
  1726. var source = this.values;
  1727. var target = result.values;
  1728. var value, type;
  1729. for (var prop in source) {
  1730. if (source.hasOwnProperty(prop)) {
  1731. value = source[prop];
  1732. type = ({}).toString.call(value);
  1733. if (type === '[object Array]') {
  1734. target[prop] = value.slice(0);
  1735. } else if (type === '[object Number]') {
  1736. target[prop] = value;
  1737. } else {
  1738. console.error('unexpected color value:', value);
  1739. }
  1740. }
  1741. }
  1742. return result;
  1743. }
  1744. };
  1745. Color.prototype.spaces = {
  1746. rgb: ['red', 'green', 'blue'],
  1747. hsl: ['hue', 'saturation', 'lightness'],
  1748. hsv: ['hue', 'saturation', 'value'],
  1749. hwb: ['hue', 'whiteness', 'blackness'],
  1750. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  1751. };
  1752. Color.prototype.maxes = {
  1753. rgb: [255, 255, 255],
  1754. hsl: [360, 100, 100],
  1755. hsv: [360, 100, 100],
  1756. hwb: [360, 100, 100],
  1757. cmyk: [100, 100, 100, 100]
  1758. };
  1759. Color.prototype.getValues = function (space) {
  1760. var values = this.values;
  1761. var vals = {};
  1762. for (var i = 0; i < space.length; i++) {
  1763. vals[space.charAt(i)] = values[space][i];
  1764. }
  1765. if (values.alpha !== 1) {
  1766. vals.a = values.alpha;
  1767. }
  1768. // {r: 255, g: 255, b: 255, a: 0.4}
  1769. return vals;
  1770. };
  1771. Color.prototype.setValues = function (space, vals) {
  1772. var values = this.values;
  1773. var spaces = this.spaces;
  1774. var maxes = this.maxes;
  1775. var alpha = 1;
  1776. var i;
  1777. this.valid = true;
  1778. if (space === 'alpha') {
  1779. alpha = vals;
  1780. } else if (vals.length) {
  1781. // [10, 10, 10]
  1782. values[space] = vals.slice(0, space.length);
  1783. alpha = vals[space.length];
  1784. } else if (vals[space.charAt(0)] !== undefined) {
  1785. // {r: 10, g: 10, b: 10}
  1786. for (i = 0; i < space.length; i++) {
  1787. values[space][i] = vals[space.charAt(i)];
  1788. }
  1789. alpha = vals.a;
  1790. } else if (vals[spaces[space][0]] !== undefined) {
  1791. // {red: 10, green: 10, blue: 10}
  1792. var chans = spaces[space];
  1793. for (i = 0; i < space.length; i++) {
  1794. values[space][i] = vals[chans[i]];
  1795. }
  1796. alpha = vals.alpha;
  1797. }
  1798. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  1799. if (space === 'alpha') {
  1800. return false;
  1801. }
  1802. var capped;
  1803. // cap values of the space prior converting all values
  1804. for (i = 0; i < space.length; i++) {
  1805. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  1806. values[space][i] = Math.round(capped);
  1807. }
  1808. // convert to all the other color spaces
  1809. for (var sname in spaces) {
  1810. if (sname !== space) {
  1811. values[sname] = colorConvert[space][sname](values[space]);
  1812. }
  1813. }
  1814. return true;
  1815. };
  1816. Color.prototype.setSpace = function (space, args) {
  1817. var vals = args[0];
  1818. if (vals === undefined) {
  1819. // color.rgb()
  1820. return this.getValues(space);
  1821. }
  1822. // color.rgb(10, 10, 10)
  1823. if (typeof vals === 'number') {
  1824. vals = Array.prototype.slice.call(args);
  1825. }
  1826. this.setValues(space, vals);
  1827. return this;
  1828. };
  1829. Color.prototype.setChannel = function (space, index, val) {
  1830. var svalues = this.values[space];
  1831. if (val === undefined) {
  1832. // color.red()
  1833. return svalues[index];
  1834. } else if (val === svalues[index]) {
  1835. // color.red(color.red())
  1836. return this;
  1837. }
  1838. // color.red(100)
  1839. svalues[index] = val;
  1840. this.setValues(space, svalues);
  1841. return this;
  1842. };
  1843. if (typeof window !== 'undefined') {
  1844. window.Color = Color;
  1845. }
  1846. var chartjsColor = Color;
  1847. function isValidKey(key) {
  1848. return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;
  1849. }
  1850. /**
  1851. * @namespace Chart.helpers
  1852. */
  1853. var helpers = {
  1854. /**
  1855. * An empty function that can be used, for example, for optional callback.
  1856. */
  1857. noop: function () {
  1858. },
  1859. /**
  1860. * Returns a unique id, sequentially generated from a global variable.
  1861. * @returns {number}
  1862. * @function
  1863. */
  1864. uid: (function () {
  1865. var id = 0;
  1866. return function () {
  1867. return id++;
  1868. };
  1869. }()),
  1870. /**
  1871. * Returns true if `value` is neither null nor undefined, else returns false.
  1872. * @param {*} value - The value to test.
  1873. * @returns {boolean}
  1874. * @since 2.7.0
  1875. */
  1876. isNullOrUndef: function (value) {
  1877. return value === null || typeof value === 'undefined';
  1878. },
  1879. /**
  1880. * Returns true if `value` is an array (including typed arrays), else returns false.
  1881. * @param {*} value - The value to test.
  1882. * @returns {boolean}
  1883. * @function
  1884. */
  1885. isArray: function (value) {
  1886. if (Array.isArray && Array.isArray(value)) {
  1887. return true;
  1888. }
  1889. var type = Object.prototype.toString.call(value);
  1890. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  1891. return true;
  1892. }
  1893. return false;
  1894. },
  1895. /**
  1896. * Returns true if `value` is an object (excluding null), else returns false.
  1897. * @param {*} value - The value to test.
  1898. * @returns {boolean}
  1899. * @since 2.7.0
  1900. */
  1901. isObject: function (value) {
  1902. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  1903. },
  1904. /**
  1905. * Returns true if `value` is a finite number, else returns false
  1906. * @param {*} value - The value to test.
  1907. * @returns {boolean}
  1908. */
  1909. isFinite: function (value) {
  1910. return (typeof value === 'number' || value instanceof Number) && isFinite(value);
  1911. },
  1912. /**
  1913. * Returns `value` if defined, else returns `defaultValue`.
  1914. * @param {*} value - The value to return if defined.
  1915. * @param {*} defaultValue - The value to return if `value` is undefined.
  1916. * @returns {*}
  1917. */
  1918. valueOrDefault: function (value, defaultValue) {
  1919. return typeof value === 'undefined' ? defaultValue : value;
  1920. },
  1921. /**
  1922. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  1923. * @param {Array} value - The array to lookup for value at `index`.
  1924. * @param {number} index - The index in `value` to lookup for value.
  1925. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  1926. * @returns {*}
  1927. */
  1928. valueAtIndexOrDefault: function (value, index, defaultValue) {
  1929. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  1930. },
  1931. /**
  1932. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  1933. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  1934. * @param {function} fn - The function to call.
  1935. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  1936. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1937. * @returns {*}
  1938. */
  1939. callback: function (fn, args, thisArg) {
  1940. if (fn && typeof fn.call === 'function') {
  1941. return fn.apply(thisArg, args);
  1942. }
  1943. },
  1944. /**
  1945. * Note(SB) for performance sake, this method should only be used when loopable type
  1946. * is unknown or in none intensive code (not called often and small loopable). Else
  1947. * it's preferable to use a regular for() loop and save extra function calls.
  1948. * @param {object|Array} loopable - The object or array to be iterated.
  1949. * @param {function} fn - The function to call for each item.
  1950. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1951. * @param {boolean} [reverse] - If true, iterates backward on the loopable.
  1952. */
  1953. each: function (loopable, fn, thisArg, reverse) {
  1954. var i, len, keys;
  1955. if (helpers.isArray(loopable)) {
  1956. len = loopable.length;
  1957. if (reverse) {
  1958. for (i = len - 1; i >= 0; i--) {
  1959. fn.call(thisArg, loopable[i], i);
  1960. }
  1961. } else {
  1962. for (i = 0; i < len; i++) {
  1963. fn.call(thisArg, loopable[i], i);
  1964. }
  1965. }
  1966. } else if (helpers.isObject(loopable)) {
  1967. keys = Object.keys(loopable);
  1968. len = keys.length;
  1969. for (i = 0; i < len; i++) {
  1970. fn.call(thisArg, loopable[keys[i]], keys[i]);
  1971. }
  1972. }
  1973. },
  1974. /**
  1975. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  1976. * @see https://stackoverflow.com/a/14853974
  1977. * @param {Array} a0 - The array to compare
  1978. * @param {Array} a1 - The array to compare
  1979. * @returns {boolean}
  1980. */
  1981. arrayEquals: function (a0, a1) {
  1982. var i, ilen, v0, v1;
  1983. if (!a0 || !a1 || a0.length !== a1.length) {
  1984. return false;
  1985. }
  1986. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  1987. v0 = a0[i];
  1988. v1 = a1[i];
  1989. if (v0 instanceof Array && v1 instanceof Array) {
  1990. if (!helpers.arrayEquals(v0, v1)) {
  1991. return false;
  1992. }
  1993. } else if (v0 !== v1) {
  1994. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  1995. return false;
  1996. }
  1997. }
  1998. return true;
  1999. },
  2000. /**
  2001. * Returns a deep copy of `source` without keeping references on objects and arrays.
  2002. * @param {*} source - The value to clone.
  2003. * @returns {*}
  2004. */
  2005. clone: function (source) {
  2006. if (helpers.isArray(source)) {
  2007. return source.map(helpers.clone);
  2008. }
  2009. if (helpers.isObject(source)) {
  2010. var target = Object.create(source);
  2011. var keys = Object.keys(source);
  2012. var klen = keys.length;
  2013. var k = 0;
  2014. for (; k < klen; ++k) {
  2015. target[keys[k]] = helpers.clone(source[keys[k]]);
  2016. }
  2017. return target;
  2018. }
  2019. return source;
  2020. },
  2021. /**
  2022. * The default merger when Chart.helpers.merge is called without merger option.
  2023. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
  2024. * @private
  2025. */
  2026. _merger: function (key, target, source, options) {
  2027. if (!isValidKey(key)) {
  2028. // We want to ensure we do not copy prototypes over
  2029. // as this can pollute global namespaces
  2030. return;
  2031. }
  2032. var tval = target[key];
  2033. var sval = source[key];
  2034. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  2035. helpers.merge(tval, sval, options);
  2036. } else {
  2037. target[key] = helpers.clone(sval);
  2038. }
  2039. },
  2040. /**
  2041. * Merges source[key] in target[key] only if target[key] is undefined.
  2042. * @private
  2043. */
  2044. _mergerIf: function (key, target, source) {
  2045. if (!isValidKey(key)) {
  2046. // We want to ensure we do not copy prototypes over
  2047. // as this can pollute global namespaces
  2048. return;
  2049. }
  2050. var tval = target[key];
  2051. var sval = source[key];
  2052. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  2053. helpers.mergeIf(tval, sval);
  2054. } else if (!target.hasOwnProperty(key)) {
  2055. target[key] = helpers.clone(sval);
  2056. }
  2057. },
  2058. /**
  2059. * Recursively deep copies `source` properties into `target` with the given `options`.
  2060. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2061. * @param {object} target - The target object in which all sources are merged into.
  2062. * @param {object|object[]} source - Object(s) to merge into `target`.
  2063. * @param {object} [options] - Merging options:
  2064. * @param {function} [options.merger] - The merge method (key, target, source, options)
  2065. * @returns {object} The `target` object.
  2066. */
  2067. merge: function (target, source, options) {
  2068. var sources = helpers.isArray(source) ? source : [source];
  2069. var ilen = sources.length;
  2070. var merge, i, keys, klen, k;
  2071. if (!helpers.isObject(target)) {
  2072. return target;
  2073. }
  2074. options = options || {};
  2075. merge = options.merger || helpers._merger;
  2076. for (i = 0; i < ilen; ++i) {
  2077. source = sources[i];
  2078. if (!helpers.isObject(source)) {
  2079. continue;
  2080. }
  2081. keys = Object.keys(source);
  2082. for (k = 0, klen = keys.length; k < klen; ++k) {
  2083. merge(keys[k], target, source, options);
  2084. }
  2085. }
  2086. return target;
  2087. },
  2088. /**
  2089. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  2090. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2091. * @param {object} target - The target object in which all sources are merged into.
  2092. * @param {object|object[]} source - Object(s) to merge into `target`.
  2093. * @returns {object} The `target` object.
  2094. */
  2095. mergeIf: function (target, source) {
  2096. return helpers.merge(target, source, {merger: helpers._mergerIf});
  2097. },
  2098. /**
  2099. * Applies the contents of two or more objects together into the first object.
  2100. * @param {object} target - The target object in which all objects are merged into.
  2101. * @param {object} arg1 - Object containing additional properties to merge in target.
  2102. * @param {object} argN - Additional objects containing properties to merge in target.
  2103. * @returns {object} The `target` object.
  2104. */
  2105. extend: Object.assign || function (target) {
  2106. return helpers.merge(target, [].slice.call(arguments, 1), {
  2107. merger: function (key, dst, src) {
  2108. dst[key] = src[key];
  2109. }
  2110. });
  2111. },
  2112. /**
  2113. * Basic javascript inheritance based on the model created in Backbone.js
  2114. */
  2115. inherits: function (extensions) {
  2116. var me = this;
  2117. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function () {
  2118. return me.apply(this, arguments);
  2119. };
  2120. var Surrogate = function () {
  2121. this.constructor = ChartElement;
  2122. };
  2123. Surrogate.prototype = me.prototype;
  2124. ChartElement.prototype = new Surrogate();
  2125. ChartElement.extend = helpers.inherits;
  2126. if (extensions) {
  2127. helpers.extend(ChartElement.prototype, extensions);
  2128. }
  2129. ChartElement.__super__ = me.prototype;
  2130. return ChartElement;
  2131. },
  2132. _deprecated: function (scope, value, previous, current) {
  2133. if (value !== undefined) {
  2134. console.warn(scope + ': "' + previous +
  2135. '" is deprecated. Please use "' + current + '" instead');
  2136. }
  2137. }
  2138. };
  2139. var helpers_core = helpers;
  2140. // DEPRECATIONS
  2141. /**
  2142. * Provided for backward compatibility, use Chart.helpers.callback instead.
  2143. * @function Chart.helpers.callCallback
  2144. * @deprecated since version 2.6.0
  2145. * @todo remove at version 3
  2146. * @private
  2147. */
  2148. helpers.callCallback = helpers.callback;
  2149. /**
  2150. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  2151. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  2152. * @function Chart.helpers.indexOf
  2153. * @deprecated since version 2.7.0
  2154. * @todo remove at version 3
  2155. * @private
  2156. */
  2157. helpers.indexOf = function (array, item, fromIndex) {
  2158. return Array.prototype.indexOf.call(array, item, fromIndex);
  2159. };
  2160. /**
  2161. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  2162. * @function Chart.helpers.getValueOrDefault
  2163. * @deprecated since version 2.7.0
  2164. * @todo remove at version 3
  2165. * @private
  2166. */
  2167. helpers.getValueOrDefault = helpers.valueOrDefault;
  2168. /**
  2169. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  2170. * @function Chart.helpers.getValueAtIndexOrDefault
  2171. * @deprecated since version 2.7.0
  2172. * @todo remove at version 3
  2173. * @private
  2174. */
  2175. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  2176. /**
  2177. * Easing functions adapted from Robert Penner's easing equations.
  2178. * @namespace Chart.helpers.easingEffects
  2179. * @see http://www.robertpenner.com/easing/
  2180. */
  2181. var effects = {
  2182. linear: function (t) {
  2183. return t;
  2184. },
  2185. easeInQuad: function (t) {
  2186. return t * t;
  2187. },
  2188. easeOutQuad: function (t) {
  2189. return -t * (t - 2);
  2190. },
  2191. easeInOutQuad: function (t) {
  2192. if ((t /= 0.5) < 1) {
  2193. return 0.5 * t * t;
  2194. }
  2195. return -0.5 * ((--t) * (t - 2) - 1);
  2196. },
  2197. easeInCubic: function (t) {
  2198. return t * t * t;
  2199. },
  2200. easeOutCubic: function (t) {
  2201. return (t = t - 1) * t * t + 1;
  2202. },
  2203. easeInOutCubic: function (t) {
  2204. if ((t /= 0.5) < 1) {
  2205. return 0.5 * t * t * t;
  2206. }
  2207. return 0.5 * ((t -= 2) * t * t + 2);
  2208. },
  2209. easeInQuart: function (t) {
  2210. return t * t * t * t;
  2211. },
  2212. easeOutQuart: function (t) {
  2213. return -((t = t - 1) * t * t * t - 1);
  2214. },
  2215. easeInOutQuart: function (t) {
  2216. if ((t /= 0.5) < 1) {
  2217. return 0.5 * t * t * t * t;
  2218. }
  2219. return -0.5 * ((t -= 2) * t * t * t - 2);
  2220. },
  2221. easeInQuint: function (t) {
  2222. return t * t * t * t * t;
  2223. },
  2224. easeOutQuint: function (t) {
  2225. return (t = t - 1) * t * t * t * t + 1;
  2226. },
  2227. easeInOutQuint: function (t) {
  2228. if ((t /= 0.5) < 1) {
  2229. return 0.5 * t * t * t * t * t;
  2230. }
  2231. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  2232. },
  2233. easeInSine: function (t) {
  2234. return -Math.cos(t * (Math.PI / 2)) + 1;
  2235. },
  2236. easeOutSine: function (t) {
  2237. return Math.sin(t * (Math.PI / 2));
  2238. },
  2239. easeInOutSine: function (t) {
  2240. return -0.5 * (Math.cos(Math.PI * t) - 1);
  2241. },
  2242. easeInExpo: function (t) {
  2243. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  2244. },
  2245. easeOutExpo: function (t) {
  2246. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  2247. },
  2248. easeInOutExpo: function (t) {
  2249. if (t === 0) {
  2250. return 0;
  2251. }
  2252. if (t === 1) {
  2253. return 1;
  2254. }
  2255. if ((t /= 0.5) < 1) {
  2256. return 0.5 * Math.pow(2, 10 * (t - 1));
  2257. }
  2258. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  2259. },
  2260. easeInCirc: function (t) {
  2261. if (t >= 1) {
  2262. return t;
  2263. }
  2264. return -(Math.sqrt(1 - t * t) - 1);
  2265. },
  2266. easeOutCirc: function (t) {
  2267. return Math.sqrt(1 - (t = t - 1) * t);
  2268. },
  2269. easeInOutCirc: function (t) {
  2270. if ((t /= 0.5) < 1) {
  2271. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  2272. }
  2273. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  2274. },
  2275. easeInElastic: function (t) {
  2276. var s = 1.70158;
  2277. var p = 0;
  2278. var a = 1;
  2279. if (t === 0) {
  2280. return 0;
  2281. }
  2282. if (t === 1) {
  2283. return 1;
  2284. }
  2285. if (!p) {
  2286. p = 0.3;
  2287. }
  2288. if (a < 1) {
  2289. a = 1;
  2290. s = p / 4;
  2291. } else {
  2292. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2293. }
  2294. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2295. },
  2296. easeOutElastic: function (t) {
  2297. var s = 1.70158;
  2298. var p = 0;
  2299. var a = 1;
  2300. if (t === 0) {
  2301. return 0;
  2302. }
  2303. if (t === 1) {
  2304. return 1;
  2305. }
  2306. if (!p) {
  2307. p = 0.3;
  2308. }
  2309. if (a < 1) {
  2310. a = 1;
  2311. s = p / 4;
  2312. } else {
  2313. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2314. }
  2315. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  2316. },
  2317. easeInOutElastic: function (t) {
  2318. var s = 1.70158;
  2319. var p = 0;
  2320. var a = 1;
  2321. if (t === 0) {
  2322. return 0;
  2323. }
  2324. if ((t /= 0.5) === 2) {
  2325. return 1;
  2326. }
  2327. if (!p) {
  2328. p = 0.45;
  2329. }
  2330. if (a < 1) {
  2331. a = 1;
  2332. s = p / 4;
  2333. } else {
  2334. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2335. }
  2336. if (t < 1) {
  2337. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2338. }
  2339. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2340. },
  2341. easeInBack: function (t) {
  2342. var s = 1.70158;
  2343. return t * t * ((s + 1) * t - s);
  2344. },
  2345. easeOutBack: function (t) {
  2346. var s = 1.70158;
  2347. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  2348. },
  2349. easeInOutBack: function (t) {
  2350. var s = 1.70158;
  2351. if ((t /= 0.5) < 1) {
  2352. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  2353. }
  2354. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  2355. },
  2356. easeInBounce: function (t) {
  2357. return 1 - effects.easeOutBounce(1 - t);
  2358. },
  2359. easeOutBounce: function (t) {
  2360. if (t < (1 / 2.75)) {
  2361. return 7.5625 * t * t;
  2362. }
  2363. if (t < (2 / 2.75)) {
  2364. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  2365. }
  2366. if (t < (2.5 / 2.75)) {
  2367. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  2368. }
  2369. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  2370. },
  2371. easeInOutBounce: function (t) {
  2372. if (t < 0.5) {
  2373. return effects.easeInBounce(t * 2) * 0.5;
  2374. }
  2375. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  2376. }
  2377. };
  2378. var helpers_easing = {
  2379. effects: effects
  2380. };
  2381. // DEPRECATIONS
  2382. /**
  2383. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  2384. * @function Chart.helpers.easingEffects
  2385. * @deprecated since version 2.7.0
  2386. * @todo remove at version 3
  2387. * @private
  2388. */
  2389. helpers_core.easingEffects = effects;
  2390. var PI = Math.PI;
  2391. var RAD_PER_DEG = PI / 180;
  2392. var DOUBLE_PI = PI * 2;
  2393. var HALF_PI = PI / 2;
  2394. var QUARTER_PI = PI / 4;
  2395. var TWO_THIRDS_PI = PI * 2 / 3;
  2396. /**
  2397. * @namespace Chart.helpers.canvas
  2398. */
  2399. var exports$1 = {
  2400. /**
  2401. * Clears the entire canvas associated to the given `chart`.
  2402. * @param {Chart} chart - The chart for which to clear the canvas.
  2403. */
  2404. clear: function (chart) {
  2405. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  2406. },
  2407. /**
  2408. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  2409. * given size (width, height) and the same `radius` for all corners.
  2410. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  2411. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  2412. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  2413. * @param {number} width - The rectangle's width.
  2414. * @param {number} height - The rectangle's height.
  2415. * @param {number} radius - The rounded amount (in pixels) for the four corners.
  2416. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  2417. */
  2418. roundedRect: function (ctx, x, y, width, height, radius) {
  2419. if (radius) {
  2420. var r = Math.min(radius, height / 2, width / 2);
  2421. var left = x + r;
  2422. var top = y + r;
  2423. var right = x + width - r;
  2424. var bottom = y + height - r;
  2425. ctx.moveTo(x, top);
  2426. if (left < right && top < bottom) {
  2427. ctx.arc(left, top, r, -PI, -HALF_PI);
  2428. ctx.arc(right, top, r, -HALF_PI, 0);
  2429. ctx.arc(right, bottom, r, 0, HALF_PI);
  2430. ctx.arc(left, bottom, r, HALF_PI, PI);
  2431. } else if (left < right) {
  2432. ctx.moveTo(left, y);
  2433. ctx.arc(right, top, r, -HALF_PI, HALF_PI);
  2434. ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
  2435. } else if (top < bottom) {
  2436. ctx.arc(left, top, r, -PI, 0);
  2437. ctx.arc(left, bottom, r, 0, PI);
  2438. } else {
  2439. ctx.arc(left, top, r, -PI, PI);
  2440. }
  2441. ctx.closePath();
  2442. ctx.moveTo(x, y);
  2443. } else {
  2444. ctx.rect(x, y, width, height);
  2445. }
  2446. },
  2447. drawPoint: function (ctx, style, radius, x, y, rotation) {
  2448. var type, xOffset, yOffset, size, cornerRadius;
  2449. var rad = (rotation || 0) * RAD_PER_DEG;
  2450. if (style && typeof style === 'object') {
  2451. type = style.toString();
  2452. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  2453. ctx.save();
  2454. ctx.translate(x, y);
  2455. ctx.rotate(rad);
  2456. ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
  2457. ctx.restore();
  2458. return;
  2459. }
  2460. }
  2461. if (isNaN(radius) || radius <= 0) {
  2462. return;
  2463. }
  2464. ctx.beginPath();
  2465. switch (style) {
  2466. // Default includes circle
  2467. default:
  2468. ctx.arc(x, y, radius, 0, DOUBLE_PI);
  2469. ctx.closePath();
  2470. break;
  2471. case 'triangle':
  2472. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2473. rad += TWO_THIRDS_PI;
  2474. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2475. rad += TWO_THIRDS_PI;
  2476. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2477. ctx.closePath();
  2478. break;
  2479. case 'rectRounded':
  2480. // NOTE: the rounded rect implementation changed to use `arc` instead of
  2481. // `quadraticCurveTo` since it generates better results when rect is
  2482. // almost a circle. 0.516 (instead of 0.5) produces results with visually
  2483. // closer proportion to the previous impl and it is inscribed in the
  2484. // circle with `radius`. For more details, see the following PRs:
  2485. // https://github.com/chartjs/Chart.js/issues/5597
  2486. // https://github.com/chartjs/Chart.js/issues/5858
  2487. cornerRadius = radius * 0.516;
  2488. size = radius - cornerRadius;
  2489. xOffset = Math.cos(rad + QUARTER_PI) * size;
  2490. yOffset = Math.sin(rad + QUARTER_PI) * size;
  2491. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  2492. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  2493. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  2494. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  2495. ctx.closePath();
  2496. break;
  2497. case 'rect':
  2498. if (!rotation) {
  2499. size = Math.SQRT1_2 * radius;
  2500. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  2501. break;
  2502. }
  2503. rad += QUARTER_PI;
  2504. /* falls through */
  2505. case 'rectRot':
  2506. xOffset = Math.cos(rad) * radius;
  2507. yOffset = Math.sin(rad) * radius;
  2508. ctx.moveTo(x - xOffset, y - yOffset);
  2509. ctx.lineTo(x + yOffset, y - xOffset);
  2510. ctx.lineTo(x + xOffset, y + yOffset);
  2511. ctx.lineTo(x - yOffset, y + xOffset);
  2512. ctx.closePath();
  2513. break;
  2514. case 'crossRot':
  2515. rad += QUARTER_PI;
  2516. /* falls through */
  2517. case 'cross':
  2518. xOffset = Math.cos(rad) * radius;
  2519. yOffset = Math.sin(rad) * radius;
  2520. ctx.moveTo(x - xOffset, y - yOffset);
  2521. ctx.lineTo(x + xOffset, y + yOffset);
  2522. ctx.moveTo(x + yOffset, y - xOffset);
  2523. ctx.lineTo(x - yOffset, y + xOffset);
  2524. break;
  2525. case 'star':
  2526. xOffset = Math.cos(rad) * radius;
  2527. yOffset = Math.sin(rad) * radius;
  2528. ctx.moveTo(x - xOffset, y - yOffset);
  2529. ctx.lineTo(x + xOffset, y + yOffset);
  2530. ctx.moveTo(x + yOffset, y - xOffset);
  2531. ctx.lineTo(x - yOffset, y + xOffset);
  2532. rad += QUARTER_PI;
  2533. xOffset = Math.cos(rad) * radius;
  2534. yOffset = Math.sin(rad) * radius;
  2535. ctx.moveTo(x - xOffset, y - yOffset);
  2536. ctx.lineTo(x + xOffset, y + yOffset);
  2537. ctx.moveTo(x + yOffset, y - xOffset);
  2538. ctx.lineTo(x - yOffset, y + xOffset);
  2539. break;
  2540. case 'line':
  2541. xOffset = Math.cos(rad) * radius;
  2542. yOffset = Math.sin(rad) * radius;
  2543. ctx.moveTo(x - xOffset, y - yOffset);
  2544. ctx.lineTo(x + xOffset, y + yOffset);
  2545. break;
  2546. case 'dash':
  2547. ctx.moveTo(x, y);
  2548. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  2549. break;
  2550. }
  2551. ctx.fill();
  2552. ctx.stroke();
  2553. },
  2554. /**
  2555. * Returns true if the point is inside the rectangle
  2556. * @param {object} point - The point to test
  2557. * @param {object} area - The rectangle
  2558. * @returns {boolean}
  2559. * @private
  2560. */
  2561. _isPointInArea: function (point, area) {
  2562. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  2563. return point.x > area.left - epsilon && point.x < area.right + epsilon &&
  2564. point.y > area.top - epsilon && point.y < area.bottom + epsilon;
  2565. },
  2566. clipArea: function (ctx, area) {
  2567. ctx.save();
  2568. ctx.beginPath();
  2569. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  2570. ctx.clip();
  2571. },
  2572. unclipArea: function (ctx) {
  2573. ctx.restore();
  2574. },
  2575. lineTo: function (ctx, previous, target, flip) {
  2576. var stepped = target.steppedLine;
  2577. if (stepped) {
  2578. if (stepped === 'middle') {
  2579. var midpoint = (previous.x + target.x) / 2.0;
  2580. ctx.lineTo(midpoint, flip ? target.y : previous.y);
  2581. ctx.lineTo(midpoint, flip ? previous.y : target.y);
  2582. } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
  2583. ctx.lineTo(previous.x, target.y);
  2584. } else {
  2585. ctx.lineTo(target.x, previous.y);
  2586. }
  2587. ctx.lineTo(target.x, target.y);
  2588. return;
  2589. }
  2590. if (!target.tension) {
  2591. ctx.lineTo(target.x, target.y);
  2592. return;
  2593. }
  2594. ctx.bezierCurveTo(
  2595. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  2596. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  2597. flip ? target.controlPointNextX : target.controlPointPreviousX,
  2598. flip ? target.controlPointNextY : target.controlPointPreviousY,
  2599. target.x,
  2600. target.y);
  2601. }
  2602. };
  2603. var helpers_canvas = exports$1;
  2604. // DEPRECATIONS
  2605. /**
  2606. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  2607. * @namespace Chart.helpers.clear
  2608. * @deprecated since version 2.7.0
  2609. * @todo remove at version 3
  2610. * @private
  2611. */
  2612. helpers_core.clear = exports$1.clear;
  2613. /**
  2614. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  2615. * @namespace Chart.helpers.drawRoundedRectangle
  2616. * @deprecated since version 2.7.0
  2617. * @todo remove at version 3
  2618. * @private
  2619. */
  2620. helpers_core.drawRoundedRectangle = function (ctx) {
  2621. ctx.beginPath();
  2622. exports$1.roundedRect.apply(exports$1, arguments);
  2623. };
  2624. var defaults = {
  2625. /**
  2626. * @private
  2627. */
  2628. _set: function (scope, values) {
  2629. return helpers_core.merge(this[scope] || (this[scope] = {}), values);
  2630. }
  2631. };
  2632. // TODO(v3): remove 'global' from namespace. all default are global and
  2633. // there's inconsistency around which options are under 'global'
  2634. defaults._set('global', {
  2635. defaultColor: 'rgba(0,0,0,0.1)',
  2636. defaultFontColor: '#666',
  2637. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  2638. defaultFontSize: 12,
  2639. defaultFontStyle: 'normal',
  2640. defaultLineHeight: 1.2,
  2641. showLines: true
  2642. });
  2643. var core_defaults = defaults;
  2644. var valueOrDefault = helpers_core.valueOrDefault;
  2645. /**
  2646. * Converts the given font object into a CSS font string.
  2647. * @param {object} font - A font object.
  2648. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
  2649. * @private
  2650. */
  2651. function toFontString(font) {
  2652. if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
  2653. return null;
  2654. }
  2655. return (font.style ? font.style + ' ' : '')
  2656. + (font.weight ? font.weight + ' ' : '')
  2657. + font.size + 'px '
  2658. + font.family;
  2659. }
  2660. /**
  2661. * @alias Chart.helpers.options
  2662. * @namespace
  2663. */
  2664. var helpers_options = {
  2665. /**
  2666. * Converts the given line height `value` in pixels for a specific font `size`.
  2667. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  2668. * @param {number} size - The font size (in pixels) used to resolve relative `value`.
  2669. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
  2670. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  2671. * @since 2.7.0
  2672. */
  2673. toLineHeight: function (value, size) {
  2674. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  2675. if (!matches || matches[1] === 'normal') {
  2676. return size * 1.2;
  2677. }
  2678. value = +matches[2];
  2679. switch (matches[3]) {
  2680. case 'px':
  2681. return value;
  2682. case '%':
  2683. value /= 100;
  2684. break;
  2685. }
  2686. return size * value;
  2687. },
  2688. /**
  2689. * Converts the given value into a padding object with pre-computed width/height.
  2690. * @param {number|object} value - If a number, set the value to all TRBL component,
  2691. * else, if and object, use defined properties and sets undefined ones to 0.
  2692. * @returns {object} The padding values (top, right, bottom, left, width, height)
  2693. * @since 2.7.0
  2694. */
  2695. toPadding: function (value) {
  2696. var t, r, b, l;
  2697. if (helpers_core.isObject(value)) {
  2698. t = +value.top || 0;
  2699. r = +value.right || 0;
  2700. b = +value.bottom || 0;
  2701. l = +value.left || 0;
  2702. } else {
  2703. t = r = b = l = +value || 0;
  2704. }
  2705. return {
  2706. top: t,
  2707. right: r,
  2708. bottom: b,
  2709. left: l,
  2710. height: t + b,
  2711. width: l + r
  2712. };
  2713. },
  2714. /**
  2715. * Parses font options and returns the font object.
  2716. * @param {object} options - A object that contains font options to be parsed.
  2717. * @return {object} The font object.
  2718. * @todo Support font.* options and renamed to toFont().
  2719. * @private
  2720. */
  2721. _parseFont: function (options) {
  2722. var globalDefaults = core_defaults.global;
  2723. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  2724. var font = {
  2725. family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
  2726. lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
  2727. size: size,
  2728. style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
  2729. weight: null,
  2730. string: ''
  2731. };
  2732. font.string = toFontString(font);
  2733. return font;
  2734. },
  2735. /**
  2736. * Evaluates the given `inputs` sequentially and returns the first defined value.
  2737. * @param {Array} inputs - An array of values, falling back to the last value.
  2738. * @param {object} [context] - If defined and the current value is a function, the value
  2739. * is called with `context` as first argument and the result becomes the new input.
  2740. * @param {number} [index] - If defined and the current value is an array, the value
  2741. * at `index` become the new input.
  2742. * @param {object} [info] - object to return information about resolution in
  2743. * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable.
  2744. * @since 2.7.0
  2745. */
  2746. resolve: function (inputs, context, index, info) {
  2747. var cacheable = true;
  2748. var i, ilen, value;
  2749. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  2750. value = inputs[i];
  2751. if (value === undefined) {
  2752. continue;
  2753. }
  2754. if (context !== undefined && typeof value === 'function') {
  2755. value = value(context);
  2756. cacheable = false;
  2757. }
  2758. if (index !== undefined && helpers_core.isArray(value)) {
  2759. value = value[index];
  2760. cacheable = false;
  2761. }
  2762. if (value !== undefined) {
  2763. if (info && !cacheable) {
  2764. info.cacheable = false;
  2765. }
  2766. return value;
  2767. }
  2768. }
  2769. }
  2770. };
  2771. /**
  2772. * @alias Chart.helpers.math
  2773. * @namespace
  2774. */
  2775. var exports$2 = {
  2776. /**
  2777. * Returns an array of factors sorted from 1 to sqrt(value)
  2778. * @private
  2779. */
  2780. _factorize: function (value) {
  2781. var result = [];
  2782. var sqrt = Math.sqrt(value);
  2783. var i;
  2784. for (i = 1; i < sqrt; i++) {
  2785. if (value % i === 0) {
  2786. result.push(i);
  2787. result.push(value / i);
  2788. }
  2789. }
  2790. if (sqrt === (sqrt | 0)) { // if value is a square number
  2791. result.push(sqrt);
  2792. }
  2793. result.sort(function (a, b) {
  2794. return a - b;
  2795. }).pop();
  2796. return result;
  2797. },
  2798. log10: Math.log10 || function (x) {
  2799. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  2800. // Check for whole powers of 10,
  2801. // which due to floating point rounding error should be corrected.
  2802. var powerOf10 = Math.round(exponent);
  2803. var isPowerOf10 = x === Math.pow(10, powerOf10);
  2804. return isPowerOf10 ? powerOf10 : exponent;
  2805. }
  2806. };
  2807. var helpers_math = exports$2;
  2808. // DEPRECATIONS
  2809. /**
  2810. * Provided for backward compatibility, use Chart.helpers.math.log10 instead.
  2811. * @namespace Chart.helpers.log10
  2812. * @deprecated since version 2.9.0
  2813. * @todo remove at version 3
  2814. * @private
  2815. */
  2816. helpers_core.log10 = exports$2.log10;
  2817. var getRtlAdapter = function (rectX, width) {
  2818. return {
  2819. x: function (x) {
  2820. return rectX + rectX + width - x;
  2821. },
  2822. setWidth: function (w) {
  2823. width = w;
  2824. },
  2825. textAlign: function (align) {
  2826. if (align === 'center') {
  2827. return align;
  2828. }
  2829. return align === 'right' ? 'left' : 'right';
  2830. },
  2831. xPlus: function (x, value) {
  2832. return x - value;
  2833. },
  2834. leftForLtr: function (x, itemWidth) {
  2835. return x - itemWidth;
  2836. },
  2837. };
  2838. };
  2839. var getLtrAdapter = function () {
  2840. return {
  2841. x: function (x) {
  2842. return x;
  2843. },
  2844. setWidth: function (w) { // eslint-disable-line no-unused-vars
  2845. },
  2846. textAlign: function (align) {
  2847. return align;
  2848. },
  2849. xPlus: function (x, value) {
  2850. return x + value;
  2851. },
  2852. leftForLtr: function (x, _itemWidth) { // eslint-disable-line no-unused-vars
  2853. return x;
  2854. },
  2855. };
  2856. };
  2857. var getAdapter = function (rtl, rectX, width) {
  2858. return rtl ? getRtlAdapter(rectX, width) : getLtrAdapter();
  2859. };
  2860. var overrideTextDirection = function (ctx, direction) {
  2861. var style, original;
  2862. if (direction === 'ltr' || direction === 'rtl') {
  2863. style = ctx.canvas.style;
  2864. original = [
  2865. style.getPropertyValue('direction'),
  2866. style.getPropertyPriority('direction'),
  2867. ];
  2868. style.setProperty('direction', direction, 'important');
  2869. ctx.prevTextDirection = original;
  2870. }
  2871. };
  2872. var restoreTextDirection = function (ctx) {
  2873. var original = ctx.prevTextDirection;
  2874. if (original !== undefined) {
  2875. delete ctx.prevTextDirection;
  2876. ctx.canvas.style.setProperty('direction', original[0], original[1]);
  2877. }
  2878. };
  2879. var helpers_rtl = {
  2880. getRtlAdapter: getAdapter,
  2881. overrideTextDirection: overrideTextDirection,
  2882. restoreTextDirection: restoreTextDirection,
  2883. };
  2884. var helpers$1 = helpers_core;
  2885. var easing = helpers_easing;
  2886. var canvas = helpers_canvas;
  2887. var options = helpers_options;
  2888. var math = helpers_math;
  2889. var rtl = helpers_rtl;
  2890. helpers$1.easing = easing;
  2891. helpers$1.canvas = canvas;
  2892. helpers$1.options = options;
  2893. helpers$1.math = math;
  2894. helpers$1.rtl = rtl;
  2895. function interpolate(start, view, model, ease) {
  2896. var keys = Object.keys(model);
  2897. var i, ilen, key, actual, origin, target, type, c0, c1;
  2898. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  2899. key = keys[i];
  2900. target = model[key];
  2901. // if a value is added to the model after pivot() has been called, the view
  2902. // doesn't contain it, so let's initialize the view to the target value.
  2903. if (!view.hasOwnProperty(key)) {
  2904. view[key] = target;
  2905. }
  2906. actual = view[key];
  2907. if (actual === target || key[0] === '_') {
  2908. continue;
  2909. }
  2910. if (!start.hasOwnProperty(key)) {
  2911. start[key] = actual;
  2912. }
  2913. origin = start[key];
  2914. type = typeof target;
  2915. if (type === typeof origin) {
  2916. if (type === 'string') {
  2917. c0 = chartjsColor(origin);
  2918. if (c0.valid) {
  2919. c1 = chartjsColor(target);
  2920. if (c1.valid) {
  2921. view[key] = c1.mix(c0, ease).rgbString();
  2922. continue;
  2923. }
  2924. }
  2925. } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
  2926. view[key] = origin + (target - origin) * ease;
  2927. continue;
  2928. }
  2929. }
  2930. view[key] = target;
  2931. }
  2932. }
  2933. var Element = function (configuration) {
  2934. helpers$1.extend(this, configuration);
  2935. this.initialize.apply(this, arguments);
  2936. };
  2937. helpers$1.extend(Element.prototype, {
  2938. _type: undefined,
  2939. initialize: function () {
  2940. this.hidden = false;
  2941. },
  2942. pivot: function () {
  2943. var me = this;
  2944. if (!me._view) {
  2945. me._view = helpers$1.extend({}, me._model);
  2946. }
  2947. me._start = {};
  2948. return me;
  2949. },
  2950. transition: function (ease) {
  2951. var me = this;
  2952. var model = me._model;
  2953. var start = me._start;
  2954. var view = me._view;
  2955. // No animation -> No Transition
  2956. if (!model || ease === 1) {
  2957. me._view = helpers$1.extend({}, model);
  2958. me._start = null;
  2959. return me;
  2960. }
  2961. if (!view) {
  2962. view = me._view = {};
  2963. }
  2964. if (!start) {
  2965. start = me._start = {};
  2966. }
  2967. interpolate(start, view, model, ease);
  2968. return me;
  2969. },
  2970. tooltipPosition: function () {
  2971. return {
  2972. x: this._model.x,
  2973. y: this._model.y
  2974. };
  2975. },
  2976. hasValue: function () {
  2977. return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
  2978. }
  2979. });
  2980. Element.extend = helpers$1.inherits;
  2981. var core_element = Element;
  2982. var exports$3 = core_element.extend({
  2983. chart: null, // the animation associated chart instance
  2984. currentStep: 0, // the current animation step
  2985. numSteps: 60, // default number of steps
  2986. easing: '', // the easing to use for this animation
  2987. render: null, // render function used by the animation service
  2988. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  2989. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  2990. });
  2991. var core_animation = exports$3;
  2992. // DEPRECATIONS
  2993. /**
  2994. * Provided for backward compatibility, use Chart.Animation instead
  2995. * @prop Chart.Animation#animationObject
  2996. * @deprecated since version 2.6.0
  2997. * @todo remove at version 3
  2998. */
  2999. Object.defineProperty(exports$3.prototype, 'animationObject', {
  3000. get: function () {
  3001. return this;
  3002. }
  3003. });
  3004. /**
  3005. * Provided for backward compatibility, use Chart.Animation#chart instead
  3006. * @prop Chart.Animation#chartInstance
  3007. * @deprecated since version 2.6.0
  3008. * @todo remove at version 3
  3009. */
  3010. Object.defineProperty(exports$3.prototype, 'chartInstance', {
  3011. get: function () {
  3012. return this.chart;
  3013. },
  3014. set: function (value) {
  3015. this.chart = value;
  3016. }
  3017. });
  3018. core_defaults._set('global', {
  3019. animation: {
  3020. duration: 1000,
  3021. easing: 'easeOutQuart',
  3022. onProgress: helpers$1.noop,
  3023. onComplete: helpers$1.noop
  3024. }
  3025. });
  3026. var core_animations = {
  3027. animations: [],
  3028. request: null,
  3029. /**
  3030. * @param {Chart} chart - The chart to animate.
  3031. * @param {Chart.Animation} animation - The animation that we will animate.
  3032. * @param {number} duration - The animation duration in ms.
  3033. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  3034. */
  3035. addAnimation: function (chart, animation, duration, lazy) {
  3036. var animations = this.animations;
  3037. var i, ilen;
  3038. animation.chart = chart;
  3039. animation.startTime = Date.now();
  3040. animation.duration = duration;
  3041. if (!lazy) {
  3042. chart.animating = true;
  3043. }
  3044. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  3045. if (animations[i].chart === chart) {
  3046. animations[i] = animation;
  3047. return;
  3048. }
  3049. }
  3050. animations.push(animation);
  3051. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  3052. if (animations.length === 1) {
  3053. this.requestAnimationFrame();
  3054. }
  3055. },
  3056. cancelAnimation: function (chart) {
  3057. var index = helpers$1.findIndex(this.animations, function (animation) {
  3058. return animation.chart === chart;
  3059. });
  3060. if (index !== -1) {
  3061. this.animations.splice(index, 1);
  3062. chart.animating = false;
  3063. }
  3064. },
  3065. requestAnimationFrame: function () {
  3066. var me = this;
  3067. if (me.request === null) {
  3068. // Skip animation frame requests until the active one is executed.
  3069. // This can happen when processing mouse events, e.g. 'mousemove'
  3070. // and 'mouseout' events will trigger multiple renders.
  3071. me.request = helpers$1.requestAnimFrame.call(window, function () {
  3072. me.request = null;
  3073. me.startDigest();
  3074. });
  3075. }
  3076. },
  3077. /**
  3078. * @private
  3079. */
  3080. startDigest: function () {
  3081. var me = this;
  3082. me.advance();
  3083. // Do we have more stuff to animate?
  3084. if (me.animations.length > 0) {
  3085. me.requestAnimationFrame();
  3086. }
  3087. },
  3088. /**
  3089. * @private
  3090. */
  3091. advance: function () {
  3092. var animations = this.animations;
  3093. var animation, chart, numSteps, nextStep;
  3094. var i = 0;
  3095. // 1 animation per chart, so we are looping charts here
  3096. while (i < animations.length) {
  3097. animation = animations[i];
  3098. chart = animation.chart;
  3099. numSteps = animation.numSteps;
  3100. // Make sure that currentStep starts at 1
  3101. // https://github.com/chartjs/Chart.js/issues/6104
  3102. nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
  3103. animation.currentStep = Math.min(nextStep, numSteps);
  3104. helpers$1.callback(animation.render, [chart, animation], chart);
  3105. helpers$1.callback(animation.onAnimationProgress, [animation], chart);
  3106. if (animation.currentStep >= numSteps) {
  3107. helpers$1.callback(animation.onAnimationComplete, [animation], chart);
  3108. chart.animating = false;
  3109. animations.splice(i, 1);
  3110. } else {
  3111. ++i;
  3112. }
  3113. }
  3114. }
  3115. };
  3116. var resolve = helpers$1.options.resolve;
  3117. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  3118. /**
  3119. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  3120. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  3121. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  3122. */
  3123. function listenArrayEvents(array, listener) {
  3124. if (array._chartjs) {
  3125. array._chartjs.listeners.push(listener);
  3126. return;
  3127. }
  3128. Object.defineProperty(array, '_chartjs', {
  3129. configurable: true,
  3130. enumerable: false,
  3131. value: {
  3132. listeners: [listener]
  3133. }
  3134. });
  3135. arrayEvents.forEach(function (key) {
  3136. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  3137. var base = array[key];
  3138. Object.defineProperty(array, key, {
  3139. configurable: true,
  3140. enumerable: false,
  3141. value: function () {
  3142. var args = Array.prototype.slice.call(arguments);
  3143. var res = base.apply(this, args);
  3144. helpers$1.each(array._chartjs.listeners, function (object) {
  3145. if (typeof object[method] === 'function') {
  3146. object[method].apply(object, args);
  3147. }
  3148. });
  3149. return res;
  3150. }
  3151. });
  3152. });
  3153. }
  3154. /**
  3155. * Removes the given array event listener and cleanup extra attached properties (such as
  3156. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  3157. */
  3158. function unlistenArrayEvents(array, listener) {
  3159. var stub = array._chartjs;
  3160. if (!stub) {
  3161. return;
  3162. }
  3163. var listeners = stub.listeners;
  3164. var index = listeners.indexOf(listener);
  3165. if (index !== -1) {
  3166. listeners.splice(index, 1);
  3167. }
  3168. if (listeners.length > 0) {
  3169. return;
  3170. }
  3171. arrayEvents.forEach(function (key) {
  3172. delete array[key];
  3173. });
  3174. delete array._chartjs;
  3175. }
  3176. // Base class for all dataset controllers (line, bar, etc)
  3177. var DatasetController = function (chart, datasetIndex) {
  3178. this.initialize(chart, datasetIndex);
  3179. };
  3180. helpers$1.extend(DatasetController.prototype, {
  3181. /**
  3182. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  3183. * @type {Chart.core.element}
  3184. */
  3185. datasetElementType: null,
  3186. /**
  3187. * Element type used to generate a meta data (e.g. Chart.element.Point).
  3188. * @type {Chart.core.element}
  3189. */
  3190. dataElementType: null,
  3191. /**
  3192. * Dataset element option keys to be resolved in _resolveDatasetElementOptions.
  3193. * A derived controller may override this to resolve controller-specific options.
  3194. * The keys defined here are for backward compatibility for legend styles.
  3195. * @private
  3196. */
  3197. _datasetElementOptions: [
  3198. 'backgroundColor',
  3199. 'borderCapStyle',
  3200. 'borderColor',
  3201. 'borderDash',
  3202. 'borderDashOffset',
  3203. 'borderJoinStyle',
  3204. 'borderWidth'
  3205. ],
  3206. /**
  3207. * Data element option keys to be resolved in _resolveDataElementOptions.
  3208. * A derived controller may override this to resolve controller-specific options.
  3209. * The keys defined here are for backward compatibility for legend styles.
  3210. * @private
  3211. */
  3212. _dataElementOptions: [
  3213. 'backgroundColor',
  3214. 'borderColor',
  3215. 'borderWidth',
  3216. 'pointStyle'
  3217. ],
  3218. initialize: function (chart, datasetIndex) {
  3219. var me = this;
  3220. me.chart = chart;
  3221. me.index = datasetIndex;
  3222. me.linkScales();
  3223. me.addElements();
  3224. me._type = me.getMeta().type;
  3225. },
  3226. updateIndex: function (datasetIndex) {
  3227. this.index = datasetIndex;
  3228. },
  3229. linkScales: function () {
  3230. var me = this;
  3231. var meta = me.getMeta();
  3232. var chart = me.chart;
  3233. var scales = chart.scales;
  3234. var dataset = me.getDataset();
  3235. var scalesOpts = chart.options.scales;
  3236. if (meta.xAxisID === null || !(meta.xAxisID in scales) || dataset.xAxisID) {
  3237. meta.xAxisID = dataset.xAxisID || scalesOpts.xAxes[0].id;
  3238. }
  3239. if (meta.yAxisID === null || !(meta.yAxisID in scales) || dataset.yAxisID) {
  3240. meta.yAxisID = dataset.yAxisID || scalesOpts.yAxes[0].id;
  3241. }
  3242. },
  3243. getDataset: function () {
  3244. return this.chart.data.datasets[this.index];
  3245. },
  3246. getMeta: function () {
  3247. return this.chart.getDatasetMeta(this.index);
  3248. },
  3249. getScaleForId: function (scaleID) {
  3250. return this.chart.scales[scaleID];
  3251. },
  3252. /**
  3253. * @private
  3254. */
  3255. _getValueScaleId: function () {
  3256. return this.getMeta().yAxisID;
  3257. },
  3258. /**
  3259. * @private
  3260. */
  3261. _getIndexScaleId: function () {
  3262. return this.getMeta().xAxisID;
  3263. },
  3264. /**
  3265. * @private
  3266. */
  3267. _getValueScale: function () {
  3268. return this.getScaleForId(this._getValueScaleId());
  3269. },
  3270. /**
  3271. * @private
  3272. */
  3273. _getIndexScale: function () {
  3274. return this.getScaleForId(this._getIndexScaleId());
  3275. },
  3276. reset: function () {
  3277. this._update(true);
  3278. },
  3279. /**
  3280. * @private
  3281. */
  3282. destroy: function () {
  3283. if (this._data) {
  3284. unlistenArrayEvents(this._data, this);
  3285. }
  3286. },
  3287. createMetaDataset: function () {
  3288. var me = this;
  3289. var type = me.datasetElementType;
  3290. return type && new type({
  3291. _chart: me.chart,
  3292. _datasetIndex: me.index
  3293. });
  3294. },
  3295. createMetaData: function (index) {
  3296. var me = this;
  3297. var type = me.dataElementType;
  3298. return type && new type({
  3299. _chart: me.chart,
  3300. _datasetIndex: me.index,
  3301. _index: index
  3302. });
  3303. },
  3304. addElements: function () {
  3305. var me = this;
  3306. var meta = me.getMeta();
  3307. var data = me.getDataset().data || [];
  3308. var metaData = meta.data;
  3309. var i, ilen;
  3310. for (i = 0, ilen = data.length; i < ilen; ++i) {
  3311. metaData[i] = metaData[i] || me.createMetaData(i);
  3312. }
  3313. meta.dataset = meta.dataset || me.createMetaDataset();
  3314. },
  3315. addElementAndReset: function (index) {
  3316. var element = this.createMetaData(index);
  3317. this.getMeta().data.splice(index, 0, element);
  3318. this.updateElement(element, index, true);
  3319. },
  3320. buildOrUpdateElements: function () {
  3321. var me = this;
  3322. var dataset = me.getDataset();
  3323. var data = dataset.data || (dataset.data = []);
  3324. // In order to correctly handle data addition/deletion animation (an thus simulate
  3325. // real-time charts), we need to monitor these data modifications and synchronize
  3326. // the internal meta data accordingly.
  3327. if (me._data !== data) {
  3328. if (me._data) {
  3329. // This case happens when the user replaced the data array instance.
  3330. unlistenArrayEvents(me._data, me);
  3331. }
  3332. if (data && Object.isExtensible(data)) {
  3333. listenArrayEvents(data, me);
  3334. }
  3335. me._data = data;
  3336. }
  3337. // Re-sync meta data in case the user replaced the data array or if we missed
  3338. // any updates and so make sure that we handle number of datapoints changing.
  3339. me.resyncElements();
  3340. },
  3341. /**
  3342. * Returns the merged user-supplied and default dataset-level options
  3343. * @private
  3344. */
  3345. _configure: function () {
  3346. var me = this;
  3347. me._config = helpers$1.merge(Object.create(null), [
  3348. me.chart.options.datasets[me._type],
  3349. me.getDataset(),
  3350. ], {
  3351. merger: function (key, target, source) {
  3352. if (key !== '_meta' && key !== 'data') {
  3353. helpers$1._merger(key, target, source);
  3354. }
  3355. }
  3356. });
  3357. },
  3358. _update: function (reset) {
  3359. var me = this;
  3360. me._configure();
  3361. me._cachedDataOpts = null;
  3362. me.update(reset);
  3363. },
  3364. update: helpers$1.noop,
  3365. transition: function (easingValue) {
  3366. var meta = this.getMeta();
  3367. var elements = meta.data || [];
  3368. var ilen = elements.length;
  3369. var i = 0;
  3370. for (; i < ilen; ++i) {
  3371. elements[i].transition(easingValue);
  3372. }
  3373. if (meta.dataset) {
  3374. meta.dataset.transition(easingValue);
  3375. }
  3376. },
  3377. draw: function () {
  3378. var meta = this.getMeta();
  3379. var elements = meta.data || [];
  3380. var ilen = elements.length;
  3381. var i = 0;
  3382. if (meta.dataset) {
  3383. meta.dataset.draw();
  3384. }
  3385. for (; i < ilen; ++i) {
  3386. elements[i].draw();
  3387. }
  3388. },
  3389. /**
  3390. * Returns a set of predefined style properties that should be used to represent the dataset
  3391. * or the data if the index is specified
  3392. * @param {number} index - data index
  3393. * @return {IStyleInterface} style object
  3394. */
  3395. getStyle: function (index) {
  3396. var me = this;
  3397. var meta = me.getMeta();
  3398. var dataset = meta.dataset;
  3399. var style;
  3400. me._configure();
  3401. if (dataset && index === undefined) {
  3402. style = me._resolveDatasetElementOptions(dataset || {});
  3403. } else {
  3404. index = index || 0;
  3405. style = me._resolveDataElementOptions(meta.data[index] || {}, index);
  3406. }
  3407. if (style.fill === false || style.fill === null) {
  3408. style.backgroundColor = style.borderColor;
  3409. }
  3410. return style;
  3411. },
  3412. /**
  3413. * @private
  3414. */
  3415. _resolveDatasetElementOptions: function (element, hover) {
  3416. var me = this;
  3417. var chart = me.chart;
  3418. var datasetOpts = me._config;
  3419. var custom = element.custom || {};
  3420. var options = chart.options.elements[me.datasetElementType.prototype._type] || {};
  3421. var elementOptions = me._datasetElementOptions;
  3422. var values = {};
  3423. var i, ilen, key, readKey;
  3424. // Scriptable options
  3425. var context = {
  3426. chart: chart,
  3427. dataset: me.getDataset(),
  3428. datasetIndex: me.index,
  3429. hover: hover
  3430. };
  3431. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3432. key = elementOptions[i];
  3433. readKey = hover ? 'hover' + key.charAt(0).toUpperCase() + key.slice(1) : key;
  3434. values[key] = resolve([
  3435. custom[readKey],
  3436. datasetOpts[readKey],
  3437. options[readKey]
  3438. ], context);
  3439. }
  3440. return values;
  3441. },
  3442. /**
  3443. * @private
  3444. */
  3445. _resolveDataElementOptions: function (element, index) {
  3446. var me = this;
  3447. var custom = element && element.custom;
  3448. var cached = me._cachedDataOpts;
  3449. if (cached && !custom) {
  3450. return cached;
  3451. }
  3452. var chart = me.chart;
  3453. var datasetOpts = me._config;
  3454. var options = chart.options.elements[me.dataElementType.prototype._type] || {};
  3455. var elementOptions = me._dataElementOptions;
  3456. var values = {};
  3457. // Scriptable options
  3458. var context = {
  3459. chart: chart,
  3460. dataIndex: index,
  3461. dataset: me.getDataset(),
  3462. datasetIndex: me.index
  3463. };
  3464. // `resolve` sets cacheable to `false` if any option is indexed or scripted
  3465. var info = {cacheable: !custom};
  3466. var keys, i, ilen, key;
  3467. custom = custom || {};
  3468. if (helpers$1.isArray(elementOptions)) {
  3469. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3470. key = elementOptions[i];
  3471. values[key] = resolve([
  3472. custom[key],
  3473. datasetOpts[key],
  3474. options[key]
  3475. ], context, index, info);
  3476. }
  3477. } else {
  3478. keys = Object.keys(elementOptions);
  3479. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3480. key = keys[i];
  3481. values[key] = resolve([
  3482. custom[key],
  3483. datasetOpts[elementOptions[key]],
  3484. datasetOpts[key],
  3485. options[key]
  3486. ], context, index, info);
  3487. }
  3488. }
  3489. if (info.cacheable) {
  3490. me._cachedDataOpts = Object.freeze(values);
  3491. }
  3492. return values;
  3493. },
  3494. removeHoverStyle: function (element) {
  3495. helpers$1.merge(element._model, element.$previousStyle || {});
  3496. delete element.$previousStyle;
  3497. },
  3498. setHoverStyle: function (element) {
  3499. var dataset = this.chart.data.datasets[element._datasetIndex];
  3500. var index = element._index;
  3501. var custom = element.custom || {};
  3502. var model = element._model;
  3503. var getHoverColor = helpers$1.getHoverColor;
  3504. element.$previousStyle = {
  3505. backgroundColor: model.backgroundColor,
  3506. borderColor: model.borderColor,
  3507. borderWidth: model.borderWidth
  3508. };
  3509. model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
  3510. model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
  3511. model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
  3512. },
  3513. /**
  3514. * @private
  3515. */
  3516. _removeDatasetHoverStyle: function () {
  3517. var element = this.getMeta().dataset;
  3518. if (element) {
  3519. this.removeHoverStyle(element);
  3520. }
  3521. },
  3522. /**
  3523. * @private
  3524. */
  3525. _setDatasetHoverStyle: function () {
  3526. var element = this.getMeta().dataset;
  3527. var prev = {};
  3528. var i, ilen, key, keys, hoverOptions, model;
  3529. if (!element) {
  3530. return;
  3531. }
  3532. model = element._model;
  3533. hoverOptions = this._resolveDatasetElementOptions(element, true);
  3534. keys = Object.keys(hoverOptions);
  3535. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3536. key = keys[i];
  3537. prev[key] = model[key];
  3538. model[key] = hoverOptions[key];
  3539. }
  3540. element.$previousStyle = prev;
  3541. },
  3542. /**
  3543. * @private
  3544. */
  3545. resyncElements: function () {
  3546. var me = this;
  3547. var meta = me.getMeta();
  3548. var data = me.getDataset().data;
  3549. var numMeta = meta.data.length;
  3550. var numData = data.length;
  3551. if (numData < numMeta) {
  3552. meta.data.splice(numData, numMeta - numData);
  3553. } else if (numData > numMeta) {
  3554. me.insertElements(numMeta, numData - numMeta);
  3555. }
  3556. },
  3557. /**
  3558. * @private
  3559. */
  3560. insertElements: function (start, count) {
  3561. for (var i = 0; i < count; ++i) {
  3562. this.addElementAndReset(start + i);
  3563. }
  3564. },
  3565. /**
  3566. * @private
  3567. */
  3568. onDataPush: function () {
  3569. var count = arguments.length;
  3570. this.insertElements(this.getDataset().data.length - count, count);
  3571. },
  3572. /**
  3573. * @private
  3574. */
  3575. onDataPop: function () {
  3576. this.getMeta().data.pop();
  3577. },
  3578. /**
  3579. * @private
  3580. */
  3581. onDataShift: function () {
  3582. this.getMeta().data.shift();
  3583. },
  3584. /**
  3585. * @private
  3586. */
  3587. onDataSplice: function (start, count) {
  3588. this.getMeta().data.splice(start, count);
  3589. this.insertElements(start, arguments.length - 2);
  3590. },
  3591. /**
  3592. * @private
  3593. */
  3594. onDataUnshift: function () {
  3595. this.insertElements(0, arguments.length);
  3596. }
  3597. });
  3598. DatasetController.extend = helpers$1.inherits;
  3599. var core_datasetController = DatasetController;
  3600. var TAU = Math.PI * 2;
  3601. core_defaults._set('global', {
  3602. elements: {
  3603. arc: {
  3604. backgroundColor: core_defaults.global.defaultColor,
  3605. borderColor: '#fff',
  3606. borderWidth: 2,
  3607. borderAlign: 'center'
  3608. }
  3609. }
  3610. });
  3611. function clipArc(ctx, arc) {
  3612. var startAngle = arc.startAngle;
  3613. var endAngle = arc.endAngle;
  3614. var pixelMargin = arc.pixelMargin;
  3615. var angleMargin = pixelMargin / arc.outerRadius;
  3616. var x = arc.x;
  3617. var y = arc.y;
  3618. // Draw an inner border by cliping the arc and drawing a double-width border
  3619. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  3620. ctx.beginPath();
  3621. ctx.arc(x, y, arc.outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  3622. if (arc.innerRadius > pixelMargin) {
  3623. angleMargin = pixelMargin / arc.innerRadius;
  3624. ctx.arc(x, y, arc.innerRadius - pixelMargin, endAngle + angleMargin, startAngle - angleMargin, true);
  3625. } else {
  3626. ctx.arc(x, y, pixelMargin, endAngle + Math.PI / 2, startAngle - Math.PI / 2);
  3627. }
  3628. ctx.closePath();
  3629. ctx.clip();
  3630. }
  3631. function drawFullCircleBorders(ctx, vm, arc, inner) {
  3632. var endAngle = arc.endAngle;
  3633. var i;
  3634. if (inner) {
  3635. arc.endAngle = arc.startAngle + TAU;
  3636. clipArc(ctx, arc);
  3637. arc.endAngle = endAngle;
  3638. if (arc.endAngle === arc.startAngle && arc.fullCircles) {
  3639. arc.endAngle += TAU;
  3640. arc.fullCircles--;
  3641. }
  3642. }
  3643. ctx.beginPath();
  3644. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.startAngle + TAU, arc.startAngle, true);
  3645. for (i = 0; i < arc.fullCircles; ++i) {
  3646. ctx.stroke();
  3647. }
  3648. ctx.beginPath();
  3649. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.startAngle + TAU);
  3650. for (i = 0; i < arc.fullCircles; ++i) {
  3651. ctx.stroke();
  3652. }
  3653. }
  3654. function drawBorder(ctx, vm, arc) {
  3655. var inner = vm.borderAlign === 'inner';
  3656. if (inner) {
  3657. ctx.lineWidth = vm.borderWidth * 2;
  3658. ctx.lineJoin = 'round';
  3659. } else {
  3660. ctx.lineWidth = vm.borderWidth;
  3661. ctx.lineJoin = 'bevel';
  3662. }
  3663. if (arc.fullCircles) {
  3664. drawFullCircleBorders(ctx, vm, arc, inner);
  3665. }
  3666. if (inner) {
  3667. clipArc(ctx, arc);
  3668. }
  3669. ctx.beginPath();
  3670. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.endAngle);
  3671. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3672. ctx.closePath();
  3673. ctx.stroke();
  3674. }
  3675. var element_arc = core_element.extend({
  3676. _type: 'arc',
  3677. inLabelRange: function (mouseX) {
  3678. var vm = this._view;
  3679. if (vm) {
  3680. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  3681. }
  3682. return false;
  3683. },
  3684. inRange: function (chartX, chartY) {
  3685. var vm = this._view;
  3686. if (vm) {
  3687. var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
  3688. var angle = pointRelativePosition.angle;
  3689. var distance = pointRelativePosition.distance;
  3690. // Sanitise angle range
  3691. var startAngle = vm.startAngle;
  3692. var endAngle = vm.endAngle;
  3693. while (endAngle < startAngle) {
  3694. endAngle += TAU;
  3695. }
  3696. while (angle > endAngle) {
  3697. angle -= TAU;
  3698. }
  3699. while (angle < startAngle) {
  3700. angle += TAU;
  3701. }
  3702. // Check if within the range of the open/close angle
  3703. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  3704. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  3705. return (betweenAngles && withinRadius);
  3706. }
  3707. return false;
  3708. },
  3709. getCenterPoint: function () {
  3710. var vm = this._view;
  3711. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  3712. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  3713. return {
  3714. x: vm.x + Math.cos(halfAngle) * halfRadius,
  3715. y: vm.y + Math.sin(halfAngle) * halfRadius
  3716. };
  3717. },
  3718. getArea: function () {
  3719. var vm = this._view;
  3720. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  3721. },
  3722. tooltipPosition: function () {
  3723. var vm = this._view;
  3724. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  3725. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  3726. return {
  3727. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  3728. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  3729. };
  3730. },
  3731. draw: function () {
  3732. var ctx = this._chart.ctx;
  3733. var vm = this._view;
  3734. var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
  3735. var arc = {
  3736. x: vm.x,
  3737. y: vm.y,
  3738. innerRadius: vm.innerRadius,
  3739. outerRadius: Math.max(vm.outerRadius - pixelMargin, 0),
  3740. pixelMargin: pixelMargin,
  3741. startAngle: vm.startAngle,
  3742. endAngle: vm.endAngle,
  3743. fullCircles: Math.floor(vm.circumference / TAU)
  3744. };
  3745. var i;
  3746. ctx.save();
  3747. ctx.fillStyle = vm.backgroundColor;
  3748. ctx.strokeStyle = vm.borderColor;
  3749. if (arc.fullCircles) {
  3750. arc.endAngle = arc.startAngle + TAU;
  3751. ctx.beginPath();
  3752. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3753. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3754. ctx.closePath();
  3755. for (i = 0; i < arc.fullCircles; ++i) {
  3756. ctx.fill();
  3757. }
  3758. arc.endAngle = arc.startAngle + vm.circumference % TAU;
  3759. }
  3760. ctx.beginPath();
  3761. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3762. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3763. ctx.closePath();
  3764. ctx.fill();
  3765. if (vm.borderWidth) {
  3766. drawBorder(ctx, vm, arc);
  3767. }
  3768. ctx.restore();
  3769. }
  3770. });
  3771. var valueOrDefault$1 = helpers$1.valueOrDefault;
  3772. var defaultColor = core_defaults.global.defaultColor;
  3773. core_defaults._set('global', {
  3774. elements: {
  3775. line: {
  3776. tension: 0.4,
  3777. backgroundColor: defaultColor,
  3778. borderWidth: 3,
  3779. borderColor: defaultColor,
  3780. borderCapStyle: 'butt',
  3781. borderDash: [],
  3782. borderDashOffset: 0.0,
  3783. borderJoinStyle: 'miter',
  3784. capBezierPoints: true,
  3785. fill: true, // do we fill in the area between the line and its base axis
  3786. }
  3787. }
  3788. });
  3789. var element_line = core_element.extend({
  3790. _type: 'line',
  3791. draw: function () {
  3792. var me = this;
  3793. var vm = me._view;
  3794. var ctx = me._chart.ctx;
  3795. var spanGaps = vm.spanGaps;
  3796. var points = me._children.slice(); // clone array
  3797. var globalDefaults = core_defaults.global;
  3798. var globalOptionLineElements = globalDefaults.elements.line;
  3799. var lastDrawnIndex = -1;
  3800. var closePath = me._loop;
  3801. var index, previous, currentVM;
  3802. if (!points.length) {
  3803. return;
  3804. }
  3805. if (me._loop) {
  3806. for (index = 0; index < points.length; ++index) {
  3807. previous = helpers$1.previousItem(points, index);
  3808. // If the line has an open path, shift the point array
  3809. if (!points[index]._view.skip && previous._view.skip) {
  3810. points = points.slice(index).concat(points.slice(0, index));
  3811. closePath = spanGaps;
  3812. break;
  3813. }
  3814. }
  3815. // If the line has a close path, add the first point again
  3816. if (closePath) {
  3817. points.push(points[0]);
  3818. }
  3819. }
  3820. ctx.save();
  3821. // Stroke Line Options
  3822. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  3823. // IE 9 and 10 do not support line dash
  3824. if (ctx.setLineDash) {
  3825. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  3826. }
  3827. ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
  3828. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  3829. ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
  3830. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  3831. // Stroke Line
  3832. ctx.beginPath();
  3833. // First point moves to it's starting position no matter what
  3834. currentVM = points[0]._view;
  3835. if (!currentVM.skip) {
  3836. ctx.moveTo(currentVM.x, currentVM.y);
  3837. lastDrawnIndex = 0;
  3838. }
  3839. for (index = 1; index < points.length; ++index) {
  3840. currentVM = points[index]._view;
  3841. previous = lastDrawnIndex === -1 ? helpers$1.previousItem(points, index) : points[lastDrawnIndex];
  3842. if (!currentVM.skip) {
  3843. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  3844. // There was a gap and this is the first point after the gap
  3845. ctx.moveTo(currentVM.x, currentVM.y);
  3846. } else {
  3847. // Line to next point
  3848. helpers$1.canvas.lineTo(ctx, previous._view, currentVM);
  3849. }
  3850. lastDrawnIndex = index;
  3851. }
  3852. }
  3853. if (closePath) {
  3854. ctx.closePath();
  3855. }
  3856. ctx.stroke();
  3857. ctx.restore();
  3858. }
  3859. });
  3860. var valueOrDefault$2 = helpers$1.valueOrDefault;
  3861. var defaultColor$1 = core_defaults.global.defaultColor;
  3862. core_defaults._set('global', {
  3863. elements: {
  3864. point: {
  3865. radius: 3,
  3866. pointStyle: 'circle',
  3867. backgroundColor: defaultColor$1,
  3868. borderColor: defaultColor$1,
  3869. borderWidth: 1,
  3870. // Hover
  3871. hitRadius: 1,
  3872. hoverRadius: 4,
  3873. hoverBorderWidth: 1
  3874. }
  3875. }
  3876. });
  3877. function xRange(mouseX) {
  3878. var vm = this._view;
  3879. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  3880. }
  3881. function yRange(mouseY) {
  3882. var vm = this._view;
  3883. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  3884. }
  3885. var element_point = core_element.extend({
  3886. _type: 'point',
  3887. inRange: function (mouseX, mouseY) {
  3888. var vm = this._view;
  3889. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  3890. },
  3891. inLabelRange: xRange,
  3892. inXRange: xRange,
  3893. inYRange: yRange,
  3894. getCenterPoint: function () {
  3895. var vm = this._view;
  3896. return {
  3897. x: vm.x,
  3898. y: vm.y
  3899. };
  3900. },
  3901. getArea: function () {
  3902. return Math.PI * Math.pow(this._view.radius, 2);
  3903. },
  3904. tooltipPosition: function () {
  3905. var vm = this._view;
  3906. return {
  3907. x: vm.x,
  3908. y: vm.y,
  3909. padding: vm.radius + vm.borderWidth
  3910. };
  3911. },
  3912. draw: function (chartArea) {
  3913. var vm = this._view;
  3914. var ctx = this._chart.ctx;
  3915. var pointStyle = vm.pointStyle;
  3916. var rotation = vm.rotation;
  3917. var radius = vm.radius;
  3918. var x = vm.x;
  3919. var y = vm.y;
  3920. var globalDefaults = core_defaults.global;
  3921. var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
  3922. if (vm.skip) {
  3923. return;
  3924. }
  3925. // Clipping for Points.
  3926. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
  3927. ctx.strokeStyle = vm.borderColor || defaultColor;
  3928. ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
  3929. ctx.fillStyle = vm.backgroundColor || defaultColor;
  3930. helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  3931. }
  3932. }
  3933. });
  3934. var defaultColor$2 = core_defaults.global.defaultColor;
  3935. core_defaults._set('global', {
  3936. elements: {
  3937. rectangle: {
  3938. backgroundColor: defaultColor$2,
  3939. borderColor: defaultColor$2,
  3940. borderSkipped: 'bottom',
  3941. borderWidth: 0
  3942. }
  3943. }
  3944. });
  3945. function isVertical(vm) {
  3946. return vm && vm.width !== undefined;
  3947. }
  3948. /**
  3949. * Helper function to get the bounds of the bar regardless of the orientation
  3950. * @param bar {Chart.Element.Rectangle} the bar
  3951. * @return {Bounds} bounds of the bar
  3952. * @private
  3953. */
  3954. function getBarBounds(vm) {
  3955. var x1, x2, y1, y2, half;
  3956. if (isVertical(vm)) {
  3957. half = vm.width / 2;
  3958. x1 = vm.x - half;
  3959. x2 = vm.x + half;
  3960. y1 = Math.min(vm.y, vm.base);
  3961. y2 = Math.max(vm.y, vm.base);
  3962. } else {
  3963. half = vm.height / 2;
  3964. x1 = Math.min(vm.x, vm.base);
  3965. x2 = Math.max(vm.x, vm.base);
  3966. y1 = vm.y - half;
  3967. y2 = vm.y + half;
  3968. }
  3969. return {
  3970. left: x1,
  3971. top: y1,
  3972. right: x2,
  3973. bottom: y2
  3974. };
  3975. }
  3976. function swap(orig, v1, v2) {
  3977. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  3978. }
  3979. function parseBorderSkipped(vm) {
  3980. var edge = vm.borderSkipped;
  3981. var res = {};
  3982. if (!edge) {
  3983. return res;
  3984. }
  3985. if (vm.horizontal) {
  3986. if (vm.base > vm.x) {
  3987. edge = swap(edge, 'left', 'right');
  3988. }
  3989. } else if (vm.base < vm.y) {
  3990. edge = swap(edge, 'bottom', 'top');
  3991. }
  3992. res[edge] = true;
  3993. return res;
  3994. }
  3995. function parseBorderWidth(vm, maxW, maxH) {
  3996. var value = vm.borderWidth;
  3997. var skip = parseBorderSkipped(vm);
  3998. var t, r, b, l;
  3999. if (helpers$1.isObject(value)) {
  4000. t = +value.top || 0;
  4001. r = +value.right || 0;
  4002. b = +value.bottom || 0;
  4003. l = +value.left || 0;
  4004. } else {
  4005. t = r = b = l = +value || 0;
  4006. }
  4007. return {
  4008. t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
  4009. r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
  4010. b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
  4011. l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
  4012. };
  4013. }
  4014. function boundingRects(vm) {
  4015. var bounds = getBarBounds(vm);
  4016. var width = bounds.right - bounds.left;
  4017. var height = bounds.bottom - bounds.top;
  4018. var border = parseBorderWidth(vm, width / 2, height / 2);
  4019. return {
  4020. outer: {
  4021. x: bounds.left,
  4022. y: bounds.top,
  4023. w: width,
  4024. h: height
  4025. },
  4026. inner: {
  4027. x: bounds.left + border.l,
  4028. y: bounds.top + border.t,
  4029. w: width - border.l - border.r,
  4030. h: height - border.t - border.b
  4031. }
  4032. };
  4033. }
  4034. function inRange(vm, x, y) {
  4035. var skipX = x === null;
  4036. var skipY = y === null;
  4037. var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
  4038. return bounds
  4039. && (skipX || x >= bounds.left && x <= bounds.right)
  4040. && (skipY || y >= bounds.top && y <= bounds.bottom);
  4041. }
  4042. var element_rectangle = core_element.extend({
  4043. _type: 'rectangle',
  4044. draw: function () {
  4045. var ctx = this._chart.ctx;
  4046. var vm = this._view;
  4047. var rects = boundingRects(vm);
  4048. var outer = rects.outer;
  4049. var inner = rects.inner;
  4050. ctx.fillStyle = vm.backgroundColor;
  4051. ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
  4052. if (outer.w === inner.w && outer.h === inner.h) {
  4053. return;
  4054. }
  4055. ctx.save();
  4056. ctx.beginPath();
  4057. ctx.rect(outer.x, outer.y, outer.w, outer.h);
  4058. ctx.clip();
  4059. ctx.fillStyle = vm.borderColor;
  4060. ctx.rect(inner.x, inner.y, inner.w, inner.h);
  4061. ctx.fill('evenodd');
  4062. ctx.restore();
  4063. },
  4064. height: function () {
  4065. var vm = this._view;
  4066. return vm.base - vm.y;
  4067. },
  4068. inRange: function (mouseX, mouseY) {
  4069. return inRange(this._view, mouseX, mouseY);
  4070. },
  4071. inLabelRange: function (mouseX, mouseY) {
  4072. var vm = this._view;
  4073. return isVertical(vm)
  4074. ? inRange(vm, mouseX, null)
  4075. : inRange(vm, null, mouseY);
  4076. },
  4077. inXRange: function (mouseX) {
  4078. return inRange(this._view, mouseX, null);
  4079. },
  4080. inYRange: function (mouseY) {
  4081. return inRange(this._view, null, mouseY);
  4082. },
  4083. getCenterPoint: function () {
  4084. var vm = this._view;
  4085. var x, y;
  4086. if (isVertical(vm)) {
  4087. x = vm.x;
  4088. y = (vm.y + vm.base) / 2;
  4089. } else {
  4090. x = (vm.x + vm.base) / 2;
  4091. y = vm.y;
  4092. }
  4093. return {x: x, y: y};
  4094. },
  4095. getArea: function () {
  4096. var vm = this._view;
  4097. return isVertical(vm)
  4098. ? vm.width * Math.abs(vm.y - vm.base)
  4099. : vm.height * Math.abs(vm.x - vm.base);
  4100. },
  4101. tooltipPosition: function () {
  4102. var vm = this._view;
  4103. return {
  4104. x: vm.x,
  4105. y: vm.y
  4106. };
  4107. }
  4108. });
  4109. var elements = {};
  4110. var Arc = element_arc;
  4111. var Line = element_line;
  4112. var Point = element_point;
  4113. var Rectangle = element_rectangle;
  4114. elements.Arc = Arc;
  4115. elements.Line = Line;
  4116. elements.Point = Point;
  4117. elements.Rectangle = Rectangle;
  4118. var deprecated = helpers$1._deprecated;
  4119. var valueOrDefault$3 = helpers$1.valueOrDefault;
  4120. core_defaults._set('bar', {
  4121. hover: {
  4122. mode: 'label'
  4123. },
  4124. scales: {
  4125. xAxes: [{
  4126. type: 'category',
  4127. offset: true,
  4128. gridLines: {
  4129. offsetGridLines: true
  4130. }
  4131. }],
  4132. yAxes: [{
  4133. type: 'linear'
  4134. }]
  4135. }
  4136. });
  4137. core_defaults._set('global', {
  4138. datasets: {
  4139. bar: {
  4140. categoryPercentage: 0.8,
  4141. barPercentage: 0.9
  4142. }
  4143. }
  4144. });
  4145. /**
  4146. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  4147. * @private
  4148. */
  4149. function computeMinSampleSize(scale, pixels) {
  4150. var min = scale._length;
  4151. var prev, curr, i, ilen;
  4152. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  4153. min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
  4154. }
  4155. for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) {
  4156. curr = scale.getPixelForTick(i);
  4157. min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;
  4158. prev = curr;
  4159. }
  4160. return min;
  4161. }
  4162. /**
  4163. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  4164. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  4165. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  4166. * @private
  4167. */
  4168. function computeFitCategoryTraits(index, ruler, options) {
  4169. var thickness = options.barThickness;
  4170. var count = ruler.stackCount;
  4171. var curr = ruler.pixels[index];
  4172. var min = helpers$1.isNullOrUndef(thickness)
  4173. ? computeMinSampleSize(ruler.scale, ruler.pixels)
  4174. : -1;
  4175. var size, ratio;
  4176. if (helpers$1.isNullOrUndef(thickness)) {
  4177. size = min * options.categoryPercentage;
  4178. ratio = options.barPercentage;
  4179. } else {
  4180. // When bar thickness is enforced, category and bar percentages are ignored.
  4181. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  4182. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  4183. size = thickness * count;
  4184. ratio = 1;
  4185. }
  4186. return {
  4187. chunk: size / count,
  4188. ratio: ratio,
  4189. start: curr - (size / 2)
  4190. };
  4191. }
  4192. /**
  4193. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  4194. * percentage options are 1), based on the previous and following categories. This mode
  4195. * generates bars with different widths when data are not evenly spaced.
  4196. * @private
  4197. */
  4198. function computeFlexCategoryTraits(index, ruler, options) {
  4199. var pixels = ruler.pixels;
  4200. var curr = pixels[index];
  4201. var prev = index > 0 ? pixels[index - 1] : null;
  4202. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  4203. var percent = options.categoryPercentage;
  4204. var start, size;
  4205. if (prev === null) {
  4206. // first data: its size is double based on the next point or,
  4207. // if it's also the last data, we use the scale size.
  4208. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  4209. }
  4210. if (next === null) {
  4211. // last data: its size is also double based on the previous point.
  4212. next = curr + curr - prev;
  4213. }
  4214. start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  4215. size = Math.abs(next - prev) / 2 * percent;
  4216. return {
  4217. chunk: size / ruler.stackCount,
  4218. ratio: options.barPercentage,
  4219. start: start
  4220. };
  4221. }
  4222. var controller_bar = core_datasetController.extend({
  4223. dataElementType: elements.Rectangle,
  4224. /**
  4225. * @private
  4226. */
  4227. _dataElementOptions: [
  4228. 'backgroundColor',
  4229. 'borderColor',
  4230. 'borderSkipped',
  4231. 'borderWidth',
  4232. 'barPercentage',
  4233. 'barThickness',
  4234. 'categoryPercentage',
  4235. 'maxBarThickness',
  4236. 'minBarLength'
  4237. ],
  4238. initialize: function () {
  4239. var me = this;
  4240. var meta, scaleOpts;
  4241. core_datasetController.prototype.initialize.apply(me, arguments);
  4242. meta = me.getMeta();
  4243. meta.stack = me.getDataset().stack;
  4244. meta.bar = true;
  4245. scaleOpts = me._getIndexScale().options;
  4246. deprecated('bar chart', scaleOpts.barPercentage, 'scales.[x/y]Axes.barPercentage', 'dataset.barPercentage');
  4247. deprecated('bar chart', scaleOpts.barThickness, 'scales.[x/y]Axes.barThickness', 'dataset.barThickness');
  4248. deprecated('bar chart', scaleOpts.categoryPercentage, 'scales.[x/y]Axes.categoryPercentage', 'dataset.categoryPercentage');
  4249. deprecated('bar chart', me._getValueScale().options.minBarLength, 'scales.[x/y]Axes.minBarLength', 'dataset.minBarLength');
  4250. deprecated('bar chart', scaleOpts.maxBarThickness, 'scales.[x/y]Axes.maxBarThickness', 'dataset.maxBarThickness');
  4251. },
  4252. update: function (reset) {
  4253. var me = this;
  4254. var rects = me.getMeta().data;
  4255. var i, ilen;
  4256. me._ruler = me.getRuler();
  4257. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  4258. me.updateElement(rects[i], i, reset);
  4259. }
  4260. },
  4261. updateElement: function (rectangle, index, reset) {
  4262. var me = this;
  4263. var meta = me.getMeta();
  4264. var dataset = me.getDataset();
  4265. var options = me._resolveDataElementOptions(rectangle, index);
  4266. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  4267. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  4268. rectangle._datasetIndex = me.index;
  4269. rectangle._index = index;
  4270. rectangle._model = {
  4271. backgroundColor: options.backgroundColor,
  4272. borderColor: options.borderColor,
  4273. borderSkipped: options.borderSkipped,
  4274. borderWidth: options.borderWidth,
  4275. datasetLabel: dataset.label,
  4276. label: me.chart.data.labels[index]
  4277. };
  4278. if (helpers$1.isArray(dataset.data[index])) {
  4279. rectangle._model.borderSkipped = null;
  4280. }
  4281. me._updateElementGeometry(rectangle, index, reset, options);
  4282. rectangle.pivot();
  4283. },
  4284. /**
  4285. * @private
  4286. */
  4287. _updateElementGeometry: function (rectangle, index, reset, options) {
  4288. var me = this;
  4289. var model = rectangle._model;
  4290. var vscale = me._getValueScale();
  4291. var base = vscale.getBasePixel();
  4292. var horizontal = vscale.isHorizontal();
  4293. var ruler = me._ruler || me.getRuler();
  4294. var vpixels = me.calculateBarValuePixels(me.index, index, options);
  4295. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler, options);
  4296. model.horizontal = horizontal;
  4297. model.base = reset ? base : vpixels.base;
  4298. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  4299. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  4300. model.height = horizontal ? ipixels.size : undefined;
  4301. model.width = horizontal ? undefined : ipixels.size;
  4302. },
  4303. /**
  4304. * Returns the stacks based on groups and bar visibility.
  4305. * @param {number} [last] - The dataset index
  4306. * @returns {string[]} The list of stack IDs
  4307. * @private
  4308. */
  4309. _getStacks: function (last) {
  4310. var me = this;
  4311. var scale = me._getIndexScale();
  4312. var metasets = scale._getMatchingVisibleMetas(me._type);
  4313. var stacked = scale.options.stacked;
  4314. var ilen = metasets.length;
  4315. var stacks = [];
  4316. var i, meta;
  4317. for (i = 0; i < ilen; ++i) {
  4318. meta = metasets[i];
  4319. // stacked | meta.stack
  4320. // | found | not found | undefined
  4321. // false | x | x | x
  4322. // true | | x |
  4323. // undefined | | x | x
  4324. if (stacked === false || stacks.indexOf(meta.stack) === -1 ||
  4325. (stacked === undefined && meta.stack === undefined)) {
  4326. stacks.push(meta.stack);
  4327. }
  4328. if (meta.index === last) {
  4329. break;
  4330. }
  4331. }
  4332. return stacks;
  4333. },
  4334. /**
  4335. * Returns the effective number of stacks based on groups and bar visibility.
  4336. * @private
  4337. */
  4338. getStackCount: function () {
  4339. return this._getStacks().length;
  4340. },
  4341. /**
  4342. * Returns the stack index for the given dataset based on groups and bar visibility.
  4343. * @param {number} [datasetIndex] - The dataset index
  4344. * @param {string} [name] - The stack name to find
  4345. * @returns {number} The stack index
  4346. * @private
  4347. */
  4348. getStackIndex: function (datasetIndex, name) {
  4349. var stacks = this._getStacks(datasetIndex);
  4350. var index = (name !== undefined)
  4351. ? stacks.indexOf(name)
  4352. : -1; // indexOf returns -1 if element is not present
  4353. return (index === -1)
  4354. ? stacks.length - 1
  4355. : index;
  4356. },
  4357. /**
  4358. * @private
  4359. */
  4360. getRuler: function () {
  4361. var me = this;
  4362. var scale = me._getIndexScale();
  4363. var pixels = [];
  4364. var i, ilen;
  4365. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  4366. pixels.push(scale.getPixelForValue(null, i, me.index));
  4367. }
  4368. return {
  4369. pixels: pixels,
  4370. start: scale._startPixel,
  4371. end: scale._endPixel,
  4372. stackCount: me.getStackCount(),
  4373. scale: scale
  4374. };
  4375. },
  4376. /**
  4377. * Note: pixel values are not clamped to the scale area.
  4378. * @private
  4379. */
  4380. calculateBarValuePixels: function (datasetIndex, index, options) {
  4381. var me = this;
  4382. var chart = me.chart;
  4383. var scale = me._getValueScale();
  4384. var isHorizontal = scale.isHorizontal();
  4385. var datasets = chart.data.datasets;
  4386. var metasets = scale._getMatchingVisibleMetas(me._type);
  4387. var value = scale._parseValue(datasets[datasetIndex].data[index]);
  4388. var minBarLength = options.minBarLength;
  4389. var stacked = scale.options.stacked;
  4390. var stack = me.getMeta().stack;
  4391. var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;
  4392. var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;
  4393. var ilen = metasets.length;
  4394. var i, imeta, ivalue, base, head, size, stackLength;
  4395. if (stacked || (stacked === undefined && stack !== undefined)) {
  4396. for (i = 0; i < ilen; ++i) {
  4397. imeta = metasets[i];
  4398. if (imeta.index === datasetIndex) {
  4399. break;
  4400. }
  4401. if (imeta.stack === stack) {
  4402. stackLength = scale._parseValue(datasets[imeta.index].data[index]);
  4403. ivalue = stackLength.start === undefined ? stackLength.end : stackLength.min >= 0 && stackLength.max >= 0 ? stackLength.max : stackLength.min;
  4404. if ((value.min < 0 && ivalue < 0) || (value.max >= 0 && ivalue > 0)) {
  4405. start += ivalue;
  4406. }
  4407. }
  4408. }
  4409. }
  4410. base = scale.getPixelForValue(start);
  4411. head = scale.getPixelForValue(start + length);
  4412. size = head - base;
  4413. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  4414. size = minBarLength;
  4415. if (length >= 0 && !isHorizontal || length < 0 && isHorizontal) {
  4416. head = base - minBarLength;
  4417. } else {
  4418. head = base + minBarLength;
  4419. }
  4420. }
  4421. return {
  4422. size: size,
  4423. base: base,
  4424. head: head,
  4425. center: head + size / 2
  4426. };
  4427. },
  4428. /**
  4429. * @private
  4430. */
  4431. calculateBarIndexPixels: function (datasetIndex, index, ruler, options) {
  4432. var me = this;
  4433. var range = options.barThickness === 'flex'
  4434. ? computeFlexCategoryTraits(index, ruler, options)
  4435. : computeFitCategoryTraits(index, ruler, options);
  4436. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  4437. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  4438. var size = Math.min(
  4439. valueOrDefault$3(options.maxBarThickness, Infinity),
  4440. range.chunk * range.ratio);
  4441. return {
  4442. base: center - size / 2,
  4443. head: center + size / 2,
  4444. center: center,
  4445. size: size
  4446. };
  4447. },
  4448. draw: function () {
  4449. var me = this;
  4450. var chart = me.chart;
  4451. var scale = me._getValueScale();
  4452. var rects = me.getMeta().data;
  4453. var dataset = me.getDataset();
  4454. var ilen = rects.length;
  4455. var i = 0;
  4456. helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
  4457. for (; i < ilen; ++i) {
  4458. var val = scale._parseValue(dataset.data[i]);
  4459. if (!isNaN(val.min) && !isNaN(val.max)) {
  4460. rects[i].draw();
  4461. }
  4462. }
  4463. helpers$1.canvas.unclipArea(chart.ctx);
  4464. },
  4465. /**
  4466. * @private
  4467. */
  4468. _resolveDataElementOptions: function () {
  4469. var me = this;
  4470. var values = helpers$1.extend({}, core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments));
  4471. var indexOpts = me._getIndexScale().options;
  4472. var valueOpts = me._getValueScale().options;
  4473. values.barPercentage = valueOrDefault$3(indexOpts.barPercentage, values.barPercentage);
  4474. values.barThickness = valueOrDefault$3(indexOpts.barThickness, values.barThickness);
  4475. values.categoryPercentage = valueOrDefault$3(indexOpts.categoryPercentage, values.categoryPercentage);
  4476. values.maxBarThickness = valueOrDefault$3(indexOpts.maxBarThickness, values.maxBarThickness);
  4477. values.minBarLength = valueOrDefault$3(valueOpts.minBarLength, values.minBarLength);
  4478. return values;
  4479. }
  4480. });
  4481. var valueOrDefault$4 = helpers$1.valueOrDefault;
  4482. var resolve$1 = helpers$1.options.resolve;
  4483. core_defaults._set('bubble', {
  4484. hover: {
  4485. mode: 'single'
  4486. },
  4487. scales: {
  4488. xAxes: [{
  4489. type: 'linear', // bubble should probably use a linear scale by default
  4490. position: 'bottom',
  4491. id: 'x-axis-0' // need an ID so datasets can reference the scale
  4492. }],
  4493. yAxes: [{
  4494. type: 'linear',
  4495. position: 'left',
  4496. id: 'y-axis-0'
  4497. }]
  4498. },
  4499. tooltips: {
  4500. callbacks: {
  4501. title: function () {
  4502. // Title doesn't make sense for scatter since we format the data as a point
  4503. return '';
  4504. },
  4505. label: function (item, data) {
  4506. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  4507. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  4508. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  4509. }
  4510. }
  4511. }
  4512. });
  4513. var controller_bubble = core_datasetController.extend({
  4514. /**
  4515. * @protected
  4516. */
  4517. dataElementType: elements.Point,
  4518. /**
  4519. * @private
  4520. */
  4521. _dataElementOptions: [
  4522. 'backgroundColor',
  4523. 'borderColor',
  4524. 'borderWidth',
  4525. 'hoverBackgroundColor',
  4526. 'hoverBorderColor',
  4527. 'hoverBorderWidth',
  4528. 'hoverRadius',
  4529. 'hitRadius',
  4530. 'pointStyle',
  4531. 'rotation'
  4532. ],
  4533. /**
  4534. * @protected
  4535. */
  4536. update: function (reset) {
  4537. var me = this;
  4538. var meta = me.getMeta();
  4539. var points = meta.data;
  4540. // Update Points
  4541. helpers$1.each(points, function (point, index) {
  4542. me.updateElement(point, index, reset);
  4543. });
  4544. },
  4545. /**
  4546. * @protected
  4547. */
  4548. updateElement: function (point, index, reset) {
  4549. var me = this;
  4550. var meta = me.getMeta();
  4551. var custom = point.custom || {};
  4552. var xScale = me.getScaleForId(meta.xAxisID);
  4553. var yScale = me.getScaleForId(meta.yAxisID);
  4554. var options = me._resolveDataElementOptions(point, index);
  4555. var data = me.getDataset().data[index];
  4556. var dsIndex = me.index;
  4557. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  4558. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  4559. point._xScale = xScale;
  4560. point._yScale = yScale;
  4561. point._options = options;
  4562. point._datasetIndex = dsIndex;
  4563. point._index = index;
  4564. point._model = {
  4565. backgroundColor: options.backgroundColor,
  4566. borderColor: options.borderColor,
  4567. borderWidth: options.borderWidth,
  4568. hitRadius: options.hitRadius,
  4569. pointStyle: options.pointStyle,
  4570. rotation: options.rotation,
  4571. radius: reset ? 0 : options.radius,
  4572. skip: custom.skip || isNaN(x) || isNaN(y),
  4573. x: x,
  4574. y: y,
  4575. };
  4576. point.pivot();
  4577. },
  4578. /**
  4579. * @protected
  4580. */
  4581. setHoverStyle: function (point) {
  4582. var model = point._model;
  4583. var options = point._options;
  4584. var getHoverColor = helpers$1.getHoverColor;
  4585. point.$previousStyle = {
  4586. backgroundColor: model.backgroundColor,
  4587. borderColor: model.borderColor,
  4588. borderWidth: model.borderWidth,
  4589. radius: model.radius
  4590. };
  4591. model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4592. model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
  4593. model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
  4594. model.radius = options.radius + options.hoverRadius;
  4595. },
  4596. /**
  4597. * @private
  4598. */
  4599. _resolveDataElementOptions: function (point, index) {
  4600. var me = this;
  4601. var chart = me.chart;
  4602. var dataset = me.getDataset();
  4603. var custom = point.custom || {};
  4604. var data = dataset.data[index] || {};
  4605. var values = core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments);
  4606. // Scriptable options
  4607. var context = {
  4608. chart: chart,
  4609. dataIndex: index,
  4610. dataset: dataset,
  4611. datasetIndex: me.index
  4612. };
  4613. // In case values were cached (and thus frozen), we need to clone the values
  4614. if (me._cachedDataOpts === values) {
  4615. values = helpers$1.extend({}, values);
  4616. }
  4617. // Custom radius resolution
  4618. values.radius = resolve$1([
  4619. custom.radius,
  4620. data.r,
  4621. me._config.radius,
  4622. chart.options.elements.point.radius
  4623. ], context, index);
  4624. return values;
  4625. }
  4626. });
  4627. var valueOrDefault$5 = helpers$1.valueOrDefault;
  4628. var PI$1 = Math.PI;
  4629. var DOUBLE_PI$1 = PI$1 * 2;
  4630. var HALF_PI$1 = PI$1 / 2;
  4631. core_defaults._set('doughnut', {
  4632. animation: {
  4633. // Boolean - Whether we animate the rotation of the Doughnut
  4634. animateRotate: true,
  4635. // Boolean - Whether we animate scaling the Doughnut from the centre
  4636. animateScale: false
  4637. },
  4638. hover: {
  4639. mode: 'single'
  4640. },
  4641. legendCallback: function (chart) {
  4642. var list = document.createElement('ul');
  4643. var data = chart.data;
  4644. var datasets = data.datasets;
  4645. var labels = data.labels;
  4646. var i, ilen, listItem, listItemSpan;
  4647. list.setAttribute('class', chart.id + '-legend');
  4648. if (datasets.length) {
  4649. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  4650. listItem = list.appendChild(document.createElement('li'));
  4651. listItemSpan = listItem.appendChild(document.createElement('span'));
  4652. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  4653. if (labels[i]) {
  4654. listItem.appendChild(document.createTextNode(labels[i]));
  4655. }
  4656. }
  4657. }
  4658. return list.outerHTML;
  4659. },
  4660. legend: {
  4661. labels: {
  4662. generateLabels: function (chart) {
  4663. var data = chart.data;
  4664. if (data.labels.length && data.datasets.length) {
  4665. return data.labels.map(function (label, i) {
  4666. var meta = chart.getDatasetMeta(0);
  4667. var style = meta.controller.getStyle(i);
  4668. return {
  4669. text: label,
  4670. fillStyle: style.backgroundColor,
  4671. strokeStyle: style.borderColor,
  4672. lineWidth: style.borderWidth,
  4673. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  4674. // Extra data used for toggling the correct item
  4675. index: i
  4676. };
  4677. });
  4678. }
  4679. return [];
  4680. }
  4681. },
  4682. onClick: function (e, legendItem) {
  4683. var index = legendItem.index;
  4684. var chart = this.chart;
  4685. var i, ilen, meta;
  4686. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  4687. meta = chart.getDatasetMeta(i);
  4688. // toggle visibility of index if exists
  4689. if (meta.data[index]) {
  4690. meta.data[index].hidden = !meta.data[index].hidden;
  4691. }
  4692. }
  4693. chart.update();
  4694. }
  4695. },
  4696. // The percentage of the chart that we cut out of the middle.
  4697. cutoutPercentage: 50,
  4698. // The rotation of the chart, where the first data arc begins.
  4699. rotation: -HALF_PI$1,
  4700. // The total circumference of the chart.
  4701. circumference: DOUBLE_PI$1,
  4702. // Need to override these to give a nice default
  4703. tooltips: {
  4704. callbacks: {
  4705. title: function () {
  4706. return '';
  4707. },
  4708. label: function (tooltipItem, data) {
  4709. var dataLabel = data.labels[tooltipItem.index];
  4710. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  4711. if (helpers$1.isArray(dataLabel)) {
  4712. // show value on first line of multiline label
  4713. // need to clone because we are changing the value
  4714. dataLabel = dataLabel.slice();
  4715. dataLabel[0] += value;
  4716. } else {
  4717. dataLabel += value;
  4718. }
  4719. return dataLabel;
  4720. }
  4721. }
  4722. }
  4723. });
  4724. var controller_doughnut = core_datasetController.extend({
  4725. dataElementType: elements.Arc,
  4726. linkScales: helpers$1.noop,
  4727. /**
  4728. * @private
  4729. */
  4730. _dataElementOptions: [
  4731. 'backgroundColor',
  4732. 'borderColor',
  4733. 'borderWidth',
  4734. 'borderAlign',
  4735. 'hoverBackgroundColor',
  4736. 'hoverBorderColor',
  4737. 'hoverBorderWidth',
  4738. ],
  4739. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  4740. getRingIndex: function (datasetIndex) {
  4741. var ringIndex = 0;
  4742. for (var j = 0; j < datasetIndex; ++j) {
  4743. if (this.chart.isDatasetVisible(j)) {
  4744. ++ringIndex;
  4745. }
  4746. }
  4747. return ringIndex;
  4748. },
  4749. update: function (reset) {
  4750. var me = this;
  4751. var chart = me.chart;
  4752. var chartArea = chart.chartArea;
  4753. var opts = chart.options;
  4754. var ratioX = 1;
  4755. var ratioY = 1;
  4756. var offsetX = 0;
  4757. var offsetY = 0;
  4758. var meta = me.getMeta();
  4759. var arcs = meta.data;
  4760. var cutout = opts.cutoutPercentage / 100 || 0;
  4761. var circumference = opts.circumference;
  4762. var chartWeight = me._getRingWeight(me.index);
  4763. var maxWidth, maxHeight, i, ilen;
  4764. // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc
  4765. if (circumference < DOUBLE_PI$1) {
  4766. var startAngle = opts.rotation % DOUBLE_PI$1;
  4767. startAngle += startAngle >= PI$1 ? -DOUBLE_PI$1 : startAngle < -PI$1 ? DOUBLE_PI$1 : 0;
  4768. var endAngle = startAngle + circumference;
  4769. var startX = Math.cos(startAngle);
  4770. var startY = Math.sin(startAngle);
  4771. var endX = Math.cos(endAngle);
  4772. var endY = Math.sin(endAngle);
  4773. var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI$1;
  4774. var contains90 = (startAngle <= HALF_PI$1 && endAngle >= HALF_PI$1) || endAngle >= DOUBLE_PI$1 + HALF_PI$1;
  4775. var contains180 = startAngle === -PI$1 || endAngle >= PI$1;
  4776. var contains270 = (startAngle <= -HALF_PI$1 && endAngle >= -HALF_PI$1) || endAngle >= PI$1 + HALF_PI$1;
  4777. var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);
  4778. var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);
  4779. var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);
  4780. var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);
  4781. ratioX = (maxX - minX) / 2;
  4782. ratioY = (maxY - minY) / 2;
  4783. offsetX = -(maxX + minX) / 2;
  4784. offsetY = -(maxY + minY) / 2;
  4785. }
  4786. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4787. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  4788. }
  4789. chart.borderWidth = me.getMaxBorderWidth();
  4790. maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;
  4791. maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;
  4792. chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  4793. chart.innerRadius = Math.max(chart.outerRadius * cutout, 0);
  4794. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
  4795. chart.offsetX = offsetX * chart.outerRadius;
  4796. chart.offsetY = offsetY * chart.outerRadius;
  4797. meta.total = me.calculateTotal();
  4798. me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
  4799. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
  4800. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4801. me.updateElement(arcs[i], i, reset);
  4802. }
  4803. },
  4804. updateElement: function (arc, index, reset) {
  4805. var me = this;
  4806. var chart = me.chart;
  4807. var chartArea = chart.chartArea;
  4808. var opts = chart.options;
  4809. var animationOpts = opts.animation;
  4810. var centerX = (chartArea.left + chartArea.right) / 2;
  4811. var centerY = (chartArea.top + chartArea.bottom) / 2;
  4812. var startAngle = opts.rotation; // non reset case handled later
  4813. var endAngle = opts.rotation; // non reset case handled later
  4814. var dataset = me.getDataset();
  4815. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / DOUBLE_PI$1);
  4816. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  4817. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  4818. var options = arc._options || {};
  4819. helpers$1.extend(arc, {
  4820. // Utility
  4821. _datasetIndex: me.index,
  4822. _index: index,
  4823. // Desired view properties
  4824. _model: {
  4825. backgroundColor: options.backgroundColor,
  4826. borderColor: options.borderColor,
  4827. borderWidth: options.borderWidth,
  4828. borderAlign: options.borderAlign,
  4829. x: centerX + chart.offsetX,
  4830. y: centerY + chart.offsetY,
  4831. startAngle: startAngle,
  4832. endAngle: endAngle,
  4833. circumference: circumference,
  4834. outerRadius: outerRadius,
  4835. innerRadius: innerRadius,
  4836. label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  4837. }
  4838. });
  4839. var model = arc._model;
  4840. // Set correct angles if not resetting
  4841. if (!reset || !animationOpts.animateRotate) {
  4842. if (index === 0) {
  4843. model.startAngle = opts.rotation;
  4844. } else {
  4845. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  4846. }
  4847. model.endAngle = model.startAngle + model.circumference;
  4848. }
  4849. arc.pivot();
  4850. },
  4851. calculateTotal: function () {
  4852. var dataset = this.getDataset();
  4853. var meta = this.getMeta();
  4854. var total = 0;
  4855. var value;
  4856. helpers$1.each(meta.data, function (element, index) {
  4857. value = dataset.data[index];
  4858. if (!isNaN(value) && !element.hidden) {
  4859. total += Math.abs(value);
  4860. }
  4861. });
  4862. /* if (total === 0) {
  4863. total = NaN;
  4864. }*/
  4865. return total;
  4866. },
  4867. calculateCircumference: function (value) {
  4868. var total = this.getMeta().total;
  4869. if (total > 0 && !isNaN(value)) {
  4870. return DOUBLE_PI$1 * (Math.abs(value) / total);
  4871. }
  4872. return 0;
  4873. },
  4874. // gets the max border or hover width to properly scale pie charts
  4875. getMaxBorderWidth: function (arcs) {
  4876. var me = this;
  4877. var max = 0;
  4878. var chart = me.chart;
  4879. var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
  4880. if (!arcs) {
  4881. // Find the outmost visible dataset
  4882. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  4883. if (chart.isDatasetVisible(i)) {
  4884. meta = chart.getDatasetMeta(i);
  4885. arcs = meta.data;
  4886. if (i !== me.index) {
  4887. controller = meta.controller;
  4888. }
  4889. break;
  4890. }
  4891. }
  4892. }
  4893. if (!arcs) {
  4894. return 0;
  4895. }
  4896. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4897. arc = arcs[i];
  4898. if (controller) {
  4899. controller._configure();
  4900. options = controller._resolveDataElementOptions(arc, i);
  4901. } else {
  4902. options = arc._options;
  4903. }
  4904. if (options.borderAlign !== 'inner') {
  4905. borderWidth = options.borderWidth;
  4906. hoverWidth = options.hoverBorderWidth;
  4907. max = borderWidth > max ? borderWidth : max;
  4908. max = hoverWidth > max ? hoverWidth : max;
  4909. }
  4910. }
  4911. return max;
  4912. },
  4913. /**
  4914. * @protected
  4915. */
  4916. setHoverStyle: function (arc) {
  4917. var model = arc._model;
  4918. var options = arc._options;
  4919. var getHoverColor = helpers$1.getHoverColor;
  4920. arc.$previousStyle = {
  4921. backgroundColor: model.backgroundColor,
  4922. borderColor: model.borderColor,
  4923. borderWidth: model.borderWidth,
  4924. };
  4925. model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4926. model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
  4927. model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
  4928. },
  4929. /**
  4930. * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
  4931. * @private
  4932. */
  4933. _getRingWeightOffset: function (datasetIndex) {
  4934. var ringWeightOffset = 0;
  4935. for (var i = 0; i < datasetIndex; ++i) {
  4936. if (this.chart.isDatasetVisible(i)) {
  4937. ringWeightOffset += this._getRingWeight(i);
  4938. }
  4939. }
  4940. return ringWeightOffset;
  4941. },
  4942. /**
  4943. * @private
  4944. */
  4945. _getRingWeight: function (dataSetIndex) {
  4946. return Math.max(valueOrDefault$5(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
  4947. },
  4948. /**
  4949. * Returns the sum of all visibile data set weights. This value can be 0.
  4950. * @private
  4951. */
  4952. _getVisibleDatasetWeightTotal: function () {
  4953. return this._getRingWeightOffset(this.chart.data.datasets.length);
  4954. }
  4955. });
  4956. core_defaults._set('horizontalBar', {
  4957. hover: {
  4958. mode: 'index',
  4959. axis: 'y'
  4960. },
  4961. scales: {
  4962. xAxes: [{
  4963. type: 'linear',
  4964. position: 'bottom'
  4965. }],
  4966. yAxes: [{
  4967. type: 'category',
  4968. position: 'left',
  4969. offset: true,
  4970. gridLines: {
  4971. offsetGridLines: true
  4972. }
  4973. }]
  4974. },
  4975. elements: {
  4976. rectangle: {
  4977. borderSkipped: 'left'
  4978. }
  4979. },
  4980. tooltips: {
  4981. mode: 'index',
  4982. axis: 'y'
  4983. }
  4984. });
  4985. core_defaults._set('global', {
  4986. datasets: {
  4987. horizontalBar: {
  4988. categoryPercentage: 0.8,
  4989. barPercentage: 0.9
  4990. }
  4991. }
  4992. });
  4993. var controller_horizontalBar = controller_bar.extend({
  4994. /**
  4995. * @private
  4996. */
  4997. _getValueScaleId: function () {
  4998. return this.getMeta().xAxisID;
  4999. },
  5000. /**
  5001. * @private
  5002. */
  5003. _getIndexScaleId: function () {
  5004. return this.getMeta().yAxisID;
  5005. }
  5006. });
  5007. var valueOrDefault$6 = helpers$1.valueOrDefault;
  5008. var resolve$2 = helpers$1.options.resolve;
  5009. var isPointInArea = helpers$1.canvas._isPointInArea;
  5010. core_defaults._set('line', {
  5011. showLines: true,
  5012. spanGaps: false,
  5013. hover: {
  5014. mode: 'label'
  5015. },
  5016. scales: {
  5017. xAxes: [{
  5018. type: 'category',
  5019. id: 'x-axis-0'
  5020. }],
  5021. yAxes: [{
  5022. type: 'linear',
  5023. id: 'y-axis-0'
  5024. }]
  5025. }
  5026. });
  5027. function scaleClip(scale, halfBorderWidth) {
  5028. var tickOpts = scale && scale.options.ticks || {};
  5029. var reverse = tickOpts.reverse;
  5030. var min = tickOpts.min === undefined ? halfBorderWidth : 0;
  5031. var max = tickOpts.max === undefined ? halfBorderWidth : 0;
  5032. return {
  5033. start: reverse ? max : min,
  5034. end: reverse ? min : max
  5035. };
  5036. }
  5037. function defaultClip(xScale, yScale, borderWidth) {
  5038. var halfBorderWidth = borderWidth / 2;
  5039. var x = scaleClip(xScale, halfBorderWidth);
  5040. var y = scaleClip(yScale, halfBorderWidth);
  5041. return {
  5042. top: y.end,
  5043. right: x.end,
  5044. bottom: y.start,
  5045. left: x.start
  5046. };
  5047. }
  5048. function toClip(value) {
  5049. var t, r, b, l;
  5050. if (helpers$1.isObject(value)) {
  5051. t = value.top;
  5052. r = value.right;
  5053. b = value.bottom;
  5054. l = value.left;
  5055. } else {
  5056. t = r = b = l = value;
  5057. }
  5058. return {
  5059. top: t,
  5060. right: r,
  5061. bottom: b,
  5062. left: l
  5063. };
  5064. }
  5065. var controller_line = core_datasetController.extend({
  5066. datasetElementType: elements.Line,
  5067. dataElementType: elements.Point,
  5068. /**
  5069. * @private
  5070. */
  5071. _datasetElementOptions: [
  5072. 'backgroundColor',
  5073. 'borderCapStyle',
  5074. 'borderColor',
  5075. 'borderDash',
  5076. 'borderDashOffset',
  5077. 'borderJoinStyle',
  5078. 'borderWidth',
  5079. 'cubicInterpolationMode',
  5080. 'fill'
  5081. ],
  5082. /**
  5083. * @private
  5084. */
  5085. _dataElementOptions: {
  5086. backgroundColor: 'pointBackgroundColor',
  5087. borderColor: 'pointBorderColor',
  5088. borderWidth: 'pointBorderWidth',
  5089. hitRadius: 'pointHitRadius',
  5090. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5091. hoverBorderColor: 'pointHoverBorderColor',
  5092. hoverBorderWidth: 'pointHoverBorderWidth',
  5093. hoverRadius: 'pointHoverRadius',
  5094. pointStyle: 'pointStyle',
  5095. radius: 'pointRadius',
  5096. rotation: 'pointRotation'
  5097. },
  5098. update: function (reset) {
  5099. var me = this;
  5100. var meta = me.getMeta();
  5101. var line = meta.dataset;
  5102. var points = meta.data || [];
  5103. var options = me.chart.options;
  5104. var config = me._config;
  5105. var showLine = me._showLine = valueOrDefault$6(config.showLine, options.showLines);
  5106. var i, ilen;
  5107. me._xScale = me.getScaleForId(meta.xAxisID);
  5108. me._yScale = me.getScaleForId(meta.yAxisID);
  5109. // Update Line
  5110. if (showLine) {
  5111. // Compatibility: If the properties are defined with only the old name, use those values
  5112. if (config.tension !== undefined && config.lineTension === undefined) {
  5113. config.lineTension = config.tension;
  5114. }
  5115. // Utility
  5116. line._scale = me._yScale;
  5117. line._datasetIndex = me.index;
  5118. // Data
  5119. line._children = points;
  5120. // Model
  5121. line._model = me._resolveDatasetElementOptions(line);
  5122. line.pivot();
  5123. }
  5124. // Update Points
  5125. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5126. me.updateElement(points[i], i, reset);
  5127. }
  5128. if (showLine && line._model.tension !== 0) {
  5129. me.updateBezierControlPoints();
  5130. }
  5131. // Now pivot the point for animation
  5132. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5133. points[i].pivot();
  5134. }
  5135. },
  5136. updateElement: function (point, index, reset) {
  5137. var me = this;
  5138. var meta = me.getMeta();
  5139. var custom = point.custom || {};
  5140. var dataset = me.getDataset();
  5141. var datasetIndex = me.index;
  5142. var value = dataset.data[index];
  5143. var xScale = me._xScale;
  5144. var yScale = me._yScale;
  5145. var lineModel = meta.dataset._model;
  5146. var x, y;
  5147. var options = me._resolveDataElementOptions(point, index);
  5148. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  5149. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  5150. // Utility
  5151. point._xScale = xScale;
  5152. point._yScale = yScale;
  5153. point._options = options;
  5154. point._datasetIndex = datasetIndex;
  5155. point._index = index;
  5156. // Desired view properties
  5157. point._model = {
  5158. x: x,
  5159. y: y,
  5160. skip: custom.skip || isNaN(x) || isNaN(y),
  5161. // Appearance
  5162. radius: options.radius,
  5163. pointStyle: options.pointStyle,
  5164. rotation: options.rotation,
  5165. backgroundColor: options.backgroundColor,
  5166. borderColor: options.borderColor,
  5167. borderWidth: options.borderWidth,
  5168. tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0),
  5169. steppedLine: lineModel ? lineModel.steppedLine : false,
  5170. // Tooltip
  5171. hitRadius: options.hitRadius
  5172. };
  5173. },
  5174. /**
  5175. * @private
  5176. */
  5177. _resolveDatasetElementOptions: function (element) {
  5178. var me = this;
  5179. var config = me._config;
  5180. var custom = element.custom || {};
  5181. var options = me.chart.options;
  5182. var lineOptions = options.elements.line;
  5183. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5184. // The default behavior of lines is to break at null values, according
  5185. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  5186. // This option gives lines the ability to span gaps
  5187. values.spanGaps = valueOrDefault$6(config.spanGaps, options.spanGaps);
  5188. values.tension = valueOrDefault$6(config.lineTension, lineOptions.tension);
  5189. values.steppedLine = resolve$2([custom.steppedLine, config.steppedLine, lineOptions.stepped]);
  5190. values.clip = toClip(valueOrDefault$6(config.clip, defaultClip(me._xScale, me._yScale, values.borderWidth)));
  5191. return values;
  5192. },
  5193. calculatePointY: function (value, index, datasetIndex) {
  5194. var me = this;
  5195. var chart = me.chart;
  5196. var yScale = me._yScale;
  5197. var sumPos = 0;
  5198. var sumNeg = 0;
  5199. var i, ds, dsMeta, stackedRightValue, rightValue, metasets, ilen;
  5200. if (yScale.options.stacked) {
  5201. rightValue = +yScale.getRightValue(value);
  5202. metasets = chart._getSortedVisibleDatasetMetas();
  5203. ilen = metasets.length;
  5204. for (i = 0; i < ilen; ++i) {
  5205. dsMeta = metasets[i];
  5206. if (dsMeta.index === datasetIndex) {
  5207. break;
  5208. }
  5209. ds = chart.data.datasets[dsMeta.index];
  5210. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id) {
  5211. stackedRightValue = +yScale.getRightValue(ds.data[index]);
  5212. if (stackedRightValue < 0) {
  5213. sumNeg += stackedRightValue || 0;
  5214. } else {
  5215. sumPos += stackedRightValue || 0;
  5216. }
  5217. }
  5218. }
  5219. if (rightValue < 0) {
  5220. return yScale.getPixelForValue(sumNeg + rightValue);
  5221. }
  5222. return yScale.getPixelForValue(sumPos + rightValue);
  5223. }
  5224. return yScale.getPixelForValue(value);
  5225. },
  5226. updateBezierControlPoints: function () {
  5227. var me = this;
  5228. var chart = me.chart;
  5229. var meta = me.getMeta();
  5230. var lineModel = meta.dataset._model;
  5231. var area = chart.chartArea;
  5232. var points = meta.data || [];
  5233. var i, ilen, model, controlPoints;
  5234. // Only consider points that are drawn in case the spanGaps option is used
  5235. if (lineModel.spanGaps) {
  5236. points = points.filter(function (pt) {
  5237. return !pt._model.skip;
  5238. });
  5239. }
  5240. function capControlPoint(pt, min, max) {
  5241. return Math.max(Math.min(pt, max), min);
  5242. }
  5243. if (lineModel.cubicInterpolationMode === 'monotone') {
  5244. helpers$1.splineCurveMonotone(points);
  5245. } else {
  5246. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5247. model = points[i]._model;
  5248. controlPoints = helpers$1.splineCurve(
  5249. helpers$1.previousItem(points, i)._model,
  5250. model,
  5251. helpers$1.nextItem(points, i)._model,
  5252. lineModel.tension
  5253. );
  5254. model.controlPointPreviousX = controlPoints.previous.x;
  5255. model.controlPointPreviousY = controlPoints.previous.y;
  5256. model.controlPointNextX = controlPoints.next.x;
  5257. model.controlPointNextY = controlPoints.next.y;
  5258. }
  5259. }
  5260. if (chart.options.elements.line.capBezierPoints) {
  5261. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5262. model = points[i]._model;
  5263. if (isPointInArea(model, area)) {
  5264. if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
  5265. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  5266. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  5267. }
  5268. if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
  5269. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  5270. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  5271. }
  5272. }
  5273. }
  5274. }
  5275. },
  5276. draw: function () {
  5277. var me = this;
  5278. var chart = me.chart;
  5279. var meta = me.getMeta();
  5280. var points = meta.data || [];
  5281. var area = chart.chartArea;
  5282. var canvas = chart.canvas;
  5283. var i = 0;
  5284. var ilen = points.length;
  5285. var clip;
  5286. if (me._showLine) {
  5287. clip = meta.dataset._model.clip;
  5288. helpers$1.canvas.clipArea(chart.ctx, {
  5289. left: clip.left === false ? 0 : area.left - clip.left,
  5290. right: clip.right === false ? canvas.width : area.right + clip.right,
  5291. top: clip.top === false ? 0 : area.top - clip.top,
  5292. bottom: clip.bottom === false ? canvas.height : area.bottom + clip.bottom
  5293. });
  5294. meta.dataset.draw();
  5295. helpers$1.canvas.unclipArea(chart.ctx);
  5296. }
  5297. // Draw the points
  5298. for (; i < ilen; ++i) {
  5299. points[i].draw(area);
  5300. }
  5301. },
  5302. /**
  5303. * @protected
  5304. */
  5305. setHoverStyle: function (point) {
  5306. var model = point._model;
  5307. var options = point._options;
  5308. var getHoverColor = helpers$1.getHoverColor;
  5309. point.$previousStyle = {
  5310. backgroundColor: model.backgroundColor,
  5311. borderColor: model.borderColor,
  5312. borderWidth: model.borderWidth,
  5313. radius: model.radius
  5314. };
  5315. model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5316. model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));
  5317. model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);
  5318. model.radius = valueOrDefault$6(options.hoverRadius, options.radius);
  5319. },
  5320. });
  5321. var resolve$3 = helpers$1.options.resolve;
  5322. core_defaults._set('polarArea', {
  5323. scale: {
  5324. type: 'radialLinear',
  5325. angleLines: {
  5326. display: false
  5327. },
  5328. gridLines: {
  5329. circular: true
  5330. },
  5331. pointLabels: {
  5332. display: false
  5333. },
  5334. ticks: {
  5335. beginAtZero: true
  5336. }
  5337. },
  5338. // Boolean - Whether to animate the rotation of the chart
  5339. animation: {
  5340. animateRotate: true,
  5341. animateScale: true
  5342. },
  5343. startAngle: -0.5 * Math.PI,
  5344. legendCallback: function (chart) {
  5345. var list = document.createElement('ul');
  5346. var data = chart.data;
  5347. var datasets = data.datasets;
  5348. var labels = data.labels;
  5349. var i, ilen, listItem, listItemSpan;
  5350. list.setAttribute('class', chart.id + '-legend');
  5351. if (datasets.length) {
  5352. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  5353. listItem = list.appendChild(document.createElement('li'));
  5354. listItemSpan = listItem.appendChild(document.createElement('span'));
  5355. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  5356. if (labels[i]) {
  5357. listItem.appendChild(document.createTextNode(labels[i]));
  5358. }
  5359. }
  5360. }
  5361. return list.outerHTML;
  5362. },
  5363. legend: {
  5364. labels: {
  5365. generateLabels: function (chart) {
  5366. var data = chart.data;
  5367. if (data.labels.length && data.datasets.length) {
  5368. return data.labels.map(function (label, i) {
  5369. var meta = chart.getDatasetMeta(0);
  5370. var style = meta.controller.getStyle(i);
  5371. return {
  5372. text: label,
  5373. fillStyle: style.backgroundColor,
  5374. strokeStyle: style.borderColor,
  5375. lineWidth: style.borderWidth,
  5376. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  5377. // Extra data used for toggling the correct item
  5378. index: i
  5379. };
  5380. });
  5381. }
  5382. return [];
  5383. }
  5384. },
  5385. onClick: function (e, legendItem) {
  5386. var index = legendItem.index;
  5387. var chart = this.chart;
  5388. var i, ilen, meta;
  5389. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  5390. meta = chart.getDatasetMeta(i);
  5391. meta.data[index].hidden = !meta.data[index].hidden;
  5392. }
  5393. chart.update();
  5394. }
  5395. },
  5396. // Need to override these to give a nice default
  5397. tooltips: {
  5398. callbacks: {
  5399. title: function () {
  5400. return '';
  5401. },
  5402. label: function (item, data) {
  5403. return data.labels[item.index] + ': ' + item.yLabel;
  5404. }
  5405. }
  5406. }
  5407. });
  5408. var controller_polarArea = core_datasetController.extend({
  5409. dataElementType: elements.Arc,
  5410. linkScales: helpers$1.noop,
  5411. /**
  5412. * @private
  5413. */
  5414. _dataElementOptions: [
  5415. 'backgroundColor',
  5416. 'borderColor',
  5417. 'borderWidth',
  5418. 'borderAlign',
  5419. 'hoverBackgroundColor',
  5420. 'hoverBorderColor',
  5421. 'hoverBorderWidth',
  5422. ],
  5423. /**
  5424. * @private
  5425. */
  5426. _getIndexScaleId: function () {
  5427. return this.chart.scale.id;
  5428. },
  5429. /**
  5430. * @private
  5431. */
  5432. _getValueScaleId: function () {
  5433. return this.chart.scale.id;
  5434. },
  5435. update: function (reset) {
  5436. var me = this;
  5437. var dataset = me.getDataset();
  5438. var meta = me.getMeta();
  5439. var start = me.chart.options.startAngle || 0;
  5440. var starts = me._starts = [];
  5441. var angles = me._angles = [];
  5442. var arcs = meta.data;
  5443. var i, ilen, angle;
  5444. me._updateRadius();
  5445. meta.count = me.countVisibleElements();
  5446. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  5447. starts[i] = start;
  5448. angle = me._computeAngle(i);
  5449. angles[i] = angle;
  5450. start += angle;
  5451. }
  5452. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  5453. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  5454. me.updateElement(arcs[i], i, reset);
  5455. }
  5456. },
  5457. /**
  5458. * @private
  5459. */
  5460. _updateRadius: function () {
  5461. var me = this;
  5462. var chart = me.chart;
  5463. var chartArea = chart.chartArea;
  5464. var opts = chart.options;
  5465. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  5466. chart.outerRadius = Math.max(minSize / 2, 0);
  5467. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  5468. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  5469. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  5470. me.innerRadius = me.outerRadius - chart.radiusLength;
  5471. },
  5472. updateElement: function (arc, index, reset) {
  5473. var me = this;
  5474. var chart = me.chart;
  5475. var dataset = me.getDataset();
  5476. var opts = chart.options;
  5477. var animationOpts = opts.animation;
  5478. var scale = chart.scale;
  5479. var labels = chart.data.labels;
  5480. var centerX = scale.xCenter;
  5481. var centerY = scale.yCenter;
  5482. // var negHalfPI = -0.5 * Math.PI;
  5483. var datasetStartAngle = opts.startAngle;
  5484. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5485. var startAngle = me._starts[index];
  5486. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  5487. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5488. var options = arc._options || {};
  5489. helpers$1.extend(arc, {
  5490. // Utility
  5491. _datasetIndex: me.index,
  5492. _index: index,
  5493. _scale: scale,
  5494. // Desired view properties
  5495. _model: {
  5496. backgroundColor: options.backgroundColor,
  5497. borderColor: options.borderColor,
  5498. borderWidth: options.borderWidth,
  5499. borderAlign: options.borderAlign,
  5500. x: centerX,
  5501. y: centerY,
  5502. innerRadius: 0,
  5503. outerRadius: reset ? resetRadius : distance,
  5504. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  5505. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  5506. label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
  5507. }
  5508. });
  5509. arc.pivot();
  5510. },
  5511. countVisibleElements: function () {
  5512. var dataset = this.getDataset();
  5513. var meta = this.getMeta();
  5514. var count = 0;
  5515. helpers$1.each(meta.data, function (element, index) {
  5516. if (!isNaN(dataset.data[index]) && !element.hidden) {
  5517. count++;
  5518. }
  5519. });
  5520. return count;
  5521. },
  5522. /**
  5523. * @protected
  5524. */
  5525. setHoverStyle: function (arc) {
  5526. var model = arc._model;
  5527. var options = arc._options;
  5528. var getHoverColor = helpers$1.getHoverColor;
  5529. var valueOrDefault = helpers$1.valueOrDefault;
  5530. arc.$previousStyle = {
  5531. backgroundColor: model.backgroundColor,
  5532. borderColor: model.borderColor,
  5533. borderWidth: model.borderWidth,
  5534. };
  5535. model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5536. model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
  5537. model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  5538. },
  5539. /**
  5540. * @private
  5541. */
  5542. _computeAngle: function (index) {
  5543. var me = this;
  5544. var count = this.getMeta().count;
  5545. var dataset = me.getDataset();
  5546. var meta = me.getMeta();
  5547. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  5548. return 0;
  5549. }
  5550. // Scriptable options
  5551. var context = {
  5552. chart: me.chart,
  5553. dataIndex: index,
  5554. dataset: dataset,
  5555. datasetIndex: me.index
  5556. };
  5557. return resolve$3([
  5558. me.chart.options.elements.arc.angle,
  5559. (2 * Math.PI) / count
  5560. ], context, index);
  5561. }
  5562. });
  5563. core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
  5564. core_defaults._set('pie', {
  5565. cutoutPercentage: 0
  5566. });
  5567. // Pie charts are Doughnut chart with different defaults
  5568. var controller_pie = controller_doughnut;
  5569. var valueOrDefault$7 = helpers$1.valueOrDefault;
  5570. core_defaults._set('radar', {
  5571. spanGaps: false,
  5572. scale: {
  5573. type: 'radialLinear'
  5574. },
  5575. elements: {
  5576. line: {
  5577. fill: 'start',
  5578. tension: 0 // no bezier in radar
  5579. }
  5580. }
  5581. });
  5582. var controller_radar = core_datasetController.extend({
  5583. datasetElementType: elements.Line,
  5584. dataElementType: elements.Point,
  5585. linkScales: helpers$1.noop,
  5586. /**
  5587. * @private
  5588. */
  5589. _datasetElementOptions: [
  5590. 'backgroundColor',
  5591. 'borderWidth',
  5592. 'borderColor',
  5593. 'borderCapStyle',
  5594. 'borderDash',
  5595. 'borderDashOffset',
  5596. 'borderJoinStyle',
  5597. 'fill'
  5598. ],
  5599. /**
  5600. * @private
  5601. */
  5602. _dataElementOptions: {
  5603. backgroundColor: 'pointBackgroundColor',
  5604. borderColor: 'pointBorderColor',
  5605. borderWidth: 'pointBorderWidth',
  5606. hitRadius: 'pointHitRadius',
  5607. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5608. hoverBorderColor: 'pointHoverBorderColor',
  5609. hoverBorderWidth: 'pointHoverBorderWidth',
  5610. hoverRadius: 'pointHoverRadius',
  5611. pointStyle: 'pointStyle',
  5612. radius: 'pointRadius',
  5613. rotation: 'pointRotation'
  5614. },
  5615. /**
  5616. * @private
  5617. */
  5618. _getIndexScaleId: function () {
  5619. return this.chart.scale.id;
  5620. },
  5621. /**
  5622. * @private
  5623. */
  5624. _getValueScaleId: function () {
  5625. return this.chart.scale.id;
  5626. },
  5627. update: function (reset) {
  5628. var me = this;
  5629. var meta = me.getMeta();
  5630. var line = meta.dataset;
  5631. var points = meta.data || [];
  5632. var scale = me.chart.scale;
  5633. var config = me._config;
  5634. var i, ilen;
  5635. // Compatibility: If the properties are defined with only the old name, use those values
  5636. if (config.tension !== undefined && config.lineTension === undefined) {
  5637. config.lineTension = config.tension;
  5638. }
  5639. // Utility
  5640. line._scale = scale;
  5641. line._datasetIndex = me.index;
  5642. // Data
  5643. line._children = points;
  5644. line._loop = true;
  5645. // Model
  5646. line._model = me._resolveDatasetElementOptions(line);
  5647. line.pivot();
  5648. // Update Points
  5649. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5650. me.updateElement(points[i], i, reset);
  5651. }
  5652. // Update bezier control points
  5653. me.updateBezierControlPoints();
  5654. // Now pivot the point for animation
  5655. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5656. points[i].pivot();
  5657. }
  5658. },
  5659. updateElement: function (point, index, reset) {
  5660. var me = this;
  5661. var custom = point.custom || {};
  5662. var dataset = me.getDataset();
  5663. var scale = me.chart.scale;
  5664. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  5665. var options = me._resolveDataElementOptions(point, index);
  5666. var lineModel = me.getMeta().dataset._model;
  5667. var x = reset ? scale.xCenter : pointPosition.x;
  5668. var y = reset ? scale.yCenter : pointPosition.y;
  5669. // Utility
  5670. point._scale = scale;
  5671. point._options = options;
  5672. point._datasetIndex = me.index;
  5673. point._index = index;
  5674. // Desired view properties
  5675. point._model = {
  5676. x: x, // value not used in dataset scale, but we want a consistent API between scales
  5677. y: y,
  5678. skip: custom.skip || isNaN(x) || isNaN(y),
  5679. // Appearance
  5680. radius: options.radius,
  5681. pointStyle: options.pointStyle,
  5682. rotation: options.rotation,
  5683. backgroundColor: options.backgroundColor,
  5684. borderColor: options.borderColor,
  5685. borderWidth: options.borderWidth,
  5686. tension: valueOrDefault$7(custom.tension, lineModel ? lineModel.tension : 0),
  5687. // Tooltip
  5688. hitRadius: options.hitRadius
  5689. };
  5690. },
  5691. /**
  5692. * @private
  5693. */
  5694. _resolveDatasetElementOptions: function () {
  5695. var me = this;
  5696. var config = me._config;
  5697. var options = me.chart.options;
  5698. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5699. values.spanGaps = valueOrDefault$7(config.spanGaps, options.spanGaps);
  5700. values.tension = valueOrDefault$7(config.lineTension, options.elements.line.tension);
  5701. return values;
  5702. },
  5703. updateBezierControlPoints: function () {
  5704. var me = this;
  5705. var meta = me.getMeta();
  5706. var area = me.chart.chartArea;
  5707. var points = meta.data || [];
  5708. var i, ilen, model, controlPoints;
  5709. // Only consider points that are drawn in case the spanGaps option is used
  5710. if (meta.dataset._model.spanGaps) {
  5711. points = points.filter(function (pt) {
  5712. return !pt._model.skip;
  5713. });
  5714. }
  5715. function capControlPoint(pt, min, max) {
  5716. return Math.max(Math.min(pt, max), min);
  5717. }
  5718. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5719. model = points[i]._model;
  5720. controlPoints = helpers$1.splineCurve(
  5721. helpers$1.previousItem(points, i, true)._model,
  5722. model,
  5723. helpers$1.nextItem(points, i, true)._model,
  5724. model.tension
  5725. );
  5726. // Prevent the bezier going outside of the bounds of the graph
  5727. model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
  5728. model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
  5729. model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
  5730. model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
  5731. }
  5732. },
  5733. setHoverStyle: function (point) {
  5734. var model = point._model;
  5735. var options = point._options;
  5736. var getHoverColor = helpers$1.getHoverColor;
  5737. point.$previousStyle = {
  5738. backgroundColor: model.backgroundColor,
  5739. borderColor: model.borderColor,
  5740. borderWidth: model.borderWidth,
  5741. radius: model.radius
  5742. };
  5743. model.backgroundColor = valueOrDefault$7(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5744. model.borderColor = valueOrDefault$7(options.hoverBorderColor, getHoverColor(options.borderColor));
  5745. model.borderWidth = valueOrDefault$7(options.hoverBorderWidth, options.borderWidth);
  5746. model.radius = valueOrDefault$7(options.hoverRadius, options.radius);
  5747. }
  5748. });
  5749. core_defaults._set('scatter', {
  5750. hover: {
  5751. mode: 'single'
  5752. },
  5753. scales: {
  5754. xAxes: [{
  5755. id: 'x-axis-1', // need an ID so datasets can reference the scale
  5756. type: 'linear', // scatter should not use a category axis
  5757. position: 'bottom'
  5758. }],
  5759. yAxes: [{
  5760. id: 'y-axis-1',
  5761. type: 'linear',
  5762. position: 'left'
  5763. }]
  5764. },
  5765. tooltips: {
  5766. callbacks: {
  5767. title: function () {
  5768. return ''; // doesn't make sense for scatter since data are formatted as a point
  5769. },
  5770. label: function (item) {
  5771. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  5772. }
  5773. }
  5774. }
  5775. });
  5776. core_defaults._set('global', {
  5777. datasets: {
  5778. scatter: {
  5779. showLine: false
  5780. }
  5781. }
  5782. });
  5783. // Scatter charts use line controllers
  5784. var controller_scatter = controller_line;
  5785. // NOTE export a map in which the key represents the controller type, not
  5786. // the class, and so must be CamelCase in order to be correctly retrieved
  5787. // by the controller in core.controller.js (`controllers[meta.type]`).
  5788. var controllers = {
  5789. bar: controller_bar,
  5790. bubble: controller_bubble,
  5791. doughnut: controller_doughnut,
  5792. horizontalBar: controller_horizontalBar,
  5793. line: controller_line,
  5794. polarArea: controller_polarArea,
  5795. pie: controller_pie,
  5796. radar: controller_radar,
  5797. scatter: controller_scatter
  5798. };
  5799. /**
  5800. * Helper function to get relative position for an event
  5801. * @param {Event|IEvent} event - The event to get the position for
  5802. * @param {Chart} chart - The chart
  5803. * @returns {object} the event position
  5804. */
  5805. function getRelativePosition(e, chart) {
  5806. if (e.native) {
  5807. return {
  5808. x: e.x,
  5809. y: e.y
  5810. };
  5811. }
  5812. return helpers$1.getRelativePosition(e, chart);
  5813. }
  5814. /**
  5815. * Helper function to traverse all of the visible elements in the chart
  5816. * @param {Chart} chart - the chart
  5817. * @param {function} handler - the callback to execute for each visible item
  5818. */
  5819. function parseVisibleItems(chart, handler) {
  5820. var metasets = chart._getSortedVisibleDatasetMetas();
  5821. var metadata, i, j, ilen, jlen, element;
  5822. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  5823. metadata = metasets[i].data;
  5824. for (j = 0, jlen = metadata.length; j < jlen; ++j) {
  5825. element = metadata[j];
  5826. if (!element._view.skip) {
  5827. handler(element);
  5828. }
  5829. }
  5830. }
  5831. }
  5832. /**
  5833. * Helper function to get the items that intersect the event position
  5834. * @param {ChartElement[]} items - elements to filter
  5835. * @param {object} position - the point to be nearest to
  5836. * @return {ChartElement[]} the nearest items
  5837. */
  5838. function getIntersectItems(chart, position) {
  5839. var elements = [];
  5840. parseVisibleItems(chart, function (element) {
  5841. if (element.inRange(position.x, position.y)) {
  5842. elements.push(element);
  5843. }
  5844. });
  5845. return elements;
  5846. }
  5847. /**
  5848. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  5849. * @param {Chart} chart - the chart to look at elements from
  5850. * @param {object} position - the point to be nearest to
  5851. * @param {boolean} intersect - if true, only consider items that intersect the position
  5852. * @param {function} distanceMetric - function to provide the distance between points
  5853. * @return {ChartElement[]} the nearest items
  5854. */
  5855. function getNearestItems(chart, position, intersect, distanceMetric) {
  5856. var minDistance = Number.POSITIVE_INFINITY;
  5857. var nearestItems = [];
  5858. parseVisibleItems(chart, function (element) {
  5859. if (intersect && !element.inRange(position.x, position.y)) {
  5860. return;
  5861. }
  5862. var center = element.getCenterPoint();
  5863. var distance = distanceMetric(position, center);
  5864. if (distance < minDistance) {
  5865. nearestItems = [element];
  5866. minDistance = distance;
  5867. } else if (distance === minDistance) {
  5868. // Can have multiple items at the same distance in which case we sort by size
  5869. nearestItems.push(element);
  5870. }
  5871. });
  5872. return nearestItems;
  5873. }
  5874. /**
  5875. * Get a distance metric function for two points based on the
  5876. * axis mode setting
  5877. * @param {string} axis - the axis mode. x|y|xy
  5878. */
  5879. function getDistanceMetricForAxis(axis) {
  5880. var useX = axis.indexOf('x') !== -1;
  5881. var useY = axis.indexOf('y') !== -1;
  5882. return function (pt1, pt2) {
  5883. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  5884. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  5885. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  5886. };
  5887. }
  5888. function indexMode(chart, e, options) {
  5889. var position = getRelativePosition(e, chart);
  5890. // Default axis for index mode is 'x' to match old behaviour
  5891. options.axis = options.axis || 'x';
  5892. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5893. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5894. var elements = [];
  5895. if (!items.length) {
  5896. return [];
  5897. }
  5898. chart._getSortedVisibleDatasetMetas().forEach(function (meta) {
  5899. var element = meta.data[items[0]._index];
  5900. // don't count items that are skipped (null data)
  5901. if (element && !element._view.skip) {
  5902. elements.push(element);
  5903. }
  5904. });
  5905. return elements;
  5906. }
  5907. /**
  5908. * @interface IInteractionOptions
  5909. */
  5910. /**
  5911. * If true, only consider items that intersect the point
  5912. * @name IInterfaceOptions#boolean
  5913. * @type Boolean
  5914. */
  5915. /**
  5916. * Contains interaction related functions
  5917. * @namespace Chart.Interaction
  5918. */
  5919. var core_interaction = {
  5920. // Helper function for different modes
  5921. modes: {
  5922. single: function (chart, e) {
  5923. var position = getRelativePosition(e, chart);
  5924. var elements = [];
  5925. parseVisibleItems(chart, function (element) {
  5926. if (element.inRange(position.x, position.y)) {
  5927. elements.push(element);
  5928. return elements;
  5929. }
  5930. });
  5931. return elements.slice(0, 1);
  5932. },
  5933. /**
  5934. * @function Chart.Interaction.modes.label
  5935. * @deprecated since version 2.4.0
  5936. * @todo remove at version 3
  5937. * @private
  5938. */
  5939. label: indexMode,
  5940. /**
  5941. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  5942. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  5943. * @function Chart.Interaction.modes.index
  5944. * @since v2.4.0
  5945. * @param {Chart} chart - the chart we are returning items from
  5946. * @param {Event} e - the event we are find things at
  5947. * @param {IInteractionOptions} options - options to use during interaction
  5948. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5949. */
  5950. index: indexMode,
  5951. /**
  5952. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  5953. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  5954. * @function Chart.Interaction.modes.dataset
  5955. * @param {Chart} chart - the chart we are returning items from
  5956. * @param {Event} e - the event we are find things at
  5957. * @param {IInteractionOptions} options - options to use during interaction
  5958. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5959. */
  5960. dataset: function (chart, e, options) {
  5961. var position = getRelativePosition(e, chart);
  5962. options.axis = options.axis || 'xy';
  5963. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5964. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5965. if (items.length > 0) {
  5966. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  5967. }
  5968. return items;
  5969. },
  5970. /**
  5971. * @function Chart.Interaction.modes.x-axis
  5972. * @deprecated since version 2.4.0. Use index mode and intersect == true
  5973. * @todo remove at version 3
  5974. * @private
  5975. */
  5976. 'x-axis': function (chart, e) {
  5977. return indexMode(chart, e, {intersect: false});
  5978. },
  5979. /**
  5980. * Point mode returns all elements that hit test based on the event position
  5981. * of the event
  5982. * @function Chart.Interaction.modes.intersect
  5983. * @param {Chart} chart - the chart we are returning items from
  5984. * @param {Event} e - the event we are find things at
  5985. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5986. */
  5987. point: function (chart, e) {
  5988. var position = getRelativePosition(e, chart);
  5989. return getIntersectItems(chart, position);
  5990. },
  5991. /**
  5992. * nearest mode returns the element closest to the point
  5993. * @function Chart.Interaction.modes.intersect
  5994. * @param {Chart} chart - the chart we are returning items from
  5995. * @param {Event} e - the event we are find things at
  5996. * @param {IInteractionOptions} options - options to use
  5997. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5998. */
  5999. nearest: function (chart, e, options) {
  6000. var position = getRelativePosition(e, chart);
  6001. options.axis = options.axis || 'xy';
  6002. var distanceMetric = getDistanceMetricForAxis(options.axis);
  6003. return getNearestItems(chart, position, options.intersect, distanceMetric);
  6004. },
  6005. /**
  6006. * x mode returns the elements that hit-test at the current x coordinate
  6007. * @function Chart.Interaction.modes.x
  6008. * @param {Chart} chart - the chart we are returning items from
  6009. * @param {Event} e - the event we are find things at
  6010. * @param {IInteractionOptions} options - options to use
  6011. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  6012. */
  6013. x: function (chart, e, options) {
  6014. var position = getRelativePosition(e, chart);
  6015. var items = [];
  6016. var intersectsItem = false;
  6017. parseVisibleItems(chart, function (element) {
  6018. if (element.inXRange(position.x)) {
  6019. items.push(element);
  6020. }
  6021. if (element.inRange(position.x, position.y)) {
  6022. intersectsItem = true;
  6023. }
  6024. });
  6025. // If we want to trigger on an intersect and we don't have any items
  6026. // that intersect the position, return nothing
  6027. if (options.intersect && !intersectsItem) {
  6028. items = [];
  6029. }
  6030. return items;
  6031. },
  6032. /**
  6033. * y mode returns the elements that hit-test at the current y coordinate
  6034. * @function Chart.Interaction.modes.y
  6035. * @param {Chart} chart - the chart we are returning items from
  6036. * @param {Event} e - the event we are find things at
  6037. * @param {IInteractionOptions} options - options to use
  6038. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  6039. */
  6040. y: function (chart, e, options) {
  6041. var position = getRelativePosition(e, chart);
  6042. var items = [];
  6043. var intersectsItem = false;
  6044. parseVisibleItems(chart, function (element) {
  6045. if (element.inYRange(position.y)) {
  6046. items.push(element);
  6047. }
  6048. if (element.inRange(position.x, position.y)) {
  6049. intersectsItem = true;
  6050. }
  6051. });
  6052. // If we want to trigger on an intersect and we don't have any items
  6053. // that intersect the position, return nothing
  6054. if (options.intersect && !intersectsItem) {
  6055. items = [];
  6056. }
  6057. return items;
  6058. }
  6059. }
  6060. };
  6061. var extend = helpers$1.extend;
  6062. function filterByPosition(array, position) {
  6063. return helpers$1.where(array, function (v) {
  6064. return v.pos === position;
  6065. });
  6066. }
  6067. function sortByWeight(array, reverse) {
  6068. return array.sort(function (a, b) {
  6069. var v0 = reverse ? b : a;
  6070. var v1 = reverse ? a : b;
  6071. return v0.weight === v1.weight ?
  6072. v0.index - v1.index :
  6073. v0.weight - v1.weight;
  6074. });
  6075. }
  6076. function wrapBoxes(boxes) {
  6077. var layoutBoxes = [];
  6078. var i, ilen, box;
  6079. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  6080. box = boxes[i];
  6081. layoutBoxes.push({
  6082. index: i,
  6083. box: box,
  6084. pos: box.position,
  6085. horizontal: box.isHorizontal(),
  6086. weight: box.weight
  6087. });
  6088. }
  6089. return layoutBoxes;
  6090. }
  6091. function setLayoutDims(layouts, params) {
  6092. var i, ilen, layout;
  6093. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  6094. layout = layouts[i];
  6095. // store width used instead of chartArea.w in fitBoxes
  6096. layout.width = layout.horizontal
  6097. ? layout.box.fullWidth && params.availableWidth
  6098. : params.vBoxMaxWidth;
  6099. // store height used instead of chartArea.h in fitBoxes
  6100. layout.height = layout.horizontal && params.hBoxMaxHeight;
  6101. }
  6102. }
  6103. function buildLayoutBoxes(boxes) {
  6104. var layoutBoxes = wrapBoxes(boxes);
  6105. var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  6106. var right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  6107. var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  6108. var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  6109. return {
  6110. leftAndTop: left.concat(top),
  6111. rightAndBottom: right.concat(bottom),
  6112. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  6113. vertical: left.concat(right),
  6114. horizontal: top.concat(bottom)
  6115. };
  6116. }
  6117. function getCombinedMax(maxPadding, chartArea, a, b) {
  6118. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  6119. }
  6120. function updateDims(chartArea, params, layout) {
  6121. var box = layout.box;
  6122. var maxPadding = chartArea.maxPadding;
  6123. var newWidth, newHeight;
  6124. if (layout.size) {
  6125. // this layout was already counted for, lets first reduce old size
  6126. chartArea[layout.pos] -= layout.size;
  6127. }
  6128. layout.size = layout.horizontal ? box.height : box.width;
  6129. chartArea[layout.pos] += layout.size;
  6130. if (box.getPadding) {
  6131. var boxPadding = box.getPadding();
  6132. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  6133. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  6134. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  6135. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  6136. }
  6137. newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right');
  6138. newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom');
  6139. if (newWidth !== chartArea.w || newHeight !== chartArea.h) {
  6140. chartArea.w = newWidth;
  6141. chartArea.h = newHeight;
  6142. // return true if chart area changed in layout's direction
  6143. var sizes = layout.horizontal ? [newWidth, chartArea.w] : [newHeight, chartArea.h];
  6144. return sizes[0] !== sizes[1] && (!isNaN(sizes[0]) || !isNaN(sizes[1]));
  6145. }
  6146. }
  6147. function handleMaxPadding(chartArea) {
  6148. var maxPadding = chartArea.maxPadding;
  6149. function updatePos(pos) {
  6150. var change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  6151. chartArea[pos] += change;
  6152. return change;
  6153. }
  6154. chartArea.y += updatePos('top');
  6155. chartArea.x += updatePos('left');
  6156. updatePos('right');
  6157. updatePos('bottom');
  6158. }
  6159. function getMargins(horizontal, chartArea) {
  6160. var maxPadding = chartArea.maxPadding;
  6161. function marginForPositions(positions) {
  6162. var margin = {left: 0, top: 0, right: 0, bottom: 0};
  6163. positions.forEach(function (pos) {
  6164. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  6165. });
  6166. return margin;
  6167. }
  6168. return horizontal
  6169. ? marginForPositions(['left', 'right'])
  6170. : marginForPositions(['top', 'bottom']);
  6171. }
  6172. function fitBoxes(boxes, chartArea, params) {
  6173. var refitBoxes = [];
  6174. var i, ilen, layout, box, refit, changed;
  6175. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6176. layout = boxes[i];
  6177. box = layout.box;
  6178. box.update(
  6179. layout.width || chartArea.w,
  6180. layout.height || chartArea.h,
  6181. getMargins(layout.horizontal, chartArea)
  6182. );
  6183. if (updateDims(chartArea, params, layout)) {
  6184. changed = true;
  6185. if (refitBoxes.length) {
  6186. // Dimensions changed and there were non full width boxes before this
  6187. // -> we have to refit those
  6188. refit = true;
  6189. }
  6190. }
  6191. if (!box.fullWidth) { // fullWidth boxes don't need to be re-fitted in any case
  6192. refitBoxes.push(layout);
  6193. }
  6194. }
  6195. return refit ? fitBoxes(refitBoxes, chartArea, params) || changed : changed;
  6196. }
  6197. function placeBoxes(boxes, chartArea, params) {
  6198. var userPadding = params.padding;
  6199. var x = chartArea.x;
  6200. var y = chartArea.y;
  6201. var i, ilen, layout, box;
  6202. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6203. layout = boxes[i];
  6204. box = layout.box;
  6205. if (layout.horizontal) {
  6206. box.left = box.fullWidth ? userPadding.left : chartArea.left;
  6207. box.right = box.fullWidth ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;
  6208. box.top = y;
  6209. box.bottom = y + box.height;
  6210. box.width = box.right - box.left;
  6211. y = box.bottom;
  6212. } else {
  6213. box.left = x;
  6214. box.right = x + box.width;
  6215. box.top = chartArea.top;
  6216. box.bottom = chartArea.top + chartArea.h;
  6217. box.height = box.bottom - box.top;
  6218. x = box.right;
  6219. }
  6220. }
  6221. chartArea.x = x;
  6222. chartArea.y = y;
  6223. }
  6224. core_defaults._set('global', {
  6225. layout: {
  6226. padding: {
  6227. top: 0,
  6228. right: 0,
  6229. bottom: 0,
  6230. left: 0
  6231. }
  6232. }
  6233. });
  6234. /**
  6235. * @interface ILayoutItem
  6236. * @prop {string} position - The position of the item in the chart layout. Possible values are
  6237. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  6238. * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  6239. * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  6240. * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  6241. * @prop {function} update - Takes two parameters: width and height. Returns size of item
  6242. * @prop {function} getPadding - Returns an object with padding on the edges
  6243. * @prop {number} width - Width of item. Must be valid after update()
  6244. * @prop {number} height - Height of item. Must be valid after update()
  6245. * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
  6246. * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
  6247. * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
  6248. * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  6249. */
  6250. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  6251. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  6252. // It is this service's responsibility of carrying out that layout.
  6253. var core_layouts = {
  6254. defaults: {},
  6255. /**
  6256. * Register a box to a chart.
  6257. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  6258. * @param {Chart} chart - the chart to use
  6259. * @param {ILayoutItem} item - the item to add to be layed out
  6260. */
  6261. addBox: function (chart, item) {
  6262. if (!chart.boxes) {
  6263. chart.boxes = [];
  6264. }
  6265. // initialize item with default values
  6266. item.fullWidth = item.fullWidth || false;
  6267. item.position = item.position || 'top';
  6268. item.weight = item.weight || 0;
  6269. item._layers = item._layers || function () {
  6270. return [{
  6271. z: 0,
  6272. draw: function () {
  6273. item.draw.apply(item, arguments);
  6274. }
  6275. }];
  6276. };
  6277. chart.boxes.push(item);
  6278. },
  6279. /**
  6280. * Remove a layoutItem from a chart
  6281. * @param {Chart} chart - the chart to remove the box from
  6282. * @param {ILayoutItem} layoutItem - the item to remove from the layout
  6283. */
  6284. removeBox: function (chart, layoutItem) {
  6285. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  6286. if (index !== -1) {
  6287. chart.boxes.splice(index, 1);
  6288. }
  6289. },
  6290. /**
  6291. * Sets (or updates) options on the given `item`.
  6292. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  6293. * @param {ILayoutItem} item - the item to configure with the given options
  6294. * @param {object} options - the new item options.
  6295. */
  6296. configure: function (chart, item, options) {
  6297. var props = ['fullWidth', 'position', 'weight'];
  6298. var ilen = props.length;
  6299. var i = 0;
  6300. var prop;
  6301. for (; i < ilen; ++i) {
  6302. prop = props[i];
  6303. if (options.hasOwnProperty(prop)) {
  6304. item[prop] = options[prop];
  6305. }
  6306. }
  6307. },
  6308. /**
  6309. * Fits boxes of the given chart into the given size by having each box measure itself
  6310. * then running a fitting algorithm
  6311. * @param {Chart} chart - the chart
  6312. * @param {number} width - the width to fit into
  6313. * @param {number} height - the height to fit into
  6314. */
  6315. update: function (chart, width, height) {
  6316. if (!chart) {
  6317. return;
  6318. }
  6319. var layoutOptions = chart.options.layout || {};
  6320. var padding = helpers$1.options.toPadding(layoutOptions.padding);
  6321. var availableWidth = width - padding.width;
  6322. var availableHeight = height - padding.height;
  6323. var boxes = buildLayoutBoxes(chart.boxes);
  6324. var verticalBoxes = boxes.vertical;
  6325. var horizontalBoxes = boxes.horizontal;
  6326. // Essentially we now have any number of boxes on each of the 4 sides.
  6327. // Our canvas looks like the following.
  6328. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  6329. // B1 is the bottom axis
  6330. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  6331. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  6332. // an error will be thrown.
  6333. //
  6334. // |----------------------------------------------------|
  6335. // | T1 (Full Width) |
  6336. // |----------------------------------------------------|
  6337. // | | | T2 | |
  6338. // | |----|-------------------------------------|----|
  6339. // | | | C1 | | C2 | |
  6340. // | | |----| |----| |
  6341. // | | | | |
  6342. // | L1 | L2 | ChartArea (C0) | R1 |
  6343. // | | | | |
  6344. // | | |----| |----| |
  6345. // | | | C3 | | C4 | |
  6346. // | |----|-------------------------------------|----|
  6347. // | | | B1 | |
  6348. // |----------------------------------------------------|
  6349. // | B2 (Full Width) |
  6350. // |----------------------------------------------------|
  6351. //
  6352. var params = Object.freeze({
  6353. outerWidth: width,
  6354. outerHeight: height,
  6355. padding: padding,
  6356. availableWidth: availableWidth,
  6357. vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length,
  6358. hBoxMaxHeight: availableHeight / 2
  6359. });
  6360. var chartArea = extend({
  6361. maxPadding: extend({}, padding),
  6362. w: availableWidth,
  6363. h: availableHeight,
  6364. x: padding.left,
  6365. y: padding.top
  6366. }, padding);
  6367. setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  6368. // First fit vertical boxes
  6369. fitBoxes(verticalBoxes, chartArea, params);
  6370. // Then fit horizontal boxes
  6371. if (fitBoxes(horizontalBoxes, chartArea, params)) {
  6372. // if the area changed, re-fit vertical boxes
  6373. fitBoxes(verticalBoxes, chartArea, params);
  6374. }
  6375. handleMaxPadding(chartArea);
  6376. // Finally place the boxes to correct coordinates
  6377. placeBoxes(boxes.leftAndTop, chartArea, params);
  6378. // Move to opposite side of chart
  6379. chartArea.x += chartArea.w;
  6380. chartArea.y += chartArea.h;
  6381. placeBoxes(boxes.rightAndBottom, chartArea, params);
  6382. chart.chartArea = {
  6383. left: chartArea.left,
  6384. top: chartArea.top,
  6385. right: chartArea.left + chartArea.w,
  6386. bottom: chartArea.top + chartArea.h
  6387. };
  6388. // Finally update boxes in chartArea (radial scale for example)
  6389. helpers$1.each(boxes.chartArea, function (layout) {
  6390. var box = layout.box;
  6391. extend(box, chart.chartArea);
  6392. box.update(chartArea.w, chartArea.h);
  6393. });
  6394. }
  6395. };
  6396. /**
  6397. * Platform fallback implementation (minimal).
  6398. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  6399. */
  6400. var platform_basic = {
  6401. acquireContext: function (item) {
  6402. if (item && item.canvas) {
  6403. // Support for any object associated to a canvas (including a context2d)
  6404. item = item.canvas;
  6405. }
  6406. return item && item.getContext('2d') || null;
  6407. }
  6408. };
  6409. var platform_dom = "/*\r\n * DOM element rendering detection\r\n * https://davidwalsh.name/detect-node-insertion\r\n */\r\n@keyframes chartjs-render-animation {\r\n\tfrom { opacity: 0.99; }\r\n\tto { opacity: 1; }\r\n}\r\n\r\n.chartjs-render-monitor {\r\n\tanimation: chartjs-render-animation 0.001s;\r\n}\r\n\r\n/*\r\n * DOM element resizing detection\r\n * https://github.com/marcj/css-element-queries\r\n */\r\n.chartjs-size-monitor,\r\n.chartjs-size-monitor-expand,\r\n.chartjs-size-monitor-shrink {\r\n\tposition: absolute;\r\n\tdirection: ltr;\r\n\tleft: 0;\r\n\ttop: 0;\r\n\tright: 0;\r\n\tbottom: 0;\r\n\toverflow: hidden;\r\n\tpointer-events: none;\r\n\tvisibility: hidden;\r\n\tz-index: -1;\r\n}\r\n\r\n.chartjs-size-monitor-expand > div {\r\n\tposition: absolute;\r\n\twidth: 1000000px;\r\n\theight: 1000000px;\r\n\tleft: 0;\r\n\ttop: 0;\r\n}\r\n\r\n.chartjs-size-monitor-shrink > div {\r\n\tposition: absolute;\r\n\twidth: 200%;\r\n\theight: 200%;\r\n\tleft: 0;\r\n\ttop: 0;\r\n}\r\n";
  6410. var platform_dom$1 = /*#__PURE__*/Object.freeze({
  6411. __proto__: null,
  6412. 'default': platform_dom
  6413. });
  6414. var stylesheet = getCjsExportFromNamespace(platform_dom$1);
  6415. var EXPANDO_KEY = '$chartjs';
  6416. var CSS_PREFIX = 'chartjs-';
  6417. var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';
  6418. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  6419. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  6420. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  6421. /**
  6422. * DOM event types -> Chart.js event types.
  6423. * Note: only events with different types are mapped.
  6424. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  6425. */
  6426. var EVENT_TYPES = {
  6427. touchstart: 'mousedown',
  6428. touchmove: 'mousemove',
  6429. touchend: 'mouseup',
  6430. pointerenter: 'mouseenter',
  6431. pointerdown: 'mousedown',
  6432. pointermove: 'mousemove',
  6433. pointerup: 'mouseup',
  6434. pointerleave: 'mouseout',
  6435. pointerout: 'mouseout'
  6436. };
  6437. /**
  6438. * The "used" size is the final value of a dimension property after all calculations have
  6439. * been performed. This method uses the computed style of `element` but returns undefined
  6440. * if the computed style is not expressed in pixels. That can happen in some cases where
  6441. * `element` has a size relative to its parent and this last one is not yet displayed,
  6442. * for example because of `display: none` on a parent node.
  6443. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  6444. * @returns {number} Size in pixels or undefined if unknown.
  6445. */
  6446. function readUsedSize(element, property) {
  6447. var value = helpers$1.getStyle(element, property);
  6448. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  6449. return matches ? Number(matches[1]) : undefined;
  6450. }
  6451. /**
  6452. * Initializes the canvas style and render size without modifying the canvas display size,
  6453. * since responsiveness is handled by the controller.resize() method. The config is used
  6454. * to determine the aspect ratio to apply in case no explicit height has been specified.
  6455. */
  6456. function initCanvas(canvas, config) {
  6457. var style = canvas.style;
  6458. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  6459. // returns null or '' if no explicit value has been set to the canvas attribute.
  6460. var renderHeight = canvas.getAttribute('height');
  6461. var renderWidth = canvas.getAttribute('width');
  6462. // Chart.js modifies some canvas values that we want to restore on destroy
  6463. canvas[EXPANDO_KEY] = {
  6464. initial: {
  6465. height: renderHeight,
  6466. width: renderWidth,
  6467. style: {
  6468. display: style.display,
  6469. height: style.height,
  6470. width: style.width
  6471. }
  6472. }
  6473. };
  6474. // Force canvas to display as block to avoid extra space caused by inline
  6475. // elements, which would interfere with the responsive resize process.
  6476. // https://github.com/chartjs/Chart.js/issues/2538
  6477. style.display = style.display || 'block';
  6478. if (renderWidth === null || renderWidth === '') {
  6479. var displayWidth = readUsedSize(canvas, 'width');
  6480. if (displayWidth !== undefined) {
  6481. canvas.width = displayWidth;
  6482. }
  6483. }
  6484. if (renderHeight === null || renderHeight === '') {
  6485. if (canvas.style.height === '') {
  6486. // If no explicit render height and style height, let's apply the aspect ratio,
  6487. // which one can be specified by the user but also by charts as default option
  6488. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  6489. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  6490. } else {
  6491. var displayHeight = readUsedSize(canvas, 'height');
  6492. if (displayWidth !== undefined) {
  6493. canvas.height = displayHeight;
  6494. }
  6495. }
  6496. }
  6497. return canvas;
  6498. }
  6499. /**
  6500. * Detects support for options object argument in addEventListener.
  6501. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  6502. * @private
  6503. */
  6504. var supportsEventListenerOptions = (function () {
  6505. var supports = false;
  6506. try {
  6507. var options = Object.defineProperty({}, 'passive', {
  6508. // eslint-disable-next-line getter-return
  6509. get: function () {
  6510. supports = true;
  6511. }
  6512. });
  6513. window.addEventListener('e', null, options);
  6514. } catch (e) {
  6515. // continue regardless of error
  6516. }
  6517. return supports;
  6518. }());
  6519. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  6520. // https://github.com/chartjs/Chart.js/issues/4287
  6521. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  6522. function addListener(node, type, listener) {
  6523. node.addEventListener(type, listener, eventListenerOptions);
  6524. }
  6525. function removeListener(node, type, listener) {
  6526. node.removeEventListener(type, listener, eventListenerOptions);
  6527. }
  6528. function createEvent(type, chart, x, y, nativeEvent) {
  6529. return {
  6530. type: type,
  6531. chart: chart,
  6532. native: nativeEvent || null,
  6533. x: x !== undefined ? x : null,
  6534. y: y !== undefined ? y : null,
  6535. };
  6536. }
  6537. function fromNativeEvent(event, chart) {
  6538. var type = EVENT_TYPES[event.type] || event.type;
  6539. var pos = helpers$1.getRelativePosition(event, chart);
  6540. return createEvent(type, chart, pos.x, pos.y, event);
  6541. }
  6542. function throttled(fn, thisArg) {
  6543. var ticking = false;
  6544. var args = [];
  6545. return function () {
  6546. args = Array.prototype.slice.call(arguments);
  6547. thisArg = thisArg || this;
  6548. if (!ticking) {
  6549. ticking = true;
  6550. helpers$1.requestAnimFrame.call(window, function () {
  6551. ticking = false;
  6552. fn.apply(thisArg, args);
  6553. });
  6554. }
  6555. };
  6556. }
  6557. function createDiv(cls) {
  6558. var el = document.createElement('div');
  6559. el.className = cls || '';
  6560. return el;
  6561. }
  6562. // Implementation based on https://github.com/marcj/css-element-queries
  6563. function createResizer(handler) {
  6564. var maxSize = 1000000;
  6565. // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
  6566. // https://github.com/chartjs/Chart.js/issues/5902
  6567. var resizer = createDiv(CSS_SIZE_MONITOR);
  6568. var expand = createDiv(CSS_SIZE_MONITOR + '-expand');
  6569. var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');
  6570. expand.appendChild(createDiv());
  6571. shrink.appendChild(createDiv());
  6572. resizer.appendChild(expand);
  6573. resizer.appendChild(shrink);
  6574. resizer._reset = function () {
  6575. expand.scrollLeft = maxSize;
  6576. expand.scrollTop = maxSize;
  6577. shrink.scrollLeft = maxSize;
  6578. shrink.scrollTop = maxSize;
  6579. };
  6580. var onScroll = function () {
  6581. resizer._reset();
  6582. handler();
  6583. };
  6584. addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  6585. addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  6586. return resizer;
  6587. }
  6588. // https://davidwalsh.name/detect-node-insertion
  6589. function watchForRender(node, handler) {
  6590. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6591. var proxy = expando.renderProxy = function (e) {
  6592. if (e.animationName === CSS_RENDER_ANIMATION) {
  6593. handler();
  6594. }
  6595. };
  6596. helpers$1.each(ANIMATION_START_EVENTS, function (type) {
  6597. addListener(node, type, proxy);
  6598. });
  6599. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  6600. // is removed then added back immediately (same animation frame?). Accessing the
  6601. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  6602. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  6603. // https://github.com/chartjs/Chart.js/issues/4737
  6604. expando.reflow = !!node.offsetParent;
  6605. node.classList.add(CSS_RENDER_MONITOR);
  6606. }
  6607. function unwatchForRender(node) {
  6608. var expando = node[EXPANDO_KEY] || {};
  6609. var proxy = expando.renderProxy;
  6610. if (proxy) {
  6611. helpers$1.each(ANIMATION_START_EVENTS, function (type) {
  6612. removeListener(node, type, proxy);
  6613. });
  6614. delete expando.renderProxy;
  6615. }
  6616. node.classList.remove(CSS_RENDER_MONITOR);
  6617. }
  6618. function addResizeListener(node, listener, chart) {
  6619. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6620. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  6621. var resizer = expando.resizer = createResizer(throttled(function () {
  6622. if (expando.resizer) {
  6623. var container = chart.options.maintainAspectRatio && node.parentNode;
  6624. var w = container ? container.clientWidth : 0;
  6625. listener(createEvent('resize', chart));
  6626. if (container && container.clientWidth < w && chart.canvas) {
  6627. // If the container size shrank during chart resize, let's assume
  6628. // scrollbar appeared. So we resize again with the scrollbar visible -
  6629. // effectively making chart smaller and the scrollbar hidden again.
  6630. // Because we are inside `throttled`, and currently `ticking`, scroll
  6631. // events are ignored during this whole 2 resize process.
  6632. // If we assumed wrong and something else happened, we are resizing
  6633. // twice in a frame (potential performance issue)
  6634. listener(createEvent('resize', chart));
  6635. }
  6636. }
  6637. }));
  6638. // The resizer needs to be attached to the node parent, so we first need to be
  6639. // sure that `node` is attached to the DOM before injecting the resizer element.
  6640. watchForRender(node, function () {
  6641. if (expando.resizer) {
  6642. var container = node.parentNode;
  6643. if (container && container !== resizer.parentNode) {
  6644. container.insertBefore(resizer, container.firstChild);
  6645. }
  6646. // The container size might have changed, let's reset the resizer state.
  6647. resizer._reset();
  6648. }
  6649. });
  6650. }
  6651. function removeResizeListener(node) {
  6652. var expando = node[EXPANDO_KEY] || {};
  6653. var resizer = expando.resizer;
  6654. delete expando.resizer;
  6655. unwatchForRender(node);
  6656. if (resizer && resizer.parentNode) {
  6657. resizer.parentNode.removeChild(resizer);
  6658. }
  6659. }
  6660. /**
  6661. * Injects CSS styles inline if the styles are not already present.
  6662. * @param {HTMLDocument|ShadowRoot} rootNode - the node to contain the <style>.
  6663. * @param {string} css - the CSS to be injected.
  6664. */
  6665. function injectCSS(rootNode, css) {
  6666. // https://stackoverflow.com/q/3922139
  6667. var expando = rootNode[EXPANDO_KEY] || (rootNode[EXPANDO_KEY] = {});
  6668. if (!expando.containsStyles) {
  6669. expando.containsStyles = true;
  6670. css = '/* Chart.js */\n' + css;
  6671. var style = document.createElement('style');
  6672. style.setAttribute('type', 'text/css');
  6673. style.appendChild(document.createTextNode(css));
  6674. rootNode.appendChild(style);
  6675. }
  6676. }
  6677. var platform_dom$2 = {
  6678. /**
  6679. * When `true`, prevents the automatic injection of the stylesheet required to
  6680. * correctly detect when the chart is added to the DOM and then resized. This
  6681. * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)
  6682. * to be manually imported to make this library compatible with any CSP.
  6683. * See https://github.com/chartjs/Chart.js/issues/5208
  6684. */
  6685. disableCSSInjection: false,
  6686. /**
  6687. * This property holds whether this platform is enabled for the current environment.
  6688. * Currently used by platform.js to select the proper implementation.
  6689. * @private
  6690. */
  6691. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  6692. /**
  6693. * Initializes resources that depend on platform options.
  6694. * @param {HTMLCanvasElement} canvas - The Canvas element.
  6695. * @private
  6696. */
  6697. _ensureLoaded: function (canvas) {
  6698. if (!this.disableCSSInjection) {
  6699. // If the canvas is in a shadow DOM, then the styles must also be inserted
  6700. // into the same shadow DOM.
  6701. // https://github.com/chartjs/Chart.js/issues/5763
  6702. var root = canvas.getRootNode ? canvas.getRootNode() : document;
  6703. var targetNode = root.host ? root : document.head;
  6704. injectCSS(targetNode, stylesheet);
  6705. }
  6706. },
  6707. acquireContext: function (item, config) {
  6708. if (typeof item === 'string') {
  6709. item = document.getElementById(item);
  6710. } else if (item.length) {
  6711. // Support for array based queries (such as jQuery)
  6712. item = item[0];
  6713. }
  6714. if (item && item.canvas) {
  6715. // Support for any object associated to a canvas (including a context2d)
  6716. item = item.canvas;
  6717. }
  6718. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  6719. // method, for example: https://github.com/kkapsner/CanvasBlocker
  6720. // https://github.com/chartjs/Chart.js/issues/2807
  6721. var context = item && item.getContext && item.getContext('2d');
  6722. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  6723. // inside an iframe or when running in a protected environment. We could guess the
  6724. // types from their toString() value but let's keep things flexible and assume it's
  6725. // a sufficient condition if the item has a context2D which has item as `canvas`.
  6726. // https://github.com/chartjs/Chart.js/issues/3887
  6727. // https://github.com/chartjs/Chart.js/issues/4102
  6728. // https://github.com/chartjs/Chart.js/issues/4152
  6729. if (context && context.canvas === item) {
  6730. // Load platform resources on first chart creation, to make it possible to
  6731. // import the library before setting platform options.
  6732. this._ensureLoaded(item);
  6733. initCanvas(item, config);
  6734. return context;
  6735. }
  6736. return null;
  6737. },
  6738. releaseContext: function (context) {
  6739. var canvas = context.canvas;
  6740. if (!canvas[EXPANDO_KEY]) {
  6741. return;
  6742. }
  6743. var initial = canvas[EXPANDO_KEY].initial;
  6744. ['height', 'width'].forEach(function (prop) {
  6745. var value = initial[prop];
  6746. if (helpers$1.isNullOrUndef(value)) {
  6747. canvas.removeAttribute(prop);
  6748. } else {
  6749. canvas.setAttribute(prop, value);
  6750. }
  6751. });
  6752. helpers$1.each(initial.style || {}, function (value, key) {
  6753. canvas.style[key] = value;
  6754. });
  6755. // The canvas render size might have been changed (and thus the state stack discarded),
  6756. // we can't use save() and restore() to restore the initial state. So make sure that at
  6757. // least the canvas context is reset to the default state by setting the canvas width.
  6758. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  6759. // eslint-disable-next-line no-self-assign
  6760. canvas.width = canvas.width;
  6761. delete canvas[EXPANDO_KEY];
  6762. },
  6763. addEventListener: function (chart, type, listener) {
  6764. var canvas = chart.canvas;
  6765. if (type === 'resize') {
  6766. // Note: the resize event is not supported on all browsers.
  6767. addResizeListener(canvas, listener, chart);
  6768. return;
  6769. }
  6770. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  6771. var proxies = expando.proxies || (expando.proxies = {});
  6772. var proxy = proxies[chart.id + '_' + type] = function (event) {
  6773. listener(fromNativeEvent(event, chart));
  6774. };
  6775. addListener(canvas, type, proxy);
  6776. },
  6777. removeEventListener: function (chart, type, listener) {
  6778. var canvas = chart.canvas;
  6779. if (type === 'resize') {
  6780. // Note: the resize event is not supported on all browsers.
  6781. removeResizeListener(canvas);
  6782. return;
  6783. }
  6784. var expando = listener[EXPANDO_KEY] || {};
  6785. var proxies = expando.proxies || {};
  6786. var proxy = proxies[chart.id + '_' + type];
  6787. if (!proxy) {
  6788. return;
  6789. }
  6790. removeListener(canvas, type, proxy);
  6791. }
  6792. };
  6793. // DEPRECATIONS
  6794. /**
  6795. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  6796. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6797. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  6798. * @function Chart.helpers.addEvent
  6799. * @deprecated since version 2.7.0
  6800. * @todo remove at version 3
  6801. * @private
  6802. */
  6803. helpers$1.addEvent = addListener;
  6804. /**
  6805. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  6806. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6807. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  6808. * @function Chart.helpers.removeEvent
  6809. * @deprecated since version 2.7.0
  6810. * @todo remove at version 3
  6811. * @private
  6812. */
  6813. helpers$1.removeEvent = removeListener;
  6814. // @TODO Make possible to select another platform at build time.
  6815. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;
  6816. /**
  6817. * @namespace Chart.platform
  6818. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  6819. * @since 2.4.0
  6820. */
  6821. var platform = helpers$1.extend({
  6822. /**
  6823. * @since 2.7.0
  6824. */
  6825. initialize: function () {
  6826. },
  6827. /**
  6828. * Called at chart construction time, returns a context2d instance implementing
  6829. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  6830. * @param {*} item - The native item from which to acquire context (platform specific)
  6831. * @param {object} options - The chart options
  6832. * @returns {CanvasRenderingContext2D} context2d instance
  6833. */
  6834. acquireContext: function () {
  6835. },
  6836. /**
  6837. * Called at chart destruction time, releases any resources associated to the context
  6838. * previously returned by the acquireContext() method.
  6839. * @param {CanvasRenderingContext2D} context - The context2d instance
  6840. * @returns {boolean} true if the method succeeded, else false
  6841. */
  6842. releaseContext: function () {
  6843. },
  6844. /**
  6845. * Registers the specified listener on the given chart.
  6846. * @param {Chart} chart - Chart from which to listen for event
  6847. * @param {string} type - The ({@link IEvent}) type to listen for
  6848. * @param {function} listener - Receives a notification (an object that implements
  6849. * the {@link IEvent} interface) when an event of the specified type occurs.
  6850. */
  6851. addEventListener: function () {
  6852. },
  6853. /**
  6854. * Removes the specified listener previously registered with addEventListener.
  6855. * @param {Chart} chart - Chart from which to remove the listener
  6856. * @param {string} type - The ({@link IEvent}) type to remove
  6857. * @param {function} listener - The listener function to remove from the event target.
  6858. */
  6859. removeEventListener: function () {
  6860. }
  6861. }, implementation);
  6862. core_defaults._set('global', {
  6863. plugins: {}
  6864. });
  6865. /**
  6866. * The plugin service singleton
  6867. * @namespace Chart.plugins
  6868. * @since 2.1.0
  6869. */
  6870. var core_plugins = {
  6871. /**
  6872. * Globally registered plugins.
  6873. * @private
  6874. */
  6875. _plugins: [],
  6876. /**
  6877. * This identifier is used to invalidate the descriptors cache attached to each chart
  6878. * when a global plugin is registered or unregistered. In this case, the cache ID is
  6879. * incremented and descriptors are regenerated during following API calls.
  6880. * @private
  6881. */
  6882. _cacheId: 0,
  6883. /**
  6884. * Registers the given plugin(s) if not already registered.
  6885. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6886. */
  6887. register: function (plugins) {
  6888. var p = this._plugins;
  6889. ([]).concat(plugins).forEach(function (plugin) {
  6890. if (p.indexOf(plugin) === -1) {
  6891. p.push(plugin);
  6892. }
  6893. });
  6894. this._cacheId++;
  6895. },
  6896. /**
  6897. * Unregisters the given plugin(s) only if registered.
  6898. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6899. */
  6900. unregister: function (plugins) {
  6901. var p = this._plugins;
  6902. ([]).concat(plugins).forEach(function (plugin) {
  6903. var idx = p.indexOf(plugin);
  6904. if (idx !== -1) {
  6905. p.splice(idx, 1);
  6906. }
  6907. });
  6908. this._cacheId++;
  6909. },
  6910. /**
  6911. * Remove all registered plugins.
  6912. * @since 2.1.5
  6913. */
  6914. clear: function () {
  6915. this._plugins = [];
  6916. this._cacheId++;
  6917. },
  6918. /**
  6919. * Returns the number of registered plugins?
  6920. * @returns {number}
  6921. * @since 2.1.5
  6922. */
  6923. count: function () {
  6924. return this._plugins.length;
  6925. },
  6926. /**
  6927. * Returns all registered plugin instances.
  6928. * @returns {IPlugin[]} array of plugin objects.
  6929. * @since 2.1.5
  6930. */
  6931. getAll: function () {
  6932. return this._plugins;
  6933. },
  6934. /**
  6935. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  6936. * This method immediately returns as soon as a plugin explicitly returns false. The
  6937. * returned value can be used, for instance, to interrupt the current action.
  6938. * @param {Chart} chart - The chart instance for which plugins should be called.
  6939. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  6940. * @param {Array} [args] - Extra arguments to apply to the hook call.
  6941. * @returns {boolean} false if any of the plugins return false, else returns true.
  6942. */
  6943. notify: function (chart, hook, args) {
  6944. var descriptors = this.descriptors(chart);
  6945. var ilen = descriptors.length;
  6946. var i, descriptor, plugin, params, method;
  6947. for (i = 0; i < ilen; ++i) {
  6948. descriptor = descriptors[i];
  6949. plugin = descriptor.plugin;
  6950. method = plugin[hook];
  6951. if (typeof method === 'function') {
  6952. params = [chart].concat(args || []);
  6953. params.push(descriptor.options);
  6954. if (method.apply(plugin, params) === false) {
  6955. return false;
  6956. }
  6957. }
  6958. }
  6959. return true;
  6960. },
  6961. /**
  6962. * Returns descriptors of enabled plugins for the given chart.
  6963. * @returns {object[]} [{ plugin, options }]
  6964. * @private
  6965. */
  6966. descriptors: function (chart) {
  6967. var cache = chart.$plugins || (chart.$plugins = {});
  6968. if (cache.id === this._cacheId) {
  6969. return cache.descriptors;
  6970. }
  6971. var plugins = [];
  6972. var descriptors = [];
  6973. var config = (chart && chart.config) || {};
  6974. var options = (config.options && config.options.plugins) || {};
  6975. this._plugins.concat(config.plugins || []).forEach(function (plugin) {
  6976. var idx = plugins.indexOf(plugin);
  6977. if (idx !== -1) {
  6978. return;
  6979. }
  6980. var id = plugin.id;
  6981. var opts = options[id];
  6982. if (opts === false) {
  6983. return;
  6984. }
  6985. if (opts === true) {
  6986. opts = helpers$1.clone(core_defaults.global.plugins[id]);
  6987. }
  6988. plugins.push(plugin);
  6989. descriptors.push({
  6990. plugin: plugin,
  6991. options: opts || {}
  6992. });
  6993. });
  6994. cache.descriptors = descriptors;
  6995. cache.id = this._cacheId;
  6996. return descriptors;
  6997. },
  6998. /**
  6999. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  7000. * but in some cases, this reference can be changed by the user when updating options.
  7001. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  7002. * @private
  7003. */
  7004. _invalidate: function (chart) {
  7005. delete chart.$plugins;
  7006. }
  7007. };
  7008. var core_scaleService = {
  7009. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  7010. // use the new chart options to grab the correct scale
  7011. constructors: {},
  7012. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  7013. // old browsers
  7014. // Scale config defaults
  7015. defaults: {},
  7016. registerScaleType: function (type, scaleConstructor, scaleDefaults) {
  7017. this.constructors[type] = scaleConstructor;
  7018. this.defaults[type] = helpers$1.clone(scaleDefaults);
  7019. },
  7020. getScaleConstructor: function (type) {
  7021. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  7022. },
  7023. getScaleDefaults: function (type) {
  7024. // Return the scale defaults merged with the global settings so that we always use the latest ones
  7025. return this.defaults.hasOwnProperty(type) ? helpers$1.merge(Object.create(null), [core_defaults.scale, this.defaults[type]]) : {};
  7026. },
  7027. updateScaleDefaults: function (type, additions) {
  7028. var me = this;
  7029. if (me.defaults.hasOwnProperty(type)) {
  7030. me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
  7031. }
  7032. },
  7033. addScalesToLayout: function (chart) {
  7034. // Adds each scale to the chart.boxes array to be sized accordingly
  7035. helpers$1.each(chart.scales, function (scale) {
  7036. // Set ILayoutItem parameters for backwards compatibility
  7037. scale.fullWidth = scale.options.fullWidth;
  7038. scale.position = scale.options.position;
  7039. scale.weight = scale.options.weight;
  7040. core_layouts.addBox(chart, scale);
  7041. });
  7042. }
  7043. };
  7044. var valueOrDefault$8 = helpers$1.valueOrDefault;
  7045. var getRtlHelper = helpers$1.rtl.getRtlAdapter;
  7046. core_defaults._set('global', {
  7047. tooltips: {
  7048. enabled: true,
  7049. custom: null,
  7050. mode: 'nearest',
  7051. position: 'average',
  7052. intersect: true,
  7053. backgroundColor: 'rgba(0,0,0,0.8)',
  7054. titleFontStyle: 'bold',
  7055. titleSpacing: 2,
  7056. titleMarginBottom: 6,
  7057. titleFontColor: '#fff',
  7058. titleAlign: 'left',
  7059. bodySpacing: 2,
  7060. bodyFontColor: '#fff',
  7061. bodyAlign: 'left',
  7062. footerFontStyle: 'bold',
  7063. footerSpacing: 2,
  7064. footerMarginTop: 6,
  7065. footerFontColor: '#fff',
  7066. footerAlign: 'left',
  7067. yPadding: 6,
  7068. xPadding: 6,
  7069. caretPadding: 2,
  7070. caretSize: 5,
  7071. cornerRadius: 6,
  7072. multiKeyBackground: '#fff',
  7073. displayColors: true,
  7074. borderColor: 'rgba(0,0,0,0)',
  7075. borderWidth: 0,
  7076. callbacks: {
  7077. // Args are: (tooltipItems, data)
  7078. beforeTitle: helpers$1.noop,
  7079. title: function (tooltipItems, data) {
  7080. var title = '';
  7081. var labels = data.labels;
  7082. var labelCount = labels ? labels.length : 0;
  7083. if (tooltipItems.length > 0) {
  7084. var item = tooltipItems[0];
  7085. if (item.label) {
  7086. title = item.label;
  7087. } else if (item.xLabel) {
  7088. title = item.xLabel;
  7089. } else if (labelCount > 0 && item.index < labelCount) {
  7090. title = labels[item.index];
  7091. }
  7092. }
  7093. return title;
  7094. },
  7095. afterTitle: helpers$1.noop,
  7096. // Args are: (tooltipItems, data)
  7097. beforeBody: helpers$1.noop,
  7098. // Args are: (tooltipItem, data)
  7099. beforeLabel: helpers$1.noop,
  7100. label: function (tooltipItem, data) {
  7101. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  7102. if (label) {
  7103. label += ': ';
  7104. }
  7105. if (!helpers$1.isNullOrUndef(tooltipItem.value)) {
  7106. label += tooltipItem.value;
  7107. } else {
  7108. label += tooltipItem.yLabel;
  7109. }
  7110. return label;
  7111. },
  7112. labelColor: function (tooltipItem, chart) {
  7113. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  7114. var activeElement = meta.data[tooltipItem.index];
  7115. var view = activeElement._view;
  7116. return {
  7117. borderColor: view.borderColor,
  7118. backgroundColor: view.backgroundColor
  7119. };
  7120. },
  7121. labelTextColor: function () {
  7122. return this._options.bodyFontColor;
  7123. },
  7124. afterLabel: helpers$1.noop,
  7125. // Args are: (tooltipItems, data)
  7126. afterBody: helpers$1.noop,
  7127. // Args are: (tooltipItems, data)
  7128. beforeFooter: helpers$1.noop,
  7129. footer: helpers$1.noop,
  7130. afterFooter: helpers$1.noop
  7131. }
  7132. }
  7133. });
  7134. var positioners = {
  7135. /**
  7136. * Average mode places the tooltip at the average position of the elements shown
  7137. * @function Chart.Tooltip.positioners.average
  7138. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  7139. * @returns {object} tooltip position
  7140. */
  7141. average: function (elements) {
  7142. if (!elements.length) {
  7143. return false;
  7144. }
  7145. var i, len;
  7146. var x = 0;
  7147. var y = 0;
  7148. var count = 0;
  7149. for (i = 0, len = elements.length; i < len; ++i) {
  7150. var el = elements[i];
  7151. if (el && el.hasValue()) {
  7152. var pos = el.tooltipPosition();
  7153. x += pos.x;
  7154. y += pos.y;
  7155. ++count;
  7156. }
  7157. }
  7158. return {
  7159. x: x / count,
  7160. y: y / count
  7161. };
  7162. },
  7163. /**
  7164. * Gets the tooltip position nearest of the item nearest to the event position
  7165. * @function Chart.Tooltip.positioners.nearest
  7166. * @param elements {Chart.Element[]} the tooltip elements
  7167. * @param eventPosition {object} the position of the event in canvas coordinates
  7168. * @returns {object} the tooltip position
  7169. */
  7170. nearest: function (elements, eventPosition) {
  7171. var x = eventPosition.x;
  7172. var y = eventPosition.y;
  7173. var minDistance = Number.POSITIVE_INFINITY;
  7174. var i, len, nearestElement;
  7175. for (i = 0, len = elements.length; i < len; ++i) {
  7176. var el = elements[i];
  7177. if (el && el.hasValue()) {
  7178. var center = el.getCenterPoint();
  7179. var d = helpers$1.distanceBetweenPoints(eventPosition, center);
  7180. if (d < minDistance) {
  7181. minDistance = d;
  7182. nearestElement = el;
  7183. }
  7184. }
  7185. }
  7186. if (nearestElement) {
  7187. var tp = nearestElement.tooltipPosition();
  7188. x = tp.x;
  7189. y = tp.y;
  7190. }
  7191. return {
  7192. x: x,
  7193. y: y
  7194. };
  7195. }
  7196. };
  7197. // Helper to push or concat based on if the 2nd parameter is an array or not
  7198. function pushOrConcat(base, toPush) {
  7199. if (toPush) {
  7200. if (helpers$1.isArray(toPush)) {
  7201. // base = base.concat(toPush);
  7202. Array.prototype.push.apply(base, toPush);
  7203. } else {
  7204. base.push(toPush);
  7205. }
  7206. }
  7207. return base;
  7208. }
  7209. /**
  7210. * Returns array of strings split by newline
  7211. * @param {string} value - The value to split by newline.
  7212. * @returns {string[]} value if newline present - Returned from String split() method
  7213. * @function
  7214. */
  7215. function splitNewlines(str) {
  7216. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  7217. return str.split('\n');
  7218. }
  7219. return str;
  7220. }
  7221. /**
  7222. * Private helper to create a tooltip item model
  7223. * @param element - the chart element (point, arc, bar) to create the tooltip item for
  7224. * @return new tooltip item
  7225. */
  7226. function createTooltipItem(element) {
  7227. var xScale = element._xScale;
  7228. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  7229. var index = element._index;
  7230. var datasetIndex = element._datasetIndex;
  7231. var controller = element._chart.getDatasetMeta(datasetIndex).controller;
  7232. var indexScale = controller._getIndexScale();
  7233. var valueScale = controller._getValueScale();
  7234. return {
  7235. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  7236. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  7237. label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',
  7238. value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',
  7239. index: index,
  7240. datasetIndex: datasetIndex,
  7241. x: element._model.x,
  7242. y: element._model.y
  7243. };
  7244. }
  7245. /**
  7246. * Helper to get the reset model for the tooltip
  7247. * @param tooltipOpts {object} the tooltip options
  7248. */
  7249. function getBaseModel(tooltipOpts) {
  7250. var globalDefaults = core_defaults.global;
  7251. return {
  7252. // Positioning
  7253. xPadding: tooltipOpts.xPadding,
  7254. yPadding: tooltipOpts.yPadding,
  7255. xAlign: tooltipOpts.xAlign,
  7256. yAlign: tooltipOpts.yAlign,
  7257. // Drawing direction and text direction
  7258. rtl: tooltipOpts.rtl,
  7259. textDirection: tooltipOpts.textDirection,
  7260. // Body
  7261. bodyFontColor: tooltipOpts.bodyFontColor,
  7262. _bodyFontFamily: valueOrDefault$8(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  7263. _bodyFontStyle: valueOrDefault$8(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  7264. _bodyAlign: tooltipOpts.bodyAlign,
  7265. bodyFontSize: valueOrDefault$8(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  7266. bodySpacing: tooltipOpts.bodySpacing,
  7267. // Title
  7268. titleFontColor: tooltipOpts.titleFontColor,
  7269. _titleFontFamily: valueOrDefault$8(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  7270. _titleFontStyle: valueOrDefault$8(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  7271. titleFontSize: valueOrDefault$8(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  7272. _titleAlign: tooltipOpts.titleAlign,
  7273. titleSpacing: tooltipOpts.titleSpacing,
  7274. titleMarginBottom: tooltipOpts.titleMarginBottom,
  7275. // Footer
  7276. footerFontColor: tooltipOpts.footerFontColor,
  7277. _footerFontFamily: valueOrDefault$8(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  7278. _footerFontStyle: valueOrDefault$8(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  7279. footerFontSize: valueOrDefault$8(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  7280. _footerAlign: tooltipOpts.footerAlign,
  7281. footerSpacing: tooltipOpts.footerSpacing,
  7282. footerMarginTop: tooltipOpts.footerMarginTop,
  7283. // Appearance
  7284. caretSize: tooltipOpts.caretSize,
  7285. cornerRadius: tooltipOpts.cornerRadius,
  7286. backgroundColor: tooltipOpts.backgroundColor,
  7287. opacity: 0,
  7288. legendColorBackground: tooltipOpts.multiKeyBackground,
  7289. displayColors: tooltipOpts.displayColors,
  7290. borderColor: tooltipOpts.borderColor,
  7291. borderWidth: tooltipOpts.borderWidth
  7292. };
  7293. }
  7294. /**
  7295. * Get the size of the tooltip
  7296. */
  7297. function getTooltipSize(tooltip, model) {
  7298. var ctx = tooltip._chart.ctx;
  7299. var height = model.yPadding * 2; // Tooltip Padding
  7300. var width = 0;
  7301. // Count of all lines in the body
  7302. var body = model.body;
  7303. var combinedBodyLength = body.reduce(function (count, bodyItem) {
  7304. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  7305. }, 0);
  7306. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  7307. var titleLineCount = model.title.length;
  7308. var footerLineCount = model.footer.length;
  7309. var titleFontSize = model.titleFontSize;
  7310. var bodyFontSize = model.bodyFontSize;
  7311. var footerFontSize = model.footerFontSize;
  7312. height += titleLineCount * titleFontSize; // Title Lines
  7313. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  7314. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  7315. height += combinedBodyLength * bodyFontSize; // Body Lines
  7316. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  7317. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  7318. height += footerLineCount * (footerFontSize); // Footer Lines
  7319. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  7320. // Title width
  7321. var widthPadding = 0;
  7322. var maxLineWidth = function (line) {
  7323. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  7324. };
  7325. ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  7326. helpers$1.each(model.title, maxLineWidth);
  7327. // Body width
  7328. ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  7329. helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  7330. // Body lines may include some extra width due to the color box
  7331. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  7332. helpers$1.each(body, function (bodyItem) {
  7333. helpers$1.each(bodyItem.before, maxLineWidth);
  7334. helpers$1.each(bodyItem.lines, maxLineWidth);
  7335. helpers$1.each(bodyItem.after, maxLineWidth);
  7336. });
  7337. // Reset back to 0
  7338. widthPadding = 0;
  7339. // Footer width
  7340. ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  7341. helpers$1.each(model.footer, maxLineWidth);
  7342. // Add padding
  7343. width += 2 * model.xPadding;
  7344. return {
  7345. width: width,
  7346. height: height
  7347. };
  7348. }
  7349. /**
  7350. * Helper to get the alignment of a tooltip given the size
  7351. */
  7352. function determineAlignment(tooltip, size) {
  7353. var model = tooltip._model;
  7354. var chart = tooltip._chart;
  7355. var chartArea = tooltip._chart.chartArea;
  7356. var xAlign = 'center';
  7357. var yAlign = 'center';
  7358. if (model.y < size.height) {
  7359. yAlign = 'top';
  7360. } else if (model.y > (chart.height - size.height)) {
  7361. yAlign = 'bottom';
  7362. }
  7363. var lf, rf; // functions to determine left, right alignment
  7364. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  7365. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  7366. var midX = (chartArea.left + chartArea.right) / 2;
  7367. var midY = (chartArea.top + chartArea.bottom) / 2;
  7368. if (yAlign === 'center') {
  7369. lf = function (x) {
  7370. return x <= midX;
  7371. };
  7372. rf = function (x) {
  7373. return x > midX;
  7374. };
  7375. } else {
  7376. lf = function (x) {
  7377. return x <= (size.width / 2);
  7378. };
  7379. rf = function (x) {
  7380. return x >= (chart.width - (size.width / 2));
  7381. };
  7382. }
  7383. olf = function (x) {
  7384. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  7385. };
  7386. orf = function (x) {
  7387. return x - size.width - model.caretSize - model.caretPadding < 0;
  7388. };
  7389. yf = function (y) {
  7390. return y <= midY ? 'top' : 'bottom';
  7391. };
  7392. if (lf(model.x)) {
  7393. xAlign = 'left';
  7394. // Is tooltip too wide and goes over the right side of the chart.?
  7395. if (olf(model.x)) {
  7396. xAlign = 'center';
  7397. yAlign = yf(model.y);
  7398. }
  7399. } else if (rf(model.x)) {
  7400. xAlign = 'right';
  7401. // Is tooltip too wide and goes outside left edge of canvas?
  7402. if (orf(model.x)) {
  7403. xAlign = 'center';
  7404. yAlign = yf(model.y);
  7405. }
  7406. }
  7407. var opts = tooltip._options;
  7408. return {
  7409. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  7410. yAlign: opts.yAlign ? opts.yAlign : yAlign
  7411. };
  7412. }
  7413. /**
  7414. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  7415. */
  7416. function getBackgroundPoint(vm, size, alignment, chart) {
  7417. // Background Position
  7418. var x = vm.x;
  7419. var y = vm.y;
  7420. var caretSize = vm.caretSize;
  7421. var caretPadding = vm.caretPadding;
  7422. var cornerRadius = vm.cornerRadius;
  7423. var xAlign = alignment.xAlign;
  7424. var yAlign = alignment.yAlign;
  7425. var paddingAndSize = caretSize + caretPadding;
  7426. var radiusAndPadding = cornerRadius + caretPadding;
  7427. if (xAlign === 'right') {
  7428. x -= size.width;
  7429. } else if (xAlign === 'center') {
  7430. x -= (size.width / 2);
  7431. if (x + size.width > chart.width) {
  7432. x = chart.width - size.width;
  7433. }
  7434. if (x < 0) {
  7435. x = 0;
  7436. }
  7437. }
  7438. if (yAlign === 'top') {
  7439. y += paddingAndSize;
  7440. } else if (yAlign === 'bottom') {
  7441. y -= size.height + paddingAndSize;
  7442. } else {
  7443. y -= (size.height / 2);
  7444. }
  7445. if (yAlign === 'center') {
  7446. if (xAlign === 'left') {
  7447. x += paddingAndSize;
  7448. } else if (xAlign === 'right') {
  7449. x -= paddingAndSize;
  7450. }
  7451. } else if (xAlign === 'left') {
  7452. x -= radiusAndPadding;
  7453. } else if (xAlign === 'right') {
  7454. x += radiusAndPadding;
  7455. }
  7456. return {
  7457. x: x,
  7458. y: y
  7459. };
  7460. }
  7461. function getAlignedX(vm, align) {
  7462. return align === 'center'
  7463. ? vm.x + vm.width / 2
  7464. : align === 'right'
  7465. ? vm.x + vm.width - vm.xPadding
  7466. : vm.x + vm.xPadding;
  7467. }
  7468. /**
  7469. * Helper to build before and after body lines
  7470. */
  7471. function getBeforeAfterBodyLines(callback) {
  7472. return pushOrConcat([], splitNewlines(callback));
  7473. }
  7474. var exports$4 = core_element.extend({
  7475. initialize: function () {
  7476. this._model = getBaseModel(this._options);
  7477. this._lastActive = [];
  7478. },
  7479. // Get the title
  7480. // Args are: (tooltipItem, data)
  7481. getTitle: function () {
  7482. var me = this;
  7483. var opts = me._options;
  7484. var callbacks = opts.callbacks;
  7485. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  7486. var title = callbacks.title.apply(me, arguments);
  7487. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  7488. var lines = [];
  7489. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  7490. lines = pushOrConcat(lines, splitNewlines(title));
  7491. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  7492. return lines;
  7493. },
  7494. // Args are: (tooltipItem, data)
  7495. getBeforeBody: function () {
  7496. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  7497. },
  7498. // Args are: (tooltipItem, data)
  7499. getBody: function (tooltipItems, data) {
  7500. var me = this;
  7501. var callbacks = me._options.callbacks;
  7502. var bodyItems = [];
  7503. helpers$1.each(tooltipItems, function (tooltipItem) {
  7504. var bodyItem = {
  7505. before: [],
  7506. lines: [],
  7507. after: []
  7508. };
  7509. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  7510. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  7511. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  7512. bodyItems.push(bodyItem);
  7513. });
  7514. return bodyItems;
  7515. },
  7516. // Args are: (tooltipItem, data)
  7517. getAfterBody: function () {
  7518. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  7519. },
  7520. // Get the footer and beforeFooter and afterFooter lines
  7521. // Args are: (tooltipItem, data)
  7522. getFooter: function () {
  7523. var me = this;
  7524. var callbacks = me._options.callbacks;
  7525. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  7526. var footer = callbacks.footer.apply(me, arguments);
  7527. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  7528. var lines = [];
  7529. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  7530. lines = pushOrConcat(lines, splitNewlines(footer));
  7531. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  7532. return lines;
  7533. },
  7534. update: function (changed) {
  7535. var me = this;
  7536. var opts = me._options;
  7537. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  7538. // that does _view = _model if ease === 1. This causes the 2nd tooltip update to set properties in both the view and model at the same time
  7539. // which breaks any animations.
  7540. var existingModel = me._model;
  7541. var model = me._model = getBaseModel(opts);
  7542. var active = me._active;
  7543. var data = me._data;
  7544. // In the case where active.length === 0 we need to keep these at existing values for good animations
  7545. var alignment = {
  7546. xAlign: existingModel.xAlign,
  7547. yAlign: existingModel.yAlign
  7548. };
  7549. var backgroundPoint = {
  7550. x: existingModel.x,
  7551. y: existingModel.y
  7552. };
  7553. var tooltipSize = {
  7554. width: existingModel.width,
  7555. height: existingModel.height
  7556. };
  7557. var tooltipPosition = {
  7558. x: existingModel.caretX,
  7559. y: existingModel.caretY
  7560. };
  7561. var i, len;
  7562. if (active.length) {
  7563. model.opacity = 1;
  7564. var labelColors = [];
  7565. var labelTextColors = [];
  7566. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  7567. var tooltipItems = [];
  7568. for (i = 0, len = active.length; i < len; ++i) {
  7569. tooltipItems.push(createTooltipItem(active[i]));
  7570. }
  7571. // If the user provided a filter function, use it to modify the tooltip items
  7572. if (opts.filter) {
  7573. tooltipItems = tooltipItems.filter(function (a) {
  7574. return opts.filter(a, data);
  7575. });
  7576. }
  7577. // If the user provided a sorting function, use it to modify the tooltip items
  7578. if (opts.itemSort) {
  7579. tooltipItems = tooltipItems.sort(function (a, b) {
  7580. return opts.itemSort(a, b, data);
  7581. });
  7582. }
  7583. // Determine colors for boxes
  7584. helpers$1.each(tooltipItems, function (tooltipItem) {
  7585. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  7586. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  7587. });
  7588. // Build the Text Lines
  7589. model.title = me.getTitle(tooltipItems, data);
  7590. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  7591. model.body = me.getBody(tooltipItems, data);
  7592. model.afterBody = me.getAfterBody(tooltipItems, data);
  7593. model.footer = me.getFooter(tooltipItems, data);
  7594. // Initial positioning and colors
  7595. model.x = tooltipPosition.x;
  7596. model.y = tooltipPosition.y;
  7597. model.caretPadding = opts.caretPadding;
  7598. model.labelColors = labelColors;
  7599. model.labelTextColors = labelTextColors;
  7600. // data points
  7601. model.dataPoints = tooltipItems;
  7602. // We need to determine alignment of the tooltip
  7603. tooltipSize = getTooltipSize(this, model);
  7604. alignment = determineAlignment(this, tooltipSize);
  7605. // Final Size and Position
  7606. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  7607. } else {
  7608. model.opacity = 0;
  7609. }
  7610. model.xAlign = alignment.xAlign;
  7611. model.yAlign = alignment.yAlign;
  7612. model.x = backgroundPoint.x;
  7613. model.y = backgroundPoint.y;
  7614. model.width = tooltipSize.width;
  7615. model.height = tooltipSize.height;
  7616. // Point where the caret on the tooltip points to
  7617. model.caretX = tooltipPosition.x;
  7618. model.caretY = tooltipPosition.y;
  7619. me._model = model;
  7620. if (changed && opts.custom) {
  7621. opts.custom.call(me, model);
  7622. }
  7623. return me;
  7624. },
  7625. drawCaret: function (tooltipPoint, size) {
  7626. var ctx = this._chart.ctx;
  7627. var vm = this._view;
  7628. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  7629. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  7630. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  7631. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  7632. },
  7633. getCaretPosition: function (tooltipPoint, size, vm) {
  7634. var x1, x2, x3, y1, y2, y3;
  7635. var caretSize = vm.caretSize;
  7636. var cornerRadius = vm.cornerRadius;
  7637. var xAlign = vm.xAlign;
  7638. var yAlign = vm.yAlign;
  7639. var ptX = tooltipPoint.x;
  7640. var ptY = tooltipPoint.y;
  7641. var width = size.width;
  7642. var height = size.height;
  7643. if (yAlign === 'center') {
  7644. y2 = ptY + (height / 2);
  7645. if (xAlign === 'left') {
  7646. x1 = ptX;
  7647. x2 = x1 - caretSize;
  7648. x3 = x1;
  7649. y1 = y2 + caretSize;
  7650. y3 = y2 - caretSize;
  7651. } else {
  7652. x1 = ptX + width;
  7653. x2 = x1 + caretSize;
  7654. x3 = x1;
  7655. y1 = y2 - caretSize;
  7656. y3 = y2 + caretSize;
  7657. }
  7658. } else {
  7659. if (xAlign === 'left') {
  7660. x2 = ptX + cornerRadius + (caretSize);
  7661. x1 = x2 - caretSize;
  7662. x3 = x2 + caretSize;
  7663. } else if (xAlign === 'right') {
  7664. x2 = ptX + width - cornerRadius - caretSize;
  7665. x1 = x2 - caretSize;
  7666. x3 = x2 + caretSize;
  7667. } else {
  7668. x2 = vm.caretX;
  7669. x1 = x2 - caretSize;
  7670. x3 = x2 + caretSize;
  7671. }
  7672. if (yAlign === 'top') {
  7673. y1 = ptY;
  7674. y2 = y1 - caretSize;
  7675. y3 = y1;
  7676. } else {
  7677. y1 = ptY + height;
  7678. y2 = y1 + caretSize;
  7679. y3 = y1;
  7680. // invert drawing order
  7681. var tmp = x3;
  7682. x3 = x1;
  7683. x1 = tmp;
  7684. }
  7685. }
  7686. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  7687. },
  7688. drawTitle: function (pt, vm, ctx) {
  7689. var title = vm.title;
  7690. var length = title.length;
  7691. var titleFontSize, titleSpacing, i;
  7692. if (length) {
  7693. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7694. pt.x = getAlignedX(vm, vm._titleAlign);
  7695. ctx.textAlign = rtlHelper.textAlign(vm._titleAlign);
  7696. ctx.textBaseline = 'middle';
  7697. titleFontSize = vm.titleFontSize;
  7698. titleSpacing = vm.titleSpacing;
  7699. ctx.fillStyle = vm.titleFontColor;
  7700. ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  7701. for (i = 0; i < length; ++i) {
  7702. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFontSize / 2);
  7703. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  7704. if (i + 1 === length) {
  7705. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  7706. }
  7707. }
  7708. }
  7709. },
  7710. drawBody: function (pt, vm, ctx) {
  7711. var bodyFontSize = vm.bodyFontSize;
  7712. var bodySpacing = vm.bodySpacing;
  7713. var bodyAlign = vm._bodyAlign;
  7714. var body = vm.body;
  7715. var drawColorBoxes = vm.displayColors;
  7716. var xLinePadding = 0;
  7717. var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
  7718. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7719. var fillLineOfText = function (line) {
  7720. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyFontSize / 2);
  7721. pt.y += bodyFontSize + bodySpacing;
  7722. };
  7723. var bodyItem, textColor, labelColors, lines, i, j, ilen, jlen;
  7724. var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  7725. ctx.textAlign = bodyAlign;
  7726. ctx.textBaseline = 'middle';
  7727. ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  7728. pt.x = getAlignedX(vm, bodyAlignForCalculation);
  7729. // Before body lines
  7730. ctx.fillStyle = vm.bodyFontColor;
  7731. helpers$1.each(vm.beforeBody, fillLineOfText);
  7732. xLinePadding = drawColorBoxes && bodyAlignForCalculation !== 'right'
  7733. ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
  7734. : 0;
  7735. // Draw body lines now
  7736. for (i = 0, ilen = body.length; i < ilen; ++i) {
  7737. bodyItem = body[i];
  7738. textColor = vm.labelTextColors[i];
  7739. labelColors = vm.labelColors[i];
  7740. ctx.fillStyle = textColor;
  7741. helpers$1.each(bodyItem.before, fillLineOfText);
  7742. lines = bodyItem.lines;
  7743. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  7744. // Draw Legend-like boxes if needed
  7745. if (drawColorBoxes) {
  7746. var rtlColorX = rtlHelper.x(colorX);
  7747. // Fill a white rect so that colours merge nicely if the opacity is < 1
  7748. ctx.fillStyle = vm.legendColorBackground;
  7749. ctx.fillRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7750. // Border
  7751. ctx.lineWidth = 1;
  7752. ctx.strokeStyle = labelColors.borderColor;
  7753. ctx.strokeRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7754. // Inner square
  7755. ctx.fillStyle = labelColors.backgroundColor;
  7756. ctx.fillRect(rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), bodyFontSize - 2), pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  7757. ctx.fillStyle = textColor;
  7758. }
  7759. fillLineOfText(lines[j]);
  7760. }
  7761. helpers$1.each(bodyItem.after, fillLineOfText);
  7762. }
  7763. // Reset back to 0 for after body
  7764. xLinePadding = 0;
  7765. // After body lines
  7766. helpers$1.each(vm.afterBody, fillLineOfText);
  7767. pt.y -= bodySpacing; // Remove last body spacing
  7768. },
  7769. drawFooter: function (pt, vm, ctx) {
  7770. var footer = vm.footer;
  7771. var length = footer.length;
  7772. var footerFontSize, i;
  7773. if (length) {
  7774. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7775. pt.x = getAlignedX(vm, vm._footerAlign);
  7776. pt.y += vm.footerMarginTop;
  7777. ctx.textAlign = rtlHelper.textAlign(vm._footerAlign);
  7778. ctx.textBaseline = 'middle';
  7779. footerFontSize = vm.footerFontSize;
  7780. ctx.fillStyle = vm.footerFontColor;
  7781. ctx.font = helpers$1.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  7782. for (i = 0; i < length; ++i) {
  7783. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFontSize / 2);
  7784. pt.y += footerFontSize + vm.footerSpacing;
  7785. }
  7786. }
  7787. },
  7788. drawBackground: function (pt, vm, ctx, tooltipSize) {
  7789. ctx.fillStyle = vm.backgroundColor;
  7790. ctx.strokeStyle = vm.borderColor;
  7791. ctx.lineWidth = vm.borderWidth;
  7792. var xAlign = vm.xAlign;
  7793. var yAlign = vm.yAlign;
  7794. var x = pt.x;
  7795. var y = pt.y;
  7796. var width = tooltipSize.width;
  7797. var height = tooltipSize.height;
  7798. var radius = vm.cornerRadius;
  7799. ctx.beginPath();
  7800. ctx.moveTo(x + radius, y);
  7801. if (yAlign === 'top') {
  7802. this.drawCaret(pt, tooltipSize);
  7803. }
  7804. ctx.lineTo(x + width - radius, y);
  7805. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  7806. if (yAlign === 'center' && xAlign === 'right') {
  7807. this.drawCaret(pt, tooltipSize);
  7808. }
  7809. ctx.lineTo(x + width, y + height - radius);
  7810. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  7811. if (yAlign === 'bottom') {
  7812. this.drawCaret(pt, tooltipSize);
  7813. }
  7814. ctx.lineTo(x + radius, y + height);
  7815. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  7816. if (yAlign === 'center' && xAlign === 'left') {
  7817. this.drawCaret(pt, tooltipSize);
  7818. }
  7819. ctx.lineTo(x, y + radius);
  7820. ctx.quadraticCurveTo(x, y, x + radius, y);
  7821. ctx.closePath();
  7822. ctx.fill();
  7823. if (vm.borderWidth > 0) {
  7824. ctx.stroke();
  7825. }
  7826. },
  7827. draw: function () {
  7828. var ctx = this._chart.ctx;
  7829. var vm = this._view;
  7830. if (vm.opacity === 0) {
  7831. return;
  7832. }
  7833. var tooltipSize = {
  7834. width: vm.width,
  7835. height: vm.height
  7836. };
  7837. var pt = {
  7838. x: vm.x,
  7839. y: vm.y
  7840. };
  7841. // IE11/Edge does not like very small opacities, so snap to 0
  7842. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  7843. // Truthy/falsey value for empty tooltip
  7844. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  7845. if (this._options.enabled && hasTooltipContent) {
  7846. ctx.save();
  7847. ctx.globalAlpha = opacity;
  7848. // Draw Background
  7849. this.drawBackground(pt, vm, ctx, tooltipSize);
  7850. // Draw Title, Body, and Footer
  7851. pt.y += vm.yPadding;
  7852. helpers$1.rtl.overrideTextDirection(ctx, vm.textDirection);
  7853. // Titles
  7854. this.drawTitle(pt, vm, ctx);
  7855. // Body
  7856. this.drawBody(pt, vm, ctx);
  7857. // Footer
  7858. this.drawFooter(pt, vm, ctx);
  7859. helpers$1.rtl.restoreTextDirection(ctx, vm.textDirection);
  7860. ctx.restore();
  7861. }
  7862. },
  7863. /**
  7864. * Handle an event
  7865. * @private
  7866. * @param {IEvent} event - The event to handle
  7867. * @returns {boolean} true if the tooltip changed
  7868. */
  7869. handleEvent: function (e) {
  7870. var me = this;
  7871. var options = me._options;
  7872. var changed = false;
  7873. me._lastActive = me._lastActive || [];
  7874. // Find Active Elements for tooltips
  7875. if (e.type === 'mouseout') {
  7876. me._active = [];
  7877. } else {
  7878. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  7879. if (options.reverse) {
  7880. me._active.reverse();
  7881. }
  7882. }
  7883. // Remember Last Actives
  7884. changed = !helpers$1.arrayEquals(me._active, me._lastActive);
  7885. // Only handle target event on tooltip change
  7886. if (changed) {
  7887. me._lastActive = me._active;
  7888. if (options.enabled || options.custom) {
  7889. me._eventPosition = {
  7890. x: e.x,
  7891. y: e.y
  7892. };
  7893. me.update(true);
  7894. me.pivot();
  7895. }
  7896. }
  7897. return changed;
  7898. }
  7899. });
  7900. /**
  7901. * @namespace Chart.Tooltip.positioners
  7902. */
  7903. var positioners_1 = positioners;
  7904. var core_tooltip = exports$4;
  7905. core_tooltip.positioners = positioners_1;
  7906. var valueOrDefault$9 = helpers$1.valueOrDefault;
  7907. core_defaults._set('global', {
  7908. elements: {},
  7909. events: [
  7910. 'mousemove',
  7911. 'mouseout',
  7912. 'click',
  7913. 'touchstart',
  7914. 'touchmove'
  7915. ],
  7916. hover: {
  7917. onHover: null,
  7918. mode: 'nearest',
  7919. intersect: true,
  7920. animationDuration: 400
  7921. },
  7922. onClick: null,
  7923. maintainAspectRatio: true,
  7924. responsive: true,
  7925. responsiveAnimationDuration: 0
  7926. });
  7927. /**
  7928. * Recursively merge the given config objects representing the `scales` option
  7929. * by incorporating scale defaults in `xAxes` and `yAxes` array items, then
  7930. * returns a deep copy of the result, thus doesn't alter inputs.
  7931. */
  7932. function mergeScaleConfig(/* config objects ... */) {
  7933. return helpers$1.merge(Object.create(null), [].slice.call(arguments), {
  7934. merger: function (key, target, source, options) {
  7935. if (key === 'xAxes' || key === 'yAxes') {
  7936. var slen = source[key].length;
  7937. var i, type, scale;
  7938. if (!target[key]) {
  7939. target[key] = [];
  7940. }
  7941. for (i = 0; i < slen; ++i) {
  7942. scale = source[key][i];
  7943. type = valueOrDefault$9(scale.type, key === 'xAxes' ? 'category' : 'linear');
  7944. if (i >= target[key].length) {
  7945. target[key].push({});
  7946. }
  7947. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  7948. // new/untyped scale or type changed: let's apply the new defaults
  7949. // then merge source scale to correctly overwrite the defaults.
  7950. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
  7951. } else {
  7952. // scales type are the same
  7953. helpers$1.merge(target[key][i], scale);
  7954. }
  7955. }
  7956. } else {
  7957. helpers$1._merger(key, target, source, options);
  7958. }
  7959. }
  7960. });
  7961. }
  7962. /**
  7963. * Recursively merge the given config objects as the root options by handling
  7964. * default scale options for the `scales` and `scale` properties, then returns
  7965. * a deep copy of the result, thus doesn't alter inputs.
  7966. */
  7967. function mergeConfig(/* config objects ... */) {
  7968. return helpers$1.merge(Object.create(null), [].slice.call(arguments), {
  7969. merger: function (key, target, source, options) {
  7970. var tval = target[key] || Object.create(null);
  7971. var sval = source[key];
  7972. if (key === 'scales') {
  7973. // scale config merging is complex. Add our own function here for that
  7974. target[key] = mergeScaleConfig(tval, sval);
  7975. } else if (key === 'scale') {
  7976. // used in polar area & radar charts since there is only one scale
  7977. target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
  7978. } else {
  7979. helpers$1._merger(key, target, source, options);
  7980. }
  7981. }
  7982. });
  7983. }
  7984. function initConfig(config) {
  7985. config = config || Object.create(null);
  7986. // Do NOT use mergeConfig for the data object because this method merges arrays
  7987. // and so would change references to labels and datasets, preventing data updates.
  7988. var data = config.data = config.data || {};
  7989. data.datasets = data.datasets || [];
  7990. data.labels = data.labels || [];
  7991. config.options = mergeConfig(
  7992. core_defaults.global,
  7993. core_defaults[config.type],
  7994. config.options || {});
  7995. return config;
  7996. }
  7997. function updateConfig(chart) {
  7998. var newOptions = chart.options;
  7999. helpers$1.each(chart.scales, function (scale) {
  8000. core_layouts.removeBox(chart, scale);
  8001. });
  8002. newOptions = mergeConfig(
  8003. core_defaults.global,
  8004. core_defaults[chart.config.type],
  8005. newOptions);
  8006. chart.options = chart.config.options = newOptions;
  8007. chart.ensureScalesHaveIDs();
  8008. chart.buildOrUpdateScales();
  8009. // Tooltip
  8010. chart.tooltip._options = newOptions.tooltips;
  8011. chart.tooltip.initialize();
  8012. }
  8013. function nextAvailableScaleId(axesOpts, prefix, index) {
  8014. var id;
  8015. var hasId = function (obj) {
  8016. return obj.id === id;
  8017. };
  8018. do {
  8019. id = prefix + index++;
  8020. } while (helpers$1.findIndex(axesOpts, hasId) >= 0);
  8021. return id;
  8022. }
  8023. function positionIsHorizontal(position) {
  8024. return position === 'top' || position === 'bottom';
  8025. }
  8026. function compare2Level(l1, l2) {
  8027. return function (a, b) {
  8028. return a[l1] === b[l1]
  8029. ? a[l2] - b[l2]
  8030. : a[l1] - b[l1];
  8031. };
  8032. }
  8033. var Chart = function (item, config) {
  8034. this.construct(item, config);
  8035. return this;
  8036. };
  8037. helpers$1.extend(Chart.prototype, /** @lends Chart */ {
  8038. /**
  8039. * @private
  8040. */
  8041. construct: function (item, config) {
  8042. var me = this;
  8043. config = initConfig(config);
  8044. var context = platform.acquireContext(item, config);
  8045. var canvas = context && context.canvas;
  8046. var height = canvas && canvas.height;
  8047. var width = canvas && canvas.width;
  8048. me.id = helpers$1.uid();
  8049. me.ctx = context;
  8050. me.canvas = canvas;
  8051. me.config = config;
  8052. me.width = width;
  8053. me.height = height;
  8054. me.aspectRatio = height ? width / height : null;
  8055. me.options = config.options;
  8056. me._bufferedRender = false;
  8057. me._layers = [];
  8058. /**
  8059. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  8060. * the "instance" still need to be defined since it might be called from plugins.
  8061. * @prop Chart#chart
  8062. * @deprecated since version 2.6.0
  8063. * @todo remove at version 3
  8064. * @private
  8065. */
  8066. me.chart = me;
  8067. me.controller = me; // chart.chart.controller #inception
  8068. // Add the chart instance to the global namespace
  8069. Chart.instances[me.id] = me;
  8070. // Define alias to the config data: `chart.data === chart.config.data`
  8071. Object.defineProperty(me, 'data', {
  8072. get: function () {
  8073. return me.config.data;
  8074. },
  8075. set: function (value) {
  8076. me.config.data = value;
  8077. }
  8078. });
  8079. if (!context || !canvas) {
  8080. // The given item is not a compatible context2d element, let's return before finalizing
  8081. // the chart initialization but after setting basic chart / controller properties that
  8082. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  8083. // https://github.com/chartjs/Chart.js/issues/2807
  8084. console.error("Failed to create chart: can't acquire context from the given item");
  8085. return;
  8086. }
  8087. me.initialize();
  8088. me.update();
  8089. },
  8090. /**
  8091. * @private
  8092. */
  8093. initialize: function () {
  8094. var me = this;
  8095. // Before init plugin notification
  8096. core_plugins.notify(me, 'beforeInit');
  8097. helpers$1.retinaScale(me, me.options.devicePixelRatio);
  8098. me.bindEvents();
  8099. if (me.options.responsive) {
  8100. // Initial resize before chart draws (must be silent to preserve initial animations).
  8101. me.resize(true);
  8102. }
  8103. me.initToolTip();
  8104. // After init plugin notification
  8105. core_plugins.notify(me, 'afterInit');
  8106. return me;
  8107. },
  8108. clear: function () {
  8109. helpers$1.canvas.clear(this);
  8110. return this;
  8111. },
  8112. stop: function () {
  8113. // Stops any current animation loop occurring
  8114. core_animations.cancelAnimation(this);
  8115. return this;
  8116. },
  8117. resize: function (silent) {
  8118. var me = this;
  8119. var options = me.options;
  8120. var canvas = me.canvas;
  8121. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  8122. // the canvas render width and height will be casted to integers so make sure that
  8123. // the canvas display style uses the same integer values to avoid blurring effect.
  8124. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  8125. var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
  8126. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
  8127. if (me.width === newWidth && me.height === newHeight) {
  8128. return;
  8129. }
  8130. canvas.width = me.width = newWidth;
  8131. canvas.height = me.height = newHeight;
  8132. canvas.style.width = newWidth + 'px';
  8133. canvas.style.height = newHeight + 'px';
  8134. helpers$1.retinaScale(me, options.devicePixelRatio);
  8135. if (!silent) {
  8136. // Notify any plugins about the resize
  8137. var newSize = {width: newWidth, height: newHeight};
  8138. core_plugins.notify(me, 'resize', [newSize]);
  8139. // Notify of resize
  8140. if (options.onResize) {
  8141. options.onResize(me, newSize);
  8142. }
  8143. me.stop();
  8144. me.update({
  8145. duration: options.responsiveAnimationDuration
  8146. });
  8147. }
  8148. },
  8149. ensureScalesHaveIDs: function () {
  8150. var options = this.options;
  8151. var scalesOptions = options.scales || {};
  8152. var scaleOptions = options.scale;
  8153. helpers$1.each(scalesOptions.xAxes, function (xAxisOptions, index) {
  8154. if (!xAxisOptions.id) {
  8155. xAxisOptions.id = nextAvailableScaleId(scalesOptions.xAxes, 'x-axis-', index);
  8156. }
  8157. });
  8158. helpers$1.each(scalesOptions.yAxes, function (yAxisOptions, index) {
  8159. if (!yAxisOptions.id) {
  8160. yAxisOptions.id = nextAvailableScaleId(scalesOptions.yAxes, 'y-axis-', index);
  8161. }
  8162. });
  8163. if (scaleOptions) {
  8164. scaleOptions.id = scaleOptions.id || 'scale';
  8165. }
  8166. },
  8167. /**
  8168. * Builds a map of scale ID to scale object for future lookup.
  8169. */
  8170. buildOrUpdateScales: function () {
  8171. var me = this;
  8172. var options = me.options;
  8173. var scales = me.scales || {};
  8174. var items = [];
  8175. var updated = Object.keys(scales).reduce(function (obj, id) {
  8176. obj[id] = false;
  8177. return obj;
  8178. }, {});
  8179. if (options.scales) {
  8180. items = items.concat(
  8181. (options.scales.xAxes || []).map(function (xAxisOptions) {
  8182. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  8183. }),
  8184. (options.scales.yAxes || []).map(function (yAxisOptions) {
  8185. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  8186. })
  8187. );
  8188. }
  8189. if (options.scale) {
  8190. items.push({
  8191. options: options.scale,
  8192. dtype: 'radialLinear',
  8193. isDefault: true,
  8194. dposition: 'chartArea'
  8195. });
  8196. }
  8197. helpers$1.each(items, function (item) {
  8198. var scaleOptions = item.options;
  8199. var id = scaleOptions.id;
  8200. var scaleType = valueOrDefault$9(scaleOptions.type, item.dtype);
  8201. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  8202. scaleOptions.position = item.dposition;
  8203. }
  8204. updated[id] = true;
  8205. var scale = null;
  8206. if (id in scales && scales[id].type === scaleType) {
  8207. scale = scales[id];
  8208. scale.options = scaleOptions;
  8209. scale.ctx = me.ctx;
  8210. scale.chart = me;
  8211. } else {
  8212. var scaleClass = core_scaleService.getScaleConstructor(scaleType);
  8213. if (!scaleClass) {
  8214. return;
  8215. }
  8216. scale = new scaleClass({
  8217. id: id,
  8218. type: scaleType,
  8219. options: scaleOptions,
  8220. ctx: me.ctx,
  8221. chart: me
  8222. });
  8223. scales[scale.id] = scale;
  8224. }
  8225. scale.mergeTicksOptions();
  8226. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  8227. // and consider it as a regular scale part of the "scales"" map only! This would
  8228. // make the logic easier and remove some useless? custom code.
  8229. if (item.isDefault) {
  8230. me.scale = scale;
  8231. }
  8232. });
  8233. // clear up discarded scales
  8234. helpers$1.each(updated, function (hasUpdated, id) {
  8235. if (!hasUpdated) {
  8236. delete scales[id];
  8237. }
  8238. });
  8239. me.scales = scales;
  8240. core_scaleService.addScalesToLayout(this);
  8241. },
  8242. buildOrUpdateControllers: function () {
  8243. var me = this;
  8244. var newControllers = [];
  8245. var datasets = me.data.datasets;
  8246. var i, ilen;
  8247. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  8248. var dataset = datasets[i];
  8249. var meta = me.getDatasetMeta(i);
  8250. var type = dataset.type || me.config.type;
  8251. if (meta.type && meta.type !== type) {
  8252. me.destroyDatasetMeta(i);
  8253. meta = me.getDatasetMeta(i);
  8254. }
  8255. meta.type = type;
  8256. meta.order = dataset.order || 0;
  8257. meta.index = i;
  8258. if (meta.controller) {
  8259. meta.controller.updateIndex(i);
  8260. meta.controller.linkScales();
  8261. } else {
  8262. var ControllerClass = controllers[meta.type];
  8263. if (ControllerClass === undefined) {
  8264. throw new Error('"' + meta.type + '" is not a chart type.');
  8265. }
  8266. meta.controller = new ControllerClass(me, i);
  8267. newControllers.push(meta.controller);
  8268. }
  8269. }
  8270. return newControllers;
  8271. },
  8272. /**
  8273. * Reset the elements of all datasets
  8274. * @private
  8275. */
  8276. resetElements: function () {
  8277. var me = this;
  8278. helpers$1.each(me.data.datasets, function (dataset, datasetIndex) {
  8279. me.getDatasetMeta(datasetIndex).controller.reset();
  8280. }, me);
  8281. },
  8282. /**
  8283. * Resets the chart back to it's state before the initial animation
  8284. */
  8285. reset: function () {
  8286. this.resetElements();
  8287. this.tooltip.initialize();
  8288. },
  8289. update: function (config) {
  8290. var me = this;
  8291. var i, ilen;
  8292. if (!config || typeof config !== 'object') {
  8293. // backwards compatibility
  8294. config = {
  8295. duration: config,
  8296. lazy: arguments[1]
  8297. };
  8298. }
  8299. updateConfig(me);
  8300. // plugins options references might have change, let's invalidate the cache
  8301. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  8302. core_plugins._invalidate(me);
  8303. if (core_plugins.notify(me, 'beforeUpdate') === false) {
  8304. return;
  8305. }
  8306. // In case the entire data object changed
  8307. me.tooltip._data = me.data;
  8308. // Make sure dataset controllers are updated and new controllers are reset
  8309. var newControllers = me.buildOrUpdateControllers();
  8310. // Make sure all dataset controllers have correct meta data counts
  8311. for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
  8312. me.getDatasetMeta(i).controller.buildOrUpdateElements();
  8313. }
  8314. me.updateLayout();
  8315. // Can only reset the new controllers after the scales have been updated
  8316. if (me.options.animation && me.options.animation.duration) {
  8317. helpers$1.each(newControllers, function (controller) {
  8318. controller.reset();
  8319. });
  8320. }
  8321. me.updateDatasets();
  8322. // Need to reset tooltip in case it is displayed with elements that are removed
  8323. // after update.
  8324. me.tooltip.initialize();
  8325. // Last active contains items that were previously in the tooltip.
  8326. // When we reset the tooltip, we need to clear it
  8327. me.lastActive = [];
  8328. // Do this before render so that any plugins that need final scale updates can use it
  8329. core_plugins.notify(me, 'afterUpdate');
  8330. me._layers.sort(compare2Level('z', '_idx'));
  8331. if (me._bufferedRender) {
  8332. me._bufferedRequest = {
  8333. duration: config.duration,
  8334. easing: config.easing,
  8335. lazy: config.lazy
  8336. };
  8337. } else {
  8338. me.render(config);
  8339. }
  8340. },
  8341. /**
  8342. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  8343. * hook, in which case, plugins will not be called on `afterLayout`.
  8344. * @private
  8345. */
  8346. updateLayout: function () {
  8347. var me = this;
  8348. if (core_plugins.notify(me, 'beforeLayout') === false) {
  8349. return;
  8350. }
  8351. core_layouts.update(this, this.width, this.height);
  8352. me._layers = [];
  8353. helpers$1.each(me.boxes, function (box) {
  8354. // _configure is called twice, once in core.scale.update and once here.
  8355. // Here the boxes are fully updated and at their final positions.
  8356. if (box._configure) {
  8357. box._configure();
  8358. }
  8359. me._layers.push.apply(me._layers, box._layers());
  8360. }, me);
  8361. me._layers.forEach(function (item, index) {
  8362. item._idx = index;
  8363. });
  8364. /**
  8365. * Provided for backward compatibility, use `afterLayout` instead.
  8366. * @method IPlugin#afterScaleUpdate
  8367. * @deprecated since version 2.5.0
  8368. * @todo remove at version 3
  8369. * @private
  8370. */
  8371. core_plugins.notify(me, 'afterScaleUpdate');
  8372. core_plugins.notify(me, 'afterLayout');
  8373. },
  8374. /**
  8375. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  8376. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  8377. * @private
  8378. */
  8379. updateDatasets: function () {
  8380. var me = this;
  8381. if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  8382. return;
  8383. }
  8384. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8385. me.updateDataset(i);
  8386. }
  8387. core_plugins.notify(me, 'afterDatasetsUpdate');
  8388. },
  8389. /**
  8390. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  8391. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  8392. * @private
  8393. */
  8394. updateDataset: function (index) {
  8395. var me = this;
  8396. var meta = me.getDatasetMeta(index);
  8397. var args = {
  8398. meta: meta,
  8399. index: index
  8400. };
  8401. if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  8402. return;
  8403. }
  8404. meta.controller._update();
  8405. core_plugins.notify(me, 'afterDatasetUpdate', [args]);
  8406. },
  8407. render: function (config) {
  8408. var me = this;
  8409. if (!config || typeof config !== 'object') {
  8410. // backwards compatibility
  8411. config = {
  8412. duration: config,
  8413. lazy: arguments[1]
  8414. };
  8415. }
  8416. var animationOptions = me.options.animation;
  8417. var duration = valueOrDefault$9(config.duration, animationOptions && animationOptions.duration);
  8418. var lazy = config.lazy;
  8419. if (core_plugins.notify(me, 'beforeRender') === false) {
  8420. return;
  8421. }
  8422. var onComplete = function (animation) {
  8423. core_plugins.notify(me, 'afterRender');
  8424. helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
  8425. };
  8426. if (animationOptions && duration) {
  8427. var animation = new core_animation({
  8428. numSteps: duration / 16.66, // 60 fps
  8429. easing: config.easing || animationOptions.easing,
  8430. render: function (chart, animationObject) {
  8431. var easingFunction = helpers$1.easing.effects[animationObject.easing];
  8432. var currentStep = animationObject.currentStep;
  8433. var stepDecimal = currentStep / animationObject.numSteps;
  8434. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  8435. },
  8436. onAnimationProgress: animationOptions.onProgress,
  8437. onAnimationComplete: onComplete
  8438. });
  8439. core_animations.addAnimation(me, animation, duration, lazy);
  8440. } else {
  8441. me.draw();
  8442. // See https://github.com/chartjs/Chart.js/issues/3781
  8443. onComplete(new core_animation({numSteps: 0, chart: me}));
  8444. }
  8445. return me;
  8446. },
  8447. draw: function (easingValue) {
  8448. var me = this;
  8449. var i, layers;
  8450. me.clear();
  8451. if (helpers$1.isNullOrUndef(easingValue)) {
  8452. easingValue = 1;
  8453. }
  8454. me.transition(easingValue);
  8455. if (me.width <= 0 || me.height <= 0) {
  8456. return;
  8457. }
  8458. if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  8459. return;
  8460. }
  8461. // Because of plugin hooks (before/afterDatasetsDraw), datasets can't
  8462. // currently be part of layers. Instead, we draw
  8463. // layers <= 0 before(default, backward compat), and the rest after
  8464. layers = me._layers;
  8465. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  8466. layers[i].draw(me.chartArea);
  8467. }
  8468. me.drawDatasets(easingValue);
  8469. // Rest of layers
  8470. for (; i < layers.length; ++i) {
  8471. layers[i].draw(me.chartArea);
  8472. }
  8473. me._drawTooltip(easingValue);
  8474. core_plugins.notify(me, 'afterDraw', [easingValue]);
  8475. },
  8476. /**
  8477. * @private
  8478. */
  8479. transition: function (easingValue) {
  8480. var me = this;
  8481. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  8482. if (me.isDatasetVisible(i)) {
  8483. me.getDatasetMeta(i).controller.transition(easingValue);
  8484. }
  8485. }
  8486. me.tooltip.transition(easingValue);
  8487. },
  8488. /**
  8489. * @private
  8490. */
  8491. _getSortedDatasetMetas: function (filterVisible) {
  8492. var me = this;
  8493. var datasets = me.data.datasets || [];
  8494. var result = [];
  8495. var i, ilen;
  8496. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  8497. if (!filterVisible || me.isDatasetVisible(i)) {
  8498. result.push(me.getDatasetMeta(i));
  8499. }
  8500. }
  8501. result.sort(compare2Level('order', 'index'));
  8502. return result;
  8503. },
  8504. /**
  8505. * @private
  8506. */
  8507. _getSortedVisibleDatasetMetas: function () {
  8508. return this._getSortedDatasetMetas(true);
  8509. },
  8510. /**
  8511. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  8512. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  8513. * @private
  8514. */
  8515. drawDatasets: function (easingValue) {
  8516. var me = this;
  8517. var metasets, i;
  8518. if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  8519. return;
  8520. }
  8521. metasets = me._getSortedVisibleDatasetMetas();
  8522. for (i = metasets.length - 1; i >= 0; --i) {
  8523. me.drawDataset(metasets[i], easingValue);
  8524. }
  8525. core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  8526. },
  8527. /**
  8528. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  8529. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  8530. * @private
  8531. */
  8532. drawDataset: function (meta, easingValue) {
  8533. var me = this;
  8534. var args = {
  8535. meta: meta,
  8536. index: meta.index,
  8537. easingValue: easingValue
  8538. };
  8539. if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  8540. return;
  8541. }
  8542. meta.controller.draw(easingValue);
  8543. core_plugins.notify(me, 'afterDatasetDraw', [args]);
  8544. },
  8545. /**
  8546. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  8547. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  8548. * @private
  8549. */
  8550. _drawTooltip: function (easingValue) {
  8551. var me = this;
  8552. var tooltip = me.tooltip;
  8553. var args = {
  8554. tooltip: tooltip,
  8555. easingValue: easingValue
  8556. };
  8557. if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  8558. return;
  8559. }
  8560. tooltip.draw();
  8561. core_plugins.notify(me, 'afterTooltipDraw', [args]);
  8562. },
  8563. /**
  8564. * Get the single element that was clicked on
  8565. * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  8566. */
  8567. getElementAtEvent: function (e) {
  8568. return core_interaction.modes.single(this, e);
  8569. },
  8570. getElementsAtEvent: function (e) {
  8571. return core_interaction.modes.label(this, e, {intersect: true});
  8572. },
  8573. getElementsAtXAxis: function (e) {
  8574. return core_interaction.modes['x-axis'](this, e, {intersect: true});
  8575. },
  8576. getElementsAtEventForMode: function (e, mode, options) {
  8577. var method = core_interaction.modes[mode];
  8578. if (typeof method === 'function') {
  8579. return method(this, e, options);
  8580. }
  8581. return [];
  8582. },
  8583. getDatasetAtEvent: function (e) {
  8584. return core_interaction.modes.dataset(this, e, {intersect: true});
  8585. },
  8586. getDatasetMeta: function (datasetIndex) {
  8587. var me = this;
  8588. var dataset = me.data.datasets[datasetIndex];
  8589. if (!dataset._meta) {
  8590. dataset._meta = {};
  8591. }
  8592. var meta = dataset._meta[me.id];
  8593. if (!meta) {
  8594. meta = dataset._meta[me.id] = {
  8595. type: null,
  8596. data: [],
  8597. dataset: null,
  8598. controller: null,
  8599. hidden: null, // See isDatasetVisible() comment
  8600. xAxisID: null,
  8601. yAxisID: null,
  8602. order: dataset.order || 0,
  8603. index: datasetIndex
  8604. };
  8605. }
  8606. return meta;
  8607. },
  8608. getVisibleDatasetCount: function () {
  8609. var count = 0;
  8610. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  8611. if (this.isDatasetVisible(i)) {
  8612. count++;
  8613. }
  8614. }
  8615. return count;
  8616. },
  8617. isDatasetVisible: function (datasetIndex) {
  8618. var meta = this.getDatasetMeta(datasetIndex);
  8619. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  8620. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  8621. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  8622. },
  8623. generateLegend: function () {
  8624. return this.options.legendCallback(this);
  8625. },
  8626. /**
  8627. * @private
  8628. */
  8629. destroyDatasetMeta: function (datasetIndex) {
  8630. var id = this.id;
  8631. var dataset = this.data.datasets[datasetIndex];
  8632. var meta = dataset._meta && dataset._meta[id];
  8633. if (meta) {
  8634. meta.controller.destroy();
  8635. delete dataset._meta[id];
  8636. }
  8637. },
  8638. destroy: function () {
  8639. var me = this;
  8640. var canvas = me.canvas;
  8641. var i, ilen;
  8642. me.stop();
  8643. // dataset controllers need to cleanup associated data
  8644. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8645. me.destroyDatasetMeta(i);
  8646. }
  8647. if (canvas) {
  8648. me.unbindEvents();
  8649. helpers$1.canvas.clear(me);
  8650. platform.releaseContext(me.ctx);
  8651. me.canvas = null;
  8652. me.ctx = null;
  8653. }
  8654. core_plugins.notify(me, 'destroy');
  8655. delete Chart.instances[me.id];
  8656. },
  8657. toBase64Image: function () {
  8658. return this.canvas.toDataURL.apply(this.canvas, arguments);
  8659. },
  8660. initToolTip: function () {
  8661. var me = this;
  8662. me.tooltip = new core_tooltip({
  8663. _chart: me,
  8664. _chartInstance: me, // deprecated, backward compatibility
  8665. _data: me.data,
  8666. _options: me.options.tooltips
  8667. }, me);
  8668. },
  8669. /**
  8670. * @private
  8671. */
  8672. bindEvents: function () {
  8673. var me = this;
  8674. var listeners = me._listeners = {};
  8675. var listener = function () {
  8676. me.eventHandler.apply(me, arguments);
  8677. };
  8678. helpers$1.each(me.options.events, function (type) {
  8679. platform.addEventListener(me, type, listener);
  8680. listeners[type] = listener;
  8681. });
  8682. // Elements used to detect size change should not be injected for non responsive charts.
  8683. // See https://github.com/chartjs/Chart.js/issues/2210
  8684. if (me.options.responsive) {
  8685. listener = function () {
  8686. me.resize();
  8687. };
  8688. platform.addEventListener(me, 'resize', listener);
  8689. listeners.resize = listener;
  8690. }
  8691. },
  8692. /**
  8693. * @private
  8694. */
  8695. unbindEvents: function () {
  8696. var me = this;
  8697. var listeners = me._listeners;
  8698. if (!listeners) {
  8699. return;
  8700. }
  8701. delete me._listeners;
  8702. helpers$1.each(listeners, function (listener, type) {
  8703. platform.removeEventListener(me, type, listener);
  8704. });
  8705. },
  8706. updateHoverStyle: function (elements, mode, enabled) {
  8707. var prefix = enabled ? 'set' : 'remove';
  8708. var element, i, ilen;
  8709. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  8710. element = elements[i];
  8711. if (element) {
  8712. this.getDatasetMeta(element._datasetIndex).controller[prefix + 'HoverStyle'](element);
  8713. }
  8714. }
  8715. if (mode === 'dataset') {
  8716. this.getDatasetMeta(elements[0]._datasetIndex).controller['_' + prefix + 'DatasetHoverStyle']();
  8717. }
  8718. },
  8719. /**
  8720. * @private
  8721. */
  8722. eventHandler: function (e) {
  8723. var me = this;
  8724. var tooltip = me.tooltip;
  8725. if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
  8726. return;
  8727. }
  8728. // Buffer any update calls so that renders do not occur
  8729. me._bufferedRender = true;
  8730. me._bufferedRequest = null;
  8731. var changed = me.handleEvent(e);
  8732. // for smooth tooltip animations issue #4989
  8733. // the tooltip should be the source of change
  8734. // Animation check workaround:
  8735. // tooltip._start will be null when tooltip isn't animating
  8736. if (tooltip) {
  8737. changed = tooltip._start
  8738. ? tooltip.handleEvent(e)
  8739. : changed | tooltip.handleEvent(e);
  8740. }
  8741. core_plugins.notify(me, 'afterEvent', [e]);
  8742. var bufferedRequest = me._bufferedRequest;
  8743. if (bufferedRequest) {
  8744. // If we have an update that was triggered, we need to do a normal render
  8745. me.render(bufferedRequest);
  8746. } else if (changed && !me.animating) {
  8747. // If entering, leaving, or changing elements, animate the change via pivot
  8748. me.stop();
  8749. // We only need to render at this point. Updating will cause scales to be
  8750. // recomputed generating flicker & using more memory than necessary.
  8751. me.render({
  8752. duration: me.options.hover.animationDuration,
  8753. lazy: true
  8754. });
  8755. }
  8756. me._bufferedRender = false;
  8757. me._bufferedRequest = null;
  8758. return me;
  8759. },
  8760. /**
  8761. * Handle an event
  8762. * @private
  8763. * @param {IEvent} event the event to handle
  8764. * @return {boolean} true if the chart needs to re-render
  8765. */
  8766. handleEvent: function (e) {
  8767. var me = this;
  8768. var options = me.options || {};
  8769. var hoverOptions = options.hover;
  8770. var changed = false;
  8771. me.lastActive = me.lastActive || [];
  8772. // Find Active Elements for hover and tooltips
  8773. if (e.type === 'mouseout') {
  8774. me.active = [];
  8775. } else {
  8776. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  8777. }
  8778. // Invoke onHover hook
  8779. // Need to call with native event here to not break backwards compatibility
  8780. helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  8781. if (e.type === 'mouseup' || e.type === 'click') {
  8782. if (options.onClick) {
  8783. // Use e.native here for backwards compatibility
  8784. options.onClick.call(me, e.native, me.active);
  8785. }
  8786. }
  8787. // Remove styling for last active (even if it may still be active)
  8788. if (me.lastActive.length) {
  8789. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  8790. }
  8791. // Built in hover styling
  8792. if (me.active.length && hoverOptions.mode) {
  8793. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  8794. }
  8795. changed = !helpers$1.arrayEquals(me.active, me.lastActive);
  8796. // Remember Last Actives
  8797. me.lastActive = me.active;
  8798. return changed;
  8799. }
  8800. });
  8801. /**
  8802. * NOTE(SB) We actually don't use this container anymore but we need to keep it
  8803. * for backward compatibility. Though, it can still be useful for plugins that
  8804. * would need to work on multiple charts?!
  8805. */
  8806. Chart.instances = {};
  8807. var core_controller = Chart;
  8808. // DEPRECATIONS
  8809. /**
  8810. * Provided for backward compatibility, use Chart instead.
  8811. * @class Chart.Controller
  8812. * @deprecated since version 2.6
  8813. * @todo remove at version 3
  8814. * @private
  8815. */
  8816. Chart.Controller = Chart;
  8817. /**
  8818. * Provided for backward compatibility, not available anymore.
  8819. * @namespace Chart
  8820. * @deprecated since version 2.8
  8821. * @todo remove at version 3
  8822. * @private
  8823. */
  8824. Chart.types = {};
  8825. /**
  8826. * Provided for backward compatibility, not available anymore.
  8827. * @namespace Chart.helpers.configMerge
  8828. * @deprecated since version 2.8.0
  8829. * @todo remove at version 3
  8830. * @private
  8831. */
  8832. helpers$1.configMerge = mergeConfig;
  8833. /**
  8834. * Provided for backward compatibility, not available anymore.
  8835. * @namespace Chart.helpers.scaleMerge
  8836. * @deprecated since version 2.8.0
  8837. * @todo remove at version 3
  8838. * @private
  8839. */
  8840. helpers$1.scaleMerge = mergeScaleConfig;
  8841. var core_helpers = function () {
  8842. // -- Basic js utility methods
  8843. helpers$1.where = function (collection, filterCallback) {
  8844. if (helpers$1.isArray(collection) && Array.prototype.filter) {
  8845. return collection.filter(filterCallback);
  8846. }
  8847. var filtered = [];
  8848. helpers$1.each(collection, function (item) {
  8849. if (filterCallback(item)) {
  8850. filtered.push(item);
  8851. }
  8852. });
  8853. return filtered;
  8854. };
  8855. helpers$1.findIndex = Array.prototype.findIndex ?
  8856. function (array, callback, scope) {
  8857. return array.findIndex(callback, scope);
  8858. } :
  8859. function (array, callback, scope) {
  8860. scope = scope === undefined ? array : scope;
  8861. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  8862. if (callback.call(scope, array[i], i, array)) {
  8863. return i;
  8864. }
  8865. }
  8866. return -1;
  8867. };
  8868. helpers$1.findNextWhere = function (arrayToSearch, filterCallback, startIndex) {
  8869. // Default to start of the array
  8870. if (helpers$1.isNullOrUndef(startIndex)) {
  8871. startIndex = -1;
  8872. }
  8873. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  8874. var currentItem = arrayToSearch[i];
  8875. if (filterCallback(currentItem)) {
  8876. return currentItem;
  8877. }
  8878. }
  8879. };
  8880. helpers$1.findPreviousWhere = function (arrayToSearch, filterCallback, startIndex) {
  8881. // Default to end of the array
  8882. if (helpers$1.isNullOrUndef(startIndex)) {
  8883. startIndex = arrayToSearch.length;
  8884. }
  8885. for (var i = startIndex - 1; i >= 0; i--) {
  8886. var currentItem = arrayToSearch[i];
  8887. if (filterCallback(currentItem)) {
  8888. return currentItem;
  8889. }
  8890. }
  8891. };
  8892. // -- Math methods
  8893. helpers$1.isNumber = function (n) {
  8894. return !isNaN(parseFloat(n)) && isFinite(n);
  8895. };
  8896. helpers$1.almostEquals = function (x, y, epsilon) {
  8897. return Math.abs(x - y) < epsilon;
  8898. };
  8899. helpers$1.almostWhole = function (x, epsilon) {
  8900. var rounded = Math.round(x);
  8901. return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
  8902. };
  8903. helpers$1.max = function (array) {
  8904. return array.reduce(function (max, value) {
  8905. if (!isNaN(value)) {
  8906. return Math.max(max, value);
  8907. }
  8908. return max;
  8909. }, Number.NEGATIVE_INFINITY);
  8910. };
  8911. helpers$1.min = function (array) {
  8912. return array.reduce(function (min, value) {
  8913. if (!isNaN(value)) {
  8914. return Math.min(min, value);
  8915. }
  8916. return min;
  8917. }, Number.POSITIVE_INFINITY);
  8918. };
  8919. helpers$1.sign = Math.sign ?
  8920. function (x) {
  8921. return Math.sign(x);
  8922. } :
  8923. function (x) {
  8924. x = +x; // convert to a number
  8925. if (x === 0 || isNaN(x)) {
  8926. return x;
  8927. }
  8928. return x > 0 ? 1 : -1;
  8929. };
  8930. helpers$1.toRadians = function (degrees) {
  8931. return degrees * (Math.PI / 180);
  8932. };
  8933. helpers$1.toDegrees = function (radians) {
  8934. return radians * (180 / Math.PI);
  8935. };
  8936. /**
  8937. * Returns the number of decimal places
  8938. * i.e. the number of digits after the decimal point, of the value of this Number.
  8939. * @param {number} x - A number.
  8940. * @returns {number} The number of decimal places.
  8941. * @private
  8942. */
  8943. helpers$1._decimalPlaces = function (x) {
  8944. if (!helpers$1.isFinite(x)) {
  8945. return;
  8946. }
  8947. var e = 1;
  8948. var p = 0;
  8949. while (Math.round(x * e) / e !== x) {
  8950. e *= 10;
  8951. p++;
  8952. }
  8953. return p;
  8954. };
  8955. // Gets the angle from vertical upright to the point about a centre.
  8956. helpers$1.getAngleFromPoint = function (centrePoint, anglePoint) {
  8957. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  8958. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  8959. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  8960. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  8961. if (angle < (-0.5 * Math.PI)) {
  8962. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  8963. }
  8964. return {
  8965. angle: angle,
  8966. distance: radialDistanceFromCenter
  8967. };
  8968. };
  8969. helpers$1.distanceBetweenPoints = function (pt1, pt2) {
  8970. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  8971. };
  8972. /**
  8973. * Provided for backward compatibility, not available anymore
  8974. * @function Chart.helpers.aliasPixel
  8975. * @deprecated since version 2.8.0
  8976. * @todo remove at version 3
  8977. */
  8978. helpers$1.aliasPixel = function (pixelWidth) {
  8979. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  8980. };
  8981. /**
  8982. * Returns the aligned pixel value to avoid anti-aliasing blur
  8983. * @param {Chart} chart - The chart instance.
  8984. * @param {number} pixel - A pixel value.
  8985. * @param {number} width - The width of the element.
  8986. * @returns {number} The aligned pixel value.
  8987. * @private
  8988. */
  8989. helpers$1._alignPixel = function (chart, pixel, width) {
  8990. var devicePixelRatio = chart.currentDevicePixelRatio;
  8991. var halfWidth = width / 2;
  8992. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  8993. };
  8994. helpers$1.splineCurve = function (firstPoint, middlePoint, afterPoint, t) {
  8995. // Props to Rob Spencer at scaled innovation for his post on splining between points
  8996. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  8997. // This function must also respect "skipped" points
  8998. var previous = firstPoint.skip ? middlePoint : firstPoint;
  8999. var current = middlePoint;
  9000. var next = afterPoint.skip ? middlePoint : afterPoint;
  9001. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  9002. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  9003. var s01 = d01 / (d01 + d12);
  9004. var s12 = d12 / (d01 + d12);
  9005. // If all points are the same, s01 & s02 will be inf
  9006. s01 = isNaN(s01) ? 0 : s01;
  9007. s12 = isNaN(s12) ? 0 : s12;
  9008. var fa = t * s01; // scaling factor for triangle Ta
  9009. var fb = t * s12;
  9010. return {
  9011. previous: {
  9012. x: current.x - fa * (next.x - previous.x),
  9013. y: current.y - fa * (next.y - previous.y)
  9014. },
  9015. next: {
  9016. x: current.x + fb * (next.x - previous.x),
  9017. y: current.y + fb * (next.y - previous.y)
  9018. }
  9019. };
  9020. };
  9021. helpers$1.EPSILON = Number.EPSILON || 1e-14;
  9022. helpers$1.splineCurveMonotone = function (points) {
  9023. // This function calculates Bézier control points in a similar way than |splineCurve|,
  9024. // but preserves monotonicity of the provided data and ensures no local extremums are added
  9025. // between the dataset discrete points due to the interpolation.
  9026. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  9027. var pointsWithTangents = (points || []).map(function (point) {
  9028. return {
  9029. model: point._model,
  9030. deltaK: 0,
  9031. mK: 0
  9032. };
  9033. });
  9034. // Calculate slopes (deltaK) and initialize tangents (mK)
  9035. var pointsLen = pointsWithTangents.length;
  9036. var i, pointBefore, pointCurrent, pointAfter;
  9037. for (i = 0; i < pointsLen; ++i) {
  9038. pointCurrent = pointsWithTangents[i];
  9039. if (pointCurrent.model.skip) {
  9040. continue;
  9041. }
  9042. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  9043. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  9044. if (pointAfter && !pointAfter.model.skip) {
  9045. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  9046. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  9047. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  9048. }
  9049. if (!pointBefore || pointBefore.model.skip) {
  9050. pointCurrent.mK = pointCurrent.deltaK;
  9051. } else if (!pointAfter || pointAfter.model.skip) {
  9052. pointCurrent.mK = pointBefore.deltaK;
  9053. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  9054. pointCurrent.mK = 0;
  9055. } else {
  9056. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  9057. }
  9058. }
  9059. // Adjust tangents to ensure monotonic properties
  9060. var alphaK, betaK, tauK, squaredMagnitude;
  9061. for (i = 0; i < pointsLen - 1; ++i) {
  9062. pointCurrent = pointsWithTangents[i];
  9063. pointAfter = pointsWithTangents[i + 1];
  9064. if (pointCurrent.model.skip || pointAfter.model.skip) {
  9065. continue;
  9066. }
  9067. if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  9068. pointCurrent.mK = pointAfter.mK = 0;
  9069. continue;
  9070. }
  9071. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  9072. betaK = pointAfter.mK / pointCurrent.deltaK;
  9073. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  9074. if (squaredMagnitude <= 9) {
  9075. continue;
  9076. }
  9077. tauK = 3 / Math.sqrt(squaredMagnitude);
  9078. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  9079. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  9080. }
  9081. // Compute control points
  9082. var deltaX;
  9083. for (i = 0; i < pointsLen; ++i) {
  9084. pointCurrent = pointsWithTangents[i];
  9085. if (pointCurrent.model.skip) {
  9086. continue;
  9087. }
  9088. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  9089. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  9090. if (pointBefore && !pointBefore.model.skip) {
  9091. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  9092. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  9093. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  9094. }
  9095. if (pointAfter && !pointAfter.model.skip) {
  9096. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  9097. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  9098. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  9099. }
  9100. }
  9101. };
  9102. helpers$1.nextItem = function (collection, index, loop) {
  9103. if (loop) {
  9104. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  9105. }
  9106. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  9107. };
  9108. helpers$1.previousItem = function (collection, index, loop) {
  9109. if (loop) {
  9110. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  9111. }
  9112. return index <= 0 ? collection[0] : collection[index - 1];
  9113. };
  9114. // Implementation of the nice number algorithm used in determining where axis labels will go
  9115. helpers$1.niceNum = function (range, round) {
  9116. var exponent = Math.floor(helpers$1.log10(range));
  9117. var fraction = range / Math.pow(10, exponent);
  9118. var niceFraction;
  9119. if (round) {
  9120. if (fraction < 1.5) {
  9121. niceFraction = 1;
  9122. } else if (fraction < 3) {
  9123. niceFraction = 2;
  9124. } else if (fraction < 7) {
  9125. niceFraction = 5;
  9126. } else {
  9127. niceFraction = 10;
  9128. }
  9129. } else if (fraction <= 1.0) {
  9130. niceFraction = 1;
  9131. } else if (fraction <= 2) {
  9132. niceFraction = 2;
  9133. } else if (fraction <= 5) {
  9134. niceFraction = 5;
  9135. } else {
  9136. niceFraction = 10;
  9137. }
  9138. return niceFraction * Math.pow(10, exponent);
  9139. };
  9140. // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  9141. helpers$1.requestAnimFrame = (function () {
  9142. if (typeof window === 'undefined') {
  9143. return function (callback) {
  9144. callback();
  9145. };
  9146. }
  9147. return window.requestAnimationFrame ||
  9148. window.webkitRequestAnimationFrame ||
  9149. window.mozRequestAnimationFrame ||
  9150. window.oRequestAnimationFrame ||
  9151. window.msRequestAnimationFrame ||
  9152. function (callback) {
  9153. return window.setTimeout(callback, 1000 / 60);
  9154. };
  9155. }());
  9156. // -- DOM methods
  9157. helpers$1.getRelativePosition = function (evt, chart) {
  9158. var mouseX, mouseY;
  9159. var e = evt.originalEvent || evt;
  9160. var canvas = evt.target || evt.srcElement;
  9161. var boundingRect = canvas.getBoundingClientRect();
  9162. var touches = e.touches;
  9163. if (touches && touches.length > 0) {
  9164. mouseX = touches[0].clientX;
  9165. mouseY = touches[0].clientY;
  9166. } else {
  9167. mouseX = e.clientX;
  9168. mouseY = e.clientY;
  9169. }
  9170. // Scale mouse coordinates into canvas coordinates
  9171. // by following the pattern laid out by 'jerryj' in the comments of
  9172. // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  9173. var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
  9174. var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
  9175. var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
  9176. var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
  9177. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  9178. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  9179. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  9180. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  9181. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  9182. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  9183. return {
  9184. x: mouseX,
  9185. y: mouseY
  9186. };
  9187. };
  9188. // Private helper function to convert max-width/max-height values that may be percentages into a number
  9189. function parseMaxStyle(styleValue, node, parentProperty) {
  9190. var valueInPixels;
  9191. if (typeof styleValue === 'string') {
  9192. valueInPixels = parseInt(styleValue, 10);
  9193. if (styleValue.indexOf('%') !== -1) {
  9194. // percentage * size in dimension
  9195. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  9196. }
  9197. } else {
  9198. valueInPixels = styleValue;
  9199. }
  9200. return valueInPixels;
  9201. }
  9202. /**
  9203. * Returns if the given value contains an effective constraint.
  9204. * @private
  9205. */
  9206. function isConstrainedValue(value) {
  9207. return value !== undefined && value !== null && value !== 'none';
  9208. }
  9209. /**
  9210. * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
  9211. * @param {HTMLElement} domNode - the node to check the constraint on
  9212. * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
  9213. * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
  9214. * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
  9215. */
  9216. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  9217. var view = document.defaultView;
  9218. var parentNode = helpers$1._getParentNode(domNode);
  9219. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  9220. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  9221. var hasCNode = isConstrainedValue(constrainedNode);
  9222. var hasCContainer = isConstrainedValue(constrainedContainer);
  9223. var infinity = Number.POSITIVE_INFINITY;
  9224. if (hasCNode || hasCContainer) {
  9225. return Math.min(
  9226. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  9227. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  9228. }
  9229. return 'none';
  9230. }
  9231. // returns Number or undefined if no constraint
  9232. helpers$1.getConstraintWidth = function (domNode) {
  9233. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  9234. };
  9235. // returns Number or undefined if no constraint
  9236. helpers$1.getConstraintHeight = function (domNode) {
  9237. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  9238. };
  9239. /**
  9240. * @private
  9241. */
  9242. helpers$1._calculatePadding = function (container, padding, parentDimension) {
  9243. padding = helpers$1.getStyle(container, padding);
  9244. return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
  9245. };
  9246. /**
  9247. * @private
  9248. */
  9249. helpers$1._getParentNode = function (domNode) {
  9250. var parent = domNode.parentNode;
  9251. if (parent && parent.toString() === '[object ShadowRoot]') {
  9252. parent = parent.host;
  9253. }
  9254. return parent;
  9255. };
  9256. helpers$1.getMaximumWidth = function (domNode) {
  9257. var container = helpers$1._getParentNode(domNode);
  9258. if (!container) {
  9259. return domNode.clientWidth;
  9260. }
  9261. var clientWidth = container.clientWidth;
  9262. var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
  9263. var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
  9264. var w = clientWidth - paddingLeft - paddingRight;
  9265. var cw = helpers$1.getConstraintWidth(domNode);
  9266. return isNaN(cw) ? w : Math.min(w, cw);
  9267. };
  9268. helpers$1.getMaximumHeight = function (domNode) {
  9269. var container = helpers$1._getParentNode(domNode);
  9270. if (!container) {
  9271. return domNode.clientHeight;
  9272. }
  9273. var clientHeight = container.clientHeight;
  9274. var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
  9275. var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
  9276. var h = clientHeight - paddingTop - paddingBottom;
  9277. var ch = helpers$1.getConstraintHeight(domNode);
  9278. return isNaN(ch) ? h : Math.min(h, ch);
  9279. };
  9280. helpers$1.getStyle = function (el, property) {
  9281. return el.currentStyle ?
  9282. el.currentStyle[property] :
  9283. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  9284. };
  9285. helpers$1.retinaScale = function (chart, forceRatio) {
  9286. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  9287. if (pixelRatio === 1) {
  9288. return;
  9289. }
  9290. var canvas = chart.canvas;
  9291. var height = chart.height;
  9292. var width = chart.width;
  9293. canvas.height = height * pixelRatio;
  9294. canvas.width = width * pixelRatio;
  9295. chart.ctx.scale(pixelRatio, pixelRatio);
  9296. // If no style has been set on the canvas, the render size is used as display size,
  9297. // making the chart visually bigger, so let's enforce it to the "correct" values.
  9298. // See https://github.com/chartjs/Chart.js/issues/3575
  9299. if (!canvas.style.height && !canvas.style.width) {
  9300. canvas.style.height = height + 'px';
  9301. canvas.style.width = width + 'px';
  9302. }
  9303. };
  9304. // -- Canvas methods
  9305. helpers$1.fontString = function (pixelSize, fontStyle, fontFamily) {
  9306. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  9307. };
  9308. helpers$1.longestText = function (ctx, font, arrayOfThings, cache) {
  9309. cache = cache || {};
  9310. var data = cache.data = cache.data || {};
  9311. var gc = cache.garbageCollect = cache.garbageCollect || [];
  9312. if (cache.font !== font) {
  9313. data = cache.data = {};
  9314. gc = cache.garbageCollect = [];
  9315. cache.font = font;
  9316. }
  9317. ctx.font = font;
  9318. var longest = 0;
  9319. var ilen = arrayOfThings.length;
  9320. var i, j, jlen, thing, nestedThing;
  9321. for (i = 0; i < ilen; i++) {
  9322. thing = arrayOfThings[i];
  9323. // Undefined strings and arrays should not be measured
  9324. if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
  9325. longest = helpers$1.measureText(ctx, data, gc, longest, thing);
  9326. } else if (helpers$1.isArray(thing)) {
  9327. // if it is an array lets measure each element
  9328. // to do maybe simplify this function a bit so we can do this more recursively?
  9329. for (j = 0, jlen = thing.length; j < jlen; j++) {
  9330. nestedThing = thing[j];
  9331. // Undefined strings and arrays should not be measured
  9332. if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
  9333. longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
  9334. }
  9335. }
  9336. }
  9337. }
  9338. var gcLen = gc.length / 2;
  9339. if (gcLen > arrayOfThings.length) {
  9340. for (i = 0; i < gcLen; i++) {
  9341. delete data[gc[i]];
  9342. }
  9343. gc.splice(0, gcLen);
  9344. }
  9345. return longest;
  9346. };
  9347. helpers$1.measureText = function (ctx, data, gc, longest, string) {
  9348. var textWidth = data[string];
  9349. if (!textWidth) {
  9350. textWidth = data[string] = ctx.measureText(string).width;
  9351. gc.push(string);
  9352. }
  9353. if (textWidth > longest) {
  9354. longest = textWidth;
  9355. }
  9356. return longest;
  9357. };
  9358. /**
  9359. * @deprecated
  9360. */
  9361. helpers$1.numberOfLabelLines = function (arrayOfThings) {
  9362. var numberOfLines = 1;
  9363. helpers$1.each(arrayOfThings, function (thing) {
  9364. if (helpers$1.isArray(thing)) {
  9365. if (thing.length > numberOfLines) {
  9366. numberOfLines = thing.length;
  9367. }
  9368. }
  9369. });
  9370. return numberOfLines;
  9371. };
  9372. helpers$1.color = !chartjsColor ?
  9373. function (value) {
  9374. console.error('Color.js not found!');
  9375. return value;
  9376. } :
  9377. function (value) {
  9378. /* global CanvasGradient */
  9379. if (value instanceof CanvasGradient) {
  9380. value = core_defaults.global.defaultColor;
  9381. }
  9382. return chartjsColor(value);
  9383. };
  9384. helpers$1.getHoverColor = function (colorValue) {
  9385. /* global CanvasPattern */
  9386. return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
  9387. colorValue :
  9388. helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  9389. };
  9390. };
  9391. function abstract() {
  9392. throw new Error(
  9393. 'This method is not implemented: either no adapter can ' +
  9394. 'be found or an incomplete integration was provided.'
  9395. );
  9396. }
  9397. /**
  9398. * Date adapter (current used by the time scale)
  9399. * @namespace Chart._adapters._date
  9400. * @memberof Chart._adapters
  9401. * @private
  9402. */
  9403. /**
  9404. * Currently supported unit string values.
  9405. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
  9406. * @memberof Chart._adapters._date
  9407. * @name Unit
  9408. */
  9409. /**
  9410. * @class
  9411. */
  9412. function DateAdapter(options) {
  9413. this.options = options || {};
  9414. }
  9415. helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
  9416. /**
  9417. * Returns a map of time formats for the supported formatting units defined
  9418. * in Unit as well as 'datetime' representing a detailed date/time string.
  9419. * @returns {{string: string}}
  9420. */
  9421. formats: abstract,
  9422. /**
  9423. * Parses the given `value` and return the associated timestamp.
  9424. * @param {any} value - the value to parse (usually comes from the data)
  9425. * @param {string} [format] - the expected data format
  9426. * @returns {(number|null)}
  9427. * @function
  9428. */
  9429. parse: abstract,
  9430. /**
  9431. * Returns the formatted date in the specified `format` for a given `timestamp`.
  9432. * @param {number} timestamp - the timestamp to format
  9433. * @param {string} format - the date/time token
  9434. * @return {string}
  9435. * @function
  9436. */
  9437. format: abstract,
  9438. /**
  9439. * Adds the specified `amount` of `unit` to the given `timestamp`.
  9440. * @param {number} timestamp - the input timestamp
  9441. * @param {number} amount - the amount to add
  9442. * @param {Unit} unit - the unit as string
  9443. * @return {number}
  9444. * @function
  9445. */
  9446. add: abstract,
  9447. /**
  9448. * Returns the number of `unit` between the given timestamps.
  9449. * @param {number} max - the input timestamp (reference)
  9450. * @param {number} min - the timestamp to substract
  9451. * @param {Unit} unit - the unit as string
  9452. * @return {number}
  9453. * @function
  9454. */
  9455. diff: abstract,
  9456. /**
  9457. * Returns start of `unit` for the given `timestamp`.
  9458. * @param {number} timestamp - the input timestamp
  9459. * @param {Unit} unit - the unit as string
  9460. * @param {number} [weekday] - the ISO day of the week with 1 being Monday
  9461. * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
  9462. * @function
  9463. */
  9464. startOf: abstract,
  9465. /**
  9466. * Returns end of `unit` for the given `timestamp`.
  9467. * @param {number} timestamp - the input timestamp
  9468. * @param {Unit} unit - the unit as string
  9469. * @function
  9470. */
  9471. endOf: abstract,
  9472. // DEPRECATIONS
  9473. /**
  9474. * Provided for backward compatibility for scale.getValueForPixel(),
  9475. * this method should be overridden only by the moment adapter.
  9476. * @deprecated since version 2.8.0
  9477. * @todo remove at version 3
  9478. * @private
  9479. */
  9480. _create: function (value) {
  9481. return value;
  9482. }
  9483. });
  9484. DateAdapter.override = function (members) {
  9485. helpers$1.extend(DateAdapter.prototype, members);
  9486. };
  9487. var _date = DateAdapter;
  9488. var core_adapters = {
  9489. _date: _date
  9490. };
  9491. /**
  9492. * Namespace to hold static tick generation functions
  9493. * @namespace Chart.Ticks
  9494. */
  9495. var core_ticks = {
  9496. /**
  9497. * Namespace to hold formatters for different types of ticks
  9498. * @namespace Chart.Ticks.formatters
  9499. */
  9500. formatters: {
  9501. /**
  9502. * Formatter for value labels
  9503. * @method Chart.Ticks.formatters.values
  9504. * @param value the value to display
  9505. * @return {string|string[]} the label to display
  9506. */
  9507. values: function (value) {
  9508. return helpers$1.isArray(value) ? value : '' + value;
  9509. },
  9510. /**
  9511. * Formatter for linear numeric ticks
  9512. * @method Chart.Ticks.formatters.linear
  9513. * @param tickValue {number} the value to be formatted
  9514. * @param index {number} the position of the tickValue parameter in the ticks array
  9515. * @param ticks {number[]} the list of ticks being converted
  9516. * @return {string} string representation of the tickValue parameter
  9517. */
  9518. linear: function (tickValue, index, ticks) {
  9519. // If we have lots of ticks, don't use the ones
  9520. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  9521. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  9522. if (Math.abs(delta) > 1) {
  9523. if (tickValue !== Math.floor(tickValue)) {
  9524. // not an integer
  9525. delta = tickValue - Math.floor(tickValue);
  9526. }
  9527. }
  9528. var logDelta = helpers$1.log10(Math.abs(delta));
  9529. var tickString = '';
  9530. if (tickValue !== 0) {
  9531. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  9532. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  9533. var logTick = helpers$1.log10(Math.abs(tickValue));
  9534. var numExponential = Math.floor(logTick) - Math.floor(logDelta);
  9535. numExponential = Math.max(Math.min(numExponential, 20), 0);
  9536. tickString = tickValue.toExponential(numExponential);
  9537. } else {
  9538. var numDecimal = -1 * Math.floor(logDelta);
  9539. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  9540. tickString = tickValue.toFixed(numDecimal);
  9541. }
  9542. } else {
  9543. tickString = '0'; // never show decimal places for 0
  9544. }
  9545. return tickString;
  9546. },
  9547. logarithmic: function (tickValue, index, ticks) {
  9548. var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
  9549. if (tickValue === 0) {
  9550. return '0';
  9551. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  9552. return tickValue.toExponential();
  9553. }
  9554. return '';
  9555. }
  9556. }
  9557. };
  9558. var isArray = helpers$1.isArray;
  9559. var isNullOrUndef = helpers$1.isNullOrUndef;
  9560. var valueOrDefault$a = helpers$1.valueOrDefault;
  9561. var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
  9562. core_defaults._set('scale', {
  9563. display: true,
  9564. position: 'left',
  9565. offset: false,
  9566. // grid line settings
  9567. gridLines: {
  9568. display: true,
  9569. color: 'rgba(0,0,0,0.1)',
  9570. lineWidth: 1,
  9571. drawBorder: true,
  9572. drawOnChartArea: true,
  9573. drawTicks: true,
  9574. tickMarkLength: 10,
  9575. zeroLineWidth: 1,
  9576. zeroLineColor: 'rgba(0,0,0,0.25)',
  9577. zeroLineBorderDash: [],
  9578. zeroLineBorderDashOffset: 0.0,
  9579. offsetGridLines: false,
  9580. borderDash: [],
  9581. borderDashOffset: 0.0
  9582. },
  9583. // scale label
  9584. scaleLabel: {
  9585. // display property
  9586. display: false,
  9587. // actual label
  9588. labelString: '',
  9589. // top/bottom padding
  9590. padding: {
  9591. top: 4,
  9592. bottom: 4
  9593. }
  9594. },
  9595. // label settings
  9596. ticks: {
  9597. beginAtZero: false,
  9598. minRotation: 0,
  9599. maxRotation: 50,
  9600. mirror: false,
  9601. padding: 0,
  9602. reverse: false,
  9603. display: true,
  9604. autoSkip: true,
  9605. autoSkipPadding: 0,
  9606. labelOffset: 0,
  9607. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  9608. callback: core_ticks.formatters.values,
  9609. minor: {},
  9610. major: {}
  9611. }
  9612. });
  9613. /** Returns a new array containing numItems from arr */
  9614. function sample(arr, numItems) {
  9615. var result = [];
  9616. var increment = arr.length / numItems;
  9617. var i = 0;
  9618. var len = arr.length;
  9619. for (; i < len; i += increment) {
  9620. result.push(arr[Math.floor(i)]);
  9621. }
  9622. return result;
  9623. }
  9624. function getPixelForGridLine(scale, index, offsetGridLines) {
  9625. var length = scale.getTicks().length;
  9626. var validIndex = Math.min(index, length - 1);
  9627. var lineValue = scale.getPixelForTick(validIndex);
  9628. var start = scale._startPixel;
  9629. var end = scale._endPixel;
  9630. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  9631. var offset;
  9632. if (offsetGridLines) {
  9633. if (length === 1) {
  9634. offset = Math.max(lineValue - start, end - lineValue);
  9635. } else if (index === 0) {
  9636. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  9637. } else {
  9638. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  9639. }
  9640. lineValue += validIndex < index ? offset : -offset;
  9641. // Return undefined if the pixel is out of the range
  9642. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  9643. return;
  9644. }
  9645. }
  9646. return lineValue;
  9647. }
  9648. function garbageCollect(caches, length) {
  9649. helpers$1.each(caches, function (cache) {
  9650. var gc = cache.gc;
  9651. var gcLen = gc.length / 2;
  9652. var i;
  9653. if (gcLen > length) {
  9654. for (i = 0; i < gcLen; ++i) {
  9655. delete cache.data[gc[i]];
  9656. }
  9657. gc.splice(0, gcLen);
  9658. }
  9659. });
  9660. }
  9661. /**
  9662. * Returns {width, height, offset} objects for the first, last, widest, highest tick
  9663. * labels where offset indicates the anchor point offset from the top in pixels.
  9664. */
  9665. function computeLabelSizes(ctx, tickFonts, ticks, caches) {
  9666. var length = ticks.length;
  9667. var widths = [];
  9668. var heights = [];
  9669. var offsets = [];
  9670. var widestLabelSize = 0;
  9671. var highestLabelSize = 0;
  9672. var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest;
  9673. for (i = 0; i < length; ++i) {
  9674. label = ticks[i].label;
  9675. tickFont = ticks[i].major ? tickFonts.major : tickFonts.minor;
  9676. ctx.font = fontString = tickFont.string;
  9677. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  9678. lineHeight = tickFont.lineHeight;
  9679. width = height = 0;
  9680. // Undefined labels and arrays should not be measured
  9681. if (!isNullOrUndef(label) && !isArray(label)) {
  9682. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, label);
  9683. height = lineHeight;
  9684. } else if (isArray(label)) {
  9685. // if it is an array let's measure each element
  9686. for (j = 0, jlen = label.length; j < jlen; ++j) {
  9687. nestedLabel = label[j];
  9688. // Undefined labels and arrays should not be measured
  9689. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  9690. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  9691. height += lineHeight;
  9692. }
  9693. }
  9694. }
  9695. widths.push(width);
  9696. heights.push(height);
  9697. offsets.push(lineHeight / 2);
  9698. widestLabelSize = Math.max(width, widestLabelSize);
  9699. highestLabelSize = Math.max(height, highestLabelSize);
  9700. }
  9701. garbageCollect(caches, length);
  9702. widest = widths.indexOf(widestLabelSize);
  9703. highest = heights.indexOf(highestLabelSize);
  9704. function valueAt(idx) {
  9705. return {
  9706. width: widths[idx] || 0,
  9707. height: heights[idx] || 0,
  9708. offset: offsets[idx] || 0
  9709. };
  9710. }
  9711. return {
  9712. first: valueAt(0),
  9713. last: valueAt(length - 1),
  9714. widest: valueAt(widest),
  9715. highest: valueAt(highest)
  9716. };
  9717. }
  9718. function getTickMarkLength(options) {
  9719. return options.drawTicks ? options.tickMarkLength : 0;
  9720. }
  9721. function getScaleLabelHeight(options) {
  9722. var font, padding;
  9723. if (!options.display) {
  9724. return 0;
  9725. }
  9726. font = helpers$1.options._parseFont(options);
  9727. padding = helpers$1.options.toPadding(options.padding);
  9728. return font.lineHeight + padding.height;
  9729. }
  9730. function parseFontOptions(options, nestedOpts) {
  9731. return helpers$1.extend(helpers$1.options._parseFont({
  9732. fontFamily: valueOrDefault$a(nestedOpts.fontFamily, options.fontFamily),
  9733. fontSize: valueOrDefault$a(nestedOpts.fontSize, options.fontSize),
  9734. fontStyle: valueOrDefault$a(nestedOpts.fontStyle, options.fontStyle),
  9735. lineHeight: valueOrDefault$a(nestedOpts.lineHeight, options.lineHeight)
  9736. }), {
  9737. color: helpers$1.options.resolve([nestedOpts.fontColor, options.fontColor, core_defaults.global.defaultFontColor])
  9738. });
  9739. }
  9740. function parseTickFontOptions(options) {
  9741. var minor = parseFontOptions(options, options.minor);
  9742. var major = options.major.enabled ? parseFontOptions(options, options.major) : minor;
  9743. return {minor: minor, major: major};
  9744. }
  9745. function nonSkipped(ticksToFilter) {
  9746. var filtered = [];
  9747. var item, index, len;
  9748. for (index = 0, len = ticksToFilter.length; index < len; ++index) {
  9749. item = ticksToFilter[index];
  9750. if (typeof item._index !== 'undefined') {
  9751. filtered.push(item);
  9752. }
  9753. }
  9754. return filtered;
  9755. }
  9756. function getEvenSpacing(arr) {
  9757. var len = arr.length;
  9758. var i, diff;
  9759. if (len < 2) {
  9760. return false;
  9761. }
  9762. for (diff = arr[0], i = 1; i < len; ++i) {
  9763. if (arr[i] - arr[i - 1] !== diff) {
  9764. return false;
  9765. }
  9766. }
  9767. return diff;
  9768. }
  9769. function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
  9770. var evenMajorSpacing = getEvenSpacing(majorIndices);
  9771. var spacing = (ticks.length - 1) / ticksLimit;
  9772. var factors, factor, i, ilen;
  9773. // If the major ticks are evenly spaced apart, place the minor ticks
  9774. // so that they divide the major ticks into even chunks
  9775. if (!evenMajorSpacing) {
  9776. return Math.max(spacing, 1);
  9777. }
  9778. factors = helpers$1.math._factorize(evenMajorSpacing);
  9779. for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
  9780. factor = factors[i];
  9781. if (factor > spacing) {
  9782. return factor;
  9783. }
  9784. }
  9785. return Math.max(spacing, 1);
  9786. }
  9787. function getMajorIndices(ticks) {
  9788. var result = [];
  9789. var i, ilen;
  9790. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  9791. if (ticks[i].major) {
  9792. result.push(i);
  9793. }
  9794. }
  9795. return result;
  9796. }
  9797. function skipMajors(ticks, majorIndices, spacing) {
  9798. var count = 0;
  9799. var next = majorIndices[0];
  9800. var i, tick;
  9801. spacing = Math.ceil(spacing);
  9802. for (i = 0; i < ticks.length; i++) {
  9803. tick = ticks[i];
  9804. if (i === next) {
  9805. tick._index = i;
  9806. count++;
  9807. next = majorIndices[count * spacing];
  9808. } else {
  9809. delete tick.label;
  9810. }
  9811. }
  9812. }
  9813. function skip(ticks, spacing, majorStart, majorEnd) {
  9814. var start = valueOrDefault$a(majorStart, 0);
  9815. var end = Math.min(valueOrDefault$a(majorEnd, ticks.length), ticks.length);
  9816. var count = 0;
  9817. var length, i, tick, next;
  9818. spacing = Math.ceil(spacing);
  9819. if (majorEnd) {
  9820. length = majorEnd - majorStart;
  9821. spacing = length / Math.floor(length / spacing);
  9822. }
  9823. next = start;
  9824. while (next < 0) {
  9825. count++;
  9826. next = Math.round(start + count * spacing);
  9827. }
  9828. for (i = Math.max(start, 0); i < end; i++) {
  9829. tick = ticks[i];
  9830. if (i === next) {
  9831. tick._index = i;
  9832. count++;
  9833. next = Math.round(start + count * spacing);
  9834. } else {
  9835. delete tick.label;
  9836. }
  9837. }
  9838. }
  9839. var Scale = core_element.extend({
  9840. zeroLineIndex: 0,
  9841. /**
  9842. * Get the padding needed for the scale
  9843. * @method getPadding
  9844. * @private
  9845. * @returns {Padding} the necessary padding
  9846. */
  9847. getPadding: function () {
  9848. var me = this;
  9849. return {
  9850. left: me.paddingLeft || 0,
  9851. top: me.paddingTop || 0,
  9852. right: me.paddingRight || 0,
  9853. bottom: me.paddingBottom || 0
  9854. };
  9855. },
  9856. /**
  9857. * Returns the scale tick objects ({label, major})
  9858. * @since 2.7
  9859. */
  9860. getTicks: function () {
  9861. return this._ticks;
  9862. },
  9863. /**
  9864. * @private
  9865. */
  9866. _getLabels: function () {
  9867. var data = this.chart.data;
  9868. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  9869. },
  9870. // These methods are ordered by lifecyle. Utilities then follow.
  9871. // Any function defined here is inherited by all scale types.
  9872. // Any function can be extended by the scale type
  9873. /**
  9874. * Provided for backward compatibility, not available anymore
  9875. * @function Chart.Scale.mergeTicksOptions
  9876. * @deprecated since version 2.8.0
  9877. * @todo remove at version 3
  9878. */
  9879. mergeTicksOptions: function () {
  9880. // noop
  9881. },
  9882. beforeUpdate: function () {
  9883. helpers$1.callback(this.options.beforeUpdate, [this]);
  9884. },
  9885. /**
  9886. * @param {number} maxWidth - the max width in pixels
  9887. * @param {number} maxHeight - the max height in pixels
  9888. * @param {object} margins - the space between the edge of the other scales and edge of the chart
  9889. * This space comes from two sources:
  9890. * - padding - space that's required to show the labels at the edges of the scale
  9891. * - thickness of scales or legends in another orientation
  9892. */
  9893. update: function (maxWidth, maxHeight, margins) {
  9894. var me = this;
  9895. var tickOpts = me.options.ticks;
  9896. var sampleSize = tickOpts.sampleSize;
  9897. var i, ilen, labels, ticks, samplingEnabled;
  9898. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  9899. me.beforeUpdate();
  9900. // Absorb the master measurements
  9901. me.maxWidth = maxWidth;
  9902. me.maxHeight = maxHeight;
  9903. me.margins = helpers$1.extend({
  9904. left: 0,
  9905. right: 0,
  9906. top: 0,
  9907. bottom: 0
  9908. }, margins);
  9909. me._ticks = null;
  9910. me.ticks = null;
  9911. me._labelSizes = null;
  9912. me._maxLabelLines = 0;
  9913. me.longestLabelWidth = 0;
  9914. me.longestTextCache = me.longestTextCache || {};
  9915. me._gridLineItems = null;
  9916. me._labelItems = null;
  9917. // Dimensions
  9918. me.beforeSetDimensions();
  9919. me.setDimensions();
  9920. me.afterSetDimensions();
  9921. // Data min/max
  9922. me.beforeDataLimits();
  9923. me.determineDataLimits();
  9924. me.afterDataLimits();
  9925. // Ticks - `this.ticks` is now DEPRECATED!
  9926. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  9927. // and must not be accessed directly from outside this class. `this.ticks` being
  9928. // around for long time and not marked as private, we can't change its structure
  9929. // without unexpected breaking changes. If you need to access the scale ticks,
  9930. // use scale.getTicks() instead.
  9931. me.beforeBuildTicks();
  9932. // New implementations should return an array of objects but for BACKWARD COMPAT,
  9933. // we still support no return (`this.ticks` internally set by calling this method).
  9934. ticks = me.buildTicks() || [];
  9935. // Allow modification of ticks in callback.
  9936. ticks = me.afterBuildTicks(ticks) || ticks;
  9937. // Ensure ticks contains ticks in new tick format
  9938. if ((!ticks || !ticks.length) && me.ticks) {
  9939. ticks = [];
  9940. for (i = 0, ilen = me.ticks.length; i < ilen; ++i) {
  9941. ticks.push({
  9942. value: me.ticks[i],
  9943. major: false
  9944. });
  9945. }
  9946. }
  9947. me._ticks = ticks;
  9948. // Compute tick rotation and fit using a sampled subset of labels
  9949. // We generally don't need to compute the size of every single label for determining scale size
  9950. samplingEnabled = sampleSize < ticks.length;
  9951. labels = me._convertTicksToLabels(samplingEnabled ? sample(ticks, sampleSize) : ticks);
  9952. // _configure is called twice, once here, once from core.controller.updateLayout.
  9953. // Here we haven't been positioned yet, but dimensions are correct.
  9954. // Variables set in _configure are needed for calculateTickRotation, and
  9955. // it's ok that coordinates are not correct there, only dimensions matter.
  9956. me._configure();
  9957. // Tick Rotation
  9958. me.beforeCalculateTickRotation();
  9959. me.calculateTickRotation();
  9960. me.afterCalculateTickRotation();
  9961. me.beforeFit();
  9962. me.fit();
  9963. me.afterFit();
  9964. // Auto-skip
  9965. me._ticksToDraw = tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto') ? me._autoSkip(ticks) : ticks;
  9966. if (samplingEnabled) {
  9967. // Generate labels using all non-skipped ticks
  9968. labels = me._convertTicksToLabels(me._ticksToDraw);
  9969. }
  9970. me.ticks = labels; // BACKWARD COMPATIBILITY
  9971. // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
  9972. me.afterUpdate();
  9973. // TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused
  9974. // make maxWidth and maxHeight private
  9975. return me.minSize;
  9976. },
  9977. /**
  9978. * @private
  9979. */
  9980. _configure: function () {
  9981. var me = this;
  9982. var reversePixels = me.options.ticks.reverse;
  9983. var startPixel, endPixel;
  9984. if (me.isHorizontal()) {
  9985. startPixel = me.left;
  9986. endPixel = me.right;
  9987. } else {
  9988. startPixel = me.top;
  9989. endPixel = me.bottom;
  9990. // by default vertical scales are from bottom to top, so pixels are reversed
  9991. reversePixels = !reversePixels;
  9992. }
  9993. me._startPixel = startPixel;
  9994. me._endPixel = endPixel;
  9995. me._reversePixels = reversePixels;
  9996. me._length = endPixel - startPixel;
  9997. },
  9998. afterUpdate: function () {
  9999. helpers$1.callback(this.options.afterUpdate, [this]);
  10000. },
  10001. //
  10002. beforeSetDimensions: function () {
  10003. helpers$1.callback(this.options.beforeSetDimensions, [this]);
  10004. },
  10005. setDimensions: function () {
  10006. var me = this;
  10007. // Set the unconstrained dimension before label rotation
  10008. if (me.isHorizontal()) {
  10009. // Reset position before calculating rotation
  10010. me.width = me.maxWidth;
  10011. me.left = 0;
  10012. me.right = me.width;
  10013. } else {
  10014. me.height = me.maxHeight;
  10015. // Reset position before calculating rotation
  10016. me.top = 0;
  10017. me.bottom = me.height;
  10018. }
  10019. // Reset padding
  10020. me.paddingLeft = 0;
  10021. me.paddingTop = 0;
  10022. me.paddingRight = 0;
  10023. me.paddingBottom = 0;
  10024. },
  10025. afterSetDimensions: function () {
  10026. helpers$1.callback(this.options.afterSetDimensions, [this]);
  10027. },
  10028. // Data limits
  10029. beforeDataLimits: function () {
  10030. helpers$1.callback(this.options.beforeDataLimits, [this]);
  10031. },
  10032. determineDataLimits: helpers$1.noop,
  10033. afterDataLimits: function () {
  10034. helpers$1.callback(this.options.afterDataLimits, [this]);
  10035. },
  10036. //
  10037. beforeBuildTicks: function () {
  10038. helpers$1.callback(this.options.beforeBuildTicks, [this]);
  10039. },
  10040. buildTicks: helpers$1.noop,
  10041. afterBuildTicks: function (ticks) {
  10042. var me = this;
  10043. // ticks is empty for old axis implementations here
  10044. if (isArray(ticks) && ticks.length) {
  10045. return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
  10046. }
  10047. // Support old implementations (that modified `this.ticks` directly in buildTicks)
  10048. me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
  10049. return ticks;
  10050. },
  10051. beforeTickToLabelConversion: function () {
  10052. helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
  10053. },
  10054. convertTicksToLabels: function () {
  10055. var me = this;
  10056. // Convert ticks to strings
  10057. var tickOpts = me.options.ticks;
  10058. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  10059. },
  10060. afterTickToLabelConversion: function () {
  10061. helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
  10062. },
  10063. //
  10064. beforeCalculateTickRotation: function () {
  10065. helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
  10066. },
  10067. calculateTickRotation: function () {
  10068. var me = this;
  10069. var options = me.options;
  10070. var tickOpts = options.ticks;
  10071. var numTicks = me.getTicks().length;
  10072. var minRotation = tickOpts.minRotation || 0;
  10073. var maxRotation = tickOpts.maxRotation;
  10074. var labelRotation = minRotation;
  10075. var labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal;
  10076. if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
  10077. me.labelRotation = minRotation;
  10078. return;
  10079. }
  10080. labelSizes = me._getLabelSizes();
  10081. maxLabelWidth = labelSizes.widest.width;
  10082. maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;
  10083. // Estimate the width of each grid based on the canvas width, the maximum
  10084. // label width and the number of tick intervals
  10085. maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);
  10086. tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
  10087. // Allow 3 pixels x2 padding either side for label readability
  10088. if (maxLabelWidth + 6 > tickWidth) {
  10089. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  10090. maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)
  10091. - tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
  10092. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  10093. labelRotation = helpers$1.toDegrees(Math.min(
  10094. Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
  10095. Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
  10096. ));
  10097. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  10098. }
  10099. me.labelRotation = labelRotation;
  10100. },
  10101. afterCalculateTickRotation: function () {
  10102. helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
  10103. },
  10104. //
  10105. beforeFit: function () {
  10106. helpers$1.callback(this.options.beforeFit, [this]);
  10107. },
  10108. fit: function () {
  10109. var me = this;
  10110. // Reset
  10111. var minSize = me.minSize = {
  10112. width: 0,
  10113. height: 0
  10114. };
  10115. var chart = me.chart;
  10116. var opts = me.options;
  10117. var tickOpts = opts.ticks;
  10118. var scaleLabelOpts = opts.scaleLabel;
  10119. var gridLineOpts = opts.gridLines;
  10120. var display = me._isVisible();
  10121. var isBottom = opts.position === 'bottom';
  10122. var isHorizontal = me.isHorizontal();
  10123. // Width
  10124. if (isHorizontal) {
  10125. minSize.width = me.maxWidth;
  10126. } else if (display) {
  10127. minSize.width = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10128. }
  10129. // height
  10130. if (!isHorizontal) {
  10131. minSize.height = me.maxHeight; // fill all the height
  10132. } else if (display) {
  10133. minSize.height = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10134. }
  10135. // Don't bother fitting the ticks if we are not showing the labels
  10136. if (tickOpts.display && display) {
  10137. var tickFonts = parseTickFontOptions(tickOpts);
  10138. var labelSizes = me._getLabelSizes();
  10139. var firstLabelSize = labelSizes.first;
  10140. var lastLabelSize = labelSizes.last;
  10141. var widestLabelSize = labelSizes.widest;
  10142. var highestLabelSize = labelSizes.highest;
  10143. var lineSpace = tickFonts.minor.lineHeight * 0.4;
  10144. var tickPadding = tickOpts.padding;
  10145. if (isHorizontal) {
  10146. // A horizontal axis is more constrained by the height.
  10147. var isRotated = me.labelRotation !== 0;
  10148. var angleRadians = helpers$1.toRadians(me.labelRotation);
  10149. var cosRotation = Math.cos(angleRadians);
  10150. var sinRotation = Math.sin(angleRadians);
  10151. var labelHeight = sinRotation * widestLabelSize.width
  10152. + cosRotation * (highestLabelSize.height - (isRotated ? highestLabelSize.offset : 0))
  10153. + (isRotated ? 0 : lineSpace); // padding
  10154. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  10155. var offsetLeft = me.getPixelForTick(0) - me.left;
  10156. var offsetRight = me.right - me.getPixelForTick(me.getTicks().length - 1);
  10157. var paddingLeft, paddingRight;
  10158. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  10159. // which means that the right padding is dominated by the font height
  10160. if (isRotated) {
  10161. paddingLeft = isBottom ?
  10162. cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset :
  10163. sinRotation * (firstLabelSize.height - firstLabelSize.offset);
  10164. paddingRight = isBottom ?
  10165. sinRotation * (lastLabelSize.height - lastLabelSize.offset) :
  10166. cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset;
  10167. } else {
  10168. paddingLeft = firstLabelSize.width / 2;
  10169. paddingRight = lastLabelSize.width / 2;
  10170. }
  10171. // Adjust padding taking into account changes in offsets
  10172. // and add 3 px to move away from canvas edges
  10173. me.paddingLeft = Math.max((paddingLeft - offsetLeft) * me.width / (me.width - offsetLeft), 0) + 3;
  10174. me.paddingRight = Math.max((paddingRight - offsetRight) * me.width / (me.width - offsetRight), 0) + 3;
  10175. } else {
  10176. // A vertical axis is more constrained by the width. Labels are the
  10177. // dominant factor here, so get that length first and account for padding
  10178. var labelWidth = tickOpts.mirror ? 0 :
  10179. // use lineSpace for consistency with horizontal axis
  10180. // tickPadding is not implemented for horizontal
  10181. widestLabelSize.width + tickPadding + lineSpace;
  10182. minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth);
  10183. me.paddingTop = firstLabelSize.height / 2;
  10184. me.paddingBottom = lastLabelSize.height / 2;
  10185. }
  10186. }
  10187. me.handleMargins();
  10188. if (isHorizontal) {
  10189. me.width = me._length = chart.width - me.margins.left - me.margins.right;
  10190. me.height = minSize.height;
  10191. } else {
  10192. me.width = minSize.width;
  10193. me.height = me._length = chart.height - me.margins.top - me.margins.bottom;
  10194. }
  10195. },
  10196. /**
  10197. * Handle margins and padding interactions
  10198. * @private
  10199. */
  10200. handleMargins: function () {
  10201. var me = this;
  10202. if (me.margins) {
  10203. me.margins.left = Math.max(me.paddingLeft, me.margins.left);
  10204. me.margins.top = Math.max(me.paddingTop, me.margins.top);
  10205. me.margins.right = Math.max(me.paddingRight, me.margins.right);
  10206. me.margins.bottom = Math.max(me.paddingBottom, me.margins.bottom);
  10207. }
  10208. },
  10209. afterFit: function () {
  10210. helpers$1.callback(this.options.afterFit, [this]);
  10211. },
  10212. // Shared Methods
  10213. isHorizontal: function () {
  10214. var pos = this.options.position;
  10215. return pos === 'top' || pos === 'bottom';
  10216. },
  10217. isFullWidth: function () {
  10218. return this.options.fullWidth;
  10219. },
  10220. // Get the correct value. NaN bad inputs, If the value type is object get the x or y based on whether we are horizontal or not
  10221. getRightValue: function (rawValue) {
  10222. // Null and undefined values first
  10223. if (isNullOrUndef(rawValue)) {
  10224. return NaN;
  10225. }
  10226. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  10227. if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
  10228. return NaN;
  10229. }
  10230. // If it is in fact an object, dive in one more level
  10231. if (rawValue) {
  10232. if (this.isHorizontal()) {
  10233. if (rawValue.x !== undefined) {
  10234. return this.getRightValue(rawValue.x);
  10235. }
  10236. } else if (rawValue.y !== undefined) {
  10237. return this.getRightValue(rawValue.y);
  10238. }
  10239. }
  10240. // Value is good, return it
  10241. return rawValue;
  10242. },
  10243. _convertTicksToLabels: function (ticks) {
  10244. var me = this;
  10245. var labels, i, ilen;
  10246. me.ticks = ticks.map(function (tick) {
  10247. return tick.value;
  10248. });
  10249. me.beforeTickToLabelConversion();
  10250. // New implementations should return the formatted tick labels but for BACKWARD
  10251. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  10252. // this method and supposed to contain only string values).
  10253. labels = me.convertTicksToLabels(ticks) || me.ticks;
  10254. me.afterTickToLabelConversion();
  10255. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  10256. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10257. ticks[i].label = labels[i];
  10258. }
  10259. return labels;
  10260. },
  10261. /**
  10262. * @private
  10263. */
  10264. _getLabelSizes: function () {
  10265. var me = this;
  10266. var labelSizes = me._labelSizes;
  10267. if (!labelSizes) {
  10268. me._labelSizes = labelSizes = computeLabelSizes(me.ctx, parseTickFontOptions(me.options.ticks), me.getTicks(), me.longestTextCache);
  10269. me.longestLabelWidth = labelSizes.widest.width;
  10270. }
  10271. return labelSizes;
  10272. },
  10273. /**
  10274. * @private
  10275. */
  10276. _parseValue: function (value) {
  10277. var start, end, min, max;
  10278. if (isArray(value)) {
  10279. start = +this.getRightValue(value[0]);
  10280. end = +this.getRightValue(value[1]);
  10281. min = Math.min(start, end);
  10282. max = Math.max(start, end);
  10283. } else {
  10284. value = +this.getRightValue(value);
  10285. start = undefined;
  10286. end = value;
  10287. min = value;
  10288. max = value;
  10289. }
  10290. return {
  10291. min: min,
  10292. max: max,
  10293. start: start,
  10294. end: end
  10295. };
  10296. },
  10297. /**
  10298. * @private
  10299. */
  10300. _getScaleLabel: function (rawValue) {
  10301. var v = this._parseValue(rawValue);
  10302. if (v.start !== undefined) {
  10303. return '[' + v.start + ', ' + v.end + ']';
  10304. }
  10305. return +this.getRightValue(rawValue);
  10306. },
  10307. /**
  10308. * Used to get the value to display in the tooltip for the data at the given index
  10309. * @param index
  10310. * @param datasetIndex
  10311. */
  10312. getLabelForIndex: helpers$1.noop,
  10313. /**
  10314. * Returns the location of the given data point. Value can either be an index or a numerical value
  10315. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10316. * @param value
  10317. * @param index
  10318. * @param datasetIndex
  10319. */
  10320. getPixelForValue: helpers$1.noop,
  10321. /**
  10322. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  10323. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10324. * @param pixel
  10325. */
  10326. getValueForPixel: helpers$1.noop,
  10327. /**
  10328. * Returns the location of the tick at the given index
  10329. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10330. */
  10331. getPixelForTick: function (index) {
  10332. var me = this;
  10333. var offset = me.options.offset;
  10334. var numTicks = me._ticks.length;
  10335. var tickWidth = 1 / Math.max(numTicks - (offset ? 0 : 1), 1);
  10336. return index < 0 || index > numTicks - 1
  10337. ? null
  10338. : me.getPixelForDecimal(index * tickWidth + (offset ? tickWidth / 2 : 0));
  10339. },
  10340. /**
  10341. * Utility for getting the pixel location of a percentage of scale
  10342. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10343. */
  10344. getPixelForDecimal: function (decimal) {
  10345. var me = this;
  10346. if (me._reversePixels) {
  10347. decimal = 1 - decimal;
  10348. }
  10349. return me._startPixel + decimal * me._length;
  10350. },
  10351. getDecimalForPixel: function (pixel) {
  10352. var decimal = (pixel - this._startPixel) / this._length;
  10353. return this._reversePixels ? 1 - decimal : decimal;
  10354. },
  10355. /**
  10356. * Returns the pixel for the minimum chart value
  10357. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10358. */
  10359. getBasePixel: function () {
  10360. return this.getPixelForValue(this.getBaseValue());
  10361. },
  10362. getBaseValue: function () {
  10363. var me = this;
  10364. var min = me.min;
  10365. var max = me.max;
  10366. return me.beginAtZero ? 0 :
  10367. min < 0 && max < 0 ? max :
  10368. min > 0 && max > 0 ? min :
  10369. 0;
  10370. },
  10371. /**
  10372. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  10373. * @private
  10374. */
  10375. _autoSkip: function (ticks) {
  10376. var me = this;
  10377. var tickOpts = me.options.ticks;
  10378. var axisLength = me._length;
  10379. var ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1;
  10380. var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  10381. var numMajorIndices = majorIndices.length;
  10382. var first = majorIndices[0];
  10383. var last = majorIndices[numMajorIndices - 1];
  10384. var i, ilen, spacing, avgMajorSpacing;
  10385. // If there are too many major ticks to display them all
  10386. if (numMajorIndices > ticksLimit) {
  10387. skipMajors(ticks, majorIndices, numMajorIndices / ticksLimit);
  10388. return nonSkipped(ticks);
  10389. }
  10390. spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit);
  10391. if (numMajorIndices > 0) {
  10392. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  10393. skip(ticks, spacing, majorIndices[i], majorIndices[i + 1]);
  10394. }
  10395. avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null;
  10396. skip(ticks, spacing, helpers$1.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  10397. skip(ticks, spacing, last, helpers$1.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  10398. return nonSkipped(ticks);
  10399. }
  10400. skip(ticks, spacing);
  10401. return nonSkipped(ticks);
  10402. },
  10403. /**
  10404. * @private
  10405. */
  10406. _tickSize: function () {
  10407. var me = this;
  10408. var optionTicks = me.options.ticks;
  10409. // Calculate space needed by label in axis direction.
  10410. var rot = helpers$1.toRadians(me.labelRotation);
  10411. var cos = Math.abs(Math.cos(rot));
  10412. var sin = Math.abs(Math.sin(rot));
  10413. var labelSizes = me._getLabelSizes();
  10414. var padding = optionTicks.autoSkipPadding || 0;
  10415. var w = labelSizes ? labelSizes.widest.width + padding : 0;
  10416. var h = labelSizes ? labelSizes.highest.height + padding : 0;
  10417. // Calculate space needed for 1 tick in axis direction.
  10418. return me.isHorizontal()
  10419. ? h * cos > w * sin ? w / cos : h / sin
  10420. : h * sin < w * cos ? h / cos : w / sin;
  10421. },
  10422. /**
  10423. * @private
  10424. */
  10425. _isVisible: function () {
  10426. var me = this;
  10427. var chart = me.chart;
  10428. var display = me.options.display;
  10429. var i, ilen, meta;
  10430. if (display !== 'auto') {
  10431. return !!display;
  10432. }
  10433. // When 'auto', the scale is visible if at least one associated dataset is visible.
  10434. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  10435. if (chart.isDatasetVisible(i)) {
  10436. meta = chart.getDatasetMeta(i);
  10437. if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
  10438. return true;
  10439. }
  10440. }
  10441. }
  10442. return false;
  10443. },
  10444. /**
  10445. * @private
  10446. */
  10447. _computeGridLineItems: function (chartArea) {
  10448. var me = this;
  10449. var chart = me.chart;
  10450. var options = me.options;
  10451. var gridLines = options.gridLines;
  10452. var position = options.position;
  10453. var offsetGridLines = gridLines.offsetGridLines;
  10454. var isHorizontal = me.isHorizontal();
  10455. var ticks = me._ticksToDraw;
  10456. var ticksLength = ticks.length + (offsetGridLines ? 1 : 0);
  10457. var tl = getTickMarkLength(gridLines);
  10458. var items = [];
  10459. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10460. var axisHalfWidth = axisWidth / 2;
  10461. var alignPixel = helpers$1._alignPixel;
  10462. var alignBorderValue = function (pixel) {
  10463. return alignPixel(chart, pixel, axisWidth);
  10464. };
  10465. var borderValue, i, tick, lineValue, alignedLineValue;
  10466. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, lineWidth, lineColor, borderDash, borderDashOffset;
  10467. if (position === 'top') {
  10468. borderValue = alignBorderValue(me.bottom);
  10469. ty1 = me.bottom - tl;
  10470. ty2 = borderValue - axisHalfWidth;
  10471. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  10472. y2 = chartArea.bottom;
  10473. } else if (position === 'bottom') {
  10474. borderValue = alignBorderValue(me.top);
  10475. y1 = chartArea.top;
  10476. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  10477. ty1 = borderValue + axisHalfWidth;
  10478. ty2 = me.top + tl;
  10479. } else if (position === 'left') {
  10480. borderValue = alignBorderValue(me.right);
  10481. tx1 = me.right - tl;
  10482. tx2 = borderValue - axisHalfWidth;
  10483. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  10484. x2 = chartArea.right;
  10485. } else {
  10486. borderValue = alignBorderValue(me.left);
  10487. x1 = chartArea.left;
  10488. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  10489. tx1 = borderValue + axisHalfWidth;
  10490. tx2 = me.left + tl;
  10491. }
  10492. for (i = 0; i < ticksLength; ++i) {
  10493. tick = ticks[i] || {};
  10494. // autoskipper skipped this tick (#4635)
  10495. if (isNullOrUndef(tick.label) && i < ticks.length) {
  10496. continue;
  10497. }
  10498. if (i === me.zeroLineIndex && options.offset === offsetGridLines) {
  10499. // Draw the first index specially
  10500. lineWidth = gridLines.zeroLineWidth;
  10501. lineColor = gridLines.zeroLineColor;
  10502. borderDash = gridLines.zeroLineBorderDash || [];
  10503. borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
  10504. } else {
  10505. lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, i, 1);
  10506. lineColor = valueAtIndexOrDefault(gridLines.color, i, 'rgba(0,0,0,0.1)');
  10507. borderDash = gridLines.borderDash || [];
  10508. borderDashOffset = gridLines.borderDashOffset || 0.0;
  10509. }
  10510. lineValue = getPixelForGridLine(me, tick._index || i, offsetGridLines);
  10511. // Skip if the pixel is out of the range
  10512. if (lineValue === undefined) {
  10513. continue;
  10514. }
  10515. alignedLineValue = alignPixel(chart, lineValue, lineWidth);
  10516. if (isHorizontal) {
  10517. tx1 = tx2 = x1 = x2 = alignedLineValue;
  10518. } else {
  10519. ty1 = ty2 = y1 = y2 = alignedLineValue;
  10520. }
  10521. items.push({
  10522. tx1: tx1,
  10523. ty1: ty1,
  10524. tx2: tx2,
  10525. ty2: ty2,
  10526. x1: x1,
  10527. y1: y1,
  10528. x2: x2,
  10529. y2: y2,
  10530. width: lineWidth,
  10531. color: lineColor,
  10532. borderDash: borderDash,
  10533. borderDashOffset: borderDashOffset,
  10534. });
  10535. }
  10536. items.ticksLength = ticksLength;
  10537. items.borderValue = borderValue;
  10538. return items;
  10539. },
  10540. /**
  10541. * @private
  10542. */
  10543. _computeLabelItems: function () {
  10544. var me = this;
  10545. var options = me.options;
  10546. var optionTicks = options.ticks;
  10547. var position = options.position;
  10548. var isMirrored = optionTicks.mirror;
  10549. var isHorizontal = me.isHorizontal();
  10550. var ticks = me._ticksToDraw;
  10551. var fonts = parseTickFontOptions(optionTicks);
  10552. var tickPadding = optionTicks.padding;
  10553. var tl = getTickMarkLength(options.gridLines);
  10554. var rotation = -helpers$1.toRadians(me.labelRotation);
  10555. var items = [];
  10556. var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  10557. if (position === 'top') {
  10558. y = me.bottom - tl - tickPadding;
  10559. textAlign = !rotation ? 'center' : 'left';
  10560. } else if (position === 'bottom') {
  10561. y = me.top + tl + tickPadding;
  10562. textAlign = !rotation ? 'center' : 'right';
  10563. } else if (position === 'left') {
  10564. x = me.right - (isMirrored ? 0 : tl) - tickPadding;
  10565. textAlign = isMirrored ? 'left' : 'right';
  10566. } else {
  10567. x = me.left + (isMirrored ? 0 : tl) + tickPadding;
  10568. textAlign = isMirrored ? 'right' : 'left';
  10569. }
  10570. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10571. tick = ticks[i];
  10572. label = tick.label;
  10573. // autoskipper skipped this tick (#4635)
  10574. if (isNullOrUndef(label)) {
  10575. continue;
  10576. }
  10577. pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset;
  10578. font = tick.major ? fonts.major : fonts.minor;
  10579. lineHeight = font.lineHeight;
  10580. lineCount = isArray(label) ? label.length : 1;
  10581. if (isHorizontal) {
  10582. x = pixel;
  10583. textOffset = position === 'top'
  10584. ? ((!rotation ? 0.5 : 1) - lineCount) * lineHeight
  10585. : (!rotation ? 0.5 : 0) * lineHeight;
  10586. } else {
  10587. y = pixel;
  10588. textOffset = (1 - lineCount) * lineHeight / 2;
  10589. }
  10590. items.push({
  10591. x: x,
  10592. y: y,
  10593. rotation: rotation,
  10594. label: label,
  10595. font: font,
  10596. textOffset: textOffset,
  10597. textAlign: textAlign
  10598. });
  10599. }
  10600. return items;
  10601. },
  10602. /**
  10603. * @private
  10604. */
  10605. _drawGrid: function (chartArea) {
  10606. var me = this;
  10607. var gridLines = me.options.gridLines;
  10608. if (!gridLines.display) {
  10609. return;
  10610. }
  10611. var ctx = me.ctx;
  10612. var chart = me.chart;
  10613. var alignPixel = helpers$1._alignPixel;
  10614. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10615. var items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
  10616. var width, color, i, ilen, item;
  10617. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10618. item = items[i];
  10619. width = item.width;
  10620. color = item.color;
  10621. if (width && color) {
  10622. ctx.save();
  10623. ctx.lineWidth = width;
  10624. ctx.strokeStyle = color;
  10625. if (ctx.setLineDash) {
  10626. ctx.setLineDash(item.borderDash);
  10627. ctx.lineDashOffset = item.borderDashOffset;
  10628. }
  10629. ctx.beginPath();
  10630. if (gridLines.drawTicks) {
  10631. ctx.moveTo(item.tx1, item.ty1);
  10632. ctx.lineTo(item.tx2, item.ty2);
  10633. }
  10634. if (gridLines.drawOnChartArea) {
  10635. ctx.moveTo(item.x1, item.y1);
  10636. ctx.lineTo(item.x2, item.y2);
  10637. }
  10638. ctx.stroke();
  10639. ctx.restore();
  10640. }
  10641. }
  10642. if (axisWidth) {
  10643. // Draw the line at the edge of the axis
  10644. var firstLineWidth = axisWidth;
  10645. var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, items.ticksLength - 1, 1);
  10646. var borderValue = items.borderValue;
  10647. var x1, x2, y1, y2;
  10648. if (me.isHorizontal()) {
  10649. x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
  10650. x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  10651. y1 = y2 = borderValue;
  10652. } else {
  10653. y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
  10654. y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  10655. x1 = x2 = borderValue;
  10656. }
  10657. ctx.lineWidth = axisWidth;
  10658. ctx.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
  10659. ctx.beginPath();
  10660. ctx.moveTo(x1, y1);
  10661. ctx.lineTo(x2, y2);
  10662. ctx.stroke();
  10663. }
  10664. },
  10665. /**
  10666. * @private
  10667. */
  10668. _drawLabels: function () {
  10669. var me = this;
  10670. var optionTicks = me.options.ticks;
  10671. if (!optionTicks.display) {
  10672. return;
  10673. }
  10674. var ctx = me.ctx;
  10675. var items = me._labelItems || (me._labelItems = me._computeLabelItems());
  10676. var i, j, ilen, jlen, item, tickFont, label, y;
  10677. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10678. item = items[i];
  10679. tickFont = item.font;
  10680. // Make sure we draw text in the correct color and font
  10681. ctx.save();
  10682. ctx.translate(item.x, item.y);
  10683. ctx.rotate(item.rotation);
  10684. ctx.font = tickFont.string;
  10685. ctx.fillStyle = tickFont.color;
  10686. ctx.textBaseline = 'middle';
  10687. ctx.textAlign = item.textAlign;
  10688. label = item.label;
  10689. y = item.textOffset;
  10690. if (isArray(label)) {
  10691. for (j = 0, jlen = label.length; j < jlen; ++j) {
  10692. // We just make sure the multiline element is a string here..
  10693. ctx.fillText('' + label[j], 0, y);
  10694. y += tickFont.lineHeight;
  10695. }
  10696. } else {
  10697. ctx.fillText(label, 0, y);
  10698. }
  10699. ctx.restore();
  10700. }
  10701. },
  10702. /**
  10703. * @private
  10704. */
  10705. _drawTitle: function () {
  10706. var me = this;
  10707. var ctx = me.ctx;
  10708. var options = me.options;
  10709. var scaleLabel = options.scaleLabel;
  10710. if (!scaleLabel.display) {
  10711. return;
  10712. }
  10713. var scaleLabelFontColor = valueOrDefault$a(scaleLabel.fontColor, core_defaults.global.defaultFontColor);
  10714. var scaleLabelFont = helpers$1.options._parseFont(scaleLabel);
  10715. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
  10716. var halfLineHeight = scaleLabelFont.lineHeight / 2;
  10717. var position = options.position;
  10718. var rotation = 0;
  10719. var scaleLabelX, scaleLabelY;
  10720. if (me.isHorizontal()) {
  10721. scaleLabelX = me.left + me.width / 2; // midpoint of the width
  10722. scaleLabelY = position === 'bottom'
  10723. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  10724. : me.top + halfLineHeight + scaleLabelPadding.top;
  10725. } else {
  10726. var isLeft = position === 'left';
  10727. scaleLabelX = isLeft
  10728. ? me.left + halfLineHeight + scaleLabelPadding.top
  10729. : me.right - halfLineHeight - scaleLabelPadding.top;
  10730. scaleLabelY = me.top + me.height / 2;
  10731. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  10732. }
  10733. ctx.save();
  10734. ctx.translate(scaleLabelX, scaleLabelY);
  10735. ctx.rotate(rotation);
  10736. ctx.textAlign = 'center';
  10737. ctx.textBaseline = 'middle';
  10738. ctx.fillStyle = scaleLabelFontColor; // render in correct colour
  10739. ctx.font = scaleLabelFont.string;
  10740. ctx.fillText(scaleLabel.labelString, 0, 0);
  10741. ctx.restore();
  10742. },
  10743. draw: function (chartArea) {
  10744. var me = this;
  10745. if (!me._isVisible()) {
  10746. return;
  10747. }
  10748. me._drawGrid(chartArea);
  10749. me._drawTitle();
  10750. me._drawLabels();
  10751. },
  10752. /**
  10753. * @private
  10754. */
  10755. _layers: function () {
  10756. var me = this;
  10757. var opts = me.options;
  10758. var tz = opts.ticks && opts.ticks.z || 0;
  10759. var gz = opts.gridLines && opts.gridLines.z || 0;
  10760. if (!me._isVisible() || tz === gz || me.draw !== me._draw) {
  10761. // backward compatibility: draw has been overridden by custom scale
  10762. return [{
  10763. z: tz,
  10764. draw: function () {
  10765. me.draw.apply(me, arguments);
  10766. }
  10767. }];
  10768. }
  10769. return [{
  10770. z: gz,
  10771. draw: function () {
  10772. me._drawGrid.apply(me, arguments);
  10773. me._drawTitle.apply(me, arguments);
  10774. }
  10775. }, {
  10776. z: tz,
  10777. draw: function () {
  10778. me._drawLabels.apply(me, arguments);
  10779. }
  10780. }];
  10781. },
  10782. /**
  10783. * @private
  10784. */
  10785. _getMatchingVisibleMetas: function (type) {
  10786. var me = this;
  10787. var isHorizontal = me.isHorizontal();
  10788. return me.chart._getSortedVisibleDatasetMetas()
  10789. .filter(function (meta) {
  10790. return (!type || meta.type === type)
  10791. && (isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id);
  10792. });
  10793. }
  10794. });
  10795. Scale.prototype._draw = Scale.prototype.draw;
  10796. var core_scale = Scale;
  10797. var isNullOrUndef$1 = helpers$1.isNullOrUndef;
  10798. var defaultConfig = {
  10799. position: 'bottom'
  10800. };
  10801. var scale_category = core_scale.extend({
  10802. determineDataLimits: function () {
  10803. var me = this;
  10804. var labels = me._getLabels();
  10805. var ticksOpts = me.options.ticks;
  10806. var min = ticksOpts.min;
  10807. var max = ticksOpts.max;
  10808. var minIndex = 0;
  10809. var maxIndex = labels.length - 1;
  10810. var findIndex;
  10811. if (min !== undefined) {
  10812. // user specified min value
  10813. findIndex = labels.indexOf(min);
  10814. if (findIndex >= 0) {
  10815. minIndex = findIndex;
  10816. }
  10817. }
  10818. if (max !== undefined) {
  10819. // user specified max value
  10820. findIndex = labels.indexOf(max);
  10821. if (findIndex >= 0) {
  10822. maxIndex = findIndex;
  10823. }
  10824. }
  10825. me.minIndex = minIndex;
  10826. me.maxIndex = maxIndex;
  10827. me.min = labels[minIndex];
  10828. me.max = labels[maxIndex];
  10829. },
  10830. buildTicks: function () {
  10831. var me = this;
  10832. var labels = me._getLabels();
  10833. var minIndex = me.minIndex;
  10834. var maxIndex = me.maxIndex;
  10835. // If we are viewing some subset of labels, slice the original array
  10836. me.ticks = (minIndex === 0 && maxIndex === labels.length - 1) ? labels : labels.slice(minIndex, maxIndex + 1);
  10837. },
  10838. getLabelForIndex: function (index, datasetIndex) {
  10839. var me = this;
  10840. var chart = me.chart;
  10841. if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {
  10842. return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);
  10843. }
  10844. return me._getLabels()[index];
  10845. },
  10846. _configure: function () {
  10847. var me = this;
  10848. var offset = me.options.offset;
  10849. var ticks = me.ticks;
  10850. core_scale.prototype._configure.call(me);
  10851. if (!me.isHorizontal()) {
  10852. // For backward compatibility, vertical category scale reverse is inverted.
  10853. me._reversePixels = !me._reversePixels;
  10854. }
  10855. if (!ticks) {
  10856. return;
  10857. }
  10858. me._startValue = me.minIndex - (offset ? 0.5 : 0);
  10859. me._valueRange = Math.max(ticks.length - (offset ? 0 : 1), 1);
  10860. },
  10861. // Used to get data value locations. Value can either be an index or a numerical value
  10862. getPixelForValue: function (value, index, datasetIndex) {
  10863. var me = this;
  10864. var valueCategory, labels, idx;
  10865. if (!isNullOrUndef$1(index) && !isNullOrUndef$1(datasetIndex)) {
  10866. value = me.chart.data.datasets[datasetIndex].data[index];
  10867. }
  10868. // If value is a data object, then index is the index in the data array,
  10869. // not the index of the scale. We need to change that.
  10870. if (!isNullOrUndef$1(value)) {
  10871. valueCategory = me.isHorizontal() ? value.x : value.y;
  10872. }
  10873. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  10874. labels = me._getLabels();
  10875. value = helpers$1.valueOrDefault(valueCategory, value);
  10876. idx = labels.indexOf(value);
  10877. index = idx !== -1 ? idx : index;
  10878. if (isNaN(index)) {
  10879. index = value;
  10880. }
  10881. }
  10882. return me.getPixelForDecimal((index - me._startValue) / me._valueRange);
  10883. },
  10884. getPixelForTick: function (index) {
  10885. var ticks = this.ticks;
  10886. return index < 0 || index > ticks.length - 1
  10887. ? null
  10888. : this.getPixelForValue(ticks[index], index + this.minIndex);
  10889. },
  10890. getValueForPixel: function (pixel) {
  10891. var me = this;
  10892. var value = Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
  10893. return Math.min(Math.max(value, 0), me.ticks.length - 1);
  10894. },
  10895. getBasePixel: function () {
  10896. return this.bottom;
  10897. }
  10898. });
  10899. // INTERNAL: static default options, registered in src/index.js
  10900. var _defaults = defaultConfig;
  10901. scale_category._defaults = _defaults;
  10902. var noop = helpers$1.noop;
  10903. var isNullOrUndef$2 = helpers$1.isNullOrUndef;
  10904. /**
  10905. * Generate a set of linear ticks
  10906. * @param generationOptions the options used to generate the ticks
  10907. * @param dataRange the range of the data
  10908. * @returns {number[]} array of tick values
  10909. */
  10910. function generateTicks(generationOptions, dataRange) {
  10911. var ticks = [];
  10912. // To get a "nice" value for the tick spacing, we will use the appropriately named
  10913. // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  10914. // for details.
  10915. var MIN_SPACING = 1e-14;
  10916. var stepSize = generationOptions.stepSize;
  10917. var unit = stepSize || 1;
  10918. var maxNumSpaces = generationOptions.maxTicks - 1;
  10919. var min = generationOptions.min;
  10920. var max = generationOptions.max;
  10921. var precision = generationOptions.precision;
  10922. var rmin = dataRange.min;
  10923. var rmax = dataRange.max;
  10924. var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
  10925. var factor, niceMin, niceMax, numSpaces;
  10926. // Beyond MIN_SPACING floating point numbers being to lose precision
  10927. // such that we can't do the math necessary to generate ticks
  10928. if (spacing < MIN_SPACING && isNullOrUndef$2(min) && isNullOrUndef$2(max)) {
  10929. return [rmin, rmax];
  10930. }
  10931. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  10932. if (numSpaces > maxNumSpaces) {
  10933. // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
  10934. spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
  10935. }
  10936. if (stepSize || isNullOrUndef$2(precision)) {
  10937. // If a precision is not specified, calculate factor based on spacing
  10938. factor = Math.pow(10, helpers$1._decimalPlaces(spacing));
  10939. } else {
  10940. // If the user specified a precision, round to that number of decimal places
  10941. factor = Math.pow(10, precision);
  10942. spacing = Math.ceil(spacing * factor) / factor;
  10943. }
  10944. niceMin = Math.floor(rmin / spacing) * spacing;
  10945. niceMax = Math.ceil(rmax / spacing) * spacing;
  10946. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  10947. if (stepSize) {
  10948. // If very close to our whole number, use it.
  10949. if (!isNullOrUndef$2(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
  10950. niceMin = min;
  10951. }
  10952. if (!isNullOrUndef$2(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
  10953. niceMax = max;
  10954. }
  10955. }
  10956. numSpaces = (niceMax - niceMin) / spacing;
  10957. // If very close to our rounded value, use it.
  10958. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  10959. numSpaces = Math.round(numSpaces);
  10960. } else {
  10961. numSpaces = Math.ceil(numSpaces);
  10962. }
  10963. niceMin = Math.round(niceMin * factor) / factor;
  10964. niceMax = Math.round(niceMax * factor) / factor;
  10965. ticks.push(isNullOrUndef$2(min) ? niceMin : min);
  10966. for (var j = 1; j < numSpaces; ++j) {
  10967. ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
  10968. }
  10969. ticks.push(isNullOrUndef$2(max) ? niceMax : max);
  10970. return ticks;
  10971. }
  10972. var scale_linearbase = core_scale.extend({
  10973. getRightValue: function (value) {
  10974. if (typeof value === 'string') {
  10975. return +value;
  10976. }
  10977. return core_scale.prototype.getRightValue.call(this, value);
  10978. },
  10979. handleTickRangeOptions: function () {
  10980. var me = this;
  10981. var opts = me.options;
  10982. var tickOpts = opts.ticks;
  10983. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  10984. // do nothing since that would make the chart weird. If the user really wants a weird chart
  10985. // axis, they can manually override it
  10986. if (tickOpts.beginAtZero) {
  10987. var minSign = helpers$1.sign(me.min);
  10988. var maxSign = helpers$1.sign(me.max);
  10989. if (minSign < 0 && maxSign < 0) {
  10990. // move the top up to 0
  10991. me.max = 0;
  10992. } else if (minSign > 0 && maxSign > 0) {
  10993. // move the bottom down to 0
  10994. me.min = 0;
  10995. }
  10996. }
  10997. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  10998. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  10999. if (tickOpts.min !== undefined) {
  11000. me.min = tickOpts.min;
  11001. } else if (tickOpts.suggestedMin !== undefined) {
  11002. if (me.min === null) {
  11003. me.min = tickOpts.suggestedMin;
  11004. } else {
  11005. me.min = Math.min(me.min, tickOpts.suggestedMin);
  11006. }
  11007. }
  11008. if (tickOpts.max !== undefined) {
  11009. me.max = tickOpts.max;
  11010. } else if (tickOpts.suggestedMax !== undefined) {
  11011. if (me.max === null) {
  11012. me.max = tickOpts.suggestedMax;
  11013. } else {
  11014. me.max = Math.max(me.max, tickOpts.suggestedMax);
  11015. }
  11016. }
  11017. if (setMin !== setMax) {
  11018. // We set the min or the max but not both.
  11019. // So ensure that our range is good
  11020. // Inverted or 0 length range can happen when
  11021. // ticks.min is set, and no datasets are visible
  11022. if (me.min >= me.max) {
  11023. if (setMin) {
  11024. me.max = me.min + 1;
  11025. } else {
  11026. me.min = me.max - 1;
  11027. }
  11028. }
  11029. }
  11030. if (me.min === me.max) {
  11031. me.max++;
  11032. if (!tickOpts.beginAtZero) {
  11033. me.min--;
  11034. }
  11035. }
  11036. },
  11037. getTickLimit: function () {
  11038. var me = this;
  11039. var tickOpts = me.options.ticks;
  11040. var stepSize = tickOpts.stepSize;
  11041. var maxTicksLimit = tickOpts.maxTicksLimit;
  11042. var maxTicks;
  11043. if (stepSize) {
  11044. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  11045. } else {
  11046. maxTicks = me._computeTickLimit();
  11047. maxTicksLimit = maxTicksLimit || 11;
  11048. }
  11049. if (maxTicksLimit) {
  11050. maxTicks = Math.min(maxTicksLimit, maxTicks);
  11051. }
  11052. return maxTicks;
  11053. },
  11054. _computeTickLimit: function () {
  11055. return Number.POSITIVE_INFINITY;
  11056. },
  11057. handleDirectionalChanges: noop,
  11058. buildTicks: function () {
  11059. var me = this;
  11060. var opts = me.options;
  11061. var tickOpts = opts.ticks;
  11062. // Figure out what the max number of ticks we can support it is based on the size of
  11063. // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
  11064. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  11065. // the graph. Make sure we always have at least 2 ticks
  11066. var maxTicks = me.getTickLimit();
  11067. maxTicks = Math.max(2, maxTicks);
  11068. var numericGeneratorOptions = {
  11069. maxTicks: maxTicks,
  11070. min: tickOpts.min,
  11071. max: tickOpts.max,
  11072. precision: tickOpts.precision,
  11073. stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  11074. };
  11075. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  11076. me.handleDirectionalChanges();
  11077. // At this point, we need to update our max and min given the tick values since we have expanded the
  11078. // range of the scale
  11079. me.max = helpers$1.max(ticks);
  11080. me.min = helpers$1.min(ticks);
  11081. if (tickOpts.reverse) {
  11082. ticks.reverse();
  11083. me.start = me.max;
  11084. me.end = me.min;
  11085. } else {
  11086. me.start = me.min;
  11087. me.end = me.max;
  11088. }
  11089. },
  11090. convertTicksToLabels: function () {
  11091. var me = this;
  11092. me.ticksAsNumbers = me.ticks.slice();
  11093. me.zeroLineIndex = me.ticks.indexOf(0);
  11094. core_scale.prototype.convertTicksToLabels.call(me);
  11095. },
  11096. _configure: function () {
  11097. var me = this;
  11098. var ticks = me.getTicks();
  11099. var start = me.min;
  11100. var end = me.max;
  11101. var offset;
  11102. core_scale.prototype._configure.call(me);
  11103. if (me.options.offset && ticks.length) {
  11104. offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  11105. start -= offset;
  11106. end += offset;
  11107. }
  11108. me._startValue = start;
  11109. me._endValue = end;
  11110. me._valueRange = end - start;
  11111. }
  11112. });
  11113. var defaultConfig$1 = {
  11114. position: 'left',
  11115. ticks: {
  11116. callback: core_ticks.formatters.linear
  11117. }
  11118. };
  11119. var DEFAULT_MIN = 0;
  11120. var DEFAULT_MAX = 1;
  11121. function getOrCreateStack(stacks, stacked, meta) {
  11122. var key = [
  11123. meta.type,
  11124. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11125. stacked === undefined && meta.stack === undefined ? meta.index : '',
  11126. meta.stack
  11127. ].join('.');
  11128. if (stacks[key] === undefined) {
  11129. stacks[key] = {
  11130. pos: [],
  11131. neg: []
  11132. };
  11133. }
  11134. return stacks[key];
  11135. }
  11136. function stackData(scale, stacks, meta, data) {
  11137. var opts = scale.options;
  11138. var stacked = opts.stacked;
  11139. var stack = getOrCreateStack(stacks, stacked, meta);
  11140. var pos = stack.pos;
  11141. var neg = stack.neg;
  11142. var ilen = data.length;
  11143. var i, value;
  11144. for (i = 0; i < ilen; ++i) {
  11145. value = scale._parseValue(data[i]);
  11146. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11147. continue;
  11148. }
  11149. pos[i] = pos[i] || 0;
  11150. neg[i] = neg[i] || 0;
  11151. if (opts.relativePoints) {
  11152. pos[i] = 100;
  11153. } else if (value.min < 0 || value.max < 0) {
  11154. neg[i] += value.min;
  11155. } else {
  11156. pos[i] += value.max;
  11157. }
  11158. }
  11159. }
  11160. function updateMinMax(scale, meta, data) {
  11161. var ilen = data.length;
  11162. var i, value;
  11163. for (i = 0; i < ilen; ++i) {
  11164. value = scale._parseValue(data[i]);
  11165. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11166. continue;
  11167. }
  11168. scale.min = Math.min(scale.min, value.min);
  11169. scale.max = Math.max(scale.max, value.max);
  11170. }
  11171. }
  11172. var scale_linear = scale_linearbase.extend({
  11173. determineDataLimits: function () {
  11174. var me = this;
  11175. var opts = me.options;
  11176. var chart = me.chart;
  11177. var datasets = chart.data.datasets;
  11178. var metasets = me._getMatchingVisibleMetas();
  11179. var hasStacks = opts.stacked;
  11180. var stacks = {};
  11181. var ilen = metasets.length;
  11182. var i, meta, data, values;
  11183. me.min = Number.POSITIVE_INFINITY;
  11184. me.max = Number.NEGATIVE_INFINITY;
  11185. if (hasStacks === undefined) {
  11186. for (i = 0; !hasStacks && i < ilen; ++i) {
  11187. meta = metasets[i];
  11188. hasStacks = meta.stack !== undefined;
  11189. }
  11190. }
  11191. for (i = 0; i < ilen; ++i) {
  11192. meta = metasets[i];
  11193. data = datasets[meta.index].data;
  11194. if (hasStacks) {
  11195. stackData(me, stacks, meta, data);
  11196. } else {
  11197. updateMinMax(me, meta, data);
  11198. }
  11199. }
  11200. helpers$1.each(stacks, function (stackValues) {
  11201. values = stackValues.pos.concat(stackValues.neg);
  11202. me.min = Math.min(me.min, helpers$1.min(values));
  11203. me.max = Math.max(me.max, helpers$1.max(values));
  11204. });
  11205. me.min = helpers$1.isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  11206. me.max = helpers$1.isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  11207. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11208. me.handleTickRangeOptions();
  11209. },
  11210. // Returns the maximum number of ticks based on the scale dimension
  11211. _computeTickLimit: function () {
  11212. var me = this;
  11213. var tickFont;
  11214. if (me.isHorizontal()) {
  11215. return Math.ceil(me.width / 40);
  11216. }
  11217. tickFont = helpers$1.options._parseFont(me.options.ticks);
  11218. return Math.ceil(me.height / tickFont.lineHeight);
  11219. },
  11220. // Called after the ticks are built. We need
  11221. handleDirectionalChanges: function () {
  11222. if (!this.isHorizontal()) {
  11223. // We are in a vertical orientation. The top value is the highest. So reverse the array
  11224. this.ticks.reverse();
  11225. }
  11226. },
  11227. getLabelForIndex: function (index, datasetIndex) {
  11228. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11229. },
  11230. // Utils
  11231. getPixelForValue: function (value) {
  11232. var me = this;
  11233. return me.getPixelForDecimal((+me.getRightValue(value) - me._startValue) / me._valueRange);
  11234. },
  11235. getValueForPixel: function (pixel) {
  11236. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  11237. },
  11238. getPixelForTick: function (index) {
  11239. var ticks = this.ticksAsNumbers;
  11240. if (index < 0 || index > ticks.length - 1) {
  11241. return null;
  11242. }
  11243. return this.getPixelForValue(ticks[index]);
  11244. }
  11245. });
  11246. // INTERNAL: static default options, registered in src/index.js
  11247. var _defaults$1 = defaultConfig$1;
  11248. scale_linear._defaults = _defaults$1;
  11249. var valueOrDefault$b = helpers$1.valueOrDefault;
  11250. var log10 = helpers$1.math.log10;
  11251. /**
  11252. * Generate a set of logarithmic ticks
  11253. * @param generationOptions the options used to generate the ticks
  11254. * @param dataRange the range of the data
  11255. * @returns {number[]} array of tick values
  11256. */
  11257. function generateTicks$1(generationOptions, dataRange) {
  11258. var ticks = [];
  11259. var tickVal = valueOrDefault$b(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  11260. var endExp = Math.floor(log10(dataRange.max));
  11261. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  11262. var exp, significand;
  11263. if (tickVal === 0) {
  11264. exp = Math.floor(log10(dataRange.minNotZero));
  11265. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  11266. ticks.push(tickVal);
  11267. tickVal = significand * Math.pow(10, exp);
  11268. } else {
  11269. exp = Math.floor(log10(tickVal));
  11270. significand = Math.floor(tickVal / Math.pow(10, exp));
  11271. }
  11272. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  11273. do {
  11274. ticks.push(tickVal);
  11275. ++significand;
  11276. if (significand === 10) {
  11277. significand = 1;
  11278. ++exp;
  11279. precision = exp >= 0 ? 1 : precision;
  11280. }
  11281. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  11282. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  11283. var lastTick = valueOrDefault$b(generationOptions.max, tickVal);
  11284. ticks.push(lastTick);
  11285. return ticks;
  11286. }
  11287. var defaultConfig$2 = {
  11288. position: 'left',
  11289. // label settings
  11290. ticks: {
  11291. callback: core_ticks.formatters.logarithmic
  11292. }
  11293. };
  11294. // TODO(v3): change this to positiveOrDefault
  11295. function nonNegativeOrDefault(value, defaultValue) {
  11296. return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;
  11297. }
  11298. var scale_logarithmic = core_scale.extend({
  11299. determineDataLimits: function () {
  11300. var me = this;
  11301. var opts = me.options;
  11302. var chart = me.chart;
  11303. var datasets = chart.data.datasets;
  11304. var isHorizontal = me.isHorizontal();
  11305. function IDMatches(meta) {
  11306. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  11307. }
  11308. var datasetIndex, meta, value, data, i, ilen;
  11309. // Calculate Range
  11310. me.min = Number.POSITIVE_INFINITY;
  11311. me.max = Number.NEGATIVE_INFINITY;
  11312. me.minNotZero = Number.POSITIVE_INFINITY;
  11313. var hasStacks = opts.stacked;
  11314. if (hasStacks === undefined) {
  11315. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11316. meta = chart.getDatasetMeta(datasetIndex);
  11317. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  11318. meta.stack !== undefined) {
  11319. hasStacks = true;
  11320. break;
  11321. }
  11322. }
  11323. }
  11324. if (opts.stacked || hasStacks) {
  11325. var valuesPerStack = {};
  11326. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11327. meta = chart.getDatasetMeta(datasetIndex);
  11328. var key = [
  11329. meta.type,
  11330. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11331. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  11332. meta.stack
  11333. ].join('.');
  11334. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11335. if (valuesPerStack[key] === undefined) {
  11336. valuesPerStack[key] = [];
  11337. }
  11338. data = datasets[datasetIndex].data;
  11339. for (i = 0, ilen = data.length; i < ilen; i++) {
  11340. var values = valuesPerStack[key];
  11341. value = me._parseValue(data[i]);
  11342. // invalid, hidden and negative values are ignored
  11343. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11344. continue;
  11345. }
  11346. values[i] = values[i] || 0;
  11347. values[i] += value.max;
  11348. }
  11349. }
  11350. }
  11351. helpers$1.each(valuesPerStack, function (valuesForType) {
  11352. if (valuesForType.length > 0) {
  11353. var minVal = helpers$1.min(valuesForType);
  11354. var maxVal = helpers$1.max(valuesForType);
  11355. me.min = Math.min(me.min, minVal);
  11356. me.max = Math.max(me.max, maxVal);
  11357. }
  11358. });
  11359. } else {
  11360. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11361. meta = chart.getDatasetMeta(datasetIndex);
  11362. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11363. data = datasets[datasetIndex].data;
  11364. for (i = 0, ilen = data.length; i < ilen; i++) {
  11365. value = me._parseValue(data[i]);
  11366. // invalid, hidden and negative values are ignored
  11367. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11368. continue;
  11369. }
  11370. me.min = Math.min(value.min, me.min);
  11371. me.max = Math.max(value.max, me.max);
  11372. if (value.min !== 0) {
  11373. me.minNotZero = Math.min(value.min, me.minNotZero);
  11374. }
  11375. }
  11376. }
  11377. }
  11378. }
  11379. me.min = helpers$1.isFinite(me.min) ? me.min : null;
  11380. me.max = helpers$1.isFinite(me.max) ? me.max : null;
  11381. me.minNotZero = helpers$1.isFinite(me.minNotZero) ? me.minNotZero : null;
  11382. // Common base implementation to handle ticks.min, ticks.max
  11383. this.handleTickRangeOptions();
  11384. },
  11385. handleTickRangeOptions: function () {
  11386. var me = this;
  11387. var tickOpts = me.options.ticks;
  11388. var DEFAULT_MIN = 1;
  11389. var DEFAULT_MAX = 10;
  11390. me.min = nonNegativeOrDefault(tickOpts.min, me.min);
  11391. me.max = nonNegativeOrDefault(tickOpts.max, me.max);
  11392. if (me.min === me.max) {
  11393. if (me.min !== 0 && me.min !== null) {
  11394. me.min = Math.pow(10, Math.floor(log10(me.min)) - 1);
  11395. me.max = Math.pow(10, Math.floor(log10(me.max)) + 1);
  11396. } else {
  11397. me.min = DEFAULT_MIN;
  11398. me.max = DEFAULT_MAX;
  11399. }
  11400. }
  11401. if (me.min === null) {
  11402. me.min = Math.pow(10, Math.floor(log10(me.max)) - 1);
  11403. }
  11404. if (me.max === null) {
  11405. me.max = me.min !== 0
  11406. ? Math.pow(10, Math.floor(log10(me.min)) + 1)
  11407. : DEFAULT_MAX;
  11408. }
  11409. if (me.minNotZero === null) {
  11410. if (me.min > 0) {
  11411. me.minNotZero = me.min;
  11412. } else if (me.max < 1) {
  11413. me.minNotZero = Math.pow(10, Math.floor(log10(me.max)));
  11414. } else {
  11415. me.minNotZero = DEFAULT_MIN;
  11416. }
  11417. }
  11418. },
  11419. buildTicks: function () {
  11420. var me = this;
  11421. var tickOpts = me.options.ticks;
  11422. var reverse = !me.isHorizontal();
  11423. var generationOptions = {
  11424. min: nonNegativeOrDefault(tickOpts.min),
  11425. max: nonNegativeOrDefault(tickOpts.max)
  11426. };
  11427. var ticks = me.ticks = generateTicks$1(generationOptions, me);
  11428. // At this point, we need to update our max and min given the tick values since we have expanded the
  11429. // range of the scale
  11430. me.max = helpers$1.max(ticks);
  11431. me.min = helpers$1.min(ticks);
  11432. if (tickOpts.reverse) {
  11433. reverse = !reverse;
  11434. me.start = me.max;
  11435. me.end = me.min;
  11436. } else {
  11437. me.start = me.min;
  11438. me.end = me.max;
  11439. }
  11440. if (reverse) {
  11441. ticks.reverse();
  11442. }
  11443. },
  11444. convertTicksToLabels: function () {
  11445. this.tickValues = this.ticks.slice();
  11446. core_scale.prototype.convertTicksToLabels.call(this);
  11447. },
  11448. // Get the correct tooltip label
  11449. getLabelForIndex: function (index, datasetIndex) {
  11450. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11451. },
  11452. getPixelForTick: function (index) {
  11453. var ticks = this.tickValues;
  11454. if (index < 0 || index > ticks.length - 1) {
  11455. return null;
  11456. }
  11457. return this.getPixelForValue(ticks[index]);
  11458. },
  11459. /**
  11460. * Returns the value of the first tick.
  11461. * @param {number} value - The minimum not zero value.
  11462. * @return {number} The first tick value.
  11463. * @private
  11464. */
  11465. _getFirstTickValue: function (value) {
  11466. var exp = Math.floor(log10(value));
  11467. var significand = Math.floor(value / Math.pow(10, exp));
  11468. return significand * Math.pow(10, exp);
  11469. },
  11470. _configure: function () {
  11471. var me = this;
  11472. var start = me.min;
  11473. var offset = 0;
  11474. core_scale.prototype._configure.call(me);
  11475. if (start === 0) {
  11476. start = me._getFirstTickValue(me.minNotZero);
  11477. offset = valueOrDefault$b(me.options.ticks.fontSize, core_defaults.global.defaultFontSize) / me._length;
  11478. }
  11479. me._startValue = log10(start);
  11480. me._valueOffset = offset;
  11481. me._valueRange = (log10(me.max) - log10(start)) / (1 - offset);
  11482. },
  11483. getPixelForValue: function (value) {
  11484. var me = this;
  11485. var decimal = 0;
  11486. value = +me.getRightValue(value);
  11487. if (value > me.min && value > 0) {
  11488. decimal = (log10(value) - me._startValue) / me._valueRange + me._valueOffset;
  11489. }
  11490. return me.getPixelForDecimal(decimal);
  11491. },
  11492. getValueForPixel: function (pixel) {
  11493. var me = this;
  11494. var decimal = me.getDecimalForPixel(pixel);
  11495. return decimal === 0 && me.min === 0
  11496. ? 0
  11497. : Math.pow(10, me._startValue + (decimal - me._valueOffset) * me._valueRange);
  11498. }
  11499. });
  11500. // INTERNAL: static default options, registered in src/index.js
  11501. var _defaults$2 = defaultConfig$2;
  11502. scale_logarithmic._defaults = _defaults$2;
  11503. var valueOrDefault$c = helpers$1.valueOrDefault;
  11504. var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
  11505. var resolve$4 = helpers$1.options.resolve;
  11506. var defaultConfig$3 = {
  11507. display: true,
  11508. // Boolean - Whether to animate scaling the chart from the centre
  11509. animate: true,
  11510. position: 'chartArea',
  11511. angleLines: {
  11512. display: true,
  11513. color: 'rgba(0,0,0,0.1)',
  11514. lineWidth: 1,
  11515. borderDash: [],
  11516. borderDashOffset: 0.0
  11517. },
  11518. gridLines: {
  11519. circular: false
  11520. },
  11521. // label settings
  11522. ticks: {
  11523. // Boolean - Show a backdrop to the scale label
  11524. showLabelBackdrop: true,
  11525. // String - The colour of the label backdrop
  11526. backdropColor: 'rgba(255,255,255,0.75)',
  11527. // Number - The backdrop padding above & below the label in pixels
  11528. backdropPaddingY: 2,
  11529. // Number - The backdrop padding to the side of the label in pixels
  11530. backdropPaddingX: 2,
  11531. callback: core_ticks.formatters.linear
  11532. },
  11533. pointLabels: {
  11534. // Boolean - if true, show point labels
  11535. display: true,
  11536. // Number - Point label font size in pixels
  11537. fontSize: 10,
  11538. // Function - Used to convert point labels
  11539. callback: function (label) {
  11540. return label;
  11541. }
  11542. }
  11543. };
  11544. function getTickBackdropHeight(opts) {
  11545. var tickOpts = opts.ticks;
  11546. if (tickOpts.display && opts.display) {
  11547. return valueOrDefault$c(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
  11548. }
  11549. return 0;
  11550. }
  11551. function measureLabelSize(ctx, lineHeight, label) {
  11552. if (helpers$1.isArray(label)) {
  11553. return {
  11554. w: helpers$1.longestText(ctx, ctx.font, label),
  11555. h: label.length * lineHeight
  11556. };
  11557. }
  11558. return {
  11559. w: ctx.measureText(label).width,
  11560. h: lineHeight
  11561. };
  11562. }
  11563. function determineLimits(angle, pos, size, min, max) {
  11564. if (angle === min || angle === max) {
  11565. return {
  11566. start: pos - (size / 2),
  11567. end: pos + (size / 2)
  11568. };
  11569. } else if (angle < min || angle > max) {
  11570. return {
  11571. start: pos - size,
  11572. end: pos
  11573. };
  11574. }
  11575. return {
  11576. start: pos,
  11577. end: pos + size
  11578. };
  11579. }
  11580. /**
  11581. * Helper function to fit a radial linear scale with point labels
  11582. */
  11583. function fitWithPointLabels(scale) {
  11584. // Right, this is really confusing and there is a lot of maths going on here
  11585. // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  11586. //
  11587. // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  11588. //
  11589. // Solution:
  11590. //
  11591. // We assume the radius of the polygon is half the size of the canvas at first
  11592. // at each index we check if the text overlaps.
  11593. //
  11594. // Where it does, we store that angle and that index.
  11595. //
  11596. // After finding the largest index and angle we calculate how much we need to remove
  11597. // from the shape radius to move the point inwards by that x.
  11598. //
  11599. // We average the left and right distances to get the maximum shape radius that can fit in the box
  11600. // along with labels.
  11601. //
  11602. // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  11603. // on each side, removing that from the size, halving it and adding the left x protrusion width.
  11604. //
  11605. // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  11606. // and position it in the most space efficient manner
  11607. //
  11608. // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  11609. var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
  11610. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  11611. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  11612. var furthestLimits = {
  11613. l: 0,
  11614. r: scale.width,
  11615. t: 0,
  11616. b: scale.height - scale.paddingTop
  11617. };
  11618. var furthestAngles = {};
  11619. var i, textSize, pointPosition;
  11620. scale.ctx.font = plFont.string;
  11621. scale._pointLabelSizes = [];
  11622. var valueCount = scale.chart.data.labels.length;
  11623. for (i = 0; i < valueCount; i++) {
  11624. pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
  11625. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);
  11626. scale._pointLabelSizes[i] = textSize;
  11627. // Add quarter circle to make degree 0 mean top of circle
  11628. var angleRadians = scale.getIndexAngle(i);
  11629. var angle = helpers$1.toDegrees(angleRadians) % 360;
  11630. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  11631. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  11632. if (hLimits.start < furthestLimits.l) {
  11633. furthestLimits.l = hLimits.start;
  11634. furthestAngles.l = angleRadians;
  11635. }
  11636. if (hLimits.end > furthestLimits.r) {
  11637. furthestLimits.r = hLimits.end;
  11638. furthestAngles.r = angleRadians;
  11639. }
  11640. if (vLimits.start < furthestLimits.t) {
  11641. furthestLimits.t = vLimits.start;
  11642. furthestAngles.t = angleRadians;
  11643. }
  11644. if (vLimits.end > furthestLimits.b) {
  11645. furthestLimits.b = vLimits.end;
  11646. furthestAngles.b = angleRadians;
  11647. }
  11648. }
  11649. scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  11650. }
  11651. function getTextAlignForAngle(angle) {
  11652. if (angle === 0 || angle === 180) {
  11653. return 'center';
  11654. } else if (angle < 180) {
  11655. return 'left';
  11656. }
  11657. return 'right';
  11658. }
  11659. function fillText(ctx, text, position, lineHeight) {
  11660. var y = position.y + lineHeight / 2;
  11661. var i, ilen;
  11662. if (helpers$1.isArray(text)) {
  11663. for (i = 0, ilen = text.length; i < ilen; ++i) {
  11664. ctx.fillText(text[i], position.x, y);
  11665. y += lineHeight;
  11666. }
  11667. } else {
  11668. ctx.fillText(text, position.x, y);
  11669. }
  11670. }
  11671. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  11672. if (angle === 90 || angle === 270) {
  11673. position.y -= (textSize.h / 2);
  11674. } else if (angle > 270 || angle < 90) {
  11675. position.y -= textSize.h;
  11676. }
  11677. }
  11678. function drawPointLabels(scale) {
  11679. var ctx = scale.ctx;
  11680. var opts = scale.options;
  11681. var pointLabelOpts = opts.pointLabels;
  11682. var tickBackdropHeight = getTickBackdropHeight(opts);
  11683. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  11684. var plFont = helpers$1.options._parseFont(pointLabelOpts);
  11685. ctx.save();
  11686. ctx.font = plFont.string;
  11687. ctx.textBaseline = 'middle';
  11688. for (var i = scale.chart.data.labels.length - 1; i >= 0; i--) {
  11689. // Extra pixels out for some label spacing
  11690. var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  11691. var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
  11692. // Keep this in loop since we may support array properties here
  11693. var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
  11694. ctx.fillStyle = pointLabelFontColor;
  11695. var angleRadians = scale.getIndexAngle(i);
  11696. var angle = helpers$1.toDegrees(angleRadians);
  11697. ctx.textAlign = getTextAlignForAngle(angle);
  11698. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  11699. fillText(ctx, scale.pointLabels[i], pointLabelPosition, plFont.lineHeight);
  11700. }
  11701. ctx.restore();
  11702. }
  11703. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  11704. var ctx = scale.ctx;
  11705. var circular = gridLineOpts.circular;
  11706. var valueCount = scale.chart.data.labels.length;
  11707. var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
  11708. var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
  11709. var pointPosition;
  11710. if ((!circular && !valueCount) || !lineColor || !lineWidth) {
  11711. return;
  11712. }
  11713. ctx.save();
  11714. ctx.strokeStyle = lineColor;
  11715. ctx.lineWidth = lineWidth;
  11716. if (ctx.setLineDash) {
  11717. ctx.setLineDash(gridLineOpts.borderDash || []);
  11718. ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
  11719. }
  11720. ctx.beginPath();
  11721. if (circular) {
  11722. // Draw circular arcs between the points
  11723. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  11724. } else {
  11725. // Draw straight lines connecting each index
  11726. pointPosition = scale.getPointPosition(0, radius);
  11727. ctx.moveTo(pointPosition.x, pointPosition.y);
  11728. for (var i = 1; i < valueCount; i++) {
  11729. pointPosition = scale.getPointPosition(i, radius);
  11730. ctx.lineTo(pointPosition.x, pointPosition.y);
  11731. }
  11732. }
  11733. ctx.closePath();
  11734. ctx.stroke();
  11735. ctx.restore();
  11736. }
  11737. function numberOrZero(param) {
  11738. return helpers$1.isNumber(param) ? param : 0;
  11739. }
  11740. var scale_radialLinear = scale_linearbase.extend({
  11741. setDimensions: function () {
  11742. var me = this;
  11743. // Set the unconstrained dimension before label rotation
  11744. me.width = me.maxWidth;
  11745. me.height = me.maxHeight;
  11746. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  11747. me.xCenter = Math.floor(me.width / 2);
  11748. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  11749. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  11750. },
  11751. determineDataLimits: function () {
  11752. var me = this;
  11753. var chart = me.chart;
  11754. var min = Number.POSITIVE_INFINITY;
  11755. var max = Number.NEGATIVE_INFINITY;
  11756. helpers$1.each(chart.data.datasets, function (dataset, datasetIndex) {
  11757. if (chart.isDatasetVisible(datasetIndex)) {
  11758. var meta = chart.getDatasetMeta(datasetIndex);
  11759. helpers$1.each(dataset.data, function (rawValue, index) {
  11760. var value = +me.getRightValue(rawValue);
  11761. if (isNaN(value) || meta.data[index].hidden) {
  11762. return;
  11763. }
  11764. min = Math.min(value, min);
  11765. max = Math.max(value, max);
  11766. });
  11767. }
  11768. });
  11769. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  11770. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  11771. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11772. me.handleTickRangeOptions();
  11773. },
  11774. // Returns the maximum number of ticks based on the scale dimension
  11775. _computeTickLimit: function () {
  11776. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  11777. },
  11778. convertTicksToLabels: function () {
  11779. var me = this;
  11780. scale_linearbase.prototype.convertTicksToLabels.call(me);
  11781. // Point labels
  11782. me.pointLabels = me.chart.data.labels.map(function () {
  11783. var label = helpers$1.callback(me.options.pointLabels.callback, arguments, me);
  11784. return label || label === 0 ? label : '';
  11785. });
  11786. },
  11787. getLabelForIndex: function (index, datasetIndex) {
  11788. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  11789. },
  11790. fit: function () {
  11791. var me = this;
  11792. var opts = me.options;
  11793. if (opts.display && opts.pointLabels.display) {
  11794. fitWithPointLabels(me);
  11795. } else {
  11796. me.setCenterPoint(0, 0, 0, 0);
  11797. }
  11798. },
  11799. /**
  11800. * Set radius reductions and determine new radius and center point
  11801. * @private
  11802. */
  11803. setReductions: function (largestPossibleRadius, furthestLimits, furthestAngles) {
  11804. var me = this;
  11805. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  11806. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  11807. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  11808. var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  11809. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  11810. radiusReductionRight = numberOrZero(radiusReductionRight);
  11811. radiusReductionTop = numberOrZero(radiusReductionTop);
  11812. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  11813. me.drawingArea = Math.min(
  11814. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  11815. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  11816. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  11817. },
  11818. setCenterPoint: function (leftMovement, rightMovement, topMovement, bottomMovement) {
  11819. var me = this;
  11820. var maxRight = me.width - rightMovement - me.drawingArea;
  11821. var maxLeft = leftMovement + me.drawingArea;
  11822. var maxTop = topMovement + me.drawingArea;
  11823. var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  11824. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  11825. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  11826. },
  11827. getIndexAngle: function (index) {
  11828. var chart = this.chart;
  11829. var angleMultiplier = 360 / chart.data.labels.length;
  11830. var options = chart.options || {};
  11831. var startAngle = options.startAngle || 0;
  11832. // Start from the top instead of right, so remove a quarter of the circle
  11833. var angle = (index * angleMultiplier + startAngle) % 360;
  11834. return (angle < 0 ? angle + 360 : angle) * Math.PI * 2 / 360;
  11835. },
  11836. getDistanceFromCenterForValue: function (value) {
  11837. var me = this;
  11838. if (helpers$1.isNullOrUndef(value)) {
  11839. return NaN;
  11840. }
  11841. // Take into account half font size + the yPadding of the top value
  11842. var scalingFactor = me.drawingArea / (me.max - me.min);
  11843. if (me.options.ticks.reverse) {
  11844. return (me.max - value) * scalingFactor;
  11845. }
  11846. return (value - me.min) * scalingFactor;
  11847. },
  11848. getPointPosition: function (index, distanceFromCenter) {
  11849. var me = this;
  11850. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  11851. return {
  11852. x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
  11853. y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
  11854. };
  11855. },
  11856. getPointPositionForValue: function (index, value) {
  11857. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  11858. },
  11859. getBasePosition: function (index) {
  11860. var me = this;
  11861. var min = me.min;
  11862. var max = me.max;
  11863. return me.getPointPositionForValue(index || 0,
  11864. me.beginAtZero ? 0 :
  11865. min < 0 && max < 0 ? max :
  11866. min > 0 && max > 0 ? min :
  11867. 0);
  11868. },
  11869. /**
  11870. * @private
  11871. */
  11872. _drawGrid: function () {
  11873. var me = this;
  11874. var ctx = me.ctx;
  11875. var opts = me.options;
  11876. var gridLineOpts = opts.gridLines;
  11877. var angleLineOpts = opts.angleLines;
  11878. var lineWidth = valueOrDefault$c(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
  11879. var lineColor = valueOrDefault$c(angleLineOpts.color, gridLineOpts.color);
  11880. var i, offset, position;
  11881. if (opts.pointLabels.display) {
  11882. drawPointLabels(me);
  11883. }
  11884. if (gridLineOpts.display) {
  11885. helpers$1.each(me.ticks, function (label, index) {
  11886. if (index !== 0) {
  11887. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11888. drawRadiusLine(me, gridLineOpts, offset, index);
  11889. }
  11890. });
  11891. }
  11892. if (angleLineOpts.display && lineWidth && lineColor) {
  11893. ctx.save();
  11894. ctx.lineWidth = lineWidth;
  11895. ctx.strokeStyle = lineColor;
  11896. if (ctx.setLineDash) {
  11897. ctx.setLineDash(resolve$4([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
  11898. ctx.lineDashOffset = resolve$4([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
  11899. }
  11900. for (i = me.chart.data.labels.length - 1; i >= 0; i--) {
  11901. offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
  11902. position = me.getPointPosition(i, offset);
  11903. ctx.beginPath();
  11904. ctx.moveTo(me.xCenter, me.yCenter);
  11905. ctx.lineTo(position.x, position.y);
  11906. ctx.stroke();
  11907. }
  11908. ctx.restore();
  11909. }
  11910. },
  11911. /**
  11912. * @private
  11913. */
  11914. _drawLabels: function () {
  11915. var me = this;
  11916. var ctx = me.ctx;
  11917. var opts = me.options;
  11918. var tickOpts = opts.ticks;
  11919. if (!tickOpts.display) {
  11920. return;
  11921. }
  11922. var startAngle = me.getIndexAngle(0);
  11923. var tickFont = helpers$1.options._parseFont(tickOpts);
  11924. var tickFontColor = valueOrDefault$c(tickOpts.fontColor, core_defaults.global.defaultFontColor);
  11925. var offset, width;
  11926. ctx.save();
  11927. ctx.font = tickFont.string;
  11928. ctx.translate(me.xCenter, me.yCenter);
  11929. ctx.rotate(startAngle);
  11930. ctx.textAlign = 'center';
  11931. ctx.textBaseline = 'middle';
  11932. helpers$1.each(me.ticks, function (label, index) {
  11933. if (index === 0 && !tickOpts.reverse) {
  11934. return;
  11935. }
  11936. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11937. if (tickOpts.showLabelBackdrop) {
  11938. width = ctx.measureText(label).width;
  11939. ctx.fillStyle = tickOpts.backdropColor;
  11940. ctx.fillRect(
  11941. -width / 2 - tickOpts.backdropPaddingX,
  11942. -offset - tickFont.size / 2 - tickOpts.backdropPaddingY,
  11943. width + tickOpts.backdropPaddingX * 2,
  11944. tickFont.size + tickOpts.backdropPaddingY * 2
  11945. );
  11946. }
  11947. ctx.fillStyle = tickFontColor;
  11948. ctx.fillText(label, 0, -offset);
  11949. });
  11950. ctx.restore();
  11951. },
  11952. /**
  11953. * @private
  11954. */
  11955. _drawTitle: helpers$1.noop
  11956. });
  11957. // INTERNAL: static default options, registered in src/index.js
  11958. var _defaults$3 = defaultConfig$3;
  11959. scale_radialLinear._defaults = _defaults$3;
  11960. var deprecated$1 = helpers$1._deprecated;
  11961. var resolve$5 = helpers$1.options.resolve;
  11962. var valueOrDefault$d = helpers$1.valueOrDefault;
  11963. // Integer constants are from the ES6 spec.
  11964. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  11965. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  11966. var INTERVALS = {
  11967. millisecond: {
  11968. common: true,
  11969. size: 1,
  11970. steps: 1000
  11971. },
  11972. second: {
  11973. common: true,
  11974. size: 1000,
  11975. steps: 60
  11976. },
  11977. minute: {
  11978. common: true,
  11979. size: 60000,
  11980. steps: 60
  11981. },
  11982. hour: {
  11983. common: true,
  11984. size: 3600000,
  11985. steps: 24
  11986. },
  11987. day: {
  11988. common: true,
  11989. size: 86400000,
  11990. steps: 30
  11991. },
  11992. week: {
  11993. common: false,
  11994. size: 604800000,
  11995. steps: 4
  11996. },
  11997. month: {
  11998. common: true,
  11999. size: 2.628e9,
  12000. steps: 12
  12001. },
  12002. quarter: {
  12003. common: false,
  12004. size: 7.884e9,
  12005. steps: 4
  12006. },
  12007. year: {
  12008. common: true,
  12009. size: 3.154e10
  12010. }
  12011. };
  12012. var UNITS = Object.keys(INTERVALS);
  12013. function sorter(a, b) {
  12014. return a - b;
  12015. }
  12016. function arrayUnique(items) {
  12017. var hash = {};
  12018. var out = [];
  12019. var i, ilen, item;
  12020. for (i = 0, ilen = items.length; i < ilen; ++i) {
  12021. item = items[i];
  12022. if (!hash[item]) {
  12023. hash[item] = true;
  12024. out.push(item);
  12025. }
  12026. }
  12027. return out;
  12028. }
  12029. function getMin(options) {
  12030. return helpers$1.valueOrDefault(options.time.min, options.ticks.min);
  12031. }
  12032. function getMax(options) {
  12033. return helpers$1.valueOrDefault(options.time.max, options.ticks.max);
  12034. }
  12035. /**
  12036. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  12037. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  12038. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  12039. * extremity (left + width or top + height). Note that it would be more optimized to directly
  12040. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  12041. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  12042. *
  12043. * @param {number[]} timestamps - timestamps sorted from lowest to highest.
  12044. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
  12045. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  12046. * If 'series', timestamps will be positioned at the same distance from each other. In this
  12047. * case, only timestamps that break the time linearity are registered, meaning that in the
  12048. * best case, all timestamps are linear, the table contains only min and max.
  12049. */
  12050. function buildLookupTable(timestamps, min, max, distribution) {
  12051. if (distribution === 'linear' || !timestamps.length) {
  12052. return [
  12053. {time: min, pos: 0},
  12054. {time: max, pos: 1}
  12055. ];
  12056. }
  12057. var table = [];
  12058. var items = [min];
  12059. var i, ilen, prev, curr, next;
  12060. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12061. curr = timestamps[i];
  12062. if (curr > min && curr < max) {
  12063. items.push(curr);
  12064. }
  12065. }
  12066. items.push(max);
  12067. for (i = 0, ilen = items.length; i < ilen; ++i) {
  12068. next = items[i + 1];
  12069. prev = items[i - 1];
  12070. curr = items[i];
  12071. // only add points that breaks the scale linearity
  12072. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  12073. table.push({time: curr, pos: i / (ilen - 1)});
  12074. }
  12075. }
  12076. return table;
  12077. }
  12078. // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  12079. function lookup(table, key, value) {
  12080. var lo = 0;
  12081. var hi = table.length - 1;
  12082. var mid, i0, i1;
  12083. while (lo >= 0 && lo <= hi) {
  12084. mid = (lo + hi) >> 1;
  12085. i0 = table[mid - 1] || null;
  12086. i1 = table[mid];
  12087. if (!i0) {
  12088. // given value is outside table (before first item)
  12089. return {lo: null, hi: i1};
  12090. } else if (i1[key] < value) {
  12091. lo = mid + 1;
  12092. } else if (i0[key] > value) {
  12093. hi = mid - 1;
  12094. } else {
  12095. return {lo: i0, hi: i1};
  12096. }
  12097. }
  12098. // given value is outside table (after last item)
  12099. return {lo: i1, hi: null};
  12100. }
  12101. /**
  12102. * Linearly interpolates the given source `value` using the table items `skey` values and
  12103. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  12104. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  12105. * index [0, 1] or [n - 1, n] are used for the interpolation.
  12106. */
  12107. function interpolate$1(table, skey, sval, tkey) {
  12108. var range = lookup(table, skey, sval);
  12109. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  12110. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  12111. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  12112. var span = next[skey] - prev[skey];
  12113. var ratio = span ? (sval - prev[skey]) / span : 0;
  12114. var offset = (next[tkey] - prev[tkey]) * ratio;
  12115. return prev[tkey] + offset;
  12116. }
  12117. function toTimestamp(scale, input) {
  12118. var adapter = scale._adapter;
  12119. var options = scale.options.time;
  12120. var parser = options.parser;
  12121. var format = parser || options.format;
  12122. var value = input;
  12123. if (typeof parser === 'function') {
  12124. value = parser(value);
  12125. }
  12126. // Only parse if its not a timestamp already
  12127. if (!helpers$1.isFinite(value)) {
  12128. value = typeof format === 'string'
  12129. ? adapter.parse(value, format)
  12130. : adapter.parse(value);
  12131. }
  12132. if (value !== null) {
  12133. return +value;
  12134. }
  12135. // Labels are in an incompatible format and no `parser` has been provided.
  12136. // The user might still use the deprecated `format` option for parsing.
  12137. if (!parser && typeof format === 'function') {
  12138. value = format(input);
  12139. // `format` could return something else than a timestamp, if so, parse it
  12140. if (!helpers$1.isFinite(value)) {
  12141. value = adapter.parse(value);
  12142. }
  12143. }
  12144. return value;
  12145. }
  12146. function parse(scale, input) {
  12147. if (helpers$1.isNullOrUndef(input)) {
  12148. return null;
  12149. }
  12150. var options = scale.options.time;
  12151. var value = toTimestamp(scale, scale.getRightValue(input));
  12152. if (value === null) {
  12153. return value;
  12154. }
  12155. if (options.round) {
  12156. value = +scale._adapter.startOf(value, options.round);
  12157. }
  12158. return value;
  12159. }
  12160. /**
  12161. * Figures out what unit results in an appropriate number of auto-generated ticks
  12162. */
  12163. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  12164. var ilen = UNITS.length;
  12165. var i, interval, factor;
  12166. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  12167. interval = INTERVALS[UNITS[i]];
  12168. factor = interval.steps ? interval.steps : MAX_INTEGER;
  12169. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  12170. return UNITS[i];
  12171. }
  12172. }
  12173. return UNITS[ilen - 1];
  12174. }
  12175. /**
  12176. * Figures out what unit to format a set of ticks with
  12177. */
  12178. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  12179. var i, unit;
  12180. for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  12181. unit = UNITS[i];
  12182. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  12183. return unit;
  12184. }
  12185. }
  12186. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  12187. }
  12188. function determineMajorUnit(unit) {
  12189. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  12190. if (INTERVALS[UNITS[i]].common) {
  12191. return UNITS[i];
  12192. }
  12193. }
  12194. }
  12195. /**
  12196. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  12197. * `minor` unit using the given scale time `options`.
  12198. * Important: this method can return ticks outside the min and max range, it's the
  12199. * responsibility of the calling code to clamp values if needed.
  12200. */
  12201. function generate(scale, min, max, capacity) {
  12202. var adapter = scale._adapter;
  12203. var options = scale.options;
  12204. var timeOpts = options.time;
  12205. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  12206. var stepSize = resolve$5([timeOpts.stepSize, timeOpts.unitStepSize, 1]);
  12207. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  12208. var first = min;
  12209. var ticks = [];
  12210. var time;
  12211. // For 'week' unit, handle the first day of week option
  12212. if (weekday) {
  12213. first = +adapter.startOf(first, 'isoWeek', weekday);
  12214. }
  12215. // Align first ticks on unit
  12216. first = +adapter.startOf(first, weekday ? 'day' : minor);
  12217. // Prevent browser from freezing in case user options request millions of milliseconds
  12218. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  12219. throw min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor;
  12220. }
  12221. for (time = first; time < max; time = +adapter.add(time, stepSize, minor)) {
  12222. ticks.push(time);
  12223. }
  12224. if (time === max || options.bounds === 'ticks') {
  12225. ticks.push(time);
  12226. }
  12227. return ticks;
  12228. }
  12229. /**
  12230. * Returns the start and end offsets from edges in the form of {start, end}
  12231. * where each value is a relative width to the scale and ranges between 0 and 1.
  12232. * They add extra margins on the both sides by scaling down the original scale.
  12233. * Offsets are added when the `offset` option is true.
  12234. */
  12235. function computeOffsets(table, ticks, min, max, options) {
  12236. var start = 0;
  12237. var end = 0;
  12238. var first, last;
  12239. if (options.offset && ticks.length) {
  12240. first = interpolate$1(table, 'time', ticks[0], 'pos');
  12241. if (ticks.length === 1) {
  12242. start = 1 - first;
  12243. } else {
  12244. start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
  12245. }
  12246. last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
  12247. if (ticks.length === 1) {
  12248. end = last;
  12249. } else {
  12250. end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
  12251. }
  12252. }
  12253. return {start: start, end: end, factor: 1 / (start + 1 + end)};
  12254. }
  12255. function setMajorTicks(scale, ticks, map, majorUnit) {
  12256. var adapter = scale._adapter;
  12257. var first = +adapter.startOf(ticks[0].value, majorUnit);
  12258. var last = ticks[ticks.length - 1].value;
  12259. var major, index;
  12260. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  12261. index = map[major];
  12262. if (index >= 0) {
  12263. ticks[index].major = true;
  12264. }
  12265. }
  12266. return ticks;
  12267. }
  12268. function ticksFromTimestamps(scale, values, majorUnit) {
  12269. var ticks = [];
  12270. var map = {};
  12271. var ilen = values.length;
  12272. var i, value;
  12273. for (i = 0; i < ilen; ++i) {
  12274. value = values[i];
  12275. map[value] = i;
  12276. ticks.push({
  12277. value: value,
  12278. major: false
  12279. });
  12280. }
  12281. // We set the major ticks separately from the above loop because calling startOf for every tick
  12282. // is expensive when there is a large number of ticks
  12283. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  12284. }
  12285. var defaultConfig$4 = {
  12286. position: 'bottom',
  12287. /**
  12288. * Data distribution along the scale:
  12289. * - 'linear': data are spread according to their time (distances can vary),
  12290. * - 'series': data are spread at the same distance from each other.
  12291. * @see https://github.com/chartjs/Chart.js/pull/4507
  12292. * @since 2.7.0
  12293. */
  12294. distribution: 'linear',
  12295. /**
  12296. * Scale boundary strategy (bypassed by min/max time options)
  12297. * - `data`: make sure data are fully visible, ticks outside are removed
  12298. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  12299. * @see https://github.com/chartjs/Chart.js/pull/4556
  12300. * @since 2.7.0
  12301. */
  12302. bounds: 'data',
  12303. adapters: {},
  12304. time: {
  12305. parser: false, // false == a pattern string from https://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment
  12306. unit: false, // false == automatic or override with week, month, year, etc.
  12307. round: false, // none, or override with week, month, year, etc.
  12308. displayFormat: false, // DEPRECATED
  12309. isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
  12310. minUnit: 'millisecond',
  12311. displayFormats: {}
  12312. },
  12313. ticks: {
  12314. autoSkip: false,
  12315. /**
  12316. * Ticks generation input values:
  12317. * - 'auto': generates "optimal" ticks based on scale size and time options.
  12318. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  12319. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  12320. * @see https://github.com/chartjs/Chart.js/pull/4507
  12321. * @since 2.7.0
  12322. */
  12323. source: 'auto',
  12324. major: {
  12325. enabled: false
  12326. }
  12327. }
  12328. };
  12329. var scale_time = core_scale.extend({
  12330. initialize: function () {
  12331. this.mergeTicksOptions();
  12332. core_scale.prototype.initialize.call(this);
  12333. },
  12334. update: function () {
  12335. var me = this;
  12336. var options = me.options;
  12337. var time = options.time || (options.time = {});
  12338. var adapter = me._adapter = new core_adapters._date(options.adapters.date);
  12339. // DEPRECATIONS: output a message only one time per update
  12340. deprecated$1('time scale', time.format, 'time.format', 'time.parser');
  12341. deprecated$1('time scale', time.min, 'time.min', 'ticks.min');
  12342. deprecated$1('time scale', time.max, 'time.max', 'ticks.max');
  12343. // Backward compatibility: before introducing adapter, `displayFormats` was
  12344. // supposed to contain *all* unit/string pairs but this can't be resolved
  12345. // when loading the scale (adapters are loaded afterward), so let's populate
  12346. // missing formats on update
  12347. helpers$1.mergeIf(time.displayFormats, adapter.formats());
  12348. return core_scale.prototype.update.apply(me, arguments);
  12349. },
  12350. /**
  12351. * Allows data to be referenced via 't' attribute
  12352. */
  12353. getRightValue: function (rawValue) {
  12354. if (rawValue && rawValue.t !== undefined) {
  12355. rawValue = rawValue.t;
  12356. }
  12357. return core_scale.prototype.getRightValue.call(this, rawValue);
  12358. },
  12359. determineDataLimits: function () {
  12360. var me = this;
  12361. var chart = me.chart;
  12362. var adapter = me._adapter;
  12363. var options = me.options;
  12364. var unit = options.time.unit || 'day';
  12365. var min = MAX_INTEGER;
  12366. var max = MIN_INTEGER;
  12367. var timestamps = [];
  12368. var datasets = [];
  12369. var labels = [];
  12370. var i, j, ilen, jlen, data, timestamp, labelsAdded;
  12371. var dataLabels = me._getLabels();
  12372. for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
  12373. labels.push(parse(me, dataLabels[i]));
  12374. }
  12375. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  12376. if (chart.isDatasetVisible(i)) {
  12377. data = chart.data.datasets[i].data;
  12378. // Let's consider that all data have the same format.
  12379. if (helpers$1.isObject(data[0])) {
  12380. datasets[i] = [];
  12381. for (j = 0, jlen = data.length; j < jlen; ++j) {
  12382. timestamp = parse(me, data[j]);
  12383. timestamps.push(timestamp);
  12384. datasets[i][j] = timestamp;
  12385. }
  12386. } else {
  12387. datasets[i] = labels.slice(0);
  12388. if (!labelsAdded) {
  12389. timestamps = timestamps.concat(labels);
  12390. labelsAdded = true;
  12391. }
  12392. }
  12393. } else {
  12394. datasets[i] = [];
  12395. }
  12396. }
  12397. if (labels.length) {
  12398. min = Math.min(min, labels[0]);
  12399. max = Math.max(max, labels[labels.length - 1]);
  12400. }
  12401. if (timestamps.length) {
  12402. timestamps = ilen > 1 ? arrayUnique(timestamps).sort(sorter) : timestamps.sort(sorter);
  12403. min = Math.min(min, timestamps[0]);
  12404. max = Math.max(max, timestamps[timestamps.length - 1]);
  12405. }
  12406. min = parse(me, getMin(options)) || min;
  12407. max = parse(me, getMax(options)) || max;
  12408. // In case there is no valid min/max, set limits based on unit time option
  12409. min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
  12410. max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;
  12411. // Make sure that max is strictly higher than min (required by the lookup table)
  12412. me.min = Math.min(min, max);
  12413. me.max = Math.max(min + 1, max);
  12414. // PRIVATE
  12415. me._table = [];
  12416. me._timestamps = {
  12417. data: timestamps,
  12418. datasets: datasets,
  12419. labels: labels
  12420. };
  12421. },
  12422. buildTicks: function () {
  12423. var me = this;
  12424. var min = me.min;
  12425. var max = me.max;
  12426. var options = me.options;
  12427. var tickOpts = options.ticks;
  12428. var timeOpts = options.time;
  12429. var timestamps = me._timestamps;
  12430. var ticks = [];
  12431. var capacity = me.getLabelCapacity(min);
  12432. var source = tickOpts.source;
  12433. var distribution = options.distribution;
  12434. var i, ilen, timestamp;
  12435. if (source === 'data' || (source === 'auto' && distribution === 'series')) {
  12436. timestamps = timestamps.data;
  12437. } else if (source === 'labels') {
  12438. timestamps = timestamps.labels;
  12439. } else {
  12440. timestamps = generate(me, min, max, capacity);
  12441. }
  12442. if (options.bounds === 'ticks' && timestamps.length) {
  12443. min = timestamps[0];
  12444. max = timestamps[timestamps.length - 1];
  12445. }
  12446. // Enforce limits with user min/max options
  12447. min = parse(me, getMin(options)) || min;
  12448. max = parse(me, getMax(options)) || max;
  12449. // Remove ticks outside the min/max range
  12450. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12451. timestamp = timestamps[i];
  12452. if (timestamp >= min && timestamp <= max) {
  12453. ticks.push(timestamp);
  12454. }
  12455. }
  12456. me.min = min;
  12457. me.max = max;
  12458. // PRIVATE
  12459. // determineUnitForFormatting relies on the number of ticks so we don't use it when
  12460. // autoSkip is enabled because we don't yet know what the final number of ticks will be
  12461. me._unit = timeOpts.unit || (tickOpts.autoSkip
  12462. ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, capacity)
  12463. : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
  12464. me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
  12465. : determineMajorUnit(me._unit);
  12466. me._table = buildLookupTable(me._timestamps.data, min, max, distribution);
  12467. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  12468. if (tickOpts.reverse) {
  12469. ticks.reverse();
  12470. }
  12471. return ticksFromTimestamps(me, ticks, me._majorUnit);
  12472. },
  12473. getLabelForIndex: function (index, datasetIndex) {
  12474. var me = this;
  12475. var adapter = me._adapter;
  12476. var data = me.chart.data;
  12477. var timeOpts = me.options.time;
  12478. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  12479. var value = data.datasets[datasetIndex].data[index];
  12480. if (helpers$1.isObject(value)) {
  12481. label = me.getRightValue(value);
  12482. }
  12483. if (timeOpts.tooltipFormat) {
  12484. return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
  12485. }
  12486. if (typeof label === 'string') {
  12487. return label;
  12488. }
  12489. return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
  12490. },
  12491. /**
  12492. * Function to format an individual tick mark
  12493. * @private
  12494. */
  12495. tickFormatFunction: function (time, index, ticks, format) {
  12496. var me = this;
  12497. var adapter = me._adapter;
  12498. var options = me.options;
  12499. var formats = options.time.displayFormats;
  12500. var minorFormat = formats[me._unit];
  12501. var majorUnit = me._majorUnit;
  12502. var majorFormat = formats[majorUnit];
  12503. var tick = ticks[index];
  12504. var tickOpts = options.ticks;
  12505. var major = majorUnit && majorFormat && tick && tick.major;
  12506. var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
  12507. var nestedTickOpts = major ? tickOpts.major : tickOpts.minor;
  12508. var formatter = resolve$5([
  12509. nestedTickOpts.callback,
  12510. nestedTickOpts.userCallback,
  12511. tickOpts.callback,
  12512. tickOpts.userCallback
  12513. ]);
  12514. return formatter ? formatter(label, index, ticks) : label;
  12515. },
  12516. convertTicksToLabels: function (ticks) {
  12517. var labels = [];
  12518. var i, ilen;
  12519. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  12520. labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
  12521. }
  12522. return labels;
  12523. },
  12524. /**
  12525. * @private
  12526. */
  12527. getPixelForOffset: function (time) {
  12528. var me = this;
  12529. var offsets = me._offsets;
  12530. var pos = interpolate$1(me._table, 'time', time, 'pos');
  12531. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  12532. },
  12533. getPixelForValue: function (value, index, datasetIndex) {
  12534. var me = this;
  12535. var time = null;
  12536. if (index !== undefined && datasetIndex !== undefined) {
  12537. time = me._timestamps.datasets[datasetIndex][index];
  12538. }
  12539. if (time === null) {
  12540. time = parse(me, value);
  12541. }
  12542. if (time !== null) {
  12543. return me.getPixelForOffset(time);
  12544. }
  12545. },
  12546. getPixelForTick: function (index) {
  12547. var ticks = this.getTicks();
  12548. return index >= 0 && index < ticks.length ?
  12549. this.getPixelForOffset(ticks[index].value) :
  12550. null;
  12551. },
  12552. getValueForPixel: function (pixel) {
  12553. var me = this;
  12554. var offsets = me._offsets;
  12555. var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  12556. var time = interpolate$1(me._table, 'pos', pos, 'time');
  12557. // DEPRECATION, we should return time directly
  12558. return me._adapter._create(time);
  12559. },
  12560. /**
  12561. * @private
  12562. */
  12563. _getLabelSize: function (label) {
  12564. var me = this;
  12565. var ticksOpts = me.options.ticks;
  12566. var tickLabelWidth = me.ctx.measureText(label).width;
  12567. var angle = helpers$1.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  12568. var cosRotation = Math.cos(angle);
  12569. var sinRotation = Math.sin(angle);
  12570. var tickFontSize = valueOrDefault$d(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
  12571. return {
  12572. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  12573. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  12574. };
  12575. },
  12576. /**
  12577. * Crude approximation of what the label width might be
  12578. * @private
  12579. */
  12580. getLabelWidth: function (label) {
  12581. return this._getLabelSize(label).w;
  12582. },
  12583. /**
  12584. * @private
  12585. */
  12586. getLabelCapacity: function (exampleTime) {
  12587. var me = this;
  12588. var timeOpts = me.options.time;
  12589. var displayFormats = timeOpts.displayFormats;
  12590. // pick the longest format (milliseconds) for guestimation
  12591. var format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  12592. var exampleLabel = me.tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
  12593. var size = me._getLabelSize(exampleLabel);
  12594. var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h);
  12595. if (me.options.offset) {
  12596. capacity--;
  12597. }
  12598. return capacity > 0 ? capacity : 1;
  12599. }
  12600. });
  12601. // INTERNAL: static default options, registered in src/index.js
  12602. var _defaults$4 = defaultConfig$4;
  12603. scale_time._defaults = _defaults$4;
  12604. var scales = {
  12605. category: scale_category,
  12606. linear: scale_linear,
  12607. logarithmic: scale_logarithmic,
  12608. radialLinear: scale_radialLinear,
  12609. time: scale_time
  12610. };
  12611. var FORMATS = {
  12612. datetime: 'MMM D, YYYY, h:mm:ss a',
  12613. millisecond: 'h:mm:ss.SSS a',
  12614. second: 'h:mm:ss a',
  12615. minute: 'h:mm a',
  12616. hour: 'hA',
  12617. day: 'MMM D',
  12618. week: 'll',
  12619. month: 'MMM YYYY',
  12620. quarter: '[Q]Q - YYYY',
  12621. year: 'YYYY'
  12622. };
  12623. core_adapters._date.override(typeof moment === 'function' ? {
  12624. _id: 'moment', // DEBUG ONLY
  12625. formats: function () {
  12626. return FORMATS;
  12627. },
  12628. parse: function (value, format) {
  12629. if (typeof value === 'string' && typeof format === 'string') {
  12630. value = moment(value, format);
  12631. } else if (!(value instanceof moment)) {
  12632. value = moment(value);
  12633. }
  12634. return value.isValid() ? value.valueOf() : null;
  12635. },
  12636. format: function (time, format) {
  12637. return moment(time).format(format);
  12638. },
  12639. add: function (time, amount, unit) {
  12640. return moment(time).add(amount, unit).valueOf();
  12641. },
  12642. diff: function (max, min, unit) {
  12643. return moment(max).diff(moment(min), unit);
  12644. },
  12645. startOf: function (time, unit, weekday) {
  12646. time = moment(time);
  12647. if (unit === 'isoWeek') {
  12648. return time.isoWeekday(weekday).valueOf();
  12649. }
  12650. return time.startOf(unit).valueOf();
  12651. },
  12652. endOf: function (time, unit) {
  12653. return moment(time).endOf(unit).valueOf();
  12654. },
  12655. // DEPRECATIONS
  12656. /**
  12657. * Provided for backward compatibility with scale.getValueForPixel().
  12658. * @deprecated since version 2.8.0
  12659. * @todo remove at version 3
  12660. * @private
  12661. */
  12662. _create: function (time) {
  12663. return moment(time);
  12664. },
  12665. } : {});
  12666. core_defaults._set('global', {
  12667. plugins: {
  12668. filler: {
  12669. propagate: true
  12670. }
  12671. }
  12672. });
  12673. var mappers = {
  12674. dataset: function (source) {
  12675. var index = source.fill;
  12676. var chart = source.chart;
  12677. var meta = chart.getDatasetMeta(index);
  12678. var visible = meta && chart.isDatasetVisible(index);
  12679. var points = (visible && meta.dataset._children) || [];
  12680. var length = points.length || 0;
  12681. return !length ? null : function (point, i) {
  12682. return (i < length && points[i]._view) || null;
  12683. };
  12684. },
  12685. boundary: function (source) {
  12686. var boundary = source.boundary;
  12687. var x = boundary ? boundary.x : null;
  12688. var y = boundary ? boundary.y : null;
  12689. if (helpers$1.isArray(boundary)) {
  12690. return function (point, i) {
  12691. return boundary[i];
  12692. };
  12693. }
  12694. return function (point) {
  12695. return {
  12696. x: x === null ? point.x : x,
  12697. y: y === null ? point.y : y,
  12698. };
  12699. };
  12700. }
  12701. };
  12702. // @todo if (fill[0] === '#')
  12703. function decodeFill(el, index, count) {
  12704. var model = el._model || {};
  12705. var fill = model.fill;
  12706. var target;
  12707. if (fill === undefined) {
  12708. fill = !!model.backgroundColor;
  12709. }
  12710. if (fill === false || fill === null) {
  12711. return false;
  12712. }
  12713. if (fill === true) {
  12714. return 'origin';
  12715. }
  12716. target = parseFloat(fill, 10);
  12717. if (isFinite(target) && Math.floor(target) === target) {
  12718. if (fill[0] === '-' || fill[0] === '+') {
  12719. target = index + target;
  12720. }
  12721. if (target === index || target < 0 || target >= count) {
  12722. return false;
  12723. }
  12724. return target;
  12725. }
  12726. switch (fill) {
  12727. // compatibility
  12728. case 'bottom':
  12729. return 'start';
  12730. case 'top':
  12731. return 'end';
  12732. case 'zero':
  12733. return 'origin';
  12734. // supported boundaries
  12735. case 'origin':
  12736. case 'start':
  12737. case 'end':
  12738. return fill;
  12739. // invalid fill values
  12740. default:
  12741. return false;
  12742. }
  12743. }
  12744. function computeLinearBoundary(source) {
  12745. var model = source.el._model || {};
  12746. var scale = source.el._scale || {};
  12747. var fill = source.fill;
  12748. var target = null;
  12749. var horizontal;
  12750. if (isFinite(fill)) {
  12751. return null;
  12752. }
  12753. // Backward compatibility: until v3, we still need to support boundary values set on
  12754. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  12755. // controllers might still use it (e.g. the Smith chart).
  12756. if (fill === 'start') {
  12757. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  12758. } else if (fill === 'end') {
  12759. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  12760. } else if (model.scaleZero !== undefined) {
  12761. target = model.scaleZero;
  12762. } else if (scale.getBasePixel) {
  12763. target = scale.getBasePixel();
  12764. }
  12765. if (target !== undefined && target !== null) {
  12766. if (target.x !== undefined && target.y !== undefined) {
  12767. return target;
  12768. }
  12769. if (helpers$1.isFinite(target)) {
  12770. horizontal = scale.isHorizontal();
  12771. return {
  12772. x: horizontal ? target : null,
  12773. y: horizontal ? null : target
  12774. };
  12775. }
  12776. }
  12777. return null;
  12778. }
  12779. function computeCircularBoundary(source) {
  12780. var scale = source.el._scale;
  12781. var options = scale.options;
  12782. var length = scale.chart.data.labels.length;
  12783. var fill = source.fill;
  12784. var target = [];
  12785. var start, end, center, i, point;
  12786. if (!length) {
  12787. return null;
  12788. }
  12789. start = options.ticks.reverse ? scale.max : scale.min;
  12790. end = options.ticks.reverse ? scale.min : scale.max;
  12791. center = scale.getPointPositionForValue(0, start);
  12792. for (i = 0; i < length; ++i) {
  12793. point = fill === 'start' || fill === 'end'
  12794. ? scale.getPointPositionForValue(i, fill === 'start' ? start : end)
  12795. : scale.getBasePosition(i);
  12796. if (options.gridLines.circular) {
  12797. point.cx = center.x;
  12798. point.cy = center.y;
  12799. point.angle = scale.getIndexAngle(i) - Math.PI / 2;
  12800. }
  12801. target.push(point);
  12802. }
  12803. return target;
  12804. }
  12805. function computeBoundary(source) {
  12806. var scale = source.el._scale || {};
  12807. if (scale.getPointPositionForValue) {
  12808. return computeCircularBoundary(source);
  12809. }
  12810. return computeLinearBoundary(source);
  12811. }
  12812. function resolveTarget(sources, index, propagate) {
  12813. var source = sources[index];
  12814. var fill = source.fill;
  12815. var visited = [index];
  12816. var target;
  12817. if (!propagate) {
  12818. return fill;
  12819. }
  12820. while (fill !== false && visited.indexOf(fill) === -1) {
  12821. if (!isFinite(fill)) {
  12822. return fill;
  12823. }
  12824. target = sources[fill];
  12825. if (!target) {
  12826. return false;
  12827. }
  12828. if (target.visible) {
  12829. return fill;
  12830. }
  12831. visited.push(fill);
  12832. fill = target.fill;
  12833. }
  12834. return false;
  12835. }
  12836. function createMapper(source) {
  12837. var fill = source.fill;
  12838. var type = 'dataset';
  12839. if (fill === false) {
  12840. return null;
  12841. }
  12842. if (!isFinite(fill)) {
  12843. type = 'boundary';
  12844. }
  12845. return mappers[type](source);
  12846. }
  12847. function isDrawable(point) {
  12848. return point && !point.skip;
  12849. }
  12850. function drawArea(ctx, curve0, curve1, len0, len1) {
  12851. var i, cx, cy, r;
  12852. if (!len0 || !len1) {
  12853. return;
  12854. }
  12855. // building first area curve (normal)
  12856. ctx.moveTo(curve0[0].x, curve0[0].y);
  12857. for (i = 1; i < len0; ++i) {
  12858. helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  12859. }
  12860. if (curve1[0].angle !== undefined) {
  12861. cx = curve1[0].cx;
  12862. cy = curve1[0].cy;
  12863. r = Math.sqrt(Math.pow(curve1[0].x - cx, 2) + Math.pow(curve1[0].y - cy, 2));
  12864. for (i = len1 - 1; i > 0; --i) {
  12865. ctx.arc(cx, cy, r, curve1[i].angle, curve1[i - 1].angle, true);
  12866. }
  12867. return;
  12868. }
  12869. // joining the two area curves
  12870. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  12871. // building opposite area curve (reverse)
  12872. for (i = len1 - 1; i > 0; --i) {
  12873. helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  12874. }
  12875. }
  12876. function doFill(ctx, points, mapper, view, color, loop) {
  12877. var count = points.length;
  12878. var span = view.spanGaps;
  12879. var curve0 = [];
  12880. var curve1 = [];
  12881. var len0 = 0;
  12882. var len1 = 0;
  12883. var i, ilen, index, p0, p1, d0, d1, loopOffset;
  12884. ctx.beginPath();
  12885. for (i = 0, ilen = count; i < ilen; ++i) {
  12886. index = i % count;
  12887. p0 = points[index]._view;
  12888. p1 = mapper(p0, index, view);
  12889. d0 = isDrawable(p0);
  12890. d1 = isDrawable(p1);
  12891. if (loop && loopOffset === undefined && d0) {
  12892. loopOffset = i + 1;
  12893. ilen = count + loopOffset;
  12894. }
  12895. if (d0 && d1) {
  12896. len0 = curve0.push(p0);
  12897. len1 = curve1.push(p1);
  12898. } else if (len0 && len1) {
  12899. if (!span) {
  12900. drawArea(ctx, curve0, curve1, len0, len1);
  12901. len0 = len1 = 0;
  12902. curve0 = [];
  12903. curve1 = [];
  12904. } else {
  12905. if (d0) {
  12906. curve0.push(p0);
  12907. }
  12908. if (d1) {
  12909. curve1.push(p1);
  12910. }
  12911. }
  12912. }
  12913. }
  12914. drawArea(ctx, curve0, curve1, len0, len1);
  12915. ctx.closePath();
  12916. ctx.fillStyle = color;
  12917. ctx.fill();
  12918. }
  12919. var plugin_filler = {
  12920. id: 'filler',
  12921. afterDatasetsUpdate: function (chart, options) {
  12922. var count = (chart.data.datasets || []).length;
  12923. var propagate = options.propagate;
  12924. var sources = [];
  12925. var meta, i, el, source;
  12926. for (i = 0; i < count; ++i) {
  12927. meta = chart.getDatasetMeta(i);
  12928. el = meta.dataset;
  12929. source = null;
  12930. if (el && el._model && el instanceof elements.Line) {
  12931. source = {
  12932. visible: chart.isDatasetVisible(i),
  12933. fill: decodeFill(el, i, count),
  12934. chart: chart,
  12935. el: el
  12936. };
  12937. }
  12938. meta.$filler = source;
  12939. sources.push(source);
  12940. }
  12941. for (i = 0; i < count; ++i) {
  12942. source = sources[i];
  12943. if (!source) {
  12944. continue;
  12945. }
  12946. source.fill = resolveTarget(sources, i, propagate);
  12947. source.boundary = computeBoundary(source);
  12948. source.mapper = createMapper(source);
  12949. }
  12950. },
  12951. beforeDatasetsDraw: function (chart) {
  12952. var metasets = chart._getSortedVisibleDatasetMetas();
  12953. var ctx = chart.ctx;
  12954. var meta, i, el, view, points, mapper, color;
  12955. for (i = metasets.length - 1; i >= 0; --i) {
  12956. meta = metasets[i].$filler;
  12957. if (!meta || !meta.visible) {
  12958. continue;
  12959. }
  12960. el = meta.el;
  12961. view = el._view;
  12962. points = el._children || [];
  12963. mapper = meta.mapper;
  12964. color = view.backgroundColor || core_defaults.global.defaultColor;
  12965. if (mapper && color && points.length) {
  12966. helpers$1.canvas.clipArea(ctx, chart.chartArea);
  12967. doFill(ctx, points, mapper, view, color, el._loop);
  12968. helpers$1.canvas.unclipArea(ctx);
  12969. }
  12970. }
  12971. }
  12972. };
  12973. var getRtlHelper$1 = helpers$1.rtl.getRtlAdapter;
  12974. var noop$1 = helpers$1.noop;
  12975. var valueOrDefault$e = helpers$1.valueOrDefault;
  12976. core_defaults._set('global', {
  12977. legend: {
  12978. display: true,
  12979. position: 'top',
  12980. align: 'center',
  12981. fullWidth: true,
  12982. reverse: false,
  12983. weight: 1000,
  12984. // a callback that will handle
  12985. onClick: function (e, legendItem) {
  12986. var index = legendItem.datasetIndex;
  12987. var ci = this.chart;
  12988. var meta = ci.getDatasetMeta(index);
  12989. // See controller.isDatasetVisible comment
  12990. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  12991. // We hid a dataset ... rerender the chart
  12992. ci.update();
  12993. },
  12994. onHover: null,
  12995. onLeave: null,
  12996. labels: {
  12997. boxWidth: 40,
  12998. padding: 10,
  12999. // Generates labels shown in the legend
  13000. // Valid properties to return:
  13001. // text : text to display
  13002. // fillStyle : fill of coloured box
  13003. // strokeStyle: stroke of coloured box
  13004. // hidden : if this legend item refers to a hidden item
  13005. // lineCap : cap style for line
  13006. // lineDash
  13007. // lineDashOffset :
  13008. // lineJoin :
  13009. // lineWidth :
  13010. generateLabels: function (chart) {
  13011. var datasets = chart.data.datasets;
  13012. var options = chart.options.legend || {};
  13013. var usePointStyle = options.labels && options.labels.usePointStyle;
  13014. return chart._getSortedDatasetMetas().map(function (meta) {
  13015. var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  13016. return {
  13017. text: datasets[meta.index].label,
  13018. fillStyle: style.backgroundColor,
  13019. hidden: !chart.isDatasetVisible(meta.index),
  13020. lineCap: style.borderCapStyle,
  13021. lineDash: style.borderDash,
  13022. lineDashOffset: style.borderDashOffset,
  13023. lineJoin: style.borderJoinStyle,
  13024. lineWidth: style.borderWidth,
  13025. strokeStyle: style.borderColor,
  13026. pointStyle: style.pointStyle,
  13027. rotation: style.rotation,
  13028. // Below is extra data used for toggling the datasets
  13029. datasetIndex: meta.index
  13030. };
  13031. }, this);
  13032. }
  13033. }
  13034. },
  13035. legendCallback: function (chart) {
  13036. var list = document.createElement('ul');
  13037. var datasets = chart.data.datasets;
  13038. var i, ilen, listItem, listItemSpan;
  13039. list.setAttribute('class', chart.id + '-legend');
  13040. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  13041. listItem = list.appendChild(document.createElement('li'));
  13042. listItemSpan = listItem.appendChild(document.createElement('span'));
  13043. listItemSpan.style.backgroundColor = datasets[i].backgroundColor;
  13044. if (datasets[i].label) {
  13045. listItem.appendChild(document.createTextNode(datasets[i].label));
  13046. }
  13047. }
  13048. return list.outerHTML;
  13049. }
  13050. });
  13051. /**
  13052. * Helper function to get the box width based on the usePointStyle option
  13053. * @param {object} labelopts - the label options on the legend
  13054. * @param {number} fontSize - the label font size
  13055. * @return {number} width of the color box area
  13056. */
  13057. function getBoxWidth(labelOpts, fontSize) {
  13058. return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
  13059. fontSize :
  13060. labelOpts.boxWidth;
  13061. }
  13062. /**
  13063. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  13064. */
  13065. var Legend = core_element.extend({
  13066. initialize: function (config) {
  13067. var me = this;
  13068. helpers$1.extend(me, config);
  13069. // Contains hit boxes for each dataset (in dataset order)
  13070. me.legendHitBoxes = [];
  13071. /**
  13072. * @private
  13073. */
  13074. me._hoveredItem = null;
  13075. // Are we in doughnut mode which has a different data type
  13076. me.doughnutMode = false;
  13077. },
  13078. // These methods are ordered by lifecycle. Utilities then follow.
  13079. // Any function defined here is inherited by all legend types.
  13080. // Any function can be extended by the legend type
  13081. beforeUpdate: noop$1,
  13082. update: function (maxWidth, maxHeight, margins) {
  13083. var me = this;
  13084. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  13085. me.beforeUpdate();
  13086. // Absorb the master measurements
  13087. me.maxWidth = maxWidth;
  13088. me.maxHeight = maxHeight;
  13089. me.margins = margins;
  13090. // Dimensions
  13091. me.beforeSetDimensions();
  13092. me.setDimensions();
  13093. me.afterSetDimensions();
  13094. // Labels
  13095. me.beforeBuildLabels();
  13096. me.buildLabels();
  13097. me.afterBuildLabels();
  13098. // Fit
  13099. me.beforeFit();
  13100. me.fit();
  13101. me.afterFit();
  13102. //
  13103. me.afterUpdate();
  13104. return me.minSize;
  13105. },
  13106. afterUpdate: noop$1,
  13107. //
  13108. beforeSetDimensions: noop$1,
  13109. setDimensions: function () {
  13110. var me = this;
  13111. // Set the unconstrained dimension before label rotation
  13112. if (me.isHorizontal()) {
  13113. // Reset position before calculating rotation
  13114. me.width = me.maxWidth;
  13115. me.left = 0;
  13116. me.right = me.width;
  13117. } else {
  13118. me.height = me.maxHeight;
  13119. // Reset position before calculating rotation
  13120. me.top = 0;
  13121. me.bottom = me.height;
  13122. }
  13123. // Reset padding
  13124. me.paddingLeft = 0;
  13125. me.paddingTop = 0;
  13126. me.paddingRight = 0;
  13127. me.paddingBottom = 0;
  13128. // Reset minSize
  13129. me.minSize = {
  13130. width: 0,
  13131. height: 0
  13132. };
  13133. },
  13134. afterSetDimensions: noop$1,
  13135. //
  13136. beforeBuildLabels: noop$1,
  13137. buildLabels: function () {
  13138. var me = this;
  13139. var labelOpts = me.options.labels || {};
  13140. var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
  13141. if (labelOpts.filter) {
  13142. legendItems = legendItems.filter(function (item) {
  13143. return labelOpts.filter(item, me.chart.data);
  13144. });
  13145. }
  13146. if (me.options.reverse) {
  13147. legendItems.reverse();
  13148. }
  13149. me.legendItems = legendItems;
  13150. },
  13151. afterBuildLabels: noop$1,
  13152. //
  13153. beforeFit: noop$1,
  13154. fit: function () {
  13155. var me = this;
  13156. var opts = me.options;
  13157. var labelOpts = opts.labels;
  13158. var display = opts.display;
  13159. var ctx = me.ctx;
  13160. var labelFont = helpers$1.options._parseFont(labelOpts);
  13161. var fontSize = labelFont.size;
  13162. // Reset hit boxes
  13163. var hitboxes = me.legendHitBoxes = [];
  13164. var minSize = me.minSize;
  13165. var isHorizontal = me.isHorizontal();
  13166. if (isHorizontal) {
  13167. minSize.width = me.maxWidth; // fill all the width
  13168. minSize.height = display ? 10 : 0;
  13169. } else {
  13170. minSize.width = display ? 10 : 0;
  13171. minSize.height = me.maxHeight; // fill all the height
  13172. }
  13173. // Increase sizes here
  13174. if (!display) {
  13175. me.width = minSize.width = me.height = minSize.height = 0;
  13176. return;
  13177. }
  13178. ctx.font = labelFont.string;
  13179. if (isHorizontal) {
  13180. // Labels
  13181. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  13182. var lineWidths = me.lineWidths = [0];
  13183. var totalHeight = 0;
  13184. ctx.textAlign = 'left';
  13185. ctx.textBaseline = 'middle';
  13186. helpers$1.each(me.legendItems, function (legendItem, i) {
  13187. var boxWidth = getBoxWidth(labelOpts, fontSize);
  13188. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  13189. if (i === 0 || lineWidths[lineWidths.length - 1] + width + 2 * labelOpts.padding > minSize.width) {
  13190. totalHeight += fontSize + labelOpts.padding;
  13191. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  13192. }
  13193. // Store the hitbox width and height here. Final position will be updated in `draw`
  13194. hitboxes[i] = {
  13195. left: 0,
  13196. top: 0,
  13197. width: width,
  13198. height: fontSize
  13199. };
  13200. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  13201. });
  13202. minSize.height += totalHeight;
  13203. } else {
  13204. var vPadding = labelOpts.padding;
  13205. var columnWidths = me.columnWidths = [];
  13206. var columnHeights = me.columnHeights = [];
  13207. var totalWidth = labelOpts.padding;
  13208. var currentColWidth = 0;
  13209. var currentColHeight = 0;
  13210. helpers$1.each(me.legendItems, function (legendItem, i) {
  13211. var boxWidth = getBoxWidth(labelOpts, fontSize);
  13212. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  13213. // If too tall, go to new column
  13214. if (i > 0 && currentColHeight + fontSize + 2 * vPadding > minSize.height) {
  13215. totalWidth += currentColWidth + labelOpts.padding;
  13216. columnWidths.push(currentColWidth); // previous column width
  13217. columnHeights.push(currentColHeight);
  13218. currentColWidth = 0;
  13219. currentColHeight = 0;
  13220. }
  13221. // Get max width
  13222. currentColWidth = Math.max(currentColWidth, itemWidth);
  13223. currentColHeight += fontSize + vPadding;
  13224. // Store the hitbox width and height here. Final position will be updated in `draw`
  13225. hitboxes[i] = {
  13226. left: 0,
  13227. top: 0,
  13228. width: itemWidth,
  13229. height: fontSize
  13230. };
  13231. });
  13232. totalWidth += currentColWidth;
  13233. columnWidths.push(currentColWidth);
  13234. columnHeights.push(currentColHeight);
  13235. minSize.width += totalWidth;
  13236. }
  13237. me.width = minSize.width;
  13238. me.height = minSize.height;
  13239. },
  13240. afterFit: noop$1,
  13241. // Shared Methods
  13242. isHorizontal: function () {
  13243. return this.options.position === 'top' || this.options.position === 'bottom';
  13244. },
  13245. // Actually draw the legend on the canvas
  13246. draw: function () {
  13247. var me = this;
  13248. var opts = me.options;
  13249. var labelOpts = opts.labels;
  13250. var globalDefaults = core_defaults.global;
  13251. var defaultColor = globalDefaults.defaultColor;
  13252. var lineDefault = globalDefaults.elements.line;
  13253. var legendHeight = me.height;
  13254. var columnHeights = me.columnHeights;
  13255. var legendWidth = me.width;
  13256. var lineWidths = me.lineWidths;
  13257. if (!opts.display) {
  13258. return;
  13259. }
  13260. var rtlHelper = getRtlHelper$1(opts.rtl, me.left, me.minSize.width);
  13261. var ctx = me.ctx;
  13262. var fontColor = valueOrDefault$e(labelOpts.fontColor, globalDefaults.defaultFontColor);
  13263. var labelFont = helpers$1.options._parseFont(labelOpts);
  13264. var fontSize = labelFont.size;
  13265. var cursor;
  13266. // Canvas setup
  13267. ctx.textAlign = rtlHelper.textAlign('left');
  13268. ctx.textBaseline = 'middle';
  13269. ctx.lineWidth = 0.5;
  13270. ctx.strokeStyle = fontColor; // for strikethrough effect
  13271. ctx.fillStyle = fontColor; // render in correct colour
  13272. ctx.font = labelFont.string;
  13273. var boxWidth = getBoxWidth(labelOpts, fontSize);
  13274. var hitboxes = me.legendHitBoxes;
  13275. // current position
  13276. var drawLegendBox = function (x, y, legendItem) {
  13277. if (isNaN(boxWidth) || boxWidth <= 0) {
  13278. return;
  13279. }
  13280. // Set the ctx for the box
  13281. ctx.save();
  13282. var lineWidth = valueOrDefault$e(legendItem.lineWidth, lineDefault.borderWidth);
  13283. ctx.fillStyle = valueOrDefault$e(legendItem.fillStyle, defaultColor);
  13284. ctx.lineCap = valueOrDefault$e(legendItem.lineCap, lineDefault.borderCapStyle);
  13285. ctx.lineDashOffset = valueOrDefault$e(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  13286. ctx.lineJoin = valueOrDefault$e(legendItem.lineJoin, lineDefault.borderJoinStyle);
  13287. ctx.lineWidth = lineWidth;
  13288. ctx.strokeStyle = valueOrDefault$e(legendItem.strokeStyle, defaultColor);
  13289. if (ctx.setLineDash) {
  13290. // IE 9 and 10 do not support line dash
  13291. ctx.setLineDash(valueOrDefault$e(legendItem.lineDash, lineDefault.borderDash));
  13292. }
  13293. if (labelOpts && labelOpts.usePointStyle) {
  13294. // Recalculate x and y for drawPoint() because its expecting
  13295. // x and y to be center of figure (instead of top left)
  13296. var radius = boxWidth * Math.SQRT2 / 2;
  13297. var centerX = rtlHelper.xPlus(x, boxWidth / 2);
  13298. var centerY = y + fontSize / 2;
  13299. // Draw pointStyle as legend symbol
  13300. helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY, legendItem.rotation);
  13301. } else {
  13302. // Draw box as legend symbol
  13303. ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  13304. if (lineWidth !== 0) {
  13305. ctx.strokeRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  13306. }
  13307. }
  13308. ctx.restore();
  13309. };
  13310. var fillText = function (x, y, legendItem, textWidth) {
  13311. var halfFontSize = fontSize / 2;
  13312. var xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize);
  13313. var yMiddle = y + halfFontSize;
  13314. ctx.fillText(legendItem.text, xLeft, yMiddle);
  13315. if (legendItem.hidden) {
  13316. // Strikethrough the text if hidden
  13317. ctx.beginPath();
  13318. ctx.lineWidth = 2;
  13319. ctx.moveTo(xLeft, yMiddle);
  13320. ctx.lineTo(rtlHelper.xPlus(xLeft, textWidth), yMiddle);
  13321. ctx.stroke();
  13322. }
  13323. };
  13324. var alignmentOffset = function (dimension, blockSize) {
  13325. switch (opts.align) {
  13326. case 'start':
  13327. return labelOpts.padding;
  13328. case 'end':
  13329. return dimension - blockSize;
  13330. default: // center
  13331. return (dimension - blockSize + labelOpts.padding) / 2;
  13332. }
  13333. };
  13334. // Horizontal
  13335. var isHorizontal = me.isHorizontal();
  13336. if (isHorizontal) {
  13337. cursor = {
  13338. x: me.left + alignmentOffset(legendWidth, lineWidths[0]),
  13339. y: me.top + labelOpts.padding,
  13340. line: 0
  13341. };
  13342. } else {
  13343. cursor = {
  13344. x: me.left + labelOpts.padding,
  13345. y: me.top + alignmentOffset(legendHeight, columnHeights[0]),
  13346. line: 0
  13347. };
  13348. }
  13349. helpers$1.rtl.overrideTextDirection(me.ctx, opts.textDirection);
  13350. var itemHeight = fontSize + labelOpts.padding;
  13351. helpers$1.each(me.legendItems, function (legendItem, i) {
  13352. var textWidth = ctx.measureText(legendItem.text).width;
  13353. var width = boxWidth + (fontSize / 2) + textWidth;
  13354. var x = cursor.x;
  13355. var y = cursor.y;
  13356. rtlHelper.setWidth(me.minSize.width);
  13357. // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
  13358. // instead of me.right and me.bottom because me.width and me.height
  13359. // may have been changed since me.minSize was calculated
  13360. if (isHorizontal) {
  13361. if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
  13362. y = cursor.y += itemHeight;
  13363. cursor.line++;
  13364. x = cursor.x = me.left + alignmentOffset(legendWidth, lineWidths[cursor.line]);
  13365. }
  13366. } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
  13367. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  13368. cursor.line++;
  13369. y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]);
  13370. }
  13371. var realX = rtlHelper.x(x);
  13372. drawLegendBox(realX, y, legendItem);
  13373. hitboxes[i].left = rtlHelper.leftForLtr(realX, hitboxes[i].width);
  13374. hitboxes[i].top = y;
  13375. // Fill the actual label
  13376. fillText(realX, y, legendItem, textWidth);
  13377. if (isHorizontal) {
  13378. cursor.x += width + labelOpts.padding;
  13379. } else {
  13380. cursor.y += itemHeight;
  13381. }
  13382. });
  13383. helpers$1.rtl.restoreTextDirection(me.ctx, opts.textDirection);
  13384. },
  13385. /**
  13386. * @private
  13387. */
  13388. _getLegendItemAt: function (x, y) {
  13389. var me = this;
  13390. var i, hitBox, lh;
  13391. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  13392. // See if we are touching one of the dataset boxes
  13393. lh = me.legendHitBoxes;
  13394. for (i = 0; i < lh.length; ++i) {
  13395. hitBox = lh[i];
  13396. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  13397. // Touching an element
  13398. return me.legendItems[i];
  13399. }
  13400. }
  13401. }
  13402. return null;
  13403. },
  13404. /**
  13405. * Handle an event
  13406. * @private
  13407. * @param {IEvent} event - The event to handle
  13408. */
  13409. handleEvent: function (e) {
  13410. var me = this;
  13411. var opts = me.options;
  13412. var type = e.type === 'mouseup' ? 'click' : e.type;
  13413. var hoveredItem;
  13414. if (type === 'mousemove') {
  13415. if (!opts.onHover && !opts.onLeave) {
  13416. return;
  13417. }
  13418. } else if (type === 'click') {
  13419. if (!opts.onClick) {
  13420. return;
  13421. }
  13422. } else {
  13423. return;
  13424. }
  13425. // Chart event already has relative position in it
  13426. hoveredItem = me._getLegendItemAt(e.x, e.y);
  13427. if (type === 'click') {
  13428. if (hoveredItem && opts.onClick) {
  13429. // use e.native for backwards compatibility
  13430. opts.onClick.call(me, e.native, hoveredItem);
  13431. }
  13432. } else {
  13433. if (opts.onLeave && hoveredItem !== me._hoveredItem) {
  13434. if (me._hoveredItem) {
  13435. opts.onLeave.call(me, e.native, me._hoveredItem);
  13436. }
  13437. me._hoveredItem = hoveredItem;
  13438. }
  13439. if (opts.onHover && hoveredItem) {
  13440. // use e.native for backwards compatibility
  13441. opts.onHover.call(me, e.native, hoveredItem);
  13442. }
  13443. }
  13444. }
  13445. });
  13446. function createNewLegendAndAttach(chart, legendOpts) {
  13447. var legend = new Legend({
  13448. ctx: chart.ctx,
  13449. options: legendOpts,
  13450. chart: chart
  13451. });
  13452. core_layouts.configure(chart, legend, legendOpts);
  13453. core_layouts.addBox(chart, legend);
  13454. chart.legend = legend;
  13455. }
  13456. var plugin_legend = {
  13457. id: 'legend',
  13458. /**
  13459. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  13460. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  13461. * the plugin, which one will be re-exposed in the chart.js file.
  13462. * https://github.com/chartjs/Chart.js/pull/2640
  13463. * @private
  13464. */
  13465. _element: Legend,
  13466. beforeInit: function (chart) {
  13467. var legendOpts = chart.options.legend;
  13468. if (legendOpts) {
  13469. createNewLegendAndAttach(chart, legendOpts);
  13470. }
  13471. },
  13472. beforeUpdate: function (chart) {
  13473. var legendOpts = chart.options.legend;
  13474. var legend = chart.legend;
  13475. if (legendOpts) {
  13476. helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
  13477. if (legend) {
  13478. core_layouts.configure(chart, legend, legendOpts);
  13479. legend.options = legendOpts;
  13480. } else {
  13481. createNewLegendAndAttach(chart, legendOpts);
  13482. }
  13483. } else if (legend) {
  13484. core_layouts.removeBox(chart, legend);
  13485. delete chart.legend;
  13486. }
  13487. },
  13488. afterEvent: function (chart, e) {
  13489. var legend = chart.legend;
  13490. if (legend) {
  13491. legend.handleEvent(e);
  13492. }
  13493. }
  13494. };
  13495. var noop$2 = helpers$1.noop;
  13496. core_defaults._set('global', {
  13497. title: {
  13498. display: false,
  13499. fontStyle: 'bold',
  13500. fullWidth: true,
  13501. padding: 10,
  13502. position: 'top',
  13503. text: '',
  13504. weight: 2000 // by default greater than legend (1000) to be above
  13505. }
  13506. });
  13507. /**
  13508. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  13509. */
  13510. var Title = core_element.extend({
  13511. initialize: function (config) {
  13512. var me = this;
  13513. helpers$1.extend(me, config);
  13514. // Contains hit boxes for each dataset (in dataset order)
  13515. me.legendHitBoxes = [];
  13516. },
  13517. // These methods are ordered by lifecycle. Utilities then follow.
  13518. beforeUpdate: noop$2,
  13519. update: function (maxWidth, maxHeight, margins) {
  13520. var me = this;
  13521. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  13522. me.beforeUpdate();
  13523. // Absorb the master measurements
  13524. me.maxWidth = maxWidth;
  13525. me.maxHeight = maxHeight;
  13526. me.margins = margins;
  13527. // Dimensions
  13528. me.beforeSetDimensions();
  13529. me.setDimensions();
  13530. me.afterSetDimensions();
  13531. // Labels
  13532. me.beforeBuildLabels();
  13533. me.buildLabels();
  13534. me.afterBuildLabels();
  13535. // Fit
  13536. me.beforeFit();
  13537. me.fit();
  13538. me.afterFit();
  13539. //
  13540. me.afterUpdate();
  13541. return me.minSize;
  13542. },
  13543. afterUpdate: noop$2,
  13544. //
  13545. beforeSetDimensions: noop$2,
  13546. setDimensions: function () {
  13547. var me = this;
  13548. // Set the unconstrained dimension before label rotation
  13549. if (me.isHorizontal()) {
  13550. // Reset position before calculating rotation
  13551. me.width = me.maxWidth;
  13552. me.left = 0;
  13553. me.right = me.width;
  13554. } else {
  13555. me.height = me.maxHeight;
  13556. // Reset position before calculating rotation
  13557. me.top = 0;
  13558. me.bottom = me.height;
  13559. }
  13560. // Reset padding
  13561. me.paddingLeft = 0;
  13562. me.paddingTop = 0;
  13563. me.paddingRight = 0;
  13564. me.paddingBottom = 0;
  13565. // Reset minSize
  13566. me.minSize = {
  13567. width: 0,
  13568. height: 0
  13569. };
  13570. },
  13571. afterSetDimensions: noop$2,
  13572. //
  13573. beforeBuildLabels: noop$2,
  13574. buildLabels: noop$2,
  13575. afterBuildLabels: noop$2,
  13576. //
  13577. beforeFit: noop$2,
  13578. fit: function () {
  13579. var me = this;
  13580. var opts = me.options;
  13581. var minSize = me.minSize = {};
  13582. var isHorizontal = me.isHorizontal();
  13583. var lineCount, textSize;
  13584. if (!opts.display) {
  13585. me.width = minSize.width = me.height = minSize.height = 0;
  13586. return;
  13587. }
  13588. lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
  13589. textSize = lineCount * helpers$1.options._parseFont(opts).lineHeight + opts.padding * 2;
  13590. me.width = minSize.width = isHorizontal ? me.maxWidth : textSize;
  13591. me.height = minSize.height = isHorizontal ? textSize : me.maxHeight;
  13592. },
  13593. afterFit: noop$2,
  13594. // Shared Methods
  13595. isHorizontal: function () {
  13596. var pos = this.options.position;
  13597. return pos === 'top' || pos === 'bottom';
  13598. },
  13599. // Actually draw the title block on the canvas
  13600. draw: function () {
  13601. var me = this;
  13602. var ctx = me.ctx;
  13603. var opts = me.options;
  13604. if (!opts.display) {
  13605. return;
  13606. }
  13607. var fontOpts = helpers$1.options._parseFont(opts);
  13608. var lineHeight = fontOpts.lineHeight;
  13609. var offset = lineHeight / 2 + opts.padding;
  13610. var rotation = 0;
  13611. var top = me.top;
  13612. var left = me.left;
  13613. var bottom = me.bottom;
  13614. var right = me.right;
  13615. var maxWidth, titleX, titleY;
  13616. ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
  13617. ctx.font = fontOpts.string;
  13618. // Horizontal
  13619. if (me.isHorizontal()) {
  13620. titleX = left + ((right - left) / 2); // midpoint of the width
  13621. titleY = top + offset;
  13622. maxWidth = right - left;
  13623. } else {
  13624. titleX = opts.position === 'left' ? left + offset : right - offset;
  13625. titleY = top + ((bottom - top) / 2);
  13626. maxWidth = bottom - top;
  13627. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  13628. }
  13629. ctx.save();
  13630. ctx.translate(titleX, titleY);
  13631. ctx.rotate(rotation);
  13632. ctx.textAlign = 'center';
  13633. ctx.textBaseline = 'middle';
  13634. var text = opts.text;
  13635. if (helpers$1.isArray(text)) {
  13636. var y = 0;
  13637. for (var i = 0; i < text.length; ++i) {
  13638. ctx.fillText(text[i], 0, y, maxWidth);
  13639. y += lineHeight;
  13640. }
  13641. } else {
  13642. ctx.fillText(text, 0, 0, maxWidth);
  13643. }
  13644. ctx.restore();
  13645. }
  13646. });
  13647. function createNewTitleBlockAndAttach(chart, titleOpts) {
  13648. var title = new Title({
  13649. ctx: chart.ctx,
  13650. options: titleOpts,
  13651. chart: chart
  13652. });
  13653. core_layouts.configure(chart, title, titleOpts);
  13654. core_layouts.addBox(chart, title);
  13655. chart.titleBlock = title;
  13656. }
  13657. var plugin_title = {
  13658. id: 'title',
  13659. /**
  13660. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  13661. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  13662. * the plugin, which one will be re-exposed in the chart.js file.
  13663. * https://github.com/chartjs/Chart.js/pull/2640
  13664. * @private
  13665. */
  13666. _element: Title,
  13667. beforeInit: function (chart) {
  13668. var titleOpts = chart.options.title;
  13669. if (titleOpts) {
  13670. createNewTitleBlockAndAttach(chart, titleOpts);
  13671. }
  13672. },
  13673. beforeUpdate: function (chart) {
  13674. var titleOpts = chart.options.title;
  13675. var titleBlock = chart.titleBlock;
  13676. if (titleOpts) {
  13677. helpers$1.mergeIf(titleOpts, core_defaults.global.title);
  13678. if (titleBlock) {
  13679. core_layouts.configure(chart, titleBlock, titleOpts);
  13680. titleBlock.options = titleOpts;
  13681. } else {
  13682. createNewTitleBlockAndAttach(chart, titleOpts);
  13683. }
  13684. } else if (titleBlock) {
  13685. core_layouts.removeBox(chart, titleBlock);
  13686. delete chart.titleBlock;
  13687. }
  13688. }
  13689. };
  13690. var plugins = {};
  13691. var filler = plugin_filler;
  13692. var legend = plugin_legend;
  13693. var title = plugin_title;
  13694. plugins.filler = filler;
  13695. plugins.legend = legend;
  13696. plugins.title = title;
  13697. /**
  13698. * @namespace Chart
  13699. */
  13700. core_controller.helpers = helpers$1;
  13701. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  13702. core_helpers();
  13703. core_controller._adapters = core_adapters;
  13704. core_controller.Animation = core_animation;
  13705. core_controller.animationService = core_animations;
  13706. core_controller.controllers = controllers;
  13707. core_controller.DatasetController = core_datasetController;
  13708. core_controller.defaults = core_defaults;
  13709. core_controller.Element = core_element;
  13710. core_controller.elements = elements;
  13711. core_controller.Interaction = core_interaction;
  13712. core_controller.layouts = core_layouts;
  13713. core_controller.platform = platform;
  13714. core_controller.plugins = core_plugins;
  13715. core_controller.Scale = core_scale;
  13716. core_controller.scaleService = core_scaleService;
  13717. core_controller.Ticks = core_ticks;
  13718. core_controller.Tooltip = core_tooltip;
  13719. // Register built-in scales
  13720. core_controller.helpers.each(scales, function (scale, type) {
  13721. core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
  13722. });
  13723. // Load to register built-in adapters (as side effects)
  13724. // Loading built-in plugins
  13725. for (var k in plugins) {
  13726. if (plugins.hasOwnProperty(k)) {
  13727. core_controller.plugins.register(plugins[k]);
  13728. }
  13729. }
  13730. core_controller.platform.initialize();
  13731. var src = core_controller;
  13732. if (typeof window !== 'undefined') {
  13733. window.Chart = core_controller;
  13734. }
  13735. // DEPRECATIONS
  13736. /**
  13737. * Provided for backward compatibility, not available anymore
  13738. * @namespace Chart.Chart
  13739. * @deprecated since version 2.8.0
  13740. * @todo remove at version 3
  13741. * @private
  13742. */
  13743. core_controller.Chart = core_controller;
  13744. /**
  13745. * Provided for backward compatibility, not available anymore
  13746. * @namespace Chart.Legend
  13747. * @deprecated since version 2.1.5
  13748. * @todo remove at version 3
  13749. * @private
  13750. */
  13751. core_controller.Legend = plugins.legend._element;
  13752. /**
  13753. * Provided for backward compatibility, not available anymore
  13754. * @namespace Chart.Title
  13755. * @deprecated since version 2.1.5
  13756. * @todo remove at version 3
  13757. * @private
  13758. */
  13759. core_controller.Title = plugins.title._element;
  13760. /**
  13761. * Provided for backward compatibility, use Chart.plugins instead
  13762. * @namespace Chart.pluginService
  13763. * @deprecated since version 2.1.5
  13764. * @todo remove at version 3
  13765. * @private
  13766. */
  13767. core_controller.pluginService = core_controller.plugins;
  13768. /**
  13769. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  13770. * effect, instead simply create/register plugins via plain JavaScript objects.
  13771. * @interface Chart.PluginBase
  13772. * @deprecated since version 2.5.0
  13773. * @todo remove at version 3
  13774. * @private
  13775. */
  13776. core_controller.PluginBase = core_controller.Element.extend({});
  13777. /**
  13778. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  13779. * @namespace Chart.canvasHelpers
  13780. * @deprecated since version 2.6.0
  13781. * @todo remove at version 3
  13782. * @private
  13783. */
  13784. core_controller.canvasHelpers = core_controller.helpers.canvas;
  13785. /**
  13786. * Provided for backward compatibility, use Chart.layouts instead.
  13787. * @namespace Chart.layoutService
  13788. * @deprecated since version 2.7.3
  13789. * @todo remove at version 3
  13790. * @private
  13791. */
  13792. core_controller.layoutService = core_controller.layouts;
  13793. /**
  13794. * Provided for backward compatibility, not available anymore.
  13795. * @namespace Chart.LinearScaleBase
  13796. * @deprecated since version 2.8
  13797. * @todo remove at version 3
  13798. * @private
  13799. */
  13800. core_controller.LinearScaleBase = scale_linearbase;
  13801. /**
  13802. * Provided for backward compatibility, instead we should create a new Chart
  13803. * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
  13804. * @deprecated since version 2.8.0
  13805. * @todo remove at version 3
  13806. */
  13807. core_controller.helpers.each(
  13808. [
  13809. 'Bar',
  13810. 'Bubble',
  13811. 'Doughnut',
  13812. 'Line',
  13813. 'PolarArea',
  13814. 'Radar',
  13815. 'Scatter'
  13816. ],
  13817. function (klass) {
  13818. core_controller[klass] = function (ctx, cfg) {
  13819. return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
  13820. type: klass.charAt(0).toLowerCase() + klass.slice(1)
  13821. }));
  13822. };
  13823. }
  13824. );
  13825. return src;
  13826. })));