chart.esm.js 311 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266
  1. /*!
  2. * Chart.js v3.2.1
  3. * https://www.chartjs.org
  4. * (c) 2021 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. import { r as requestAnimFrame, a as resolve, e as effects, c as color, i as isObject, b as isArray, d as defaults, v as valueOrDefault, u as unlistenArrayEvents, l as listenArrayEvents, f as resolveObjectKey, g as isNumberFinite, h as defined, s as sign, j as isNullOrUndef, k as clipArea, m as unclipArea, _ as _arrayUnique, t as toRadians, n as toPercentage, o as toDimension, T as TAU, p as formatNumber, q as _angleBetween, H as HALF_PI, P as PI, w as isNumber, x as _limitValue, y as _lookupByKey, z as getRelativePosition$1, A as _isPointInArea, B as _rlookupByKey, C as toPadding, D as each, E as getMaximumSize, F as _getParentNode, G as readUsedSize, I as throttled, J as supportsEventListenerOptions, K as log10, L as _factorize, M as finiteOrDefault, N as callback, O as _addGrace, Q as toDegrees, R as _measureText, S as _int16Range, U as _alignPixel, V as renderText, W as toFont, X as _toLeftRightCenter, Y as _alignStartEnd, Z as overrides, $ as merge, a0 as _capitalize, a1 as descriptors, a2 as isFunction, a3 as _attachContext, a4 as _createResolver, a5 as _descriptors, a6 as mergeIf, a7 as uid, a8 as debounce, a9 as retinaScale, aa as clearCanvas, ab as setsEqual, ac as _elementsEqual, ad as getAngleFromPoint, ae as _readValueToProps, af as _updateBezierControlPoints, ag as _computeSegments, ah as _boundSegments, ai as _steppedInterpolation, aj as _bezierInterpolation, ak as _pointInLine, al as _steppedLineTo, am as _bezierCurveTo, an as drawPoint, ao as addRoundedRectPath, ap as toTRBL, aq as toTRBLCorners, ar as _boundSegment, as as _normalizeAngle, at as getRtlAdapter, au as overrideTextDirection, av as _textX, aw as restoreTextDirection, ax as noop, ay as distanceBetweenPoints, az as _setMinAndMaxByKey, aA as niceNum, aB as almostWhole, aC as almostEquals, aD as _decimalPlaces, aE as _longestText, aF as _filterBetween, aG as _lookup } from './chunks/helpers.segment.js';
  8. export { d as defaults } from './chunks/helpers.segment.js';
  9. class Animator {
  10. constructor() {
  11. this._request = null;
  12. this._charts = new Map();
  13. this._running = false;
  14. this._lastDate = undefined;
  15. }
  16. _notify(chart, anims, date, type) {
  17. const callbacks = anims.listeners[type];
  18. const numSteps = anims.duration;
  19. callbacks.forEach(fn => fn({
  20. chart,
  21. initial: anims.initial,
  22. numSteps,
  23. currentStep: Math.min(date - anims.start, numSteps)
  24. }));
  25. }
  26. _refresh() {
  27. const me = this;
  28. if (me._request) {
  29. return;
  30. }
  31. me._running = true;
  32. me._request = requestAnimFrame.call(window, () => {
  33. me._update();
  34. me._request = null;
  35. if (me._running) {
  36. me._refresh();
  37. }
  38. });
  39. }
  40. _update(date = Date.now()) {
  41. const me = this;
  42. let remaining = 0;
  43. me._charts.forEach((anims, chart) => {
  44. if (!anims.running || !anims.items.length) {
  45. return;
  46. }
  47. const items = anims.items;
  48. let i = items.length - 1;
  49. let draw = false;
  50. let item;
  51. for (; i >= 0; --i) {
  52. item = items[i];
  53. if (item._active) {
  54. if (item._total > anims.duration) {
  55. anims.duration = item._total;
  56. }
  57. item.tick(date);
  58. draw = true;
  59. } else {
  60. items[i] = items[items.length - 1];
  61. items.pop();
  62. }
  63. }
  64. if (draw) {
  65. chart.draw();
  66. me._notify(chart, anims, date, 'progress');
  67. }
  68. if (!items.length) {
  69. anims.running = false;
  70. me._notify(chart, anims, date, 'complete');
  71. anims.initial = false;
  72. }
  73. remaining += items.length;
  74. });
  75. me._lastDate = date;
  76. if (remaining === 0) {
  77. me._running = false;
  78. }
  79. }
  80. _getAnims(chart) {
  81. const charts = this._charts;
  82. let anims = charts.get(chart);
  83. if (!anims) {
  84. anims = {
  85. running: false,
  86. initial: true,
  87. items: [],
  88. listeners: {
  89. complete: [],
  90. progress: []
  91. }
  92. };
  93. charts.set(chart, anims);
  94. }
  95. return anims;
  96. }
  97. listen(chart, event, cb) {
  98. this._getAnims(chart).listeners[event].push(cb);
  99. }
  100. add(chart, items) {
  101. if (!items || !items.length) {
  102. return;
  103. }
  104. this._getAnims(chart).items.push(...items);
  105. }
  106. has(chart) {
  107. return this._getAnims(chart).items.length > 0;
  108. }
  109. start(chart) {
  110. const anims = this._charts.get(chart);
  111. if (!anims) {
  112. return;
  113. }
  114. anims.running = true;
  115. anims.start = Date.now();
  116. anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0);
  117. this._refresh();
  118. }
  119. running(chart) {
  120. if (!this._running) {
  121. return false;
  122. }
  123. const anims = this._charts.get(chart);
  124. if (!anims || !anims.running || !anims.items.length) {
  125. return false;
  126. }
  127. return true;
  128. }
  129. stop(chart) {
  130. const anims = this._charts.get(chart);
  131. if (!anims || !anims.items.length) {
  132. return;
  133. }
  134. const items = anims.items;
  135. let i = items.length - 1;
  136. for (; i >= 0; --i) {
  137. items[i].cancel();
  138. }
  139. anims.items = [];
  140. this._notify(chart, anims, Date.now(), 'complete');
  141. }
  142. remove(chart) {
  143. return this._charts.delete(chart);
  144. }
  145. }
  146. var animator = new Animator();
  147. const transparent = 'transparent';
  148. const interpolators = {
  149. boolean(from, to, factor) {
  150. return factor > 0.5 ? to : from;
  151. },
  152. color(from, to, factor) {
  153. const c0 = color(from || transparent);
  154. const c1 = c0.valid && color(to || transparent);
  155. return c1 && c1.valid
  156. ? c1.mix(c0, factor).hexString()
  157. : to;
  158. },
  159. number(from, to, factor) {
  160. return from + (to - from) * factor;
  161. }
  162. };
  163. class Animation {
  164. constructor(cfg, target, prop, to) {
  165. const currentValue = target[prop];
  166. to = resolve([cfg.to, to, currentValue, cfg.from]);
  167. const from = resolve([cfg.from, currentValue, to]);
  168. this._active = true;
  169. this._fn = cfg.fn || interpolators[cfg.type || typeof from];
  170. this._easing = effects[cfg.easing] || effects.linear;
  171. this._start = Math.floor(Date.now() + (cfg.delay || 0));
  172. this._duration = this._total = Math.floor(cfg.duration);
  173. this._loop = !!cfg.loop;
  174. this._target = target;
  175. this._prop = prop;
  176. this._from = from;
  177. this._to = to;
  178. this._promises = undefined;
  179. }
  180. active() {
  181. return this._active;
  182. }
  183. update(cfg, to, date) {
  184. const me = this;
  185. if (me._active) {
  186. me._notify(false);
  187. const currentValue = me._target[me._prop];
  188. const elapsed = date - me._start;
  189. const remain = me._duration - elapsed;
  190. me._start = date;
  191. me._duration = Math.floor(Math.max(remain, cfg.duration));
  192. me._total += elapsed;
  193. me._loop = !!cfg.loop;
  194. me._to = resolve([cfg.to, to, currentValue, cfg.from]);
  195. me._from = resolve([cfg.from, currentValue, to]);
  196. }
  197. }
  198. cancel() {
  199. const me = this;
  200. if (me._active) {
  201. me.tick(Date.now());
  202. me._active = false;
  203. me._notify(false);
  204. }
  205. }
  206. tick(date) {
  207. const me = this;
  208. const elapsed = date - me._start;
  209. const duration = me._duration;
  210. const prop = me._prop;
  211. const from = me._from;
  212. const loop = me._loop;
  213. const to = me._to;
  214. let factor;
  215. me._active = from !== to && (loop || (elapsed < duration));
  216. if (!me._active) {
  217. me._target[prop] = to;
  218. me._notify(true);
  219. return;
  220. }
  221. if (elapsed < 0) {
  222. me._target[prop] = from;
  223. return;
  224. }
  225. factor = (elapsed / duration) % 2;
  226. factor = loop && factor > 1 ? 2 - factor : factor;
  227. factor = me._easing(Math.min(1, Math.max(0, factor)));
  228. me._target[prop] = me._fn(from, to, factor);
  229. }
  230. wait() {
  231. const promises = this._promises || (this._promises = []);
  232. return new Promise((res, rej) => {
  233. promises.push({res, rej});
  234. });
  235. }
  236. _notify(resolved) {
  237. const method = resolved ? 'res' : 'rej';
  238. const promises = this._promises || [];
  239. for (let i = 0; i < promises.length; i++) {
  240. promises[i][method]();
  241. }
  242. }
  243. }
  244. const numbers = ['x', 'y', 'borderWidth', 'radius', 'tension'];
  245. const colors = ['color', 'borderColor', 'backgroundColor'];
  246. defaults.set('animation', {
  247. delay: undefined,
  248. duration: 1000,
  249. easing: 'easeOutQuart',
  250. fn: undefined,
  251. from: undefined,
  252. loop: undefined,
  253. to: undefined,
  254. type: undefined,
  255. });
  256. const animationOptions = Object.keys(defaults.animation);
  257. defaults.describe('animation', {
  258. _fallback: false,
  259. _indexable: false,
  260. _scriptable: (name) => name !== 'onProgress' && name !== 'onComplete' && name !== 'fn',
  261. });
  262. defaults.set('animations', {
  263. colors: {
  264. type: 'color',
  265. properties: colors
  266. },
  267. numbers: {
  268. type: 'number',
  269. properties: numbers
  270. },
  271. });
  272. defaults.describe('animations', {
  273. _fallback: 'animation',
  274. });
  275. defaults.set('transitions', {
  276. active: {
  277. animation: {
  278. duration: 400
  279. }
  280. },
  281. resize: {
  282. animation: {
  283. duration: 0
  284. }
  285. },
  286. show: {
  287. animations: {
  288. colors: {
  289. from: 'transparent'
  290. },
  291. visible: {
  292. type: 'boolean',
  293. duration: 0
  294. },
  295. }
  296. },
  297. hide: {
  298. animations: {
  299. colors: {
  300. to: 'transparent'
  301. },
  302. visible: {
  303. type: 'boolean',
  304. easing: 'linear',
  305. fn: v => v | 0
  306. },
  307. }
  308. }
  309. });
  310. class Animations {
  311. constructor(chart, config) {
  312. this._chart = chart;
  313. this._properties = new Map();
  314. this.configure(config);
  315. }
  316. configure(config) {
  317. if (!isObject(config)) {
  318. return;
  319. }
  320. const animatedProps = this._properties;
  321. Object.getOwnPropertyNames(config).forEach(key => {
  322. const cfg = config[key];
  323. if (!isObject(cfg)) {
  324. return;
  325. }
  326. const resolved = {};
  327. for (const option of animationOptions) {
  328. resolved[option] = cfg[option];
  329. }
  330. (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => {
  331. if (prop === key || !animatedProps.has(prop)) {
  332. animatedProps.set(prop, resolved);
  333. }
  334. });
  335. });
  336. }
  337. _animateOptions(target, values) {
  338. const newOptions = values.options;
  339. const options = resolveTargetOptions(target, newOptions);
  340. if (!options) {
  341. return [];
  342. }
  343. const animations = this._createAnimations(options, newOptions);
  344. if (newOptions.$shared) {
  345. awaitAll(target.options.$animations, newOptions).then(() => {
  346. target.options = newOptions;
  347. }, () => {
  348. });
  349. }
  350. return animations;
  351. }
  352. _createAnimations(target, values) {
  353. const animatedProps = this._properties;
  354. const animations = [];
  355. const running = target.$animations || (target.$animations = {});
  356. const props = Object.keys(values);
  357. const date = Date.now();
  358. let i;
  359. for (i = props.length - 1; i >= 0; --i) {
  360. const prop = props[i];
  361. if (prop.charAt(0) === '$') {
  362. continue;
  363. }
  364. if (prop === 'options') {
  365. animations.push(...this._animateOptions(target, values));
  366. continue;
  367. }
  368. const value = values[prop];
  369. let animation = running[prop];
  370. const cfg = animatedProps.get(prop);
  371. if (animation) {
  372. if (cfg && animation.active()) {
  373. animation.update(cfg, value, date);
  374. continue;
  375. } else {
  376. animation.cancel();
  377. }
  378. }
  379. if (!cfg || !cfg.duration) {
  380. target[prop] = value;
  381. continue;
  382. }
  383. running[prop] = animation = new Animation(cfg, target, prop, value);
  384. animations.push(animation);
  385. }
  386. return animations;
  387. }
  388. update(target, values) {
  389. if (this._properties.size === 0) {
  390. Object.assign(target, values);
  391. return;
  392. }
  393. const animations = this._createAnimations(target, values);
  394. if (animations.length) {
  395. animator.add(this._chart, animations);
  396. return true;
  397. }
  398. }
  399. }
  400. function awaitAll(animations, properties) {
  401. const running = [];
  402. const keys = Object.keys(properties);
  403. for (let i = 0; i < keys.length; i++) {
  404. const anim = animations[keys[i]];
  405. if (anim && anim.active()) {
  406. running.push(anim.wait());
  407. }
  408. }
  409. return Promise.all(running);
  410. }
  411. function resolveTargetOptions(target, newOptions) {
  412. if (!newOptions) {
  413. return;
  414. }
  415. let options = target.options;
  416. if (!options) {
  417. target.options = newOptions;
  418. return;
  419. }
  420. if (options.$shared) {
  421. target.options = options = Object.assign({}, options, {$shared: false, $animations: {}});
  422. }
  423. return options;
  424. }
  425. function scaleClip(scale, allowedOverflow) {
  426. const opts = scale && scale.options || {};
  427. const reverse = opts.reverse;
  428. const min = opts.min === undefined ? allowedOverflow : 0;
  429. const max = opts.max === undefined ? allowedOverflow : 0;
  430. return {
  431. start: reverse ? max : min,
  432. end: reverse ? min : max
  433. };
  434. }
  435. function defaultClip(xScale, yScale, allowedOverflow) {
  436. if (allowedOverflow === false) {
  437. return false;
  438. }
  439. const x = scaleClip(xScale, allowedOverflow);
  440. const y = scaleClip(yScale, allowedOverflow);
  441. return {
  442. top: y.end,
  443. right: x.end,
  444. bottom: y.start,
  445. left: x.start
  446. };
  447. }
  448. function toClip(value) {
  449. let t, r, b, l;
  450. if (isObject(value)) {
  451. t = value.top;
  452. r = value.right;
  453. b = value.bottom;
  454. l = value.left;
  455. } else {
  456. t = r = b = l = value;
  457. }
  458. return {
  459. top: t,
  460. right: r,
  461. bottom: b,
  462. left: l
  463. };
  464. }
  465. function getSortedDatasetIndices(chart, filterVisible) {
  466. const keys = [];
  467. const metasets = chart._getSortedDatasetMetas(filterVisible);
  468. let i, ilen;
  469. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  470. keys.push(metasets[i].index);
  471. }
  472. return keys;
  473. }
  474. function applyStack(stack, value, dsIndex, options) {
  475. const keys = stack.keys;
  476. const singleMode = options.mode === 'single';
  477. let i, ilen, datasetIndex, otherValue;
  478. if (value === null) {
  479. return;
  480. }
  481. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  482. datasetIndex = +keys[i];
  483. if (datasetIndex === dsIndex) {
  484. if (options.all) {
  485. continue;
  486. }
  487. break;
  488. }
  489. otherValue = stack.values[datasetIndex];
  490. if (isNumberFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) {
  491. value += otherValue;
  492. }
  493. }
  494. return value;
  495. }
  496. function convertObjectDataToArray(data) {
  497. const keys = Object.keys(data);
  498. const adata = new Array(keys.length);
  499. let i, ilen, key;
  500. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  501. key = keys[i];
  502. adata[i] = {
  503. x: key,
  504. y: data[key]
  505. };
  506. }
  507. return adata;
  508. }
  509. function isStacked(scale, meta) {
  510. const stacked = scale && scale.options.stacked;
  511. return stacked || (stacked === undefined && meta.stack !== undefined);
  512. }
  513. function getStackKey(indexScale, valueScale, meta) {
  514. return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;
  515. }
  516. function getUserBounds(scale) {
  517. const {min, max, minDefined, maxDefined} = scale.getUserBounds();
  518. return {
  519. min: minDefined ? min : Number.NEGATIVE_INFINITY,
  520. max: maxDefined ? max : Number.POSITIVE_INFINITY
  521. };
  522. }
  523. function getOrCreateStack(stacks, stackKey, indexValue) {
  524. const subStack = stacks[stackKey] || (stacks[stackKey] = {});
  525. return subStack[indexValue] || (subStack[indexValue] = {});
  526. }
  527. function getLastIndexInStack(stack, vScale, positive) {
  528. for (const meta of vScale.getMatchingVisibleMetas('bar').reverse()) {
  529. const value = stack[meta.index];
  530. if ((positive && value > 0) || (!positive && value < 0)) {
  531. return meta.index;
  532. }
  533. }
  534. return null;
  535. }
  536. function updateStacks(controller, parsed) {
  537. const {chart, _cachedMeta: meta} = controller;
  538. const stacks = chart._stacks || (chart._stacks = {});
  539. const {iScale, vScale, index: datasetIndex} = meta;
  540. const iAxis = iScale.axis;
  541. const vAxis = vScale.axis;
  542. const key = getStackKey(iScale, vScale, meta);
  543. const ilen = parsed.length;
  544. let stack;
  545. for (let i = 0; i < ilen; ++i) {
  546. const item = parsed[i];
  547. const {[iAxis]: index, [vAxis]: value} = item;
  548. const itemStacks = item._stacks || (item._stacks = {});
  549. stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);
  550. stack[datasetIndex] = value;
  551. stack._top = getLastIndexInStack(stack, vScale, true);
  552. stack._bottom = getLastIndexInStack(stack, vScale, false);
  553. }
  554. }
  555. function getFirstScaleId(chart, axis) {
  556. const scales = chart.scales;
  557. return Object.keys(scales).filter(key => scales[key].axis === axis).shift();
  558. }
  559. function createDatasetContext(parent, index) {
  560. return Object.assign(Object.create(parent),
  561. {
  562. active: false,
  563. dataset: undefined,
  564. datasetIndex: index,
  565. index,
  566. mode: 'default',
  567. type: 'dataset'
  568. }
  569. );
  570. }
  571. function createDataContext(parent, index, element) {
  572. return Object.assign(Object.create(parent), {
  573. active: false,
  574. dataIndex: index,
  575. parsed: undefined,
  576. raw: undefined,
  577. element,
  578. index,
  579. mode: 'default',
  580. type: 'data'
  581. });
  582. }
  583. function clearStacks(meta, items) {
  584. items = items || meta._parsed;
  585. for (const parsed of items) {
  586. const stacks = parsed._stacks;
  587. if (!stacks || stacks[meta.vScale.id] === undefined || stacks[meta.vScale.id][meta.index] === undefined) {
  588. return;
  589. }
  590. delete stacks[meta.vScale.id][meta.index];
  591. }
  592. }
  593. const isDirectUpdateMode = (mode) => mode === 'reset' || mode === 'none';
  594. const cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached);
  595. class DatasetController {
  596. constructor(chart, datasetIndex) {
  597. this.chart = chart;
  598. this._ctx = chart.ctx;
  599. this.index = datasetIndex;
  600. this._cachedDataOpts = {};
  601. this._cachedMeta = this.getMeta();
  602. this._type = this._cachedMeta.type;
  603. this.options = undefined;
  604. this._parsing = false;
  605. this._data = undefined;
  606. this._objectData = undefined;
  607. this._sharedOptions = undefined;
  608. this._drawStart = undefined;
  609. this._drawCount = undefined;
  610. this.enableOptionSharing = false;
  611. this.$context = undefined;
  612. this.initialize();
  613. }
  614. initialize() {
  615. const me = this;
  616. const meta = me._cachedMeta;
  617. me.configure();
  618. me.linkScales();
  619. meta._stacked = isStacked(meta.vScale, meta);
  620. me.addElements();
  621. }
  622. updateIndex(datasetIndex) {
  623. this.index = datasetIndex;
  624. }
  625. linkScales() {
  626. const me = this;
  627. const chart = me.chart;
  628. const meta = me._cachedMeta;
  629. const dataset = me.getDataset();
  630. const chooseId = (axis, x, y, r) => axis === 'x' ? x : axis === 'r' ? r : y;
  631. const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));
  632. const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));
  633. const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));
  634. const indexAxis = meta.indexAxis;
  635. const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);
  636. const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);
  637. meta.xScale = me.getScaleForId(xid);
  638. meta.yScale = me.getScaleForId(yid);
  639. meta.rScale = me.getScaleForId(rid);
  640. meta.iScale = me.getScaleForId(iid);
  641. meta.vScale = me.getScaleForId(vid);
  642. }
  643. getDataset() {
  644. return this.chart.data.datasets[this.index];
  645. }
  646. getMeta() {
  647. return this.chart.getDatasetMeta(this.index);
  648. }
  649. getScaleForId(scaleID) {
  650. return this.chart.scales[scaleID];
  651. }
  652. _getOtherScale(scale) {
  653. const meta = this._cachedMeta;
  654. return scale === meta.iScale
  655. ? meta.vScale
  656. : meta.iScale;
  657. }
  658. reset() {
  659. this._update('reset');
  660. }
  661. _destroy() {
  662. const meta = this._cachedMeta;
  663. if (this._data) {
  664. unlistenArrayEvents(this._data, this);
  665. }
  666. if (meta._stacked) {
  667. clearStacks(meta);
  668. }
  669. }
  670. _dataCheck() {
  671. const me = this;
  672. const dataset = me.getDataset();
  673. const data = dataset.data || (dataset.data = []);
  674. if (isObject(data)) {
  675. me._data = convertObjectDataToArray(data);
  676. } else if (me._data !== data) {
  677. if (me._data) {
  678. unlistenArrayEvents(me._data, me);
  679. clearStacks(me._cachedMeta);
  680. }
  681. if (data && Object.isExtensible(data)) {
  682. listenArrayEvents(data, me);
  683. }
  684. me._data = data;
  685. }
  686. }
  687. addElements() {
  688. const me = this;
  689. const meta = me._cachedMeta;
  690. me._dataCheck();
  691. if (me.datasetElementType) {
  692. meta.dataset = new me.datasetElementType();
  693. }
  694. }
  695. buildOrUpdateElements(resetNewElements) {
  696. const me = this;
  697. const meta = me._cachedMeta;
  698. const dataset = me.getDataset();
  699. let stackChanged = false;
  700. me._dataCheck();
  701. meta._stacked = isStacked(meta.vScale, meta);
  702. if (meta.stack !== dataset.stack) {
  703. stackChanged = true;
  704. clearStacks(meta);
  705. meta.stack = dataset.stack;
  706. }
  707. me._resyncElements(resetNewElements);
  708. if (stackChanged) {
  709. updateStacks(me, meta._parsed);
  710. }
  711. }
  712. configure() {
  713. const me = this;
  714. const config = me.chart.config;
  715. const scopeKeys = config.datasetScopeKeys(me._type);
  716. const scopes = config.getOptionScopes(me.getDataset(), scopeKeys, true);
  717. me.options = config.createResolver(scopes, me.getContext());
  718. me._parsing = me.options.parsing;
  719. }
  720. parse(start, count) {
  721. const me = this;
  722. const {_cachedMeta: meta, _data: data} = me;
  723. const {iScale, _stacked} = meta;
  724. const iAxis = iScale.axis;
  725. let sorted = start === 0 && count === data.length ? true : meta._sorted;
  726. let prev = start > 0 && meta._parsed[start - 1];
  727. let i, cur, parsed;
  728. if (me._parsing === false) {
  729. meta._parsed = data;
  730. meta._sorted = true;
  731. parsed = data;
  732. } else {
  733. if (isArray(data[start])) {
  734. parsed = me.parseArrayData(meta, data, start, count);
  735. } else if (isObject(data[start])) {
  736. parsed = me.parseObjectData(meta, data, start, count);
  737. } else {
  738. parsed = me.parsePrimitiveData(meta, data, start, count);
  739. }
  740. const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]);
  741. for (i = 0; i < count; ++i) {
  742. meta._parsed[i + start] = cur = parsed[i];
  743. if (sorted) {
  744. if (isNotInOrderComparedToPrev()) {
  745. sorted = false;
  746. }
  747. prev = cur;
  748. }
  749. }
  750. meta._sorted = sorted;
  751. }
  752. if (_stacked) {
  753. updateStacks(me, parsed);
  754. }
  755. }
  756. parsePrimitiveData(meta, data, start, count) {
  757. const {iScale, vScale} = meta;
  758. const iAxis = iScale.axis;
  759. const vAxis = vScale.axis;
  760. const labels = iScale.getLabels();
  761. const singleScale = iScale === vScale;
  762. const parsed = new Array(count);
  763. let i, ilen, index;
  764. for (i = 0, ilen = count; i < ilen; ++i) {
  765. index = i + start;
  766. parsed[i] = {
  767. [iAxis]: singleScale || iScale.parse(labels[index], index),
  768. [vAxis]: vScale.parse(data[index], index)
  769. };
  770. }
  771. return parsed;
  772. }
  773. parseArrayData(meta, data, start, count) {
  774. const {xScale, yScale} = meta;
  775. const parsed = new Array(count);
  776. let i, ilen, index, item;
  777. for (i = 0, ilen = count; i < ilen; ++i) {
  778. index = i + start;
  779. item = data[index];
  780. parsed[i] = {
  781. x: xScale.parse(item[0], index),
  782. y: yScale.parse(item[1], index)
  783. };
  784. }
  785. return parsed;
  786. }
  787. parseObjectData(meta, data, start, count) {
  788. const {xScale, yScale} = meta;
  789. const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;
  790. const parsed = new Array(count);
  791. let i, ilen, index, item;
  792. for (i = 0, ilen = count; i < ilen; ++i) {
  793. index = i + start;
  794. item = data[index];
  795. parsed[i] = {
  796. x: xScale.parse(resolveObjectKey(item, xAxisKey), index),
  797. y: yScale.parse(resolveObjectKey(item, yAxisKey), index)
  798. };
  799. }
  800. return parsed;
  801. }
  802. getParsed(index) {
  803. return this._cachedMeta._parsed[index];
  804. }
  805. getDataElement(index) {
  806. return this._cachedMeta.data[index];
  807. }
  808. applyStack(scale, parsed, mode) {
  809. const chart = this.chart;
  810. const meta = this._cachedMeta;
  811. const value = parsed[scale.axis];
  812. const stack = {
  813. keys: getSortedDatasetIndices(chart, true),
  814. values: parsed._stacks[scale.axis]
  815. };
  816. return applyStack(stack, value, meta.index, {mode});
  817. }
  818. updateRangeFromParsed(range, scale, parsed, stack) {
  819. const parsedValue = parsed[scale.axis];
  820. let value = parsedValue === null ? NaN : parsedValue;
  821. const values = stack && parsed._stacks[scale.axis];
  822. if (stack && values) {
  823. stack.values = values;
  824. range.min = Math.min(range.min, value);
  825. range.max = Math.max(range.max, value);
  826. value = applyStack(stack, parsedValue, this._cachedMeta.index, {all: true});
  827. }
  828. range.min = Math.min(range.min, value);
  829. range.max = Math.max(range.max, value);
  830. }
  831. getMinMax(scale, canStack) {
  832. const me = this;
  833. const meta = me._cachedMeta;
  834. const _parsed = meta._parsed;
  835. const sorted = meta._sorted && scale === meta.iScale;
  836. const ilen = _parsed.length;
  837. const otherScale = me._getOtherScale(scale);
  838. const stack = canStack && meta._stacked && {keys: getSortedDatasetIndices(me.chart, true), values: null};
  839. const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};
  840. const {min: otherMin, max: otherMax} = getUserBounds(otherScale);
  841. let i, value, parsed, otherValue;
  842. function _skip() {
  843. parsed = _parsed[i];
  844. value = parsed[scale.axis];
  845. otherValue = parsed[otherScale.axis];
  846. return !isNumberFinite(value) || otherMin > otherValue || otherMax < otherValue;
  847. }
  848. for (i = 0; i < ilen; ++i) {
  849. if (_skip()) {
  850. continue;
  851. }
  852. me.updateRangeFromParsed(range, scale, parsed, stack);
  853. if (sorted) {
  854. break;
  855. }
  856. }
  857. if (sorted) {
  858. for (i = ilen - 1; i >= 0; --i) {
  859. if (_skip()) {
  860. continue;
  861. }
  862. me.updateRangeFromParsed(range, scale, parsed, stack);
  863. break;
  864. }
  865. }
  866. return range;
  867. }
  868. getAllParsedValues(scale) {
  869. const parsed = this._cachedMeta._parsed;
  870. const values = [];
  871. let i, ilen, value;
  872. for (i = 0, ilen = parsed.length; i < ilen; ++i) {
  873. value = parsed[i][scale.axis];
  874. if (isNumberFinite(value)) {
  875. values.push(value);
  876. }
  877. }
  878. return values;
  879. }
  880. getMaxOverflow() {
  881. return false;
  882. }
  883. getLabelAndValue(index) {
  884. const me = this;
  885. const meta = me._cachedMeta;
  886. const iScale = meta.iScale;
  887. const vScale = meta.vScale;
  888. const parsed = me.getParsed(index);
  889. return {
  890. label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',
  891. value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''
  892. };
  893. }
  894. _update(mode) {
  895. const me = this;
  896. const meta = me._cachedMeta;
  897. me.configure();
  898. me._cachedDataOpts = {};
  899. me.update(mode || 'default');
  900. meta._clip = toClip(valueOrDefault(me.options.clip, defaultClip(meta.xScale, meta.yScale, me.getMaxOverflow())));
  901. }
  902. update(mode) {}
  903. draw() {
  904. const me = this;
  905. const ctx = me._ctx;
  906. const chart = me.chart;
  907. const meta = me._cachedMeta;
  908. const elements = meta.data || [];
  909. const area = chart.chartArea;
  910. const active = [];
  911. const start = me._drawStart || 0;
  912. const count = me._drawCount || (elements.length - start);
  913. let i;
  914. if (meta.dataset) {
  915. meta.dataset.draw(ctx, area, start, count);
  916. }
  917. for (i = start; i < start + count; ++i) {
  918. const element = elements[i];
  919. if (element.active) {
  920. active.push(element);
  921. } else {
  922. element.draw(ctx, area);
  923. }
  924. }
  925. for (i = 0; i < active.length; ++i) {
  926. active[i].draw(ctx, area);
  927. }
  928. }
  929. getStyle(index, active) {
  930. const mode = active ? 'active' : 'default';
  931. return index === undefined && this._cachedMeta.dataset
  932. ? this.resolveDatasetElementOptions(mode)
  933. : this.resolveDataElementOptions(index || 0, mode);
  934. }
  935. getContext(index, active, mode) {
  936. const me = this;
  937. const dataset = me.getDataset();
  938. let context;
  939. if (index >= 0 && index < me._cachedMeta.data.length) {
  940. const element = me._cachedMeta.data[index];
  941. context = element.$context ||
  942. (element.$context = createDataContext(me.getContext(), index, element));
  943. context.parsed = me.getParsed(index);
  944. context.raw = dataset.data[index];
  945. } else {
  946. context = me.$context ||
  947. (me.$context = createDatasetContext(me.chart.getContext(), me.index));
  948. context.dataset = dataset;
  949. }
  950. context.active = !!active;
  951. context.mode = mode;
  952. return context;
  953. }
  954. resolveDatasetElementOptions(mode) {
  955. return this._resolveElementOptions(this.datasetElementType.id, mode);
  956. }
  957. resolveDataElementOptions(index, mode) {
  958. return this._resolveElementOptions(this.dataElementType.id, mode, index);
  959. }
  960. _resolveElementOptions(elementType, mode = 'default', index) {
  961. const me = this;
  962. const active = mode === 'active';
  963. const cache = me._cachedDataOpts;
  964. const cacheKey = elementType + '-' + mode;
  965. const cached = cache[cacheKey];
  966. const sharing = me.enableOptionSharing && defined(index);
  967. if (cached) {
  968. return cloneIfNotShared(cached, sharing);
  969. }
  970. const config = me.chart.config;
  971. const scopeKeys = config.datasetElementScopeKeys(me._type, elementType);
  972. const prefixes = active ? [`${elementType}Hover`, 'hover', elementType, ''] : [elementType, ''];
  973. const scopes = config.getOptionScopes(me.getDataset(), scopeKeys);
  974. const names = Object.keys(defaults.elements[elementType]);
  975. const context = () => me.getContext(index, active);
  976. const values = config.resolveNamedOptions(scopes, names, context, prefixes);
  977. if (values.$shared) {
  978. values.$shared = sharing;
  979. cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));
  980. }
  981. return values;
  982. }
  983. _resolveAnimations(index, transition, active) {
  984. const me = this;
  985. const chart = me.chart;
  986. const cache = me._cachedDataOpts;
  987. const cacheKey = `animation-${transition}`;
  988. const cached = cache[cacheKey];
  989. if (cached) {
  990. return cached;
  991. }
  992. let options;
  993. if (chart.options.animation !== false) {
  994. const config = me.chart.config;
  995. const scopeKeys = config.datasetAnimationScopeKeys(me._type, transition);
  996. const scopes = config.getOptionScopes(me.getDataset(), scopeKeys);
  997. options = config.createResolver(scopes, me.getContext(index, active, transition));
  998. }
  999. const animations = new Animations(chart, options && options.animations);
  1000. if (options && options._cacheable) {
  1001. cache[cacheKey] = Object.freeze(animations);
  1002. }
  1003. return animations;
  1004. }
  1005. getSharedOptions(options) {
  1006. if (!options.$shared) {
  1007. return;
  1008. }
  1009. return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));
  1010. }
  1011. includeOptions(mode, sharedOptions) {
  1012. return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;
  1013. }
  1014. updateElement(element, index, properties, mode) {
  1015. if (isDirectUpdateMode(mode)) {
  1016. Object.assign(element, properties);
  1017. } else {
  1018. this._resolveAnimations(index, mode).update(element, properties);
  1019. }
  1020. }
  1021. updateSharedOptions(sharedOptions, mode, newOptions) {
  1022. if (sharedOptions && !isDirectUpdateMode(mode)) {
  1023. this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);
  1024. }
  1025. }
  1026. _setStyle(element, index, mode, active) {
  1027. element.active = active;
  1028. const options = this.getStyle(index, active);
  1029. this._resolveAnimations(index, mode, active).update(element, {
  1030. options: (!active && this.getSharedOptions(options)) || options
  1031. });
  1032. }
  1033. removeHoverStyle(element, datasetIndex, index) {
  1034. this._setStyle(element, index, 'active', false);
  1035. }
  1036. setHoverStyle(element, datasetIndex, index) {
  1037. this._setStyle(element, index, 'active', true);
  1038. }
  1039. _removeDatasetHoverStyle() {
  1040. const element = this._cachedMeta.dataset;
  1041. if (element) {
  1042. this._setStyle(element, undefined, 'active', false);
  1043. }
  1044. }
  1045. _setDatasetHoverStyle() {
  1046. const element = this._cachedMeta.dataset;
  1047. if (element) {
  1048. this._setStyle(element, undefined, 'active', true);
  1049. }
  1050. }
  1051. _resyncElements(resetNewElements) {
  1052. const me = this;
  1053. const numMeta = me._cachedMeta.data.length;
  1054. const numData = me._data.length;
  1055. if (numData > numMeta) {
  1056. me._insertElements(numMeta, numData - numMeta, resetNewElements);
  1057. } else if (numData < numMeta) {
  1058. me._removeElements(numData, numMeta - numData);
  1059. }
  1060. const count = Math.min(numData, numMeta);
  1061. if (count) {
  1062. me.parse(0, count);
  1063. }
  1064. }
  1065. _insertElements(start, count, resetNewElements = true) {
  1066. const me = this;
  1067. const meta = me._cachedMeta;
  1068. const data = meta.data;
  1069. const end = start + count;
  1070. let i;
  1071. const move = (arr) => {
  1072. arr.length += count;
  1073. for (i = arr.length - 1; i >= end; i--) {
  1074. arr[i] = arr[i - count];
  1075. }
  1076. };
  1077. move(data);
  1078. for (i = start; i < end; ++i) {
  1079. data[i] = new me.dataElementType();
  1080. }
  1081. if (me._parsing) {
  1082. move(meta._parsed);
  1083. }
  1084. me.parse(start, count);
  1085. if (resetNewElements) {
  1086. me.updateElements(data, start, count, 'reset');
  1087. }
  1088. }
  1089. updateElements(element, start, count, mode) {}
  1090. _removeElements(start, count) {
  1091. const me = this;
  1092. const meta = me._cachedMeta;
  1093. if (me._parsing) {
  1094. const removed = meta._parsed.splice(start, count);
  1095. if (meta._stacked) {
  1096. clearStacks(meta, removed);
  1097. }
  1098. }
  1099. meta.data.splice(start, count);
  1100. }
  1101. _onDataPush() {
  1102. const count = arguments.length;
  1103. this._insertElements(this.getDataset().data.length - count, count);
  1104. }
  1105. _onDataPop() {
  1106. this._removeElements(this._cachedMeta.data.length - 1, 1);
  1107. }
  1108. _onDataShift() {
  1109. this._removeElements(0, 1);
  1110. }
  1111. _onDataSplice(start, count) {
  1112. this._removeElements(start, count);
  1113. this._insertElements(start, arguments.length - 2);
  1114. }
  1115. _onDataUnshift() {
  1116. this._insertElements(0, arguments.length);
  1117. }
  1118. }
  1119. DatasetController.defaults = {};
  1120. DatasetController.prototype.datasetElementType = null;
  1121. DatasetController.prototype.dataElementType = null;
  1122. function getAllScaleValues(scale) {
  1123. if (!scale._cache.$bar) {
  1124. const metas = scale.getMatchingVisibleMetas('bar');
  1125. let values = [];
  1126. for (let i = 0, ilen = metas.length; i < ilen; i++) {
  1127. values = values.concat(metas[i].controller.getAllParsedValues(scale));
  1128. }
  1129. scale._cache.$bar = _arrayUnique(values.sort((a, b) => a - b));
  1130. }
  1131. return scale._cache.$bar;
  1132. }
  1133. function computeMinSampleSize(scale) {
  1134. const values = getAllScaleValues(scale);
  1135. let min = scale._length;
  1136. let i, ilen, curr, prev;
  1137. const updateMinAndPrev = () => {
  1138. if (curr === 32767 || curr === -32768) {
  1139. return;
  1140. }
  1141. if (defined(prev)) {
  1142. min = Math.min(min, Math.abs(curr - prev) || min);
  1143. }
  1144. prev = curr;
  1145. };
  1146. for (i = 0, ilen = values.length; i < ilen; ++i) {
  1147. curr = scale.getPixelForValue(values[i]);
  1148. updateMinAndPrev();
  1149. }
  1150. prev = undefined;
  1151. for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {
  1152. curr = scale.getPixelForTick(i);
  1153. updateMinAndPrev();
  1154. }
  1155. return min;
  1156. }
  1157. function computeFitCategoryTraits(index, ruler, options, stackCount) {
  1158. const thickness = options.barThickness;
  1159. let size, ratio;
  1160. if (isNullOrUndef(thickness)) {
  1161. size = ruler.min * options.categoryPercentage;
  1162. ratio = options.barPercentage;
  1163. } else {
  1164. size = thickness * stackCount;
  1165. ratio = 1;
  1166. }
  1167. return {
  1168. chunk: size / stackCount,
  1169. ratio,
  1170. start: ruler.pixels[index] - (size / 2)
  1171. };
  1172. }
  1173. function computeFlexCategoryTraits(index, ruler, options, stackCount) {
  1174. const pixels = ruler.pixels;
  1175. const curr = pixels[index];
  1176. let prev = index > 0 ? pixels[index - 1] : null;
  1177. let next = index < pixels.length - 1 ? pixels[index + 1] : null;
  1178. const percent = options.categoryPercentage;
  1179. if (prev === null) {
  1180. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  1181. }
  1182. if (next === null) {
  1183. next = curr + curr - prev;
  1184. }
  1185. const start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  1186. const size = Math.abs(next - prev) / 2 * percent;
  1187. return {
  1188. chunk: size / stackCount,
  1189. ratio: options.barPercentage,
  1190. start
  1191. };
  1192. }
  1193. function parseFloatBar(entry, item, vScale, i) {
  1194. const startValue = vScale.parse(entry[0], i);
  1195. const endValue = vScale.parse(entry[1], i);
  1196. const min = Math.min(startValue, endValue);
  1197. const max = Math.max(startValue, endValue);
  1198. let barStart = min;
  1199. let barEnd = max;
  1200. if (Math.abs(min) > Math.abs(max)) {
  1201. barStart = max;
  1202. barEnd = min;
  1203. }
  1204. item[vScale.axis] = barEnd;
  1205. item._custom = {
  1206. barStart,
  1207. barEnd,
  1208. start: startValue,
  1209. end: endValue,
  1210. min,
  1211. max
  1212. };
  1213. }
  1214. function parseValue(entry, item, vScale, i) {
  1215. if (isArray(entry)) {
  1216. parseFloatBar(entry, item, vScale, i);
  1217. } else {
  1218. item[vScale.axis] = vScale.parse(entry, i);
  1219. }
  1220. return item;
  1221. }
  1222. function parseArrayOrPrimitive(meta, data, start, count) {
  1223. const iScale = meta.iScale;
  1224. const vScale = meta.vScale;
  1225. const labels = iScale.getLabels();
  1226. const singleScale = iScale === vScale;
  1227. const parsed = [];
  1228. let i, ilen, item, entry;
  1229. for (i = start, ilen = start + count; i < ilen; ++i) {
  1230. entry = data[i];
  1231. item = {};
  1232. item[iScale.axis] = singleScale || iScale.parse(labels[i], i);
  1233. parsed.push(parseValue(entry, item, vScale, i));
  1234. }
  1235. return parsed;
  1236. }
  1237. function isFloatBar(custom) {
  1238. return custom && custom.barStart !== undefined && custom.barEnd !== undefined;
  1239. }
  1240. class BarController extends DatasetController {
  1241. parsePrimitiveData(meta, data, start, count) {
  1242. return parseArrayOrPrimitive(meta, data, start, count);
  1243. }
  1244. parseArrayData(meta, data, start, count) {
  1245. return parseArrayOrPrimitive(meta, data, start, count);
  1246. }
  1247. parseObjectData(meta, data, start, count) {
  1248. const {iScale, vScale} = meta;
  1249. const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;
  1250. const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;
  1251. const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;
  1252. const parsed = [];
  1253. let i, ilen, item, obj;
  1254. for (i = start, ilen = start + count; i < ilen; ++i) {
  1255. obj = data[i];
  1256. item = {};
  1257. item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);
  1258. parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));
  1259. }
  1260. return parsed;
  1261. }
  1262. updateRangeFromParsed(range, scale, parsed, stack) {
  1263. super.updateRangeFromParsed(range, scale, parsed, stack);
  1264. const custom = parsed._custom;
  1265. if (custom && scale === this._cachedMeta.vScale) {
  1266. range.min = Math.min(range.min, custom.min);
  1267. range.max = Math.max(range.max, custom.max);
  1268. }
  1269. }
  1270. getLabelAndValue(index) {
  1271. const me = this;
  1272. const meta = me._cachedMeta;
  1273. const {iScale, vScale} = meta;
  1274. const parsed = me.getParsed(index);
  1275. const custom = parsed._custom;
  1276. const value = isFloatBar(custom)
  1277. ? '[' + custom.start + ', ' + custom.end + ']'
  1278. : '' + vScale.getLabelForValue(parsed[vScale.axis]);
  1279. return {
  1280. label: '' + iScale.getLabelForValue(parsed[iScale.axis]),
  1281. value
  1282. };
  1283. }
  1284. initialize() {
  1285. const me = this;
  1286. me.enableOptionSharing = true;
  1287. super.initialize();
  1288. const meta = me._cachedMeta;
  1289. meta.stack = me.getDataset().stack;
  1290. }
  1291. update(mode) {
  1292. const me = this;
  1293. const meta = me._cachedMeta;
  1294. me.updateElements(meta.data, 0, meta.data.length, mode);
  1295. }
  1296. updateElements(bars, start, count, mode) {
  1297. const me = this;
  1298. const reset = mode === 'reset';
  1299. const vScale = me._cachedMeta.vScale;
  1300. const base = vScale.getBasePixel();
  1301. const horizontal = vScale.isHorizontal();
  1302. const ruler = me._getRuler();
  1303. const firstOpts = me.resolveDataElementOptions(start, mode);
  1304. const sharedOptions = me.getSharedOptions(firstOpts);
  1305. const includeOptions = me.includeOptions(mode, sharedOptions);
  1306. me.updateSharedOptions(sharedOptions, mode, firstOpts);
  1307. for (let i = start; i < start + count; i++) {
  1308. const parsed = me.getParsed(i);
  1309. const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {base, head: base} : me._calculateBarValuePixels(i);
  1310. const ipixels = me._calculateBarIndexPixels(i, ruler);
  1311. const stack = (parsed._stacks || {})[vScale.axis];
  1312. const properties = {
  1313. horizontal,
  1314. base: vpixels.base,
  1315. enableBorderRadius: !stack || isFloatBar(parsed._custom) || (me.index === stack._top || me.index === stack._bottom),
  1316. x: horizontal ? vpixels.head : ipixels.center,
  1317. y: horizontal ? ipixels.center : vpixels.head,
  1318. height: horizontal ? ipixels.size : undefined,
  1319. width: horizontal ? undefined : ipixels.size
  1320. };
  1321. if (includeOptions) {
  1322. properties.options = sharedOptions || me.resolveDataElementOptions(i, mode);
  1323. }
  1324. me.updateElement(bars[i], i, properties, mode);
  1325. }
  1326. }
  1327. _getStacks(last, dataIndex) {
  1328. const me = this;
  1329. const meta = me._cachedMeta;
  1330. const iScale = meta.iScale;
  1331. const metasets = iScale.getMatchingVisibleMetas(me._type);
  1332. const stacked = iScale.options.stacked;
  1333. const ilen = metasets.length;
  1334. const stacks = [];
  1335. let i, item;
  1336. for (i = 0; i < ilen; ++i) {
  1337. item = metasets[i];
  1338. if (typeof dataIndex !== 'undefined') {
  1339. const val = item.controller.getParsed(dataIndex)[
  1340. item.controller._cachedMeta.vScale.axis
  1341. ];
  1342. if (isNullOrUndef(val) || isNaN(val)) {
  1343. continue;
  1344. }
  1345. }
  1346. if (stacked === false || stacks.indexOf(item.stack) === -1 ||
  1347. (stacked === undefined && item.stack === undefined)) {
  1348. stacks.push(item.stack);
  1349. }
  1350. if (item.index === last) {
  1351. break;
  1352. }
  1353. }
  1354. if (!stacks.length) {
  1355. stacks.push(undefined);
  1356. }
  1357. return stacks;
  1358. }
  1359. _getStackCount(index) {
  1360. return this._getStacks(undefined, index).length;
  1361. }
  1362. _getStackIndex(datasetIndex, name, dataIndex) {
  1363. const stacks = this._getStacks(datasetIndex, dataIndex);
  1364. const index = (name !== undefined)
  1365. ? stacks.indexOf(name)
  1366. : -1;
  1367. return (index === -1)
  1368. ? stacks.length - 1
  1369. : index;
  1370. }
  1371. _getRuler() {
  1372. const me = this;
  1373. const opts = me.options;
  1374. const meta = me._cachedMeta;
  1375. const iScale = meta.iScale;
  1376. const pixels = [];
  1377. let i, ilen;
  1378. for (i = 0, ilen = meta.data.length; i < ilen; ++i) {
  1379. pixels.push(iScale.getPixelForValue(me.getParsed(i)[iScale.axis], i));
  1380. }
  1381. const barThickness = opts.barThickness;
  1382. const min = barThickness || computeMinSampleSize(iScale);
  1383. return {
  1384. min,
  1385. pixels,
  1386. start: iScale._startPixel,
  1387. end: iScale._endPixel,
  1388. stackCount: me._getStackCount(),
  1389. scale: iScale,
  1390. grouped: opts.grouped,
  1391. ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage
  1392. };
  1393. }
  1394. _calculateBarValuePixels(index) {
  1395. const me = this;
  1396. const {vScale, _stacked} = me._cachedMeta;
  1397. const {base: baseValue, minBarLength} = me.options;
  1398. const parsed = me.getParsed(index);
  1399. const custom = parsed._custom;
  1400. const floating = isFloatBar(custom);
  1401. let value = parsed[vScale.axis];
  1402. let start = 0;
  1403. let length = _stacked ? me.applyStack(vScale, parsed, _stacked) : value;
  1404. let head, size;
  1405. if (length !== value) {
  1406. start = length - value;
  1407. length = value;
  1408. }
  1409. if (floating) {
  1410. value = custom.barStart;
  1411. length = custom.barEnd - custom.barStart;
  1412. if (value !== 0 && sign(value) !== sign(custom.barEnd)) {
  1413. start = 0;
  1414. }
  1415. start += value;
  1416. }
  1417. const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;
  1418. let base = vScale.getPixelForValue(startValue);
  1419. if (this.chart.getDataVisibility(index)) {
  1420. head = vScale.getPixelForValue(start + length);
  1421. } else {
  1422. head = base;
  1423. }
  1424. size = head - base;
  1425. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  1426. size = size < 0 ? -minBarLength : minBarLength;
  1427. if (value === 0) {
  1428. base -= size / 2;
  1429. }
  1430. head = base + size;
  1431. }
  1432. const actualBase = baseValue || 0;
  1433. if (base === vScale.getPixelForValue(actualBase)) {
  1434. const halfGrid = vScale.getLineWidthForValue(actualBase) / 2;
  1435. if (size > 0) {
  1436. base += halfGrid;
  1437. size -= halfGrid;
  1438. } else if (size < 0) {
  1439. base -= halfGrid;
  1440. size += halfGrid;
  1441. }
  1442. }
  1443. return {
  1444. size,
  1445. base,
  1446. head,
  1447. center: head + size / 2
  1448. };
  1449. }
  1450. _calculateBarIndexPixels(index, ruler) {
  1451. const me = this;
  1452. const scale = ruler.scale;
  1453. const options = me.options;
  1454. const skipNull = options.skipNull;
  1455. const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);
  1456. let center, size;
  1457. if (ruler.grouped) {
  1458. const stackCount = skipNull ? me._getStackCount(index) : ruler.stackCount;
  1459. const range = options.barThickness === 'flex'
  1460. ? computeFlexCategoryTraits(index, ruler, options, stackCount)
  1461. : computeFitCategoryTraits(index, ruler, options, stackCount);
  1462. const stackIndex = me._getStackIndex(me.index, me._cachedMeta.stack, skipNull ? index : undefined);
  1463. center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  1464. size = Math.min(maxBarThickness, range.chunk * range.ratio);
  1465. } else {
  1466. center = scale.getPixelForValue(me.getParsed(index)[scale.axis], index);
  1467. size = Math.min(maxBarThickness, ruler.min * ruler.ratio);
  1468. }
  1469. return {
  1470. base: center - size / 2,
  1471. head: center + size / 2,
  1472. center,
  1473. size
  1474. };
  1475. }
  1476. draw() {
  1477. const me = this;
  1478. const chart = me.chart;
  1479. const meta = me._cachedMeta;
  1480. const vScale = meta.vScale;
  1481. const rects = meta.data;
  1482. const ilen = rects.length;
  1483. let i = 0;
  1484. clipArea(chart.ctx, chart.chartArea);
  1485. for (; i < ilen; ++i) {
  1486. if (me.getParsed(i)[vScale.axis] !== null) {
  1487. rects[i].draw(me._ctx);
  1488. }
  1489. }
  1490. unclipArea(chart.ctx);
  1491. }
  1492. }
  1493. BarController.id = 'bar';
  1494. BarController.defaults = {
  1495. datasetElementType: false,
  1496. dataElementType: 'bar',
  1497. categoryPercentage: 0.8,
  1498. barPercentage: 0.9,
  1499. grouped: true,
  1500. animations: {
  1501. numbers: {
  1502. type: 'number',
  1503. properties: ['x', 'y', 'base', 'width', 'height']
  1504. }
  1505. }
  1506. };
  1507. BarController.overrides = {
  1508. interaction: {
  1509. mode: 'index'
  1510. },
  1511. scales: {
  1512. _index_: {
  1513. type: 'category',
  1514. offset: true,
  1515. grid: {
  1516. offset: true
  1517. }
  1518. },
  1519. _value_: {
  1520. type: 'linear',
  1521. beginAtZero: true,
  1522. }
  1523. }
  1524. };
  1525. class BubbleController extends DatasetController {
  1526. initialize() {
  1527. this.enableOptionSharing = true;
  1528. super.initialize();
  1529. }
  1530. parseObjectData(meta, data, start, count) {
  1531. const {xScale, yScale} = meta;
  1532. const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;
  1533. const parsed = [];
  1534. let i, ilen, item;
  1535. for (i = start, ilen = start + count; i < ilen; ++i) {
  1536. item = data[i];
  1537. parsed.push({
  1538. x: xScale.parse(resolveObjectKey(item, xAxisKey), i),
  1539. y: yScale.parse(resolveObjectKey(item, yAxisKey), i),
  1540. _custom: item && item.r && +item.r
  1541. });
  1542. }
  1543. return parsed;
  1544. }
  1545. getMaxOverflow() {
  1546. const {data, _parsed} = this._cachedMeta;
  1547. let max = 0;
  1548. for (let i = data.length - 1; i >= 0; --i) {
  1549. max = Math.max(max, data[i].size() / 2, _parsed[i]._custom);
  1550. }
  1551. return max > 0 && max;
  1552. }
  1553. getLabelAndValue(index) {
  1554. const me = this;
  1555. const meta = me._cachedMeta;
  1556. const {xScale, yScale} = meta;
  1557. const parsed = me.getParsed(index);
  1558. const x = xScale.getLabelForValue(parsed.x);
  1559. const y = yScale.getLabelForValue(parsed.y);
  1560. const r = parsed._custom;
  1561. return {
  1562. label: meta.label,
  1563. value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'
  1564. };
  1565. }
  1566. update(mode) {
  1567. const me = this;
  1568. const points = me._cachedMeta.data;
  1569. me.updateElements(points, 0, points.length, mode);
  1570. }
  1571. updateElements(points, start, count, mode) {
  1572. const me = this;
  1573. const reset = mode === 'reset';
  1574. const {xScale, yScale} = me._cachedMeta;
  1575. const firstOpts = me.resolveDataElementOptions(start, mode);
  1576. const sharedOptions = me.getSharedOptions(firstOpts);
  1577. const includeOptions = me.includeOptions(mode, sharedOptions);
  1578. for (let i = start; i < start + count; i++) {
  1579. const point = points[i];
  1580. const parsed = !reset && me.getParsed(i);
  1581. const x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(parsed.x);
  1582. const y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(parsed.y);
  1583. const properties = {
  1584. x,
  1585. y,
  1586. skip: isNaN(x) || isNaN(y)
  1587. };
  1588. if (includeOptions) {
  1589. properties.options = me.resolveDataElementOptions(i, mode);
  1590. if (reset) {
  1591. properties.options.radius = 0;
  1592. }
  1593. }
  1594. me.updateElement(point, i, properties, mode);
  1595. }
  1596. me.updateSharedOptions(sharedOptions, mode, firstOpts);
  1597. }
  1598. resolveDataElementOptions(index, mode) {
  1599. const parsed = this.getParsed(index);
  1600. let values = super.resolveDataElementOptions(index, mode);
  1601. if (values.$shared) {
  1602. values = Object.assign({}, values, {$shared: false});
  1603. }
  1604. const radius = values.radius;
  1605. if (mode !== 'active') {
  1606. values.radius = 0;
  1607. }
  1608. values.radius += valueOrDefault(parsed && parsed._custom, radius);
  1609. return values;
  1610. }
  1611. }
  1612. BubbleController.id = 'bubble';
  1613. BubbleController.defaults = {
  1614. datasetElementType: false,
  1615. dataElementType: 'point',
  1616. animations: {
  1617. numbers: {
  1618. type: 'number',
  1619. properties: ['x', 'y', 'borderWidth', 'radius']
  1620. }
  1621. }
  1622. };
  1623. BubbleController.overrides = {
  1624. scales: {
  1625. x: {
  1626. type: 'linear'
  1627. },
  1628. y: {
  1629. type: 'linear'
  1630. }
  1631. },
  1632. plugins: {
  1633. tooltip: {
  1634. callbacks: {
  1635. title() {
  1636. return '';
  1637. }
  1638. }
  1639. }
  1640. }
  1641. };
  1642. function getRatioAndOffset(rotation, circumference, cutout) {
  1643. let ratioX = 1;
  1644. let ratioY = 1;
  1645. let offsetX = 0;
  1646. let offsetY = 0;
  1647. if (circumference < TAU) {
  1648. const startAngle = rotation;
  1649. const endAngle = startAngle + circumference;
  1650. const startX = Math.cos(startAngle);
  1651. const startY = Math.sin(startAngle);
  1652. const endX = Math.cos(endAngle);
  1653. const endY = Math.sin(endAngle);
  1654. const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle) ? 1 : Math.max(a, a * cutout, b, b * cutout);
  1655. const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle) ? -1 : Math.min(a, a * cutout, b, b * cutout);
  1656. const maxX = calcMax(0, startX, endX);
  1657. const maxY = calcMax(HALF_PI, startY, endY);
  1658. const minX = calcMin(PI, startX, endX);
  1659. const minY = calcMin(PI + HALF_PI, startY, endY);
  1660. ratioX = (maxX - minX) / 2;
  1661. ratioY = (maxY - minY) / 2;
  1662. offsetX = -(maxX + minX) / 2;
  1663. offsetY = -(maxY + minY) / 2;
  1664. }
  1665. return {ratioX, ratioY, offsetX, offsetY};
  1666. }
  1667. class DoughnutController extends DatasetController {
  1668. constructor(chart, datasetIndex) {
  1669. super(chart, datasetIndex);
  1670. this.enableOptionSharing = true;
  1671. this.innerRadius = undefined;
  1672. this.outerRadius = undefined;
  1673. this.offsetX = undefined;
  1674. this.offsetY = undefined;
  1675. }
  1676. linkScales() {}
  1677. parse(start, count) {
  1678. const data = this.getDataset().data;
  1679. const meta = this._cachedMeta;
  1680. let i, ilen;
  1681. for (i = start, ilen = start + count; i < ilen; ++i) {
  1682. meta._parsed[i] = +data[i];
  1683. }
  1684. }
  1685. _getRotation() {
  1686. return toRadians(this.options.rotation - 90);
  1687. }
  1688. _getCircumference() {
  1689. return toRadians(this.options.circumference);
  1690. }
  1691. _getRotationExtents() {
  1692. let min = TAU;
  1693. let max = -TAU;
  1694. const me = this;
  1695. for (let i = 0; i < me.chart.data.datasets.length; ++i) {
  1696. if (me.chart.isDatasetVisible(i)) {
  1697. const controller = me.chart.getDatasetMeta(i).controller;
  1698. const rotation = controller._getRotation();
  1699. const circumference = controller._getCircumference();
  1700. min = Math.min(min, rotation);
  1701. max = Math.max(max, rotation + circumference);
  1702. }
  1703. }
  1704. return {
  1705. rotation: min,
  1706. circumference: max - min,
  1707. };
  1708. }
  1709. update(mode) {
  1710. const me = this;
  1711. const chart = me.chart;
  1712. const {chartArea} = chart;
  1713. const meta = me._cachedMeta;
  1714. const arcs = meta.data;
  1715. const spacing = me.getMaxBorderWidth() + me.getMaxOffset(arcs);
  1716. const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);
  1717. const cutout = Math.min(toPercentage(me.options.cutout, maxSize), 1);
  1718. const chartWeight = me._getRingWeight(me.index);
  1719. const {circumference, rotation} = me._getRotationExtents();
  1720. const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout);
  1721. const maxWidth = (chartArea.width - spacing) / ratioX;
  1722. const maxHeight = (chartArea.height - spacing) / ratioY;
  1723. const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  1724. const outerRadius = toDimension(me.options.radius, maxRadius);
  1725. const innerRadius = Math.max(outerRadius * cutout, 0);
  1726. const radiusLength = (outerRadius - innerRadius) / me._getVisibleDatasetWeightTotal();
  1727. me.offsetX = offsetX * outerRadius;
  1728. me.offsetY = offsetY * outerRadius;
  1729. meta.total = me.calculateTotal();
  1730. me.outerRadius = outerRadius - radiusLength * me._getRingWeightOffset(me.index);
  1731. me.innerRadius = Math.max(me.outerRadius - radiusLength * chartWeight, 0);
  1732. me.updateElements(arcs, 0, arcs.length, mode);
  1733. }
  1734. _circumference(i, reset) {
  1735. const me = this;
  1736. const opts = me.options;
  1737. const meta = me._cachedMeta;
  1738. const circumference = me._getCircumference();
  1739. if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null) {
  1740. return 0;
  1741. }
  1742. return me.calculateCircumference(meta._parsed[i] * circumference / TAU);
  1743. }
  1744. updateElements(arcs, start, count, mode) {
  1745. const me = this;
  1746. const reset = mode === 'reset';
  1747. const chart = me.chart;
  1748. const chartArea = chart.chartArea;
  1749. const opts = chart.options;
  1750. const animationOpts = opts.animation;
  1751. const centerX = (chartArea.left + chartArea.right) / 2;
  1752. const centerY = (chartArea.top + chartArea.bottom) / 2;
  1753. const animateScale = reset && animationOpts.animateScale;
  1754. const innerRadius = animateScale ? 0 : me.innerRadius;
  1755. const outerRadius = animateScale ? 0 : me.outerRadius;
  1756. const firstOpts = me.resolveDataElementOptions(start, mode);
  1757. const sharedOptions = me.getSharedOptions(firstOpts);
  1758. const includeOptions = me.includeOptions(mode, sharedOptions);
  1759. let startAngle = me._getRotation();
  1760. let i;
  1761. for (i = 0; i < start; ++i) {
  1762. startAngle += me._circumference(i, reset);
  1763. }
  1764. for (i = start; i < start + count; ++i) {
  1765. const circumference = me._circumference(i, reset);
  1766. const arc = arcs[i];
  1767. const properties = {
  1768. x: centerX + me.offsetX,
  1769. y: centerY + me.offsetY,
  1770. startAngle,
  1771. endAngle: startAngle + circumference,
  1772. circumference,
  1773. outerRadius,
  1774. innerRadius
  1775. };
  1776. if (includeOptions) {
  1777. properties.options = sharedOptions || me.resolveDataElementOptions(i, mode);
  1778. }
  1779. startAngle += circumference;
  1780. me.updateElement(arc, i, properties, mode);
  1781. }
  1782. me.updateSharedOptions(sharedOptions, mode, firstOpts);
  1783. }
  1784. calculateTotal() {
  1785. const meta = this._cachedMeta;
  1786. const metaData = meta.data;
  1787. let total = 0;
  1788. let i;
  1789. for (i = 0; i < metaData.length; i++) {
  1790. const value = meta._parsed[i];
  1791. if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i)) {
  1792. total += Math.abs(value);
  1793. }
  1794. }
  1795. return total;
  1796. }
  1797. calculateCircumference(value) {
  1798. const total = this._cachedMeta.total;
  1799. if (total > 0 && !isNaN(value)) {
  1800. return TAU * (Math.abs(value) / total);
  1801. }
  1802. return 0;
  1803. }
  1804. getLabelAndValue(index) {
  1805. const me = this;
  1806. const meta = me._cachedMeta;
  1807. const chart = me.chart;
  1808. const labels = chart.data.labels || [];
  1809. const value = formatNumber(meta._parsed[index], chart.options.locale);
  1810. return {
  1811. label: labels[index] || '',
  1812. value,
  1813. };
  1814. }
  1815. getMaxBorderWidth(arcs) {
  1816. const me = this;
  1817. let max = 0;
  1818. const chart = me.chart;
  1819. let i, ilen, meta, controller, options;
  1820. if (!arcs) {
  1821. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  1822. if (chart.isDatasetVisible(i)) {
  1823. meta = chart.getDatasetMeta(i);
  1824. arcs = meta.data;
  1825. controller = meta.controller;
  1826. if (controller !== me) {
  1827. controller.configure();
  1828. }
  1829. break;
  1830. }
  1831. }
  1832. }
  1833. if (!arcs) {
  1834. return 0;
  1835. }
  1836. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  1837. options = controller.resolveDataElementOptions(i);
  1838. if (options.borderAlign !== 'inner') {
  1839. max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);
  1840. }
  1841. }
  1842. return max;
  1843. }
  1844. getMaxOffset(arcs) {
  1845. let max = 0;
  1846. for (let i = 0, ilen = arcs.length; i < ilen; ++i) {
  1847. const options = this.resolveDataElementOptions(i);
  1848. max = Math.max(max, options.offset || 0, options.hoverOffset || 0);
  1849. }
  1850. return max;
  1851. }
  1852. _getRingWeightOffset(datasetIndex) {
  1853. let ringWeightOffset = 0;
  1854. for (let i = 0; i < datasetIndex; ++i) {
  1855. if (this.chart.isDatasetVisible(i)) {
  1856. ringWeightOffset += this._getRingWeight(i);
  1857. }
  1858. }
  1859. return ringWeightOffset;
  1860. }
  1861. _getRingWeight(datasetIndex) {
  1862. return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);
  1863. }
  1864. _getVisibleDatasetWeightTotal() {
  1865. return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;
  1866. }
  1867. }
  1868. DoughnutController.id = 'doughnut';
  1869. DoughnutController.defaults = {
  1870. datasetElementType: false,
  1871. dataElementType: 'arc',
  1872. animation: {
  1873. animateRotate: true,
  1874. animateScale: false
  1875. },
  1876. animations: {
  1877. numbers: {
  1878. type: 'number',
  1879. properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth']
  1880. },
  1881. },
  1882. cutout: '50%',
  1883. rotation: 0,
  1884. circumference: 360,
  1885. radius: '100%',
  1886. indexAxis: 'r',
  1887. };
  1888. DoughnutController.overrides = {
  1889. aspectRatio: 1,
  1890. plugins: {
  1891. legend: {
  1892. labels: {
  1893. generateLabels(chart) {
  1894. const data = chart.data;
  1895. if (data.labels.length && data.datasets.length) {
  1896. return data.labels.map((label, i) => {
  1897. const meta = chart.getDatasetMeta(0);
  1898. const style = meta.controller.getStyle(i);
  1899. return {
  1900. text: label,
  1901. fillStyle: style.backgroundColor,
  1902. strokeStyle: style.borderColor,
  1903. lineWidth: style.borderWidth,
  1904. hidden: !chart.getDataVisibility(i),
  1905. index: i
  1906. };
  1907. });
  1908. }
  1909. return [];
  1910. }
  1911. },
  1912. onClick(e, legendItem, legend) {
  1913. legend.chart.toggleDataVisibility(legendItem.index);
  1914. legend.chart.update();
  1915. }
  1916. },
  1917. tooltip: {
  1918. callbacks: {
  1919. title() {
  1920. return '';
  1921. },
  1922. label(tooltipItem) {
  1923. let dataLabel = tooltipItem.label;
  1924. const value = ': ' + tooltipItem.formattedValue;
  1925. if (isArray(dataLabel)) {
  1926. dataLabel = dataLabel.slice();
  1927. dataLabel[0] += value;
  1928. } else {
  1929. dataLabel += value;
  1930. }
  1931. return dataLabel;
  1932. }
  1933. }
  1934. }
  1935. }
  1936. };
  1937. class LineController extends DatasetController {
  1938. initialize() {
  1939. this.enableOptionSharing = true;
  1940. super.initialize();
  1941. }
  1942. update(mode) {
  1943. const me = this;
  1944. const meta = me._cachedMeta;
  1945. const {dataset: line, data: points = [], _dataset} = meta;
  1946. const animationsDisabled = me.chart._animationsDisabled;
  1947. let {start, count} = getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
  1948. me._drawStart = start;
  1949. me._drawCount = count;
  1950. if (scaleRangesChanged(meta)) {
  1951. start = 0;
  1952. count = points.length;
  1953. }
  1954. line._decimated = !!_dataset._decimated;
  1955. line.points = points;
  1956. const options = me.resolveDatasetElementOptions(mode);
  1957. if (!me.options.showLine) {
  1958. options.borderWidth = 0;
  1959. }
  1960. options.segment = me.options.segment;
  1961. me.updateElement(line, undefined, {
  1962. animated: !animationsDisabled,
  1963. options
  1964. }, mode);
  1965. me.updateElements(points, start, count, mode);
  1966. }
  1967. updateElements(points, start, count, mode) {
  1968. const me = this;
  1969. const reset = mode === 'reset';
  1970. const {xScale, yScale, _stacked} = me._cachedMeta;
  1971. const firstOpts = me.resolveDataElementOptions(start, mode);
  1972. const sharedOptions = me.getSharedOptions(firstOpts);
  1973. const includeOptions = me.includeOptions(mode, sharedOptions);
  1974. const spanGaps = me.options.spanGaps;
  1975. const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
  1976. const directUpdate = me.chart._animationsDisabled || reset || mode === 'none';
  1977. let prevParsed = start > 0 && me.getParsed(start - 1);
  1978. for (let i = start; i < start + count; ++i) {
  1979. const point = points[i];
  1980. const parsed = me.getParsed(i);
  1981. const properties = directUpdate ? point : {};
  1982. const nullData = isNullOrUndef(parsed.y);
  1983. const x = properties.x = xScale.getPixelForValue(parsed.x, i);
  1984. const y = properties.y = reset || nullData ? yScale.getBasePixel() : yScale.getPixelForValue(_stacked ? me.applyStack(yScale, parsed, _stacked) : parsed.y, i);
  1985. properties.skip = isNaN(x) || isNaN(y) || nullData;
  1986. properties.stop = i > 0 && (parsed.x - prevParsed.x) > maxGapLength;
  1987. properties.parsed = parsed;
  1988. if (includeOptions) {
  1989. properties.options = sharedOptions || me.resolveDataElementOptions(i, mode);
  1990. }
  1991. if (!directUpdate) {
  1992. me.updateElement(point, i, properties, mode);
  1993. }
  1994. prevParsed = parsed;
  1995. }
  1996. me.updateSharedOptions(sharedOptions, mode, firstOpts);
  1997. }
  1998. getMaxOverflow() {
  1999. const me = this;
  2000. const meta = me._cachedMeta;
  2001. const dataset = meta.dataset;
  2002. const border = dataset.options && dataset.options.borderWidth || 0;
  2003. const data = meta.data || [];
  2004. if (!data.length) {
  2005. return border;
  2006. }
  2007. const firstPoint = data[0].size(me.resolveDataElementOptions(0));
  2008. const lastPoint = data[data.length - 1].size(me.resolveDataElementOptions(data.length - 1));
  2009. return Math.max(border, firstPoint, lastPoint) / 2;
  2010. }
  2011. draw() {
  2012. this._cachedMeta.dataset.updateControlPoints(this.chart.chartArea);
  2013. super.draw();
  2014. }
  2015. }
  2016. LineController.id = 'line';
  2017. LineController.defaults = {
  2018. datasetElementType: 'line',
  2019. dataElementType: 'point',
  2020. showLine: true,
  2021. spanGaps: false,
  2022. };
  2023. LineController.overrides = {
  2024. scales: {
  2025. _index_: {
  2026. type: 'category',
  2027. },
  2028. _value_: {
  2029. type: 'linear',
  2030. },
  2031. }
  2032. };
  2033. function getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) {
  2034. const pointCount = points.length;
  2035. let start = 0;
  2036. let count = pointCount;
  2037. if (meta._sorted) {
  2038. const {iScale, _parsed} = meta;
  2039. const axis = iScale.axis;
  2040. const {min, max, minDefined, maxDefined} = iScale.getUserBounds();
  2041. if (minDefined) {
  2042. start = _limitValue(Math.min(
  2043. _lookupByKey(_parsed, iScale.axis, min).lo,
  2044. animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo),
  2045. 0, pointCount - 1);
  2046. }
  2047. if (maxDefined) {
  2048. count = _limitValue(Math.max(
  2049. _lookupByKey(_parsed, iScale.axis, max).hi + 1,
  2050. animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max)).hi + 1),
  2051. start, pointCount) - start;
  2052. } else {
  2053. count = pointCount - start;
  2054. }
  2055. }
  2056. return {start, count};
  2057. }
  2058. function scaleRangesChanged(meta) {
  2059. const {xScale, yScale, _scaleRanges} = meta;
  2060. const newRanges = {
  2061. xmin: xScale.min,
  2062. xmax: xScale.max,
  2063. ymin: yScale.min,
  2064. ymax: yScale.max
  2065. };
  2066. if (!_scaleRanges) {
  2067. meta._scaleRanges = newRanges;
  2068. return true;
  2069. }
  2070. const changed = _scaleRanges.xmin !== xScale.min
  2071. || _scaleRanges.xmax !== xScale.max
  2072. || _scaleRanges.ymin !== yScale.min
  2073. || _scaleRanges.ymax !== yScale.max;
  2074. Object.assign(_scaleRanges, newRanges);
  2075. return changed;
  2076. }
  2077. class PolarAreaController extends DatasetController {
  2078. constructor(chart, datasetIndex) {
  2079. super(chart, datasetIndex);
  2080. this.innerRadius = undefined;
  2081. this.outerRadius = undefined;
  2082. }
  2083. update(mode) {
  2084. const arcs = this._cachedMeta.data;
  2085. this._updateRadius();
  2086. this.updateElements(arcs, 0, arcs.length, mode);
  2087. }
  2088. _updateRadius() {
  2089. const me = this;
  2090. const chart = me.chart;
  2091. const chartArea = chart.chartArea;
  2092. const opts = chart.options;
  2093. const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  2094. const outerRadius = Math.max(minSize / 2, 0);
  2095. const innerRadius = Math.max(opts.cutoutPercentage ? (outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  2096. const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();
  2097. me.outerRadius = outerRadius - (radiusLength * me.index);
  2098. me.innerRadius = me.outerRadius - radiusLength;
  2099. }
  2100. updateElements(arcs, start, count, mode) {
  2101. const me = this;
  2102. const reset = mode === 'reset';
  2103. const chart = me.chart;
  2104. const dataset = me.getDataset();
  2105. const opts = chart.options;
  2106. const animationOpts = opts.animation;
  2107. const scale = me._cachedMeta.rScale;
  2108. const centerX = scale.xCenter;
  2109. const centerY = scale.yCenter;
  2110. const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;
  2111. let angle = datasetStartAngle;
  2112. let i;
  2113. const defaultAngle = 360 / me.countVisibleElements();
  2114. for (i = 0; i < start; ++i) {
  2115. angle += me._computeAngle(i, mode, defaultAngle);
  2116. }
  2117. for (i = start; i < start + count; i++) {
  2118. const arc = arcs[i];
  2119. let startAngle = angle;
  2120. let endAngle = angle + me._computeAngle(i, mode, defaultAngle);
  2121. let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(dataset.data[i]) : 0;
  2122. angle = endAngle;
  2123. if (reset) {
  2124. if (animationOpts.animateScale) {
  2125. outerRadius = 0;
  2126. }
  2127. if (animationOpts.animateRotate) {
  2128. startAngle = endAngle = datasetStartAngle;
  2129. }
  2130. }
  2131. const properties = {
  2132. x: centerX,
  2133. y: centerY,
  2134. innerRadius: 0,
  2135. outerRadius,
  2136. startAngle,
  2137. endAngle,
  2138. options: me.resolveDataElementOptions(i, mode)
  2139. };
  2140. me.updateElement(arc, i, properties, mode);
  2141. }
  2142. }
  2143. countVisibleElements() {
  2144. const dataset = this.getDataset();
  2145. const meta = this._cachedMeta;
  2146. let count = 0;
  2147. meta.data.forEach((element, index) => {
  2148. if (!isNaN(dataset.data[index]) && this.chart.getDataVisibility(index)) {
  2149. count++;
  2150. }
  2151. });
  2152. return count;
  2153. }
  2154. _computeAngle(index, mode, defaultAngle) {
  2155. return this.chart.getDataVisibility(index)
  2156. ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle)
  2157. : 0;
  2158. }
  2159. }
  2160. PolarAreaController.id = 'polarArea';
  2161. PolarAreaController.defaults = {
  2162. dataElementType: 'arc',
  2163. animation: {
  2164. animateRotate: true,
  2165. animateScale: true
  2166. },
  2167. animations: {
  2168. numbers: {
  2169. type: 'number',
  2170. properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius']
  2171. },
  2172. },
  2173. indexAxis: 'r',
  2174. startAngle: 0,
  2175. };
  2176. PolarAreaController.overrides = {
  2177. aspectRatio: 1,
  2178. plugins: {
  2179. legend: {
  2180. labels: {
  2181. generateLabels(chart) {
  2182. const data = chart.data;
  2183. if (data.labels.length && data.datasets.length) {
  2184. return data.labels.map((label, i) => {
  2185. const meta = chart.getDatasetMeta(0);
  2186. const style = meta.controller.getStyle(i);
  2187. return {
  2188. text: label,
  2189. fillStyle: style.backgroundColor,
  2190. strokeStyle: style.borderColor,
  2191. lineWidth: style.borderWidth,
  2192. hidden: !chart.getDataVisibility(i),
  2193. index: i
  2194. };
  2195. });
  2196. }
  2197. return [];
  2198. }
  2199. },
  2200. onClick(e, legendItem, legend) {
  2201. legend.chart.toggleDataVisibility(legendItem.index);
  2202. legend.chart.update();
  2203. }
  2204. },
  2205. tooltip: {
  2206. callbacks: {
  2207. title() {
  2208. return '';
  2209. },
  2210. label(context) {
  2211. return context.chart.data.labels[context.dataIndex] + ': ' + context.formattedValue;
  2212. }
  2213. }
  2214. }
  2215. },
  2216. scales: {
  2217. r: {
  2218. type: 'radialLinear',
  2219. angleLines: {
  2220. display: false
  2221. },
  2222. beginAtZero: true,
  2223. grid: {
  2224. circular: true
  2225. },
  2226. pointLabels: {
  2227. display: false
  2228. },
  2229. startAngle: 0
  2230. }
  2231. }
  2232. };
  2233. class PieController extends DoughnutController {
  2234. }
  2235. PieController.id = 'pie';
  2236. PieController.defaults = {
  2237. cutout: 0,
  2238. rotation: 0,
  2239. circumference: 360,
  2240. radius: '100%'
  2241. };
  2242. class RadarController extends DatasetController {
  2243. getLabelAndValue(index) {
  2244. const me = this;
  2245. const vScale = me._cachedMeta.vScale;
  2246. const parsed = me.getParsed(index);
  2247. return {
  2248. label: vScale.getLabels()[index],
  2249. value: '' + vScale.getLabelForValue(parsed[vScale.axis])
  2250. };
  2251. }
  2252. update(mode) {
  2253. const me = this;
  2254. const meta = me._cachedMeta;
  2255. const line = meta.dataset;
  2256. const points = meta.data || [];
  2257. const labels = meta.iScale.getLabels();
  2258. line.points = points;
  2259. if (mode !== 'resize') {
  2260. const options = me.resolveDatasetElementOptions(mode);
  2261. if (!me.options.showLine) {
  2262. options.borderWidth = 0;
  2263. }
  2264. const properties = {
  2265. _loop: true,
  2266. _fullLoop: labels.length === points.length,
  2267. options
  2268. };
  2269. me.updateElement(line, undefined, properties, mode);
  2270. }
  2271. me.updateElements(points, 0, points.length, mode);
  2272. }
  2273. updateElements(points, start, count, mode) {
  2274. const me = this;
  2275. const dataset = me.getDataset();
  2276. const scale = me._cachedMeta.rScale;
  2277. const reset = mode === 'reset';
  2278. for (let i = start; i < start + count; i++) {
  2279. const point = points[i];
  2280. const options = me.resolveDataElementOptions(i, mode);
  2281. const pointPosition = scale.getPointPositionForValue(i, dataset.data[i]);
  2282. const x = reset ? scale.xCenter : pointPosition.x;
  2283. const y = reset ? scale.yCenter : pointPosition.y;
  2284. const properties = {
  2285. x,
  2286. y,
  2287. angle: pointPosition.angle,
  2288. skip: isNaN(x) || isNaN(y),
  2289. options
  2290. };
  2291. me.updateElement(point, i, properties, mode);
  2292. }
  2293. }
  2294. }
  2295. RadarController.id = 'radar';
  2296. RadarController.defaults = {
  2297. datasetElementType: 'line',
  2298. dataElementType: 'point',
  2299. indexAxis: 'r',
  2300. showLine: true,
  2301. elements: {
  2302. line: {
  2303. fill: 'start'
  2304. }
  2305. },
  2306. };
  2307. RadarController.overrides = {
  2308. aspectRatio: 1,
  2309. scales: {
  2310. r: {
  2311. type: 'radialLinear',
  2312. }
  2313. }
  2314. };
  2315. class ScatterController extends LineController {
  2316. }
  2317. ScatterController.id = 'scatter';
  2318. ScatterController.defaults = {
  2319. showLine: false,
  2320. fill: false
  2321. };
  2322. ScatterController.overrides = {
  2323. interaction: {
  2324. mode: 'point'
  2325. },
  2326. plugins: {
  2327. tooltip: {
  2328. callbacks: {
  2329. title() {
  2330. return '';
  2331. },
  2332. label(item) {
  2333. return '(' + item.label + ', ' + item.formattedValue + ')';
  2334. }
  2335. }
  2336. }
  2337. },
  2338. scales: {
  2339. x: {
  2340. type: 'linear'
  2341. },
  2342. y: {
  2343. type: 'linear'
  2344. }
  2345. }
  2346. };
  2347. var controllers = /*#__PURE__*/Object.freeze({
  2348. __proto__: null,
  2349. BarController: BarController,
  2350. BubbleController: BubbleController,
  2351. DoughnutController: DoughnutController,
  2352. LineController: LineController,
  2353. PolarAreaController: PolarAreaController,
  2354. PieController: PieController,
  2355. RadarController: RadarController,
  2356. ScatterController: ScatterController
  2357. });
  2358. function abstract() {
  2359. throw new Error('This method is not implemented: either no adapter can be found or an incomplete integration was provided.');
  2360. }
  2361. class DateAdapter {
  2362. constructor(options) {
  2363. this.options = options || {};
  2364. }
  2365. formats() {
  2366. return abstract();
  2367. }
  2368. parse(value, format) {
  2369. return abstract();
  2370. }
  2371. format(timestamp, format) {
  2372. return abstract();
  2373. }
  2374. add(timestamp, amount, unit) {
  2375. return abstract();
  2376. }
  2377. diff(a, b, unit) {
  2378. return abstract();
  2379. }
  2380. startOf(timestamp, unit, weekday) {
  2381. return abstract();
  2382. }
  2383. endOf(timestamp, unit) {
  2384. return abstract();
  2385. }
  2386. }
  2387. DateAdapter.override = function(members) {
  2388. Object.assign(DateAdapter.prototype, members);
  2389. };
  2390. var adapters = {
  2391. _date: DateAdapter
  2392. };
  2393. function getRelativePosition(e, chart) {
  2394. if ('native' in e) {
  2395. return {
  2396. x: e.x,
  2397. y: e.y
  2398. };
  2399. }
  2400. return getRelativePosition$1(e, chart);
  2401. }
  2402. function evaluateAllVisibleItems(chart, handler) {
  2403. const metasets = chart.getSortedVisibleDatasetMetas();
  2404. let index, data, element;
  2405. for (let i = 0, ilen = metasets.length; i < ilen; ++i) {
  2406. ({index, data} = metasets[i]);
  2407. for (let j = 0, jlen = data.length; j < jlen; ++j) {
  2408. element = data[j];
  2409. if (!element.skip) {
  2410. handler(element, index, j);
  2411. }
  2412. }
  2413. }
  2414. }
  2415. function binarySearch(metaset, axis, value, intersect) {
  2416. const {controller, data, _sorted} = metaset;
  2417. const iScale = controller._cachedMeta.iScale;
  2418. if (iScale && axis === iScale.axis && _sorted && data.length) {
  2419. const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;
  2420. if (!intersect) {
  2421. return lookupMethod(data, axis, value);
  2422. } else if (controller._sharedOptions) {
  2423. const el = data[0];
  2424. const range = typeof el.getRange === 'function' && el.getRange(axis);
  2425. if (range) {
  2426. const start = lookupMethod(data, axis, value - range);
  2427. const end = lookupMethod(data, axis, value + range);
  2428. return {lo: start.lo, hi: end.hi};
  2429. }
  2430. }
  2431. }
  2432. return {lo: 0, hi: data.length - 1};
  2433. }
  2434. function optimizedEvaluateItems(chart, axis, position, handler, intersect) {
  2435. const metasets = chart.getSortedVisibleDatasetMetas();
  2436. const value = position[axis];
  2437. for (let i = 0, ilen = metasets.length; i < ilen; ++i) {
  2438. const {index, data} = metasets[i];
  2439. const {lo, hi} = binarySearch(metasets[i], axis, value, intersect);
  2440. for (let j = lo; j <= hi; ++j) {
  2441. const element = data[j];
  2442. if (!element.skip) {
  2443. handler(element, index, j);
  2444. }
  2445. }
  2446. }
  2447. }
  2448. function getDistanceMetricForAxis(axis) {
  2449. const useX = axis.indexOf('x') !== -1;
  2450. const useY = axis.indexOf('y') !== -1;
  2451. return function(pt1, pt2) {
  2452. const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  2453. const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  2454. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  2455. };
  2456. }
  2457. function getIntersectItems(chart, position, axis, useFinalPosition) {
  2458. const items = [];
  2459. if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) {
  2460. return items;
  2461. }
  2462. const evaluationFunc = function(element, datasetIndex, index) {
  2463. if (element.inRange(position.x, position.y, useFinalPosition)) {
  2464. items.push({element, datasetIndex, index});
  2465. }
  2466. };
  2467. optimizedEvaluateItems(chart, axis, position, evaluationFunc, true);
  2468. return items;
  2469. }
  2470. function getNearestItems(chart, position, axis, intersect, useFinalPosition) {
  2471. const distanceMetric = getDistanceMetricForAxis(axis);
  2472. let minDistance = Number.POSITIVE_INFINITY;
  2473. let items = [];
  2474. if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) {
  2475. return items;
  2476. }
  2477. const evaluationFunc = function(element, datasetIndex, index) {
  2478. if (intersect && !element.inRange(position.x, position.y, useFinalPosition)) {
  2479. return;
  2480. }
  2481. const center = element.getCenterPoint(useFinalPosition);
  2482. const distance = distanceMetric(position, center);
  2483. if (distance < minDistance) {
  2484. items = [{element, datasetIndex, index}];
  2485. minDistance = distance;
  2486. } else if (distance === minDistance) {
  2487. items.push({element, datasetIndex, index});
  2488. }
  2489. };
  2490. optimizedEvaluateItems(chart, axis, position, evaluationFunc);
  2491. return items;
  2492. }
  2493. function getAxisItems(chart, e, options, useFinalPosition) {
  2494. const position = getRelativePosition(e, chart);
  2495. const items = [];
  2496. const axis = options.axis;
  2497. const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';
  2498. let intersectsItem = false;
  2499. evaluateAllVisibleItems(chart, (element, datasetIndex, index) => {
  2500. if (element[rangeMethod](position[axis], useFinalPosition)) {
  2501. items.push({element, datasetIndex, index});
  2502. }
  2503. if (element.inRange(position.x, position.y, useFinalPosition)) {
  2504. intersectsItem = true;
  2505. }
  2506. });
  2507. if (options.intersect && !intersectsItem) {
  2508. return [];
  2509. }
  2510. return items;
  2511. }
  2512. var Interaction = {
  2513. modes: {
  2514. index(chart, e, options, useFinalPosition) {
  2515. const position = getRelativePosition(e, chart);
  2516. const axis = options.axis || 'x';
  2517. const items = options.intersect
  2518. ? getIntersectItems(chart, position, axis, useFinalPosition)
  2519. : getNearestItems(chart, position, axis, false, useFinalPosition);
  2520. const elements = [];
  2521. if (!items.length) {
  2522. return [];
  2523. }
  2524. chart.getSortedVisibleDatasetMetas().forEach((meta) => {
  2525. const index = items[0].index;
  2526. const element = meta.data[index];
  2527. if (element && !element.skip) {
  2528. elements.push({element, datasetIndex: meta.index, index});
  2529. }
  2530. });
  2531. return elements;
  2532. },
  2533. dataset(chart, e, options, useFinalPosition) {
  2534. const position = getRelativePosition(e, chart);
  2535. const axis = options.axis || 'xy';
  2536. let items = options.intersect
  2537. ? getIntersectItems(chart, position, axis, useFinalPosition) :
  2538. getNearestItems(chart, position, axis, false, useFinalPosition);
  2539. if (items.length > 0) {
  2540. const datasetIndex = items[0].datasetIndex;
  2541. const data = chart.getDatasetMeta(datasetIndex).data;
  2542. items = [];
  2543. for (let i = 0; i < data.length; ++i) {
  2544. items.push({element: data[i], datasetIndex, index: i});
  2545. }
  2546. }
  2547. return items;
  2548. },
  2549. point(chart, e, options, useFinalPosition) {
  2550. const position = getRelativePosition(e, chart);
  2551. const axis = options.axis || 'xy';
  2552. return getIntersectItems(chart, position, axis, useFinalPosition);
  2553. },
  2554. nearest(chart, e, options, useFinalPosition) {
  2555. const position = getRelativePosition(e, chart);
  2556. const axis = options.axis || 'xy';
  2557. return getNearestItems(chart, position, axis, options.intersect, useFinalPosition);
  2558. },
  2559. x(chart, e, options, useFinalPosition) {
  2560. options.axis = 'x';
  2561. return getAxisItems(chart, e, options, useFinalPosition);
  2562. },
  2563. y(chart, e, options, useFinalPosition) {
  2564. options.axis = 'y';
  2565. return getAxisItems(chart, e, options, useFinalPosition);
  2566. }
  2567. }
  2568. };
  2569. const STATIC_POSITIONS = ['left', 'top', 'right', 'bottom'];
  2570. function filterByPosition(array, position) {
  2571. return array.filter(v => v.pos === position);
  2572. }
  2573. function filterDynamicPositionByAxis(array, axis) {
  2574. return array.filter(v => STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);
  2575. }
  2576. function sortByWeight(array, reverse) {
  2577. return array.sort((a, b) => {
  2578. const v0 = reverse ? b : a;
  2579. const v1 = reverse ? a : b;
  2580. return v0.weight === v1.weight ?
  2581. v0.index - v1.index :
  2582. v0.weight - v1.weight;
  2583. });
  2584. }
  2585. function wrapBoxes(boxes) {
  2586. const layoutBoxes = [];
  2587. let i, ilen, box;
  2588. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  2589. box = boxes[i];
  2590. layoutBoxes.push({
  2591. index: i,
  2592. box,
  2593. pos: box.position,
  2594. horizontal: box.isHorizontal(),
  2595. weight: box.weight
  2596. });
  2597. }
  2598. return layoutBoxes;
  2599. }
  2600. function setLayoutDims(layouts, params) {
  2601. let i, ilen, layout;
  2602. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  2603. layout = layouts[i];
  2604. if (layout.horizontal) {
  2605. layout.width = layout.box.fullSize && params.availableWidth;
  2606. layout.height = params.hBoxMaxHeight;
  2607. } else {
  2608. layout.width = params.vBoxMaxWidth;
  2609. layout.height = layout.box.fullSize && params.availableHeight;
  2610. }
  2611. }
  2612. }
  2613. function buildLayoutBoxes(boxes) {
  2614. const layoutBoxes = wrapBoxes(boxes);
  2615. const fullSize = sortByWeight(layoutBoxes.filter(wrap => wrap.box.fullSize), true);
  2616. const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  2617. const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  2618. const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  2619. const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  2620. const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');
  2621. const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');
  2622. return {
  2623. fullSize,
  2624. leftAndTop: left.concat(top),
  2625. rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),
  2626. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  2627. vertical: left.concat(right).concat(centerVertical),
  2628. horizontal: top.concat(bottom).concat(centerHorizontal)
  2629. };
  2630. }
  2631. function getCombinedMax(maxPadding, chartArea, a, b) {
  2632. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  2633. }
  2634. function updateMaxPadding(maxPadding, boxPadding) {
  2635. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  2636. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  2637. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  2638. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  2639. }
  2640. function updateDims(chartArea, params, layout) {
  2641. const box = layout.box;
  2642. const maxPadding = chartArea.maxPadding;
  2643. if (!isObject(layout.pos)) {
  2644. if (layout.size) {
  2645. chartArea[layout.pos] -= layout.size;
  2646. }
  2647. layout.size = layout.horizontal ? box.height : box.width;
  2648. chartArea[layout.pos] += layout.size;
  2649. }
  2650. if (box.getPadding) {
  2651. updateMaxPadding(maxPadding, box.getPadding());
  2652. }
  2653. const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));
  2654. const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));
  2655. const widthChanged = newWidth !== chartArea.w;
  2656. const heightChanged = newHeight !== chartArea.h;
  2657. chartArea.w = newWidth;
  2658. chartArea.h = newHeight;
  2659. return layout.horizontal
  2660. ? {same: widthChanged, other: heightChanged}
  2661. : {same: heightChanged, other: widthChanged};
  2662. }
  2663. function handleMaxPadding(chartArea) {
  2664. const maxPadding = chartArea.maxPadding;
  2665. function updatePos(pos) {
  2666. const change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  2667. chartArea[pos] += change;
  2668. return change;
  2669. }
  2670. chartArea.y += updatePos('top');
  2671. chartArea.x += updatePos('left');
  2672. updatePos('right');
  2673. updatePos('bottom');
  2674. }
  2675. function getMargins(horizontal, chartArea) {
  2676. const maxPadding = chartArea.maxPadding;
  2677. function marginForPositions(positions) {
  2678. const margin = {left: 0, top: 0, right: 0, bottom: 0};
  2679. positions.forEach((pos) => {
  2680. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  2681. });
  2682. return margin;
  2683. }
  2684. return horizontal
  2685. ? marginForPositions(['left', 'right'])
  2686. : marginForPositions(['top', 'bottom']);
  2687. }
  2688. function fitBoxes(boxes, chartArea, params) {
  2689. const refitBoxes = [];
  2690. let i, ilen, layout, box, refit, changed;
  2691. for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) {
  2692. layout = boxes[i];
  2693. box = layout.box;
  2694. box.update(
  2695. layout.width || chartArea.w,
  2696. layout.height || chartArea.h,
  2697. getMargins(layout.horizontal, chartArea)
  2698. );
  2699. const {same, other} = updateDims(chartArea, params, layout);
  2700. refit |= same && refitBoxes.length;
  2701. changed = changed || other;
  2702. if (!box.fullSize) {
  2703. refitBoxes.push(layout);
  2704. }
  2705. }
  2706. return refit && fitBoxes(refitBoxes, chartArea, params) || changed;
  2707. }
  2708. function placeBoxes(boxes, chartArea, params) {
  2709. const userPadding = params.padding;
  2710. let x = chartArea.x;
  2711. let y = chartArea.y;
  2712. let i, ilen, layout, box;
  2713. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  2714. layout = boxes[i];
  2715. box = layout.box;
  2716. if (layout.horizontal) {
  2717. box.left = box.fullSize ? userPadding.left : chartArea.left;
  2718. box.right = box.fullSize ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;
  2719. box.top = y;
  2720. box.bottom = y + box.height;
  2721. box.width = box.right - box.left;
  2722. y = box.bottom;
  2723. } else {
  2724. box.left = x;
  2725. box.right = x + box.width;
  2726. box.top = box.fullSize ? userPadding.top : chartArea.top;
  2727. box.bottom = box.fullSize ? params.outerHeight - userPadding.right : chartArea.top + chartArea.h;
  2728. box.height = box.bottom - box.top;
  2729. x = box.right;
  2730. }
  2731. }
  2732. chartArea.x = x;
  2733. chartArea.y = y;
  2734. }
  2735. defaults.set('layout', {
  2736. padding: {
  2737. top: 0,
  2738. right: 0,
  2739. bottom: 0,
  2740. left: 0
  2741. }
  2742. });
  2743. var layouts = {
  2744. addBox(chart, item) {
  2745. if (!chart.boxes) {
  2746. chart.boxes = [];
  2747. }
  2748. item.fullSize = item.fullSize || false;
  2749. item.position = item.position || 'top';
  2750. item.weight = item.weight || 0;
  2751. item._layers = item._layers || function() {
  2752. return [{
  2753. z: 0,
  2754. draw(chartArea) {
  2755. item.draw(chartArea);
  2756. }
  2757. }];
  2758. };
  2759. chart.boxes.push(item);
  2760. },
  2761. removeBox(chart, layoutItem) {
  2762. const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  2763. if (index !== -1) {
  2764. chart.boxes.splice(index, 1);
  2765. }
  2766. },
  2767. configure(chart, item, options) {
  2768. item.fullSize = options.fullSize;
  2769. item.position = options.position;
  2770. item.weight = options.weight;
  2771. },
  2772. update(chart, width, height, minPadding) {
  2773. if (!chart) {
  2774. return;
  2775. }
  2776. const padding = toPadding(chart.options.layout.padding);
  2777. const availableWidth = width - padding.width;
  2778. const availableHeight = height - padding.height;
  2779. const boxes = buildLayoutBoxes(chart.boxes);
  2780. const verticalBoxes = boxes.vertical;
  2781. const horizontalBoxes = boxes.horizontal;
  2782. each(chart.boxes, box => {
  2783. if (typeof box.beforeLayout === 'function') {
  2784. box.beforeLayout();
  2785. }
  2786. });
  2787. const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) =>
  2788. wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;
  2789. const params = Object.freeze({
  2790. outerWidth: width,
  2791. outerHeight: height,
  2792. padding,
  2793. availableWidth,
  2794. availableHeight,
  2795. vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,
  2796. hBoxMaxHeight: availableHeight / 2
  2797. });
  2798. const maxPadding = Object.assign({}, padding);
  2799. updateMaxPadding(maxPadding, toPadding(minPadding));
  2800. const chartArea = Object.assign({
  2801. maxPadding,
  2802. w: availableWidth,
  2803. h: availableHeight,
  2804. x: padding.left,
  2805. y: padding.top
  2806. }, padding);
  2807. setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  2808. fitBoxes(boxes.fullSize, chartArea, params);
  2809. fitBoxes(verticalBoxes, chartArea, params);
  2810. if (fitBoxes(horizontalBoxes, chartArea, params)) {
  2811. fitBoxes(verticalBoxes, chartArea, params);
  2812. }
  2813. handleMaxPadding(chartArea);
  2814. placeBoxes(boxes.leftAndTop, chartArea, params);
  2815. chartArea.x += chartArea.w;
  2816. chartArea.y += chartArea.h;
  2817. placeBoxes(boxes.rightAndBottom, chartArea, params);
  2818. chart.chartArea = {
  2819. left: chartArea.left,
  2820. top: chartArea.top,
  2821. right: chartArea.left + chartArea.w,
  2822. bottom: chartArea.top + chartArea.h,
  2823. height: chartArea.h,
  2824. width: chartArea.w,
  2825. };
  2826. each(boxes.chartArea, (layout) => {
  2827. const box = layout.box;
  2828. Object.assign(box, chart.chartArea);
  2829. box.update(chartArea.w, chartArea.h);
  2830. });
  2831. }
  2832. };
  2833. class BasePlatform {
  2834. acquireContext(canvas, aspectRatio) {}
  2835. releaseContext(context) {
  2836. return false;
  2837. }
  2838. addEventListener(chart, type, listener) {}
  2839. removeEventListener(chart, type, listener) {}
  2840. getDevicePixelRatio() {
  2841. return 1;
  2842. }
  2843. getMaximumSize(element, width, height, aspectRatio) {
  2844. width = Math.max(0, width || element.width);
  2845. height = height || element.height;
  2846. return {
  2847. width,
  2848. height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)
  2849. };
  2850. }
  2851. isAttached(canvas) {
  2852. return true;
  2853. }
  2854. }
  2855. class BasicPlatform extends BasePlatform {
  2856. acquireContext(item) {
  2857. return item && item.getContext && item.getContext('2d') || null;
  2858. }
  2859. }
  2860. const EXPANDO_KEY = '$chartjs';
  2861. const EVENT_TYPES = {
  2862. touchstart: 'mousedown',
  2863. touchmove: 'mousemove',
  2864. touchend: 'mouseup',
  2865. pointerenter: 'mouseenter',
  2866. pointerdown: 'mousedown',
  2867. pointermove: 'mousemove',
  2868. pointerup: 'mouseup',
  2869. pointerleave: 'mouseout',
  2870. pointerout: 'mouseout'
  2871. };
  2872. const isNullOrEmpty = value => value === null || value === '';
  2873. function initCanvas(canvas, aspectRatio) {
  2874. const style = canvas.style;
  2875. const renderHeight = canvas.getAttribute('height');
  2876. const renderWidth = canvas.getAttribute('width');
  2877. canvas[EXPANDO_KEY] = {
  2878. initial: {
  2879. height: renderHeight,
  2880. width: renderWidth,
  2881. style: {
  2882. display: style.display,
  2883. height: style.height,
  2884. width: style.width
  2885. }
  2886. }
  2887. };
  2888. style.display = style.display || 'block';
  2889. style.boxSizing = style.boxSizing || 'border-box';
  2890. if (isNullOrEmpty(renderWidth)) {
  2891. const displayWidth = readUsedSize(canvas, 'width');
  2892. if (displayWidth !== undefined) {
  2893. canvas.width = displayWidth;
  2894. }
  2895. }
  2896. if (isNullOrEmpty(renderHeight)) {
  2897. if (canvas.style.height === '') {
  2898. canvas.height = canvas.width / (aspectRatio || 2);
  2899. } else {
  2900. const displayHeight = readUsedSize(canvas, 'height');
  2901. if (displayHeight !== undefined) {
  2902. canvas.height = displayHeight;
  2903. }
  2904. }
  2905. }
  2906. return canvas;
  2907. }
  2908. const eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  2909. function addListener(node, type, listener) {
  2910. node.addEventListener(type, listener, eventListenerOptions);
  2911. }
  2912. function removeListener(chart, type, listener) {
  2913. chart.canvas.removeEventListener(type, listener, eventListenerOptions);
  2914. }
  2915. function fromNativeEvent(event, chart) {
  2916. const type = EVENT_TYPES[event.type] || event.type;
  2917. const {x, y} = getRelativePosition$1(event, chart);
  2918. return {
  2919. type,
  2920. chart,
  2921. native: event,
  2922. x: x !== undefined ? x : null,
  2923. y: y !== undefined ? y : null,
  2924. };
  2925. }
  2926. function createAttachObserver(chart, type, listener) {
  2927. const canvas = chart.canvas;
  2928. const container = canvas && _getParentNode(canvas);
  2929. const element = container || canvas;
  2930. const observer = new MutationObserver(entries => {
  2931. const parent = _getParentNode(element);
  2932. entries.forEach(entry => {
  2933. for (let i = 0; i < entry.addedNodes.length; i++) {
  2934. const added = entry.addedNodes[i];
  2935. if (added === element || added === parent) {
  2936. listener(entry.target);
  2937. }
  2938. }
  2939. });
  2940. });
  2941. observer.observe(document, {childList: true, subtree: true});
  2942. return observer;
  2943. }
  2944. function createDetachObserver(chart, type, listener) {
  2945. const canvas = chart.canvas;
  2946. const container = canvas && _getParentNode(canvas);
  2947. if (!container) {
  2948. return;
  2949. }
  2950. const observer = new MutationObserver(entries => {
  2951. entries.forEach(entry => {
  2952. for (let i = 0; i < entry.removedNodes.length; i++) {
  2953. if (entry.removedNodes[i] === canvas) {
  2954. listener();
  2955. break;
  2956. }
  2957. }
  2958. });
  2959. });
  2960. observer.observe(container, {childList: true});
  2961. return observer;
  2962. }
  2963. const drpListeningCharts = new Map();
  2964. let oldDevicePixelRatio = 0;
  2965. function onWindowResize() {
  2966. const dpr = window.devicePixelRatio;
  2967. if (dpr === oldDevicePixelRatio) {
  2968. return;
  2969. }
  2970. oldDevicePixelRatio = dpr;
  2971. drpListeningCharts.forEach((resize, chart) => {
  2972. if (chart.currentDevicePixelRatio !== dpr) {
  2973. resize();
  2974. }
  2975. });
  2976. }
  2977. function listenDevicePixelRatioChanges(chart, resize) {
  2978. if (!drpListeningCharts.size) {
  2979. window.addEventListener('resize', onWindowResize);
  2980. }
  2981. drpListeningCharts.set(chart, resize);
  2982. }
  2983. function unlistenDevicePixelRatioChanges(chart) {
  2984. drpListeningCharts.delete(chart);
  2985. if (!drpListeningCharts.size) {
  2986. window.removeEventListener('resize', onWindowResize);
  2987. }
  2988. }
  2989. function createResizeObserver(chart, type, listener) {
  2990. const canvas = chart.canvas;
  2991. const container = canvas && _getParentNode(canvas);
  2992. if (!container) {
  2993. return;
  2994. }
  2995. const resize = throttled((width, height) => {
  2996. const w = container.clientWidth;
  2997. listener(width, height);
  2998. if (w < container.clientWidth) {
  2999. listener();
  3000. }
  3001. }, window);
  3002. const observer = new ResizeObserver(entries => {
  3003. const entry = entries[0];
  3004. const width = entry.contentRect.width;
  3005. const height = entry.contentRect.height;
  3006. if (width === 0 && height === 0) {
  3007. return;
  3008. }
  3009. resize(width, height);
  3010. });
  3011. observer.observe(container);
  3012. listenDevicePixelRatioChanges(chart, resize);
  3013. return observer;
  3014. }
  3015. function releaseObserver(chart, type, observer) {
  3016. if (observer) {
  3017. observer.disconnect();
  3018. }
  3019. if (type === 'resize') {
  3020. unlistenDevicePixelRatioChanges(chart);
  3021. }
  3022. }
  3023. function createProxyAndListen(chart, type, listener) {
  3024. const canvas = chart.canvas;
  3025. const proxy = throttled((event) => {
  3026. if (chart.ctx !== null) {
  3027. listener(fromNativeEvent(event, chart));
  3028. }
  3029. }, chart, (args) => {
  3030. const event = args[0];
  3031. return [event, event.offsetX, event.offsetY];
  3032. });
  3033. addListener(canvas, type, proxy);
  3034. return proxy;
  3035. }
  3036. class DomPlatform extends BasePlatform {
  3037. acquireContext(canvas, aspectRatio) {
  3038. const context = canvas && canvas.getContext && canvas.getContext('2d');
  3039. if (context && context.canvas === canvas) {
  3040. initCanvas(canvas, aspectRatio);
  3041. return context;
  3042. }
  3043. return null;
  3044. }
  3045. releaseContext(context) {
  3046. const canvas = context.canvas;
  3047. if (!canvas[EXPANDO_KEY]) {
  3048. return false;
  3049. }
  3050. const initial = canvas[EXPANDO_KEY].initial;
  3051. ['height', 'width'].forEach((prop) => {
  3052. const value = initial[prop];
  3053. if (isNullOrUndef(value)) {
  3054. canvas.removeAttribute(prop);
  3055. } else {
  3056. canvas.setAttribute(prop, value);
  3057. }
  3058. });
  3059. const style = initial.style || {};
  3060. Object.keys(style).forEach((key) => {
  3061. canvas.style[key] = style[key];
  3062. });
  3063. canvas.width = canvas.width;
  3064. delete canvas[EXPANDO_KEY];
  3065. return true;
  3066. }
  3067. addEventListener(chart, type, listener) {
  3068. this.removeEventListener(chart, type);
  3069. const proxies = chart.$proxies || (chart.$proxies = {});
  3070. const handlers = {
  3071. attach: createAttachObserver,
  3072. detach: createDetachObserver,
  3073. resize: createResizeObserver
  3074. };
  3075. const handler = handlers[type] || createProxyAndListen;
  3076. proxies[type] = handler(chart, type, listener);
  3077. }
  3078. removeEventListener(chart, type) {
  3079. const proxies = chart.$proxies || (chart.$proxies = {});
  3080. const proxy = proxies[type];
  3081. if (!proxy) {
  3082. return;
  3083. }
  3084. const handlers = {
  3085. attach: releaseObserver,
  3086. detach: releaseObserver,
  3087. resize: releaseObserver
  3088. };
  3089. const handler = handlers[type] || removeListener;
  3090. handler(chart, type, proxy);
  3091. proxies[type] = undefined;
  3092. }
  3093. getDevicePixelRatio() {
  3094. return window.devicePixelRatio;
  3095. }
  3096. getMaximumSize(canvas, width, height, aspectRatio) {
  3097. return getMaximumSize(canvas, width, height, aspectRatio);
  3098. }
  3099. isAttached(canvas) {
  3100. const container = _getParentNode(canvas);
  3101. return !!(container && _getParentNode(container));
  3102. }
  3103. }
  3104. class Element {
  3105. constructor() {
  3106. this.x = undefined;
  3107. this.y = undefined;
  3108. this.active = false;
  3109. this.options = undefined;
  3110. this.$animations = undefined;
  3111. }
  3112. tooltipPosition(useFinalPosition) {
  3113. const {x, y} = this.getProps(['x', 'y'], useFinalPosition);
  3114. return {x, y};
  3115. }
  3116. hasValue() {
  3117. return isNumber(this.x) && isNumber(this.y);
  3118. }
  3119. getProps(props, final) {
  3120. const me = this;
  3121. const anims = this.$animations;
  3122. if (!final || !anims) {
  3123. return me;
  3124. }
  3125. const ret = {};
  3126. props.forEach(prop => {
  3127. ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : me[prop];
  3128. });
  3129. return ret;
  3130. }
  3131. }
  3132. Element.defaults = {};
  3133. Element.defaultRoutes = undefined;
  3134. const formatters = {
  3135. values(value) {
  3136. return isArray(value) ? value : '' + value;
  3137. },
  3138. numeric(tickValue, index, ticks) {
  3139. if (tickValue === 0) {
  3140. return '0';
  3141. }
  3142. const locale = this.chart.options.locale;
  3143. let notation;
  3144. let delta = tickValue;
  3145. if (ticks.length > 1) {
  3146. const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));
  3147. if (maxTick < 1e-4 || maxTick > 1e+15) {
  3148. notation = 'scientific';
  3149. }
  3150. delta = calculateDelta(tickValue, ticks);
  3151. }
  3152. const logDelta = log10(Math.abs(delta));
  3153. const numDecimal = Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);
  3154. const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal};
  3155. Object.assign(options, this.options.ticks.format);
  3156. return formatNumber(tickValue, locale, options);
  3157. },
  3158. logarithmic(tickValue, index, ticks) {
  3159. if (tickValue === 0) {
  3160. return '0';
  3161. }
  3162. const remain = tickValue / (Math.pow(10, Math.floor(log10(tickValue))));
  3163. if (remain === 1 || remain === 2 || remain === 5) {
  3164. return formatters.numeric.call(this, tickValue, index, ticks);
  3165. }
  3166. return '';
  3167. }
  3168. };
  3169. function calculateDelta(tickValue, ticks) {
  3170. let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;
  3171. if (Math.abs(delta) > 1 && tickValue !== Math.floor(tickValue)) {
  3172. delta = tickValue - Math.floor(tickValue);
  3173. }
  3174. return delta;
  3175. }
  3176. var Ticks = {formatters};
  3177. defaults.set('scale', {
  3178. display: true,
  3179. offset: false,
  3180. reverse: false,
  3181. beginAtZero: false,
  3182. bounds: 'ticks',
  3183. grace: 0,
  3184. grid: {
  3185. display: true,
  3186. lineWidth: 1,
  3187. drawBorder: true,
  3188. drawOnChartArea: true,
  3189. drawTicks: true,
  3190. tickLength: 8,
  3191. tickWidth: (_ctx, options) => options.lineWidth,
  3192. tickColor: (_ctx, options) => options.color,
  3193. offset: false,
  3194. borderDash: [],
  3195. borderDashOffset: 0.0,
  3196. borderWidth: 1
  3197. },
  3198. title: {
  3199. display: false,
  3200. text: '',
  3201. padding: {
  3202. top: 4,
  3203. bottom: 4
  3204. }
  3205. },
  3206. ticks: {
  3207. minRotation: 0,
  3208. maxRotation: 50,
  3209. mirror: false,
  3210. textStrokeWidth: 0,
  3211. textStrokeColor: '',
  3212. padding: 3,
  3213. display: true,
  3214. autoSkip: true,
  3215. autoSkipPadding: 3,
  3216. labelOffset: 0,
  3217. callback: Ticks.formatters.values,
  3218. minor: {},
  3219. major: {},
  3220. align: 'center',
  3221. crossAlign: 'near',
  3222. showLabelBackdrop: false,
  3223. backdropColor: 'rgba(255, 255, 255, 0.75)',
  3224. backdropPadding: 2,
  3225. }
  3226. });
  3227. defaults.route('scale.ticks', 'color', '', 'color');
  3228. defaults.route('scale.grid', 'color', '', 'borderColor');
  3229. defaults.route('scale.grid', 'borderColor', '', 'borderColor');
  3230. defaults.route('scale.title', 'color', '', 'color');
  3231. defaults.describe('scale', {
  3232. _fallback: false,
  3233. _scriptable: (name) => !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser',
  3234. _indexable: (name) => name !== 'borderDash' && name !== 'tickBorderDash',
  3235. });
  3236. defaults.describe('scales', {
  3237. _fallback: 'scale',
  3238. });
  3239. function autoSkip(scale, ticks) {
  3240. const tickOpts = scale.options.ticks;
  3241. const ticksLimit = tickOpts.maxTicksLimit || determineMaxTicks(scale);
  3242. const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  3243. const numMajorIndices = majorIndices.length;
  3244. const first = majorIndices[0];
  3245. const last = majorIndices[numMajorIndices - 1];
  3246. const newTicks = [];
  3247. if (numMajorIndices > ticksLimit) {
  3248. skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);
  3249. return newTicks;
  3250. }
  3251. const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);
  3252. if (numMajorIndices > 0) {
  3253. let i, ilen;
  3254. const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
  3255. skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  3256. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  3257. skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
  3258. }
  3259. skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  3260. return newTicks;
  3261. }
  3262. skip(ticks, newTicks, spacing);
  3263. return newTicks;
  3264. }
  3265. function determineMaxTicks(scale) {
  3266. const offset = scale.options.offset;
  3267. const tickLength = scale._tickSize();
  3268. const maxScale = scale._length / tickLength + (offset ? 0 : 1);
  3269. const maxChart = scale._maxLength / tickLength;
  3270. return Math.floor(Math.min(maxScale, maxChart));
  3271. }
  3272. function calculateSpacing(majorIndices, ticks, ticksLimit) {
  3273. const evenMajorSpacing = getEvenSpacing(majorIndices);
  3274. const spacing = ticks.length / ticksLimit;
  3275. if (!evenMajorSpacing) {
  3276. return Math.max(spacing, 1);
  3277. }
  3278. const factors = _factorize(evenMajorSpacing);
  3279. for (let i = 0, ilen = factors.length - 1; i < ilen; i++) {
  3280. const factor = factors[i];
  3281. if (factor > spacing) {
  3282. return factor;
  3283. }
  3284. }
  3285. return Math.max(spacing, 1);
  3286. }
  3287. function getMajorIndices(ticks) {
  3288. const result = [];
  3289. let i, ilen;
  3290. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  3291. if (ticks[i].major) {
  3292. result.push(i);
  3293. }
  3294. }
  3295. return result;
  3296. }
  3297. function skipMajors(ticks, newTicks, majorIndices, spacing) {
  3298. let count = 0;
  3299. let next = majorIndices[0];
  3300. let i;
  3301. spacing = Math.ceil(spacing);
  3302. for (i = 0; i < ticks.length; i++) {
  3303. if (i === next) {
  3304. newTicks.push(ticks[i]);
  3305. count++;
  3306. next = majorIndices[count * spacing];
  3307. }
  3308. }
  3309. }
  3310. function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
  3311. const start = valueOrDefault(majorStart, 0);
  3312. const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);
  3313. let count = 0;
  3314. let length, i, next;
  3315. spacing = Math.ceil(spacing);
  3316. if (majorEnd) {
  3317. length = majorEnd - majorStart;
  3318. spacing = length / Math.floor(length / spacing);
  3319. }
  3320. next = start;
  3321. while (next < 0) {
  3322. count++;
  3323. next = Math.round(start + count * spacing);
  3324. }
  3325. for (i = Math.max(start, 0); i < end; i++) {
  3326. if (i === next) {
  3327. newTicks.push(ticks[i]);
  3328. count++;
  3329. next = Math.round(start + count * spacing);
  3330. }
  3331. }
  3332. }
  3333. function getEvenSpacing(arr) {
  3334. const len = arr.length;
  3335. let i, diff;
  3336. if (len < 2) {
  3337. return false;
  3338. }
  3339. for (diff = arr[0], i = 1; i < len; ++i) {
  3340. if (arr[i] - arr[i - 1] !== diff) {
  3341. return false;
  3342. }
  3343. }
  3344. return diff;
  3345. }
  3346. const reverseAlign = (align) => align === 'left' ? 'right' : align === 'right' ? 'left' : align;
  3347. const offsetFromEdge = (scale, edge, offset) => edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;
  3348. function sample(arr, numItems) {
  3349. const result = [];
  3350. const increment = arr.length / numItems;
  3351. const len = arr.length;
  3352. let i = 0;
  3353. for (; i < len; i += increment) {
  3354. result.push(arr[Math.floor(i)]);
  3355. }
  3356. return result;
  3357. }
  3358. function getPixelForGridLine(scale, index, offsetGridLines) {
  3359. const length = scale.ticks.length;
  3360. const validIndex = Math.min(index, length - 1);
  3361. const start = scale._startPixel;
  3362. const end = scale._endPixel;
  3363. const epsilon = 1e-6;
  3364. let lineValue = scale.getPixelForTick(validIndex);
  3365. let offset;
  3366. if (offsetGridLines) {
  3367. if (length === 1) {
  3368. offset = Math.max(lineValue - start, end - lineValue);
  3369. } else if (index === 0) {
  3370. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  3371. } else {
  3372. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  3373. }
  3374. lineValue += validIndex < index ? offset : -offset;
  3375. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  3376. return;
  3377. }
  3378. }
  3379. return lineValue;
  3380. }
  3381. function garbageCollect(caches, length) {
  3382. each(caches, (cache) => {
  3383. const gc = cache.gc;
  3384. const gcLen = gc.length / 2;
  3385. let i;
  3386. if (gcLen > length) {
  3387. for (i = 0; i < gcLen; ++i) {
  3388. delete cache.data[gc[i]];
  3389. }
  3390. gc.splice(0, gcLen);
  3391. }
  3392. });
  3393. }
  3394. function getTickMarkLength(options) {
  3395. return options.drawTicks ? options.tickLength : 0;
  3396. }
  3397. function getTitleHeight(options, fallback) {
  3398. if (!options.display) {
  3399. return 0;
  3400. }
  3401. const font = toFont(options.font, fallback);
  3402. const padding = toPadding(options.padding);
  3403. const lines = isArray(options.text) ? options.text.length : 1;
  3404. return (lines * font.lineHeight) + padding.height;
  3405. }
  3406. function createScaleContext(parent, scale) {
  3407. return Object.assign(Object.create(parent), {
  3408. scale,
  3409. type: 'scale'
  3410. });
  3411. }
  3412. function createTickContext(parent, index, tick) {
  3413. return Object.assign(Object.create(parent), {
  3414. tick,
  3415. index,
  3416. type: 'tick'
  3417. });
  3418. }
  3419. function titleAlign(align, position, reverse) {
  3420. let ret = _toLeftRightCenter(align);
  3421. if ((reverse && position !== 'right') || (!reverse && position === 'right')) {
  3422. ret = reverseAlign(ret);
  3423. }
  3424. return ret;
  3425. }
  3426. function titleArgs(scale, offset, position, align) {
  3427. const {top, left, bottom, right} = scale;
  3428. let rotation = 0;
  3429. let maxWidth, titleX, titleY;
  3430. if (scale.isHorizontal()) {
  3431. titleX = _alignStartEnd(align, left, right);
  3432. titleY = offsetFromEdge(scale, position, offset);
  3433. maxWidth = right - left;
  3434. } else {
  3435. titleX = offsetFromEdge(scale, position, offset);
  3436. titleY = _alignStartEnd(align, bottom, top);
  3437. rotation = position === 'left' ? -HALF_PI : HALF_PI;
  3438. }
  3439. return {titleX, titleY, maxWidth, rotation};
  3440. }
  3441. class Scale extends Element {
  3442. constructor(cfg) {
  3443. super();
  3444. this.id = cfg.id;
  3445. this.type = cfg.type;
  3446. this.options = undefined;
  3447. this.ctx = cfg.ctx;
  3448. this.chart = cfg.chart;
  3449. this.top = undefined;
  3450. this.bottom = undefined;
  3451. this.left = undefined;
  3452. this.right = undefined;
  3453. this.width = undefined;
  3454. this.height = undefined;
  3455. this._margins = {
  3456. left: 0,
  3457. right: 0,
  3458. top: 0,
  3459. bottom: 0
  3460. };
  3461. this.maxWidth = undefined;
  3462. this.maxHeight = undefined;
  3463. this.paddingTop = undefined;
  3464. this.paddingBottom = undefined;
  3465. this.paddingLeft = undefined;
  3466. this.paddingRight = undefined;
  3467. this.axis = undefined;
  3468. this.labelRotation = undefined;
  3469. this.min = undefined;
  3470. this.max = undefined;
  3471. this._range = undefined;
  3472. this.ticks = [];
  3473. this._gridLineItems = null;
  3474. this._labelItems = null;
  3475. this._labelSizes = null;
  3476. this._length = 0;
  3477. this._maxLength = 0;
  3478. this._longestTextCache = {};
  3479. this._startPixel = undefined;
  3480. this._endPixel = undefined;
  3481. this._reversePixels = false;
  3482. this._userMax = undefined;
  3483. this._userMin = undefined;
  3484. this._suggestedMax = undefined;
  3485. this._suggestedMin = undefined;
  3486. this._ticksLength = 0;
  3487. this._borderValue = 0;
  3488. this._cache = {};
  3489. this._dataLimitsCached = false;
  3490. this.$context = undefined;
  3491. }
  3492. init(options) {
  3493. const me = this;
  3494. me.options = options.setContext(me.getContext());
  3495. me.axis = options.axis;
  3496. me._userMin = me.parse(options.min);
  3497. me._userMax = me.parse(options.max);
  3498. me._suggestedMin = me.parse(options.suggestedMin);
  3499. me._suggestedMax = me.parse(options.suggestedMax);
  3500. }
  3501. parse(raw, index) {
  3502. return raw;
  3503. }
  3504. getUserBounds() {
  3505. let {_userMin, _userMax, _suggestedMin, _suggestedMax} = this;
  3506. _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);
  3507. _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);
  3508. _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);
  3509. _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);
  3510. return {
  3511. min: finiteOrDefault(_userMin, _suggestedMin),
  3512. max: finiteOrDefault(_userMax, _suggestedMax),
  3513. minDefined: isNumberFinite(_userMin),
  3514. maxDefined: isNumberFinite(_userMax)
  3515. };
  3516. }
  3517. getMinMax(canStack) {
  3518. const me = this;
  3519. let {min, max, minDefined, maxDefined} = me.getUserBounds();
  3520. let range;
  3521. if (minDefined && maxDefined) {
  3522. return {min, max};
  3523. }
  3524. const metas = me.getMatchingVisibleMetas();
  3525. for (let i = 0, ilen = metas.length; i < ilen; ++i) {
  3526. range = metas[i].controller.getMinMax(me, canStack);
  3527. if (!minDefined) {
  3528. min = Math.min(min, range.min);
  3529. }
  3530. if (!maxDefined) {
  3531. max = Math.max(max, range.max);
  3532. }
  3533. }
  3534. return {
  3535. min: finiteOrDefault(min, finiteOrDefault(max, min)),
  3536. max: finiteOrDefault(max, finiteOrDefault(min, max))
  3537. };
  3538. }
  3539. getPadding() {
  3540. const me = this;
  3541. return {
  3542. left: me.paddingLeft || 0,
  3543. top: me.paddingTop || 0,
  3544. right: me.paddingRight || 0,
  3545. bottom: me.paddingBottom || 0
  3546. };
  3547. }
  3548. getTicks() {
  3549. return this.ticks;
  3550. }
  3551. getLabels() {
  3552. const data = this.chart.data;
  3553. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  3554. }
  3555. beforeLayout() {
  3556. this._cache = {};
  3557. this._dataLimitsCached = false;
  3558. }
  3559. beforeUpdate() {
  3560. callback(this.options.beforeUpdate, [this]);
  3561. }
  3562. update(maxWidth, maxHeight, margins) {
  3563. const me = this;
  3564. const tickOpts = me.options.ticks;
  3565. const sampleSize = tickOpts.sampleSize;
  3566. me.beforeUpdate();
  3567. me.maxWidth = maxWidth;
  3568. me.maxHeight = maxHeight;
  3569. me._margins = margins = Object.assign({
  3570. left: 0,
  3571. right: 0,
  3572. top: 0,
  3573. bottom: 0
  3574. }, margins);
  3575. me.ticks = null;
  3576. me._labelSizes = null;
  3577. me._gridLineItems = null;
  3578. me._labelItems = null;
  3579. me.beforeSetDimensions();
  3580. me.setDimensions();
  3581. me.afterSetDimensions();
  3582. me._maxLength = me.isHorizontal()
  3583. ? me.width + margins.left + margins.right
  3584. : me.height + margins.top + margins.bottom;
  3585. if (!me._dataLimitsCached) {
  3586. me.beforeDataLimits();
  3587. me.determineDataLimits();
  3588. me.afterDataLimits();
  3589. me._range = _addGrace(me, me.options.grace);
  3590. me._dataLimitsCached = true;
  3591. }
  3592. me.beforeBuildTicks();
  3593. me.ticks = me.buildTicks() || [];
  3594. me.afterBuildTicks();
  3595. const samplingEnabled = sampleSize < me.ticks.length;
  3596. me._convertTicksToLabels(samplingEnabled ? sample(me.ticks, sampleSize) : me.ticks);
  3597. me.configure();
  3598. me.beforeCalculateLabelRotation();
  3599. me.calculateLabelRotation();
  3600. me.afterCalculateLabelRotation();
  3601. if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {
  3602. me.ticks = autoSkip(me, me.ticks);
  3603. me._labelSizes = null;
  3604. }
  3605. if (samplingEnabled) {
  3606. me._convertTicksToLabels(me.ticks);
  3607. }
  3608. me.beforeFit();
  3609. me.fit();
  3610. me.afterFit();
  3611. me.afterUpdate();
  3612. }
  3613. configure() {
  3614. const me = this;
  3615. let reversePixels = me.options.reverse;
  3616. let startPixel, endPixel;
  3617. if (me.isHorizontal()) {
  3618. startPixel = me.left;
  3619. endPixel = me.right;
  3620. } else {
  3621. startPixel = me.top;
  3622. endPixel = me.bottom;
  3623. reversePixels = !reversePixels;
  3624. }
  3625. me._startPixel = startPixel;
  3626. me._endPixel = endPixel;
  3627. me._reversePixels = reversePixels;
  3628. me._length = endPixel - startPixel;
  3629. me._alignToPixels = me.options.alignToPixels;
  3630. }
  3631. afterUpdate() {
  3632. callback(this.options.afterUpdate, [this]);
  3633. }
  3634. beforeSetDimensions() {
  3635. callback(this.options.beforeSetDimensions, [this]);
  3636. }
  3637. setDimensions() {
  3638. const me = this;
  3639. if (me.isHorizontal()) {
  3640. me.width = me.maxWidth;
  3641. me.left = 0;
  3642. me.right = me.width;
  3643. } else {
  3644. me.height = me.maxHeight;
  3645. me.top = 0;
  3646. me.bottom = me.height;
  3647. }
  3648. me.paddingLeft = 0;
  3649. me.paddingTop = 0;
  3650. me.paddingRight = 0;
  3651. me.paddingBottom = 0;
  3652. }
  3653. afterSetDimensions() {
  3654. callback(this.options.afterSetDimensions, [this]);
  3655. }
  3656. _callHooks(name) {
  3657. const me = this;
  3658. me.chart.notifyPlugins(name, me.getContext());
  3659. callback(me.options[name], [me]);
  3660. }
  3661. beforeDataLimits() {
  3662. this._callHooks('beforeDataLimits');
  3663. }
  3664. determineDataLimits() {}
  3665. afterDataLimits() {
  3666. this._callHooks('afterDataLimits');
  3667. }
  3668. beforeBuildTicks() {
  3669. this._callHooks('beforeBuildTicks');
  3670. }
  3671. buildTicks() {
  3672. return [];
  3673. }
  3674. afterBuildTicks() {
  3675. this._callHooks('afterBuildTicks');
  3676. }
  3677. beforeTickToLabelConversion() {
  3678. callback(this.options.beforeTickToLabelConversion, [this]);
  3679. }
  3680. generateTickLabels(ticks) {
  3681. const me = this;
  3682. const tickOpts = me.options.ticks;
  3683. let i, ilen, tick;
  3684. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  3685. tick = ticks[i];
  3686. tick.label = callback(tickOpts.callback, [tick.value, i, ticks], me);
  3687. }
  3688. for (i = 0; i < ilen; i++) {
  3689. if (isNullOrUndef(ticks[i].label)) {
  3690. ticks.splice(i, 1);
  3691. ilen--;
  3692. i--;
  3693. }
  3694. }
  3695. }
  3696. afterTickToLabelConversion() {
  3697. callback(this.options.afterTickToLabelConversion, [this]);
  3698. }
  3699. beforeCalculateLabelRotation() {
  3700. callback(this.options.beforeCalculateLabelRotation, [this]);
  3701. }
  3702. calculateLabelRotation() {
  3703. const me = this;
  3704. const options = me.options;
  3705. const tickOpts = options.ticks;
  3706. const numTicks = me.ticks.length;
  3707. const minRotation = tickOpts.minRotation || 0;
  3708. const maxRotation = tickOpts.maxRotation;
  3709. let labelRotation = minRotation;
  3710. let tickWidth, maxHeight, maxLabelDiagonal;
  3711. if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
  3712. me.labelRotation = minRotation;
  3713. return;
  3714. }
  3715. const labelSizes = me._getLabelSizes();
  3716. const maxLabelWidth = labelSizes.widest.width;
  3717. const maxLabelHeight = labelSizes.highest.height;
  3718. const maxWidth = _limitValue(me.chart.width - maxLabelWidth, 0, me.maxWidth);
  3719. tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
  3720. if (maxLabelWidth + 6 > tickWidth) {
  3721. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  3722. maxHeight = me.maxHeight - getTickMarkLength(options.grid)
  3723. - tickOpts.padding - getTitleHeight(options.title, me.chart.options.font);
  3724. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  3725. labelRotation = toDegrees(Math.min(
  3726. Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
  3727. Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
  3728. ));
  3729. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  3730. }
  3731. me.labelRotation = labelRotation;
  3732. }
  3733. afterCalculateLabelRotation() {
  3734. callback(this.options.afterCalculateLabelRotation, [this]);
  3735. }
  3736. beforeFit() {
  3737. callback(this.options.beforeFit, [this]);
  3738. }
  3739. fit() {
  3740. const me = this;
  3741. const minSize = {
  3742. width: 0,
  3743. height: 0
  3744. };
  3745. const {chart, options: {ticks: tickOpts, title: titleOpts, grid: gridOpts}} = me;
  3746. const display = me._isVisible();
  3747. const isHorizontal = me.isHorizontal();
  3748. if (display) {
  3749. const titleHeight = getTitleHeight(titleOpts, chart.options.font);
  3750. if (isHorizontal) {
  3751. minSize.width = me.maxWidth;
  3752. minSize.height = getTickMarkLength(gridOpts) + titleHeight;
  3753. } else {
  3754. minSize.height = me.maxHeight;
  3755. minSize.width = getTickMarkLength(gridOpts) + titleHeight;
  3756. }
  3757. if (tickOpts.display && me.ticks.length) {
  3758. const {first, last, widest, highest} = me._getLabelSizes();
  3759. const tickPadding = tickOpts.padding * 2;
  3760. const angleRadians = toRadians(me.labelRotation);
  3761. const cos = Math.cos(angleRadians);
  3762. const sin = Math.sin(angleRadians);
  3763. if (isHorizontal) {
  3764. const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;
  3765. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  3766. } else {
  3767. const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;
  3768. minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth + tickPadding);
  3769. }
  3770. me._calculatePadding(first, last, sin, cos);
  3771. }
  3772. }
  3773. me._handleMargins();
  3774. if (isHorizontal) {
  3775. me.width = me._length = chart.width - me._margins.left - me._margins.right;
  3776. me.height = minSize.height;
  3777. } else {
  3778. me.width = minSize.width;
  3779. me.height = me._length = chart.height - me._margins.top - me._margins.bottom;
  3780. }
  3781. }
  3782. _calculatePadding(first, last, sin, cos) {
  3783. const me = this;
  3784. const {ticks: {align, padding}, position} = me.options;
  3785. const isRotated = me.labelRotation !== 0;
  3786. const labelsBelowTicks = position !== 'top' && me.axis === 'x';
  3787. if (me.isHorizontal()) {
  3788. const offsetLeft = me.getPixelForTick(0) - me.left;
  3789. const offsetRight = me.right - me.getPixelForTick(me.ticks.length - 1);
  3790. let paddingLeft = 0;
  3791. let paddingRight = 0;
  3792. if (isRotated) {
  3793. if (labelsBelowTicks) {
  3794. paddingLeft = cos * first.width;
  3795. paddingRight = sin * last.height;
  3796. } else {
  3797. paddingLeft = sin * first.height;
  3798. paddingRight = cos * last.width;
  3799. }
  3800. } else if (align === 'start') {
  3801. paddingRight = last.width;
  3802. } else if (align === 'end') {
  3803. paddingLeft = first.width;
  3804. } else {
  3805. paddingLeft = first.width / 2;
  3806. paddingRight = last.width / 2;
  3807. }
  3808. me.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * me.width / (me.width - offsetLeft), 0);
  3809. me.paddingRight = Math.max((paddingRight - offsetRight + padding) * me.width / (me.width - offsetRight), 0);
  3810. } else {
  3811. let paddingTop = last.height / 2;
  3812. let paddingBottom = first.height / 2;
  3813. if (align === 'start') {
  3814. paddingTop = 0;
  3815. paddingBottom = first.height;
  3816. } else if (align === 'end') {
  3817. paddingTop = last.height;
  3818. paddingBottom = 0;
  3819. }
  3820. me.paddingTop = paddingTop + padding;
  3821. me.paddingBottom = paddingBottom + padding;
  3822. }
  3823. }
  3824. _handleMargins() {
  3825. const me = this;
  3826. if (me._margins) {
  3827. me._margins.left = Math.max(me.paddingLeft, me._margins.left);
  3828. me._margins.top = Math.max(me.paddingTop, me._margins.top);
  3829. me._margins.right = Math.max(me.paddingRight, me._margins.right);
  3830. me._margins.bottom = Math.max(me.paddingBottom, me._margins.bottom);
  3831. }
  3832. }
  3833. afterFit() {
  3834. callback(this.options.afterFit, [this]);
  3835. }
  3836. isHorizontal() {
  3837. const {axis, position} = this.options;
  3838. return position === 'top' || position === 'bottom' || axis === 'x';
  3839. }
  3840. isFullSize() {
  3841. return this.options.fullSize;
  3842. }
  3843. _convertTicksToLabels(ticks) {
  3844. const me = this;
  3845. me.beforeTickToLabelConversion();
  3846. me.generateTickLabels(ticks);
  3847. me.afterTickToLabelConversion();
  3848. }
  3849. _getLabelSizes() {
  3850. const me = this;
  3851. let labelSizes = me._labelSizes;
  3852. if (!labelSizes) {
  3853. const sampleSize = me.options.ticks.sampleSize;
  3854. let ticks = me.ticks;
  3855. if (sampleSize < ticks.length) {
  3856. ticks = sample(ticks, sampleSize);
  3857. }
  3858. me._labelSizes = labelSizes = me._computeLabelSizes(ticks, ticks.length);
  3859. }
  3860. return labelSizes;
  3861. }
  3862. _computeLabelSizes(ticks, length) {
  3863. const {ctx, _longestTextCache: caches} = this;
  3864. const widths = [];
  3865. const heights = [];
  3866. let widestLabelSize = 0;
  3867. let highestLabelSize = 0;
  3868. let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;
  3869. for (i = 0; i < length; ++i) {
  3870. label = ticks[i].label;
  3871. tickFont = this._resolveTickFontOptions(i);
  3872. ctx.font = fontString = tickFont.string;
  3873. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  3874. lineHeight = tickFont.lineHeight;
  3875. width = height = 0;
  3876. if (!isNullOrUndef(label) && !isArray(label)) {
  3877. width = _measureText(ctx, cache.data, cache.gc, width, label);
  3878. height = lineHeight;
  3879. } else if (isArray(label)) {
  3880. for (j = 0, jlen = label.length; j < jlen; ++j) {
  3881. nestedLabel = label[j];
  3882. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  3883. width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  3884. height += lineHeight;
  3885. }
  3886. }
  3887. }
  3888. widths.push(width);
  3889. heights.push(height);
  3890. widestLabelSize = Math.max(width, widestLabelSize);
  3891. highestLabelSize = Math.max(height, highestLabelSize);
  3892. }
  3893. garbageCollect(caches, length);
  3894. const widest = widths.indexOf(widestLabelSize);
  3895. const highest = heights.indexOf(highestLabelSize);
  3896. const valueAt = (idx) => ({width: widths[idx] || 0, height: heights[idx] || 0});
  3897. return {
  3898. first: valueAt(0),
  3899. last: valueAt(length - 1),
  3900. widest: valueAt(widest),
  3901. highest: valueAt(highest),
  3902. widths,
  3903. heights,
  3904. };
  3905. }
  3906. getLabelForValue(value) {
  3907. return value;
  3908. }
  3909. getPixelForValue(value, index) {
  3910. return NaN;
  3911. }
  3912. getValueForPixel(pixel) {}
  3913. getPixelForTick(index) {
  3914. const ticks = this.ticks;
  3915. if (index < 0 || index > ticks.length - 1) {
  3916. return null;
  3917. }
  3918. return this.getPixelForValue(ticks[index].value);
  3919. }
  3920. getPixelForDecimal(decimal) {
  3921. const me = this;
  3922. if (me._reversePixels) {
  3923. decimal = 1 - decimal;
  3924. }
  3925. const pixel = me._startPixel + decimal * me._length;
  3926. return _int16Range(me._alignToPixels ? _alignPixel(me.chart, pixel, 0) : pixel);
  3927. }
  3928. getDecimalForPixel(pixel) {
  3929. const decimal = (pixel - this._startPixel) / this._length;
  3930. return this._reversePixels ? 1 - decimal : decimal;
  3931. }
  3932. getBasePixel() {
  3933. return this.getPixelForValue(this.getBaseValue());
  3934. }
  3935. getBaseValue() {
  3936. const {min, max} = this;
  3937. return min < 0 && max < 0 ? max :
  3938. min > 0 && max > 0 ? min :
  3939. 0;
  3940. }
  3941. getContext(index) {
  3942. const me = this;
  3943. const ticks = me.ticks || [];
  3944. if (index >= 0 && index < ticks.length) {
  3945. const tick = ticks[index];
  3946. return tick.$context ||
  3947. (tick.$context = createTickContext(me.getContext(), index, tick));
  3948. }
  3949. return me.$context ||
  3950. (me.$context = createScaleContext(me.chart.getContext(), me));
  3951. }
  3952. _tickSize() {
  3953. const me = this;
  3954. const optionTicks = me.options.ticks;
  3955. const rot = toRadians(me.labelRotation);
  3956. const cos = Math.abs(Math.cos(rot));
  3957. const sin = Math.abs(Math.sin(rot));
  3958. const labelSizes = me._getLabelSizes();
  3959. const padding = optionTicks.autoSkipPadding || 0;
  3960. const w = labelSizes ? labelSizes.widest.width + padding : 0;
  3961. const h = labelSizes ? labelSizes.highest.height + padding : 0;
  3962. return me.isHorizontal()
  3963. ? h * cos > w * sin ? w / cos : h / sin
  3964. : h * sin < w * cos ? h / cos : w / sin;
  3965. }
  3966. _isVisible() {
  3967. const display = this.options.display;
  3968. if (display !== 'auto') {
  3969. return !!display;
  3970. }
  3971. return this.getMatchingVisibleMetas().length > 0;
  3972. }
  3973. _computeGridLineItems(chartArea) {
  3974. const me = this;
  3975. const axis = me.axis;
  3976. const chart = me.chart;
  3977. const options = me.options;
  3978. const {grid, position} = options;
  3979. const offset = grid.offset;
  3980. const isHorizontal = me.isHorizontal();
  3981. const ticks = me.ticks;
  3982. const ticksLength = ticks.length + (offset ? 1 : 0);
  3983. const tl = getTickMarkLength(grid);
  3984. const items = [];
  3985. const borderOpts = grid.setContext(me.getContext());
  3986. const axisWidth = borderOpts.drawBorder ? borderOpts.borderWidth : 0;
  3987. const axisHalfWidth = axisWidth / 2;
  3988. const alignBorderValue = function(pixel) {
  3989. return _alignPixel(chart, pixel, axisWidth);
  3990. };
  3991. let borderValue, i, lineValue, alignedLineValue;
  3992. let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
  3993. if (position === 'top') {
  3994. borderValue = alignBorderValue(me.bottom);
  3995. ty1 = me.bottom - tl;
  3996. ty2 = borderValue - axisHalfWidth;
  3997. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  3998. y2 = chartArea.bottom;
  3999. } else if (position === 'bottom') {
  4000. borderValue = alignBorderValue(me.top);
  4001. y1 = chartArea.top;
  4002. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  4003. ty1 = borderValue + axisHalfWidth;
  4004. ty2 = me.top + tl;
  4005. } else if (position === 'left') {
  4006. borderValue = alignBorderValue(me.right);
  4007. tx1 = me.right - tl;
  4008. tx2 = borderValue - axisHalfWidth;
  4009. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  4010. x2 = chartArea.right;
  4011. } else if (position === 'right') {
  4012. borderValue = alignBorderValue(me.left);
  4013. x1 = chartArea.left;
  4014. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  4015. tx1 = borderValue + axisHalfWidth;
  4016. tx2 = me.left + tl;
  4017. } else if (axis === 'x') {
  4018. if (position === 'center') {
  4019. borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);
  4020. } else if (isObject(position)) {
  4021. const positionAxisID = Object.keys(position)[0];
  4022. const value = position[positionAxisID];
  4023. borderValue = alignBorderValue(me.chart.scales[positionAxisID].getPixelForValue(value));
  4024. }
  4025. y1 = chartArea.top;
  4026. y2 = chartArea.bottom;
  4027. ty1 = borderValue + axisHalfWidth;
  4028. ty2 = ty1 + tl;
  4029. } else if (axis === 'y') {
  4030. if (position === 'center') {
  4031. borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
  4032. } else if (isObject(position)) {
  4033. const positionAxisID = Object.keys(position)[0];
  4034. const value = position[positionAxisID];
  4035. borderValue = alignBorderValue(me.chart.scales[positionAxisID].getPixelForValue(value));
  4036. }
  4037. tx1 = borderValue - axisHalfWidth;
  4038. tx2 = tx1 - tl;
  4039. x1 = chartArea.left;
  4040. x2 = chartArea.right;
  4041. }
  4042. for (i = 0; i < ticksLength; ++i) {
  4043. const optsAtIndex = grid.setContext(me.getContext(i));
  4044. const lineWidth = optsAtIndex.lineWidth;
  4045. const lineColor = optsAtIndex.color;
  4046. const borderDash = grid.borderDash || [];
  4047. const borderDashOffset = optsAtIndex.borderDashOffset;
  4048. const tickWidth = optsAtIndex.tickWidth;
  4049. const tickColor = optsAtIndex.tickColor;
  4050. const tickBorderDash = optsAtIndex.tickBorderDash || [];
  4051. const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;
  4052. lineValue = getPixelForGridLine(me, i, offset);
  4053. if (lineValue === undefined) {
  4054. continue;
  4055. }
  4056. alignedLineValue = _alignPixel(chart, lineValue, lineWidth);
  4057. if (isHorizontal) {
  4058. tx1 = tx2 = x1 = x2 = alignedLineValue;
  4059. } else {
  4060. ty1 = ty2 = y1 = y2 = alignedLineValue;
  4061. }
  4062. items.push({
  4063. tx1,
  4064. ty1,
  4065. tx2,
  4066. ty2,
  4067. x1,
  4068. y1,
  4069. x2,
  4070. y2,
  4071. width: lineWidth,
  4072. color: lineColor,
  4073. borderDash,
  4074. borderDashOffset,
  4075. tickWidth,
  4076. tickColor,
  4077. tickBorderDash,
  4078. tickBorderDashOffset,
  4079. });
  4080. }
  4081. me._ticksLength = ticksLength;
  4082. me._borderValue = borderValue;
  4083. return items;
  4084. }
  4085. _computeLabelItems(chartArea) {
  4086. const me = this;
  4087. const axis = me.axis;
  4088. const options = me.options;
  4089. const {position, ticks: optionTicks} = options;
  4090. const isHorizontal = me.isHorizontal();
  4091. const ticks = me.ticks;
  4092. const {align, crossAlign, padding, mirror} = optionTicks;
  4093. const tl = getTickMarkLength(options.grid);
  4094. const tickAndPadding = tl + padding;
  4095. const hTickAndPadding = mirror ? -padding : tickAndPadding;
  4096. const rotation = -toRadians(me.labelRotation);
  4097. const items = [];
  4098. let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  4099. let textBaseline = 'middle';
  4100. if (position === 'top') {
  4101. y = me.bottom - hTickAndPadding;
  4102. textAlign = me._getXAxisLabelAlignment();
  4103. } else if (position === 'bottom') {
  4104. y = me.top + hTickAndPadding;
  4105. textAlign = me._getXAxisLabelAlignment();
  4106. } else if (position === 'left') {
  4107. const ret = me._getYAxisLabelAlignment(tl);
  4108. textAlign = ret.textAlign;
  4109. x = ret.x;
  4110. } else if (position === 'right') {
  4111. const ret = me._getYAxisLabelAlignment(tl);
  4112. textAlign = ret.textAlign;
  4113. x = ret.x;
  4114. } else if (axis === 'x') {
  4115. if (position === 'center') {
  4116. y = ((chartArea.top + chartArea.bottom) / 2) + tickAndPadding;
  4117. } else if (isObject(position)) {
  4118. const positionAxisID = Object.keys(position)[0];
  4119. const value = position[positionAxisID];
  4120. y = me.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;
  4121. }
  4122. textAlign = me._getXAxisLabelAlignment();
  4123. } else if (axis === 'y') {
  4124. if (position === 'center') {
  4125. x = ((chartArea.left + chartArea.right) / 2) - tickAndPadding;
  4126. } else if (isObject(position)) {
  4127. const positionAxisID = Object.keys(position)[0];
  4128. const value = position[positionAxisID];
  4129. x = me.chart.scales[positionAxisID].getPixelForValue(value);
  4130. }
  4131. textAlign = me._getYAxisLabelAlignment(tl).textAlign;
  4132. }
  4133. if (axis === 'y') {
  4134. if (align === 'start') {
  4135. textBaseline = 'top';
  4136. } else if (align === 'end') {
  4137. textBaseline = 'bottom';
  4138. }
  4139. }
  4140. const labelSizes = me._getLabelSizes();
  4141. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  4142. tick = ticks[i];
  4143. label = tick.label;
  4144. const optsAtIndex = optionTicks.setContext(me.getContext(i));
  4145. pixel = me.getPixelForTick(i) + optionTicks.labelOffset;
  4146. font = me._resolveTickFontOptions(i);
  4147. lineHeight = font.lineHeight;
  4148. lineCount = isArray(label) ? label.length : 1;
  4149. const halfCount = lineCount / 2;
  4150. const color = optsAtIndex.color;
  4151. const strokeColor = optsAtIndex.textStrokeColor;
  4152. const strokeWidth = optsAtIndex.textStrokeWidth;
  4153. if (isHorizontal) {
  4154. x = pixel;
  4155. if (position === 'top') {
  4156. if (crossAlign === 'near' || rotation !== 0) {
  4157. textOffset = -lineCount * lineHeight + lineHeight / 2;
  4158. } else if (crossAlign === 'center') {
  4159. textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;
  4160. } else {
  4161. textOffset = -labelSizes.highest.height + lineHeight / 2;
  4162. }
  4163. } else {
  4164. if (crossAlign === 'near' || rotation !== 0) {
  4165. textOffset = lineHeight / 2;
  4166. } else if (crossAlign === 'center') {
  4167. textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;
  4168. } else {
  4169. textOffset = labelSizes.highest.height - lineCount * lineHeight;
  4170. }
  4171. }
  4172. if (mirror) {
  4173. textOffset *= -1;
  4174. }
  4175. } else {
  4176. y = pixel;
  4177. textOffset = (1 - lineCount) * lineHeight / 2;
  4178. }
  4179. let backdrop;
  4180. if (optsAtIndex.showLabelBackdrop) {
  4181. const labelPadding = toPadding(optsAtIndex.backdropPadding);
  4182. const height = labelSizes.heights[i];
  4183. const width = labelSizes.widths[i];
  4184. let top = y + textOffset - labelPadding.top;
  4185. let left = x - labelPadding.left;
  4186. switch (textBaseline) {
  4187. case 'middle':
  4188. top -= height / 2;
  4189. break;
  4190. case 'bottom':
  4191. top -= height;
  4192. break;
  4193. }
  4194. switch (textAlign) {
  4195. case 'center':
  4196. left -= width / 2;
  4197. break;
  4198. case 'right':
  4199. left -= width;
  4200. break;
  4201. }
  4202. backdrop = {
  4203. left,
  4204. top,
  4205. width: width + labelPadding.width,
  4206. height: height + labelPadding.height,
  4207. color: optsAtIndex.backdropColor,
  4208. };
  4209. }
  4210. items.push({
  4211. rotation,
  4212. label,
  4213. font,
  4214. color,
  4215. strokeColor,
  4216. strokeWidth,
  4217. textOffset,
  4218. textAlign,
  4219. textBaseline,
  4220. translation: [x, y],
  4221. backdrop,
  4222. });
  4223. }
  4224. return items;
  4225. }
  4226. _getXAxisLabelAlignment() {
  4227. const me = this;
  4228. const {position, ticks} = me.options;
  4229. const rotation = -toRadians(me.labelRotation);
  4230. if (rotation) {
  4231. return position === 'top' ? 'left' : 'right';
  4232. }
  4233. let align = 'center';
  4234. if (ticks.align === 'start') {
  4235. align = 'left';
  4236. } else if (ticks.align === 'end') {
  4237. align = 'right';
  4238. }
  4239. return align;
  4240. }
  4241. _getYAxisLabelAlignment(tl) {
  4242. const me = this;
  4243. const {position, ticks: {crossAlign, mirror, padding}} = me.options;
  4244. const labelSizes = me._getLabelSizes();
  4245. const tickAndPadding = tl + padding;
  4246. const widest = labelSizes.widest.width;
  4247. let textAlign;
  4248. let x;
  4249. if (position === 'left') {
  4250. if (mirror) {
  4251. textAlign = 'left';
  4252. x = me.right + padding;
  4253. } else {
  4254. x = me.right - tickAndPadding;
  4255. if (crossAlign === 'near') {
  4256. textAlign = 'right';
  4257. } else if (crossAlign === 'center') {
  4258. textAlign = 'center';
  4259. x -= (widest / 2);
  4260. } else {
  4261. textAlign = 'left';
  4262. x = me.left;
  4263. }
  4264. }
  4265. } else if (position === 'right') {
  4266. if (mirror) {
  4267. textAlign = 'right';
  4268. x = me.left + padding;
  4269. } else {
  4270. x = me.left + tickAndPadding;
  4271. if (crossAlign === 'near') {
  4272. textAlign = 'left';
  4273. } else if (crossAlign === 'center') {
  4274. textAlign = 'center';
  4275. x += widest / 2;
  4276. } else {
  4277. textAlign = 'right';
  4278. x = me.right;
  4279. }
  4280. }
  4281. } else {
  4282. textAlign = 'right';
  4283. }
  4284. return {textAlign, x};
  4285. }
  4286. _computeLabelArea() {
  4287. const me = this;
  4288. if (me.options.ticks.mirror) {
  4289. return;
  4290. }
  4291. const chart = me.chart;
  4292. const position = me.options.position;
  4293. if (position === 'left' || position === 'right') {
  4294. return {top: 0, left: me.left, bottom: chart.height, right: me.right};
  4295. } if (position === 'top' || position === 'bottom') {
  4296. return {top: me.top, left: 0, bottom: me.bottom, right: chart.width};
  4297. }
  4298. }
  4299. drawBackground() {
  4300. const {ctx, options: {backgroundColor}, left, top, width, height} = this;
  4301. if (backgroundColor) {
  4302. ctx.save();
  4303. ctx.fillStyle = backgroundColor;
  4304. ctx.fillRect(left, top, width, height);
  4305. ctx.restore();
  4306. }
  4307. }
  4308. getLineWidthForValue(value) {
  4309. const me = this;
  4310. const grid = me.options.grid;
  4311. if (!me._isVisible() || !grid.display) {
  4312. return 0;
  4313. }
  4314. const ticks = me.ticks;
  4315. const index = ticks.findIndex(t => t.value === value);
  4316. if (index >= 0) {
  4317. const opts = grid.setContext(me.getContext(index));
  4318. return opts.lineWidth;
  4319. }
  4320. return 0;
  4321. }
  4322. drawGrid(chartArea) {
  4323. const me = this;
  4324. const grid = me.options.grid;
  4325. const ctx = me.ctx;
  4326. const items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
  4327. let i, ilen;
  4328. const drawLine = (p1, p2, style) => {
  4329. if (!style.width || !style.color) {
  4330. return;
  4331. }
  4332. ctx.save();
  4333. ctx.lineWidth = style.width;
  4334. ctx.strokeStyle = style.color;
  4335. ctx.setLineDash(style.borderDash || []);
  4336. ctx.lineDashOffset = style.borderDashOffset;
  4337. ctx.beginPath();
  4338. ctx.moveTo(p1.x, p1.y);
  4339. ctx.lineTo(p2.x, p2.y);
  4340. ctx.stroke();
  4341. ctx.restore();
  4342. };
  4343. if (grid.display) {
  4344. for (i = 0, ilen = items.length; i < ilen; ++i) {
  4345. const item = items[i];
  4346. if (grid.drawOnChartArea) {
  4347. drawLine(
  4348. {x: item.x1, y: item.y1},
  4349. {x: item.x2, y: item.y2},
  4350. item
  4351. );
  4352. }
  4353. if (grid.drawTicks) {
  4354. drawLine(
  4355. {x: item.tx1, y: item.ty1},
  4356. {x: item.tx2, y: item.ty2},
  4357. {
  4358. color: item.tickColor,
  4359. width: item.tickWidth,
  4360. borderDash: item.tickBorderDash,
  4361. borderDashOffset: item.tickBorderDashOffset
  4362. }
  4363. );
  4364. }
  4365. }
  4366. }
  4367. }
  4368. drawBorder() {
  4369. const me = this;
  4370. const {chart, ctx, options: {grid}} = me;
  4371. const borderOpts = grid.setContext(me.getContext());
  4372. const axisWidth = grid.drawBorder ? borderOpts.borderWidth : 0;
  4373. if (!axisWidth) {
  4374. return;
  4375. }
  4376. const lastLineWidth = grid.setContext(me.getContext(0)).lineWidth;
  4377. const borderValue = me._borderValue;
  4378. let x1, x2, y1, y2;
  4379. if (me.isHorizontal()) {
  4380. x1 = _alignPixel(chart, me.left, axisWidth) - axisWidth / 2;
  4381. x2 = _alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  4382. y1 = y2 = borderValue;
  4383. } else {
  4384. y1 = _alignPixel(chart, me.top, axisWidth) - axisWidth / 2;
  4385. y2 = _alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  4386. x1 = x2 = borderValue;
  4387. }
  4388. ctx.save();
  4389. ctx.lineWidth = borderOpts.borderWidth;
  4390. ctx.strokeStyle = borderOpts.borderColor;
  4391. ctx.beginPath();
  4392. ctx.moveTo(x1, y1);
  4393. ctx.lineTo(x2, y2);
  4394. ctx.stroke();
  4395. ctx.restore();
  4396. }
  4397. drawLabels(chartArea) {
  4398. const me = this;
  4399. const optionTicks = me.options.ticks;
  4400. if (!optionTicks.display) {
  4401. return;
  4402. }
  4403. const ctx = me.ctx;
  4404. const area = me._computeLabelArea();
  4405. if (area) {
  4406. clipArea(ctx, area);
  4407. }
  4408. const items = me._labelItems || (me._labelItems = me._computeLabelItems(chartArea));
  4409. let i, ilen;
  4410. for (i = 0, ilen = items.length; i < ilen; ++i) {
  4411. const item = items[i];
  4412. const tickFont = item.font;
  4413. const label = item.label;
  4414. if (item.backdrop) {
  4415. ctx.fillStyle = item.backdrop.color;
  4416. ctx.fillRect(item.backdrop.left, item.backdrop.top, item.backdrop.width, item.backdrop.height);
  4417. }
  4418. let y = item.textOffset;
  4419. renderText(ctx, label, 0, y, tickFont, item);
  4420. }
  4421. if (area) {
  4422. unclipArea(ctx);
  4423. }
  4424. }
  4425. drawTitle() {
  4426. const {ctx, options: {position, title, reverse}} = this;
  4427. if (!title.display) {
  4428. return;
  4429. }
  4430. const font = toFont(title.font);
  4431. const padding = toPadding(title.padding);
  4432. const align = title.align;
  4433. let offset = font.lineHeight / 2;
  4434. if (position === 'bottom') {
  4435. offset += padding.bottom;
  4436. if (isArray(title.text)) {
  4437. offset += font.lineHeight * (title.text.length - 1);
  4438. }
  4439. } else {
  4440. offset += padding.top;
  4441. }
  4442. const {titleX, titleY, maxWidth, rotation} = titleArgs(this, offset, position, align);
  4443. renderText(ctx, title.text, 0, 0, font, {
  4444. color: title.color,
  4445. maxWidth,
  4446. rotation,
  4447. textAlign: titleAlign(align, position, reverse),
  4448. textBaseline: 'middle',
  4449. translation: [titleX, titleY],
  4450. });
  4451. }
  4452. draw(chartArea) {
  4453. const me = this;
  4454. if (!me._isVisible()) {
  4455. return;
  4456. }
  4457. me.drawBackground();
  4458. me.drawGrid(chartArea);
  4459. me.drawBorder();
  4460. me.drawTitle();
  4461. me.drawLabels(chartArea);
  4462. }
  4463. _layers() {
  4464. const me = this;
  4465. const opts = me.options;
  4466. const tz = opts.ticks && opts.ticks.z || 0;
  4467. const gz = opts.grid && opts.grid.z || 0;
  4468. if (!me._isVisible() || me.draw !== Scale.prototype.draw) {
  4469. return [{
  4470. z: tz,
  4471. draw(chartArea) {
  4472. me.draw(chartArea);
  4473. }
  4474. }];
  4475. }
  4476. return [{
  4477. z: gz,
  4478. draw(chartArea) {
  4479. me.drawBackground();
  4480. me.drawGrid(chartArea);
  4481. me.drawTitle();
  4482. }
  4483. }, {
  4484. z: gz + 1,
  4485. draw() {
  4486. me.drawBorder();
  4487. }
  4488. }, {
  4489. z: tz,
  4490. draw(chartArea) {
  4491. me.drawLabels(chartArea);
  4492. }
  4493. }];
  4494. }
  4495. getMatchingVisibleMetas(type) {
  4496. const me = this;
  4497. const metas = me.chart.getSortedVisibleDatasetMetas();
  4498. const axisID = me.axis + 'AxisID';
  4499. const result = [];
  4500. let i, ilen;
  4501. for (i = 0, ilen = metas.length; i < ilen; ++i) {
  4502. const meta = metas[i];
  4503. if (meta[axisID] === me.id && (!type || meta.type === type)) {
  4504. result.push(meta);
  4505. }
  4506. }
  4507. return result;
  4508. }
  4509. _resolveTickFontOptions(index) {
  4510. const opts = this.options.ticks.setContext(this.getContext(index));
  4511. return toFont(opts.font);
  4512. }
  4513. _maxDigits() {
  4514. const me = this;
  4515. const fontSize = me._resolveTickFontOptions(0).lineHeight;
  4516. return me.isHorizontal() ? me.width / fontSize / 0.7 : me.height / fontSize;
  4517. }
  4518. }
  4519. class TypedRegistry {
  4520. constructor(type, scope, override) {
  4521. this.type = type;
  4522. this.scope = scope;
  4523. this.override = override;
  4524. this.items = Object.create(null);
  4525. }
  4526. isForType(type) {
  4527. return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);
  4528. }
  4529. register(item) {
  4530. const me = this;
  4531. const proto = Object.getPrototypeOf(item);
  4532. let parentScope;
  4533. if (isIChartComponent(proto)) {
  4534. parentScope = me.register(proto);
  4535. }
  4536. const items = me.items;
  4537. const id = item.id;
  4538. const scope = me.scope + '.' + id;
  4539. if (!id) {
  4540. throw new Error('class does not have id: ' + item);
  4541. }
  4542. if (id in items) {
  4543. return scope;
  4544. }
  4545. items[id] = item;
  4546. registerDefaults(item, scope, parentScope);
  4547. if (me.override) {
  4548. defaults.override(item.id, item.overrides);
  4549. }
  4550. return scope;
  4551. }
  4552. get(id) {
  4553. return this.items[id];
  4554. }
  4555. unregister(item) {
  4556. const items = this.items;
  4557. const id = item.id;
  4558. const scope = this.scope;
  4559. if (id in items) {
  4560. delete items[id];
  4561. }
  4562. if (scope && id in defaults[scope]) {
  4563. delete defaults[scope][id];
  4564. if (this.override) {
  4565. delete overrides[id];
  4566. }
  4567. }
  4568. }
  4569. }
  4570. function registerDefaults(item, scope, parentScope) {
  4571. const itemDefaults = merge(Object.create(null), [
  4572. parentScope ? defaults.get(parentScope) : {},
  4573. defaults.get(scope),
  4574. item.defaults
  4575. ]);
  4576. defaults.set(scope, itemDefaults);
  4577. if (item.defaultRoutes) {
  4578. routeDefaults(scope, item.defaultRoutes);
  4579. }
  4580. if (item.descriptors) {
  4581. defaults.describe(scope, item.descriptors);
  4582. }
  4583. }
  4584. function routeDefaults(scope, routes) {
  4585. Object.keys(routes).forEach(property => {
  4586. const propertyParts = property.split('.');
  4587. const sourceName = propertyParts.pop();
  4588. const sourceScope = [scope].concat(propertyParts).join('.');
  4589. const parts = routes[property].split('.');
  4590. const targetName = parts.pop();
  4591. const targetScope = parts.join('.');
  4592. defaults.route(sourceScope, sourceName, targetScope, targetName);
  4593. });
  4594. }
  4595. function isIChartComponent(proto) {
  4596. return 'id' in proto && 'defaults' in proto;
  4597. }
  4598. class Registry {
  4599. constructor() {
  4600. this.controllers = new TypedRegistry(DatasetController, 'datasets', true);
  4601. this.elements = new TypedRegistry(Element, 'elements');
  4602. this.plugins = new TypedRegistry(Object, 'plugins');
  4603. this.scales = new TypedRegistry(Scale, 'scales');
  4604. this._typedRegistries = [this.controllers, this.scales, this.elements];
  4605. }
  4606. add(...args) {
  4607. this._each('register', args);
  4608. }
  4609. remove(...args) {
  4610. this._each('unregister', args);
  4611. }
  4612. addControllers(...args) {
  4613. this._each('register', args, this.controllers);
  4614. }
  4615. addElements(...args) {
  4616. this._each('register', args, this.elements);
  4617. }
  4618. addPlugins(...args) {
  4619. this._each('register', args, this.plugins);
  4620. }
  4621. addScales(...args) {
  4622. this._each('register', args, this.scales);
  4623. }
  4624. getController(id) {
  4625. return this._get(id, this.controllers, 'controller');
  4626. }
  4627. getElement(id) {
  4628. return this._get(id, this.elements, 'element');
  4629. }
  4630. getPlugin(id) {
  4631. return this._get(id, this.plugins, 'plugin');
  4632. }
  4633. getScale(id) {
  4634. return this._get(id, this.scales, 'scale');
  4635. }
  4636. removeControllers(...args) {
  4637. this._each('unregister', args, this.controllers);
  4638. }
  4639. removeElements(...args) {
  4640. this._each('unregister', args, this.elements);
  4641. }
  4642. removePlugins(...args) {
  4643. this._each('unregister', args, this.plugins);
  4644. }
  4645. removeScales(...args) {
  4646. this._each('unregister', args, this.scales);
  4647. }
  4648. _each(method, args, typedRegistry) {
  4649. const me = this;
  4650. [...args].forEach(arg => {
  4651. const reg = typedRegistry || me._getRegistryForType(arg);
  4652. if (typedRegistry || reg.isForType(arg) || (reg === me.plugins && arg.id)) {
  4653. me._exec(method, reg, arg);
  4654. } else {
  4655. each(arg, item => {
  4656. const itemReg = typedRegistry || me._getRegistryForType(item);
  4657. me._exec(method, itemReg, item);
  4658. });
  4659. }
  4660. });
  4661. }
  4662. _exec(method, registry, component) {
  4663. const camelMethod = _capitalize(method);
  4664. callback(component['before' + camelMethod], [], component);
  4665. registry[method](component);
  4666. callback(component['after' + camelMethod], [], component);
  4667. }
  4668. _getRegistryForType(type) {
  4669. for (let i = 0; i < this._typedRegistries.length; i++) {
  4670. const reg = this._typedRegistries[i];
  4671. if (reg.isForType(type)) {
  4672. return reg;
  4673. }
  4674. }
  4675. return this.plugins;
  4676. }
  4677. _get(id, typedRegistry, type) {
  4678. const item = typedRegistry.get(id);
  4679. if (item === undefined) {
  4680. throw new Error('"' + id + '" is not a registered ' + type + '.');
  4681. }
  4682. return item;
  4683. }
  4684. }
  4685. var registry = new Registry();
  4686. class PluginService {
  4687. constructor() {
  4688. this._init = [];
  4689. }
  4690. notify(chart, hook, args, filter) {
  4691. const me = this;
  4692. if (hook === 'beforeInit') {
  4693. me._init = me._createDescriptors(chart, true);
  4694. me._notify(me._init, chart, 'install');
  4695. }
  4696. const descriptors = filter ? me._descriptors(chart).filter(filter) : me._descriptors(chart);
  4697. const result = me._notify(descriptors, chart, hook, args);
  4698. if (hook === 'destroy') {
  4699. me._notify(descriptors, chart, 'stop');
  4700. me._notify(me._init, chart, 'uninstall');
  4701. }
  4702. return result;
  4703. }
  4704. _notify(descriptors, chart, hook, args) {
  4705. args = args || {};
  4706. for (const descriptor of descriptors) {
  4707. const plugin = descriptor.plugin;
  4708. const method = plugin[hook];
  4709. const params = [chart, args, descriptor.options];
  4710. if (callback(method, params, plugin) === false && args.cancelable) {
  4711. return false;
  4712. }
  4713. }
  4714. return true;
  4715. }
  4716. invalidate() {
  4717. if (!isNullOrUndef(this._cache)) {
  4718. this._oldCache = this._cache;
  4719. this._cache = undefined;
  4720. }
  4721. }
  4722. _descriptors(chart) {
  4723. if (this._cache) {
  4724. return this._cache;
  4725. }
  4726. const descriptors = this._cache = this._createDescriptors(chart);
  4727. this._notifyStateChanges(chart);
  4728. return descriptors;
  4729. }
  4730. _createDescriptors(chart, all) {
  4731. const config = chart && chart.config;
  4732. const options = valueOrDefault(config.options && config.options.plugins, {});
  4733. const plugins = allPlugins(config);
  4734. return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);
  4735. }
  4736. _notifyStateChanges(chart) {
  4737. const previousDescriptors = this._oldCache || [];
  4738. const descriptors = this._cache;
  4739. const diff = (a, b) => a.filter(x => !b.some(y => x.plugin.id === y.plugin.id));
  4740. this._notify(diff(previousDescriptors, descriptors), chart, 'stop');
  4741. this._notify(diff(descriptors, previousDescriptors), chart, 'start');
  4742. }
  4743. }
  4744. function allPlugins(config) {
  4745. const plugins = [];
  4746. const keys = Object.keys(registry.plugins.items);
  4747. for (let i = 0; i < keys.length; i++) {
  4748. plugins.push(registry.getPlugin(keys[i]));
  4749. }
  4750. const local = config.plugins || [];
  4751. for (let i = 0; i < local.length; i++) {
  4752. const plugin = local[i];
  4753. if (plugins.indexOf(plugin) === -1) {
  4754. plugins.push(plugin);
  4755. }
  4756. }
  4757. return plugins;
  4758. }
  4759. function getOpts(options, all) {
  4760. if (!all && options === false) {
  4761. return null;
  4762. }
  4763. if (options === true) {
  4764. return {};
  4765. }
  4766. return options;
  4767. }
  4768. function createDescriptors(chart, plugins, options, all) {
  4769. const result = [];
  4770. const context = chart.getContext();
  4771. for (let i = 0; i < plugins.length; i++) {
  4772. const plugin = plugins[i];
  4773. const id = plugin.id;
  4774. const opts = getOpts(options[id], all);
  4775. if (opts === null) {
  4776. continue;
  4777. }
  4778. result.push({
  4779. plugin,
  4780. options: pluginOpts(chart.config, plugin, opts, context)
  4781. });
  4782. }
  4783. return result;
  4784. }
  4785. function pluginOpts(config, plugin, opts, context) {
  4786. const keys = config.pluginScopeKeys(plugin);
  4787. const scopes = config.getOptionScopes(opts, keys);
  4788. return config.createResolver(scopes, context, [''], {scriptable: false, indexable: false, allKeys: true});
  4789. }
  4790. function getIndexAxis(type, options) {
  4791. const datasetDefaults = defaults.datasets[type] || {};
  4792. const datasetOptions = (options.datasets || {})[type] || {};
  4793. return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';
  4794. }
  4795. function getAxisFromDefaultScaleID(id, indexAxis) {
  4796. let axis = id;
  4797. if (id === '_index_') {
  4798. axis = indexAxis;
  4799. } else if (id === '_value_') {
  4800. axis = indexAxis === 'x' ? 'y' : 'x';
  4801. }
  4802. return axis;
  4803. }
  4804. function getDefaultScaleIDFromAxis(axis, indexAxis) {
  4805. return axis === indexAxis ? '_index_' : '_value_';
  4806. }
  4807. function axisFromPosition(position) {
  4808. if (position === 'top' || position === 'bottom') {
  4809. return 'x';
  4810. }
  4811. if (position === 'left' || position === 'right') {
  4812. return 'y';
  4813. }
  4814. }
  4815. function determineAxis(id, scaleOptions) {
  4816. if (id === 'x' || id === 'y') {
  4817. return id;
  4818. }
  4819. return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id.charAt(0).toLowerCase();
  4820. }
  4821. function mergeScaleConfig(config, options) {
  4822. const chartDefaults = overrides[config.type] || {scales: {}};
  4823. const configScales = options.scales || {};
  4824. const chartIndexAxis = getIndexAxis(config.type, options);
  4825. const firstIDs = Object.create(null);
  4826. const scales = Object.create(null);
  4827. Object.keys(configScales).forEach(id => {
  4828. const scaleConf = configScales[id];
  4829. const axis = determineAxis(id, scaleConf);
  4830. const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
  4831. const defaultScaleOptions = chartDefaults.scales || {};
  4832. firstIDs[axis] = firstIDs[axis] || id;
  4833. scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, defaultScaleOptions[axis], defaultScaleOptions[defaultId]]);
  4834. });
  4835. config.data.datasets.forEach(dataset => {
  4836. const type = dataset.type || config.type;
  4837. const indexAxis = dataset.indexAxis || getIndexAxis(type, options);
  4838. const datasetDefaults = overrides[type] || {};
  4839. const defaultScaleOptions = datasetDefaults.scales || {};
  4840. Object.keys(defaultScaleOptions).forEach(defaultID => {
  4841. const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
  4842. const id = dataset[axis + 'AxisID'] || firstIDs[axis] || axis;
  4843. scales[id] = scales[id] || Object.create(null);
  4844. mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]);
  4845. });
  4846. });
  4847. Object.keys(scales).forEach(key => {
  4848. const scale = scales[key];
  4849. mergeIf(scale, [defaults.scales[scale.type], defaults.scale]);
  4850. });
  4851. return scales;
  4852. }
  4853. function initOptions(config) {
  4854. const options = config.options || (config.options = {});
  4855. options.plugins = valueOrDefault(options.plugins, {});
  4856. options.scales = mergeScaleConfig(config, options);
  4857. }
  4858. function initData(data) {
  4859. data = data || {};
  4860. data.datasets = data.datasets || [];
  4861. data.labels = data.labels || [];
  4862. return data;
  4863. }
  4864. function initConfig(config) {
  4865. config = config || {};
  4866. config.data = initData(config.data);
  4867. initOptions(config);
  4868. return config;
  4869. }
  4870. const keyCache = new Map();
  4871. const keysCached = new Set();
  4872. function cachedKeys(cacheKey, generate) {
  4873. let keys = keyCache.get(cacheKey);
  4874. if (!keys) {
  4875. keys = generate();
  4876. keyCache.set(cacheKey, keys);
  4877. keysCached.add(keys);
  4878. }
  4879. return keys;
  4880. }
  4881. const addIfFound = (set, obj, key) => {
  4882. const opts = resolveObjectKey(obj, key);
  4883. if (opts !== undefined) {
  4884. set.add(opts);
  4885. }
  4886. };
  4887. class Config {
  4888. constructor(config) {
  4889. this._config = initConfig(config);
  4890. this._scopeCache = new Map();
  4891. this._resolverCache = new Map();
  4892. }
  4893. get type() {
  4894. return this._config.type;
  4895. }
  4896. set type(type) {
  4897. this._config.type = type;
  4898. }
  4899. get data() {
  4900. return this._config.data;
  4901. }
  4902. set data(data) {
  4903. this._config.data = initData(data);
  4904. }
  4905. get options() {
  4906. return this._config.options;
  4907. }
  4908. set options(options) {
  4909. this._config.options = options;
  4910. }
  4911. get plugins() {
  4912. return this._config.plugins;
  4913. }
  4914. update() {
  4915. const config = this._config;
  4916. this.clearCache();
  4917. initOptions(config);
  4918. }
  4919. clearCache() {
  4920. this._scopeCache.clear();
  4921. this._resolverCache.clear();
  4922. }
  4923. datasetScopeKeys(datasetType) {
  4924. return cachedKeys(datasetType,
  4925. () => [[
  4926. `datasets.${datasetType}`,
  4927. ''
  4928. ]]);
  4929. }
  4930. datasetAnimationScopeKeys(datasetType, transition) {
  4931. return cachedKeys(`${datasetType}.transition.${transition}`,
  4932. () => [
  4933. [
  4934. `datasets.${datasetType}.transitions.${transition}`,
  4935. `transitions.${transition}`,
  4936. ],
  4937. [
  4938. `datasets.${datasetType}`,
  4939. ''
  4940. ]
  4941. ]);
  4942. }
  4943. datasetElementScopeKeys(datasetType, elementType) {
  4944. return cachedKeys(`${datasetType}-${elementType}`,
  4945. () => [[
  4946. `datasets.${datasetType}.elements.${elementType}`,
  4947. `datasets.${datasetType}`,
  4948. `elements.${elementType}`,
  4949. ''
  4950. ]]);
  4951. }
  4952. pluginScopeKeys(plugin) {
  4953. const id = plugin.id;
  4954. const type = this.type;
  4955. return cachedKeys(`${type}-plugin-${id}`,
  4956. () => [[
  4957. `plugins.${id}`,
  4958. ...plugin.additionalOptionScopes || [],
  4959. ]]);
  4960. }
  4961. _cachedScopes(mainScope, resetCache) {
  4962. const _scopeCache = this._scopeCache;
  4963. let cache = _scopeCache.get(mainScope);
  4964. if (!cache || resetCache) {
  4965. cache = new Map();
  4966. _scopeCache.set(mainScope, cache);
  4967. }
  4968. return cache;
  4969. }
  4970. getOptionScopes(mainScope, keyLists, resetCache) {
  4971. const {options, type} = this;
  4972. const cache = this._cachedScopes(mainScope, resetCache);
  4973. const cached = cache.get(keyLists);
  4974. if (cached) {
  4975. return cached;
  4976. }
  4977. const scopes = new Set();
  4978. keyLists.forEach(keys => {
  4979. if (mainScope) {
  4980. scopes.add(mainScope);
  4981. keys.forEach(key => addIfFound(scopes, mainScope, key));
  4982. }
  4983. keys.forEach(key => addIfFound(scopes, options, key));
  4984. keys.forEach(key => addIfFound(scopes, overrides[type] || {}, key));
  4985. keys.forEach(key => addIfFound(scopes, defaults, key));
  4986. keys.forEach(key => addIfFound(scopes, descriptors, key));
  4987. });
  4988. const array = [...scopes];
  4989. if (keysCached.has(keyLists)) {
  4990. cache.set(keyLists, array);
  4991. }
  4992. return array;
  4993. }
  4994. chartOptionScopes() {
  4995. const {options, type} = this;
  4996. return [
  4997. options,
  4998. overrides[type] || {},
  4999. defaults.datasets[type] || {},
  5000. {type},
  5001. defaults,
  5002. descriptors
  5003. ];
  5004. }
  5005. resolveNamedOptions(scopes, names, context, prefixes = ['']) {
  5006. const result = {$shared: true};
  5007. const {resolver, subPrefixes} = getResolver(this._resolverCache, scopes, prefixes);
  5008. let options = resolver;
  5009. if (needContext(resolver, names)) {
  5010. result.$shared = false;
  5011. context = isFunction(context) ? context() : context;
  5012. const subResolver = this.createResolver(scopes, context, subPrefixes);
  5013. options = _attachContext(resolver, context, subResolver);
  5014. }
  5015. for (const prop of names) {
  5016. result[prop] = options[prop];
  5017. }
  5018. return result;
  5019. }
  5020. createResolver(scopes, context, prefixes = [''], descriptorDefaults) {
  5021. const {resolver} = getResolver(this._resolverCache, scopes, prefixes);
  5022. return isObject(context)
  5023. ? _attachContext(resolver, context, undefined, descriptorDefaults)
  5024. : resolver;
  5025. }
  5026. }
  5027. function getResolver(resolverCache, scopes, prefixes) {
  5028. let cache = resolverCache.get(scopes);
  5029. if (!cache) {
  5030. cache = new Map();
  5031. resolverCache.set(scopes, cache);
  5032. }
  5033. const cacheKey = prefixes.join();
  5034. let cached = cache.get(cacheKey);
  5035. if (!cached) {
  5036. const resolver = _createResolver(scopes, prefixes);
  5037. cached = {
  5038. resolver,
  5039. subPrefixes: prefixes.filter(p => !p.toLowerCase().includes('hover'))
  5040. };
  5041. cache.set(cacheKey, cached);
  5042. }
  5043. return cached;
  5044. }
  5045. function needContext(proxy, names) {
  5046. const {isScriptable, isIndexable} = _descriptors(proxy);
  5047. for (const prop of names) {
  5048. if ((isScriptable(prop) && isFunction(proxy[prop]))
  5049. || (isIndexable(prop) && isArray(proxy[prop]))) {
  5050. return true;
  5051. }
  5052. }
  5053. return false;
  5054. }
  5055. var version = "3.2.1";
  5056. const KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea'];
  5057. function positionIsHorizontal(position, axis) {
  5058. return position === 'top' || position === 'bottom' || (KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x');
  5059. }
  5060. function compare2Level(l1, l2) {
  5061. return function(a, b) {
  5062. return a[l1] === b[l1]
  5063. ? a[l2] - b[l2]
  5064. : a[l1] - b[l1];
  5065. };
  5066. }
  5067. function onAnimationsComplete(context) {
  5068. const chart = context.chart;
  5069. const animationOptions = chart.options.animation;
  5070. chart.notifyPlugins('afterRender');
  5071. callback(animationOptions && animationOptions.onComplete, [context], chart);
  5072. }
  5073. function onAnimationProgress(context) {
  5074. const chart = context.chart;
  5075. const animationOptions = chart.options.animation;
  5076. callback(animationOptions && animationOptions.onProgress, [context], chart);
  5077. }
  5078. function isDomSupported() {
  5079. return typeof window !== 'undefined' && typeof document !== 'undefined';
  5080. }
  5081. function getCanvas(item) {
  5082. if (isDomSupported() && typeof item === 'string') {
  5083. item = document.getElementById(item);
  5084. } else if (item && item.length) {
  5085. item = item[0];
  5086. }
  5087. if (item && item.canvas) {
  5088. item = item.canvas;
  5089. }
  5090. return item;
  5091. }
  5092. const instances = {};
  5093. const getChart = (key) => {
  5094. const canvas = getCanvas(key);
  5095. return Object.values(instances).filter((c) => c.canvas === canvas).pop();
  5096. };
  5097. class Chart {
  5098. constructor(item, config) {
  5099. const me = this;
  5100. this.config = config = new Config(config);
  5101. const initialCanvas = getCanvas(item);
  5102. const existingChart = getChart(initialCanvas);
  5103. if (existingChart) {
  5104. throw new Error(
  5105. 'Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' +
  5106. ' must be destroyed before the canvas can be reused.'
  5107. );
  5108. }
  5109. const options = config.createResolver(config.chartOptionScopes(), me.getContext());
  5110. this.platform = me._initializePlatform(initialCanvas, config);
  5111. const context = me.platform.acquireContext(initialCanvas, options.aspectRatio);
  5112. const canvas = context && context.canvas;
  5113. const height = canvas && canvas.height;
  5114. const width = canvas && canvas.width;
  5115. this.id = uid();
  5116. this.ctx = context;
  5117. this.canvas = canvas;
  5118. this.width = width;
  5119. this.height = height;
  5120. this._options = options;
  5121. this._aspectRatio = this.aspectRatio;
  5122. this._layers = [];
  5123. this._metasets = [];
  5124. this._stacks = undefined;
  5125. this.boxes = [];
  5126. this.currentDevicePixelRatio = undefined;
  5127. this.chartArea = undefined;
  5128. this._active = [];
  5129. this._lastEvent = undefined;
  5130. this._listeners = {};
  5131. this._sortedMetasets = [];
  5132. this.scales = {};
  5133. this.scale = undefined;
  5134. this._plugins = new PluginService();
  5135. this.$proxies = {};
  5136. this._hiddenIndices = {};
  5137. this.attached = false;
  5138. this._animationsDisabled = undefined;
  5139. this.$context = undefined;
  5140. this._doResize = debounce(() => this.update('resize'), options.resizeDelay || 0);
  5141. instances[me.id] = me;
  5142. if (!context || !canvas) {
  5143. console.error("Failed to create chart: can't acquire context from the given item");
  5144. return;
  5145. }
  5146. animator.listen(me, 'complete', onAnimationsComplete);
  5147. animator.listen(me, 'progress', onAnimationProgress);
  5148. me._initialize();
  5149. if (me.attached) {
  5150. me.update();
  5151. }
  5152. }
  5153. get aspectRatio() {
  5154. const {options: {aspectRatio, maintainAspectRatio}, width, height, _aspectRatio} = this;
  5155. if (!isNullOrUndef(aspectRatio)) {
  5156. return aspectRatio;
  5157. }
  5158. if (maintainAspectRatio && _aspectRatio) {
  5159. return _aspectRatio;
  5160. }
  5161. return height ? width / height : null;
  5162. }
  5163. get data() {
  5164. return this.config.data;
  5165. }
  5166. set data(data) {
  5167. this.config.data = data;
  5168. }
  5169. get options() {
  5170. return this._options;
  5171. }
  5172. set options(options) {
  5173. this.config.options = options;
  5174. }
  5175. _initialize() {
  5176. const me = this;
  5177. me.notifyPlugins('beforeInit');
  5178. if (me.options.responsive) {
  5179. me.resize();
  5180. } else {
  5181. retinaScale(me, me.options.devicePixelRatio);
  5182. }
  5183. me.bindEvents();
  5184. me.notifyPlugins('afterInit');
  5185. return me;
  5186. }
  5187. _initializePlatform(canvas, config) {
  5188. if (config.platform) {
  5189. return new config.platform();
  5190. } else if (!isDomSupported() || (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) {
  5191. return new BasicPlatform();
  5192. }
  5193. return new DomPlatform();
  5194. }
  5195. clear() {
  5196. clearCanvas(this.canvas, this.ctx);
  5197. return this;
  5198. }
  5199. stop() {
  5200. animator.stop(this);
  5201. return this;
  5202. }
  5203. resize(width, height) {
  5204. if (!animator.running(this)) {
  5205. this._resize(width, height);
  5206. } else {
  5207. this._resizeBeforeDraw = {width, height};
  5208. }
  5209. }
  5210. _resize(width, height) {
  5211. const me = this;
  5212. const options = me.options;
  5213. const canvas = me.canvas;
  5214. const aspectRatio = options.maintainAspectRatio && me.aspectRatio;
  5215. const newSize = me.platform.getMaximumSize(canvas, width, height, aspectRatio);
  5216. const oldRatio = me.currentDevicePixelRatio;
  5217. const newRatio = options.devicePixelRatio || me.platform.getDevicePixelRatio();
  5218. if (me.width === newSize.width && me.height === newSize.height && oldRatio === newRatio) {
  5219. return;
  5220. }
  5221. me.width = newSize.width;
  5222. me.height = newSize.height;
  5223. me._aspectRatio = me.aspectRatio;
  5224. retinaScale(me, newRatio, true);
  5225. me.notifyPlugins('resize', {size: newSize});
  5226. callback(options.onResize, [me, newSize], me);
  5227. if (me.attached) {
  5228. if (me._doResize()) {
  5229. me.render();
  5230. }
  5231. }
  5232. }
  5233. ensureScalesHaveIDs() {
  5234. const options = this.options;
  5235. const scalesOptions = options.scales || {};
  5236. each(scalesOptions, (axisOptions, axisID) => {
  5237. axisOptions.id = axisID;
  5238. });
  5239. }
  5240. buildOrUpdateScales() {
  5241. const me = this;
  5242. const options = me.options;
  5243. const scaleOpts = options.scales;
  5244. const scales = me.scales;
  5245. const updated = Object.keys(scales).reduce((obj, id) => {
  5246. obj[id] = false;
  5247. return obj;
  5248. }, {});
  5249. let items = [];
  5250. if (scaleOpts) {
  5251. items = items.concat(
  5252. Object.keys(scaleOpts).map((id) => {
  5253. const scaleOptions = scaleOpts[id];
  5254. const axis = determineAxis(id, scaleOptions);
  5255. const isRadial = axis === 'r';
  5256. const isHorizontal = axis === 'x';
  5257. return {
  5258. options: scaleOptions,
  5259. dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',
  5260. dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'
  5261. };
  5262. })
  5263. );
  5264. }
  5265. each(items, (item) => {
  5266. const scaleOptions = item.options;
  5267. const id = scaleOptions.id;
  5268. const axis = determineAxis(id, scaleOptions);
  5269. const scaleType = valueOrDefault(scaleOptions.type, item.dtype);
  5270. if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {
  5271. scaleOptions.position = item.dposition;
  5272. }
  5273. updated[id] = true;
  5274. let scale = null;
  5275. if (id in scales && scales[id].type === scaleType) {
  5276. scale = scales[id];
  5277. } else {
  5278. const scaleClass = registry.getScale(scaleType);
  5279. scale = new scaleClass({
  5280. id,
  5281. type: scaleType,
  5282. ctx: me.ctx,
  5283. chart: me
  5284. });
  5285. scales[scale.id] = scale;
  5286. }
  5287. scale.init(scaleOptions, options);
  5288. });
  5289. each(updated, (hasUpdated, id) => {
  5290. if (!hasUpdated) {
  5291. delete scales[id];
  5292. }
  5293. });
  5294. each(scales, (scale) => {
  5295. layouts.configure(me, scale, scale.options);
  5296. layouts.addBox(me, scale);
  5297. });
  5298. }
  5299. _updateMetasetIndex(meta, index) {
  5300. const metasets = this._metasets;
  5301. const oldIndex = meta.index;
  5302. if (oldIndex !== index) {
  5303. metasets[oldIndex] = metasets[index];
  5304. metasets[index] = meta;
  5305. meta.index = index;
  5306. }
  5307. }
  5308. _updateMetasets() {
  5309. const me = this;
  5310. const metasets = me._metasets;
  5311. const numData = me.data.datasets.length;
  5312. const numMeta = metasets.length;
  5313. if (numMeta > numData) {
  5314. for (let i = numData; i < numMeta; ++i) {
  5315. me._destroyDatasetMeta(i);
  5316. }
  5317. metasets.splice(numData, numMeta - numData);
  5318. }
  5319. me._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));
  5320. }
  5321. _removeUnreferencedMetasets() {
  5322. const me = this;
  5323. const {_metasets: metasets, data: {datasets}} = me;
  5324. if (metasets.length > datasets.length) {
  5325. delete me._stacks;
  5326. }
  5327. metasets.forEach((meta, index) => {
  5328. if (datasets.filter(x => x === meta._dataset).length === 0) {
  5329. me._destroyDatasetMeta(index);
  5330. }
  5331. });
  5332. }
  5333. buildOrUpdateControllers() {
  5334. const me = this;
  5335. const newControllers = [];
  5336. const datasets = me.data.datasets;
  5337. let i, ilen;
  5338. me._removeUnreferencedMetasets();
  5339. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  5340. const dataset = datasets[i];
  5341. let meta = me.getDatasetMeta(i);
  5342. const type = dataset.type || me.config.type;
  5343. if (meta.type && meta.type !== type) {
  5344. me._destroyDatasetMeta(i);
  5345. meta = me.getDatasetMeta(i);
  5346. }
  5347. meta.type = type;
  5348. meta.indexAxis = dataset.indexAxis || getIndexAxis(type, me.options);
  5349. meta.order = dataset.order || 0;
  5350. me._updateMetasetIndex(meta, i);
  5351. meta.label = '' + dataset.label;
  5352. meta.visible = me.isDatasetVisible(i);
  5353. if (meta.controller) {
  5354. meta.controller.updateIndex(i);
  5355. meta.controller.linkScales();
  5356. } else {
  5357. const ControllerClass = registry.getController(type);
  5358. const {datasetElementType, dataElementType} = defaults.datasets[type];
  5359. Object.assign(ControllerClass.prototype, {
  5360. dataElementType: registry.getElement(dataElementType),
  5361. datasetElementType: datasetElementType && registry.getElement(datasetElementType)
  5362. });
  5363. meta.controller = new ControllerClass(me, i);
  5364. newControllers.push(meta.controller);
  5365. }
  5366. }
  5367. me._updateMetasets();
  5368. return newControllers;
  5369. }
  5370. _resetElements() {
  5371. const me = this;
  5372. each(me.data.datasets, (dataset, datasetIndex) => {
  5373. me.getDatasetMeta(datasetIndex).controller.reset();
  5374. }, me);
  5375. }
  5376. reset() {
  5377. this._resetElements();
  5378. this.notifyPlugins('reset');
  5379. }
  5380. update(mode) {
  5381. const me = this;
  5382. const config = me.config;
  5383. config.update();
  5384. me._options = config.createResolver(config.chartOptionScopes(), me.getContext());
  5385. each(me.scales, (scale) => {
  5386. layouts.removeBox(me, scale);
  5387. });
  5388. const animsDisabled = me._animationsDisabled = !me.options.animation;
  5389. me.ensureScalesHaveIDs();
  5390. me.buildOrUpdateScales();
  5391. const existingEvents = new Set(Object.keys(me._listeners));
  5392. const newEvents = new Set(me.options.events);
  5393. if (!setsEqual(existingEvents, newEvents)) {
  5394. me.unbindEvents();
  5395. me.bindEvents();
  5396. }
  5397. me._plugins.invalidate();
  5398. if (me.notifyPlugins('beforeUpdate', {mode, cancelable: true}) === false) {
  5399. return;
  5400. }
  5401. const newControllers = me.buildOrUpdateControllers();
  5402. me.notifyPlugins('beforeElementsUpdate');
  5403. let minPadding = 0;
  5404. for (let i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
  5405. const {controller} = me.getDatasetMeta(i);
  5406. const reset = !animsDisabled && newControllers.indexOf(controller) === -1;
  5407. controller.buildOrUpdateElements(reset);
  5408. minPadding = Math.max(+controller.getMaxOverflow(), minPadding);
  5409. }
  5410. me._minPadding = minPadding;
  5411. me._updateLayout(minPadding);
  5412. if (!animsDisabled) {
  5413. each(newControllers, (controller) => {
  5414. controller.reset();
  5415. });
  5416. }
  5417. me._updateDatasets(mode);
  5418. me.notifyPlugins('afterUpdate', {mode});
  5419. me._layers.sort(compare2Level('z', '_idx'));
  5420. if (me._lastEvent) {
  5421. me._eventHandler(me._lastEvent, true);
  5422. }
  5423. me.render();
  5424. }
  5425. _updateLayout(minPadding) {
  5426. const me = this;
  5427. if (me.notifyPlugins('beforeLayout', {cancelable: true}) === false) {
  5428. return;
  5429. }
  5430. layouts.update(me, me.width, me.height, minPadding);
  5431. const area = me.chartArea;
  5432. const noArea = area.width <= 0 || area.height <= 0;
  5433. me._layers = [];
  5434. each(me.boxes, (box) => {
  5435. if (noArea && box.position === 'chartArea') {
  5436. return;
  5437. }
  5438. if (box.configure) {
  5439. box.configure();
  5440. }
  5441. me._layers.push(...box._layers());
  5442. }, me);
  5443. me._layers.forEach((item, index) => {
  5444. item._idx = index;
  5445. });
  5446. me.notifyPlugins('afterLayout');
  5447. }
  5448. _updateDatasets(mode) {
  5449. const me = this;
  5450. const isFunction = typeof mode === 'function';
  5451. if (me.notifyPlugins('beforeDatasetsUpdate', {mode, cancelable: true}) === false) {
  5452. return;
  5453. }
  5454. for (let i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  5455. me._updateDataset(i, isFunction ? mode({datasetIndex: i}) : mode);
  5456. }
  5457. me.notifyPlugins('afterDatasetsUpdate', {mode});
  5458. }
  5459. _updateDataset(index, mode) {
  5460. const me = this;
  5461. const meta = me.getDatasetMeta(index);
  5462. const args = {meta, index, mode, cancelable: true};
  5463. if (me.notifyPlugins('beforeDatasetUpdate', args) === false) {
  5464. return;
  5465. }
  5466. meta.controller._update(mode);
  5467. args.cancelable = false;
  5468. me.notifyPlugins('afterDatasetUpdate', args);
  5469. }
  5470. render() {
  5471. const me = this;
  5472. if (me.notifyPlugins('beforeRender', {cancelable: true}) === false) {
  5473. return;
  5474. }
  5475. if (animator.has(me)) {
  5476. if (me.attached && !animator.running(me)) {
  5477. animator.start(me);
  5478. }
  5479. } else {
  5480. me.draw();
  5481. onAnimationsComplete({chart: me});
  5482. }
  5483. }
  5484. draw() {
  5485. const me = this;
  5486. let i;
  5487. if (me._resizeBeforeDraw) {
  5488. const {width, height} = me._resizeBeforeDraw;
  5489. me._resize(width, height);
  5490. me._resizeBeforeDraw = null;
  5491. }
  5492. me.clear();
  5493. if (me.width <= 0 || me.height <= 0) {
  5494. return;
  5495. }
  5496. if (me.notifyPlugins('beforeDraw', {cancelable: true}) === false) {
  5497. return;
  5498. }
  5499. const layers = me._layers;
  5500. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  5501. layers[i].draw(me.chartArea);
  5502. }
  5503. me._drawDatasets();
  5504. for (; i < layers.length; ++i) {
  5505. layers[i].draw(me.chartArea);
  5506. }
  5507. me.notifyPlugins('afterDraw');
  5508. }
  5509. _getSortedDatasetMetas(filterVisible) {
  5510. const me = this;
  5511. const metasets = me._sortedMetasets;
  5512. const result = [];
  5513. let i, ilen;
  5514. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  5515. const meta = metasets[i];
  5516. if (!filterVisible || meta.visible) {
  5517. result.push(meta);
  5518. }
  5519. }
  5520. return result;
  5521. }
  5522. getSortedVisibleDatasetMetas() {
  5523. return this._getSortedDatasetMetas(true);
  5524. }
  5525. _drawDatasets() {
  5526. const me = this;
  5527. if (me.notifyPlugins('beforeDatasetsDraw', {cancelable: true}) === false) {
  5528. return;
  5529. }
  5530. const metasets = me.getSortedVisibleDatasetMetas();
  5531. for (let i = metasets.length - 1; i >= 0; --i) {
  5532. me._drawDataset(metasets[i]);
  5533. }
  5534. me.notifyPlugins('afterDatasetsDraw');
  5535. }
  5536. _drawDataset(meta) {
  5537. const me = this;
  5538. const ctx = me.ctx;
  5539. const clip = meta._clip;
  5540. const area = me.chartArea;
  5541. const args = {
  5542. meta,
  5543. index: meta.index,
  5544. cancelable: true
  5545. };
  5546. if (me.notifyPlugins('beforeDatasetDraw', args) === false) {
  5547. return;
  5548. }
  5549. clipArea(ctx, {
  5550. left: clip.left === false ? 0 : area.left - clip.left,
  5551. right: clip.right === false ? me.width : area.right + clip.right,
  5552. top: clip.top === false ? 0 : area.top - clip.top,
  5553. bottom: clip.bottom === false ? me.height : area.bottom + clip.bottom
  5554. });
  5555. meta.controller.draw();
  5556. unclipArea(ctx);
  5557. args.cancelable = false;
  5558. me.notifyPlugins('afterDatasetDraw', args);
  5559. }
  5560. getElementsAtEventForMode(e, mode, options, useFinalPosition) {
  5561. const method = Interaction.modes[mode];
  5562. if (typeof method === 'function') {
  5563. return method(this, e, options, useFinalPosition);
  5564. }
  5565. return [];
  5566. }
  5567. getDatasetMeta(datasetIndex) {
  5568. const me = this;
  5569. const dataset = me.data.datasets[datasetIndex];
  5570. const metasets = me._metasets;
  5571. let meta = metasets.filter(x => x && x._dataset === dataset).pop();
  5572. if (!meta) {
  5573. meta = metasets[datasetIndex] = {
  5574. type: null,
  5575. data: [],
  5576. dataset: null,
  5577. controller: null,
  5578. hidden: null,
  5579. xAxisID: null,
  5580. yAxisID: null,
  5581. order: dataset && dataset.order || 0,
  5582. index: datasetIndex,
  5583. _dataset: dataset,
  5584. _parsed: [],
  5585. _sorted: false
  5586. };
  5587. }
  5588. return meta;
  5589. }
  5590. getContext() {
  5591. return this.$context || (this.$context = {chart: this, type: 'chart'});
  5592. }
  5593. getVisibleDatasetCount() {
  5594. return this.getSortedVisibleDatasetMetas().length;
  5595. }
  5596. isDatasetVisible(datasetIndex) {
  5597. const dataset = this.data.datasets[datasetIndex];
  5598. if (!dataset) {
  5599. return false;
  5600. }
  5601. const meta = this.getDatasetMeta(datasetIndex);
  5602. return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;
  5603. }
  5604. setDatasetVisibility(datasetIndex, visible) {
  5605. const meta = this.getDatasetMeta(datasetIndex);
  5606. meta.hidden = !visible;
  5607. }
  5608. toggleDataVisibility(index) {
  5609. this._hiddenIndices[index] = !this._hiddenIndices[index];
  5610. }
  5611. getDataVisibility(index) {
  5612. return !this._hiddenIndices[index];
  5613. }
  5614. _updateDatasetVisibility(datasetIndex, visible) {
  5615. const me = this;
  5616. const mode = visible ? 'show' : 'hide';
  5617. const meta = me.getDatasetMeta(datasetIndex);
  5618. const anims = meta.controller._resolveAnimations(undefined, mode);
  5619. me.setDatasetVisibility(datasetIndex, visible);
  5620. anims.update(meta, {visible});
  5621. me.update((ctx) => ctx.datasetIndex === datasetIndex ? mode : undefined);
  5622. }
  5623. hide(datasetIndex) {
  5624. this._updateDatasetVisibility(datasetIndex, false);
  5625. }
  5626. show(datasetIndex) {
  5627. this._updateDatasetVisibility(datasetIndex, true);
  5628. }
  5629. _destroyDatasetMeta(datasetIndex) {
  5630. const me = this;
  5631. const meta = me._metasets && me._metasets[datasetIndex];
  5632. if (meta && meta.controller) {
  5633. meta.controller._destroy();
  5634. delete me._metasets[datasetIndex];
  5635. }
  5636. }
  5637. destroy() {
  5638. const me = this;
  5639. const {canvas, ctx} = me;
  5640. let i, ilen;
  5641. me.stop();
  5642. animator.remove(me);
  5643. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  5644. me._destroyDatasetMeta(i);
  5645. }
  5646. me.config.clearCache();
  5647. if (canvas) {
  5648. me.unbindEvents();
  5649. clearCanvas(canvas, ctx);
  5650. me.platform.releaseContext(ctx);
  5651. me.canvas = null;
  5652. me.ctx = null;
  5653. }
  5654. me.notifyPlugins('destroy');
  5655. delete instances[me.id];
  5656. }
  5657. toBase64Image(...args) {
  5658. return this.canvas.toDataURL(...args);
  5659. }
  5660. bindEvents() {
  5661. const me = this;
  5662. const listeners = me._listeners;
  5663. const platform = me.platform;
  5664. const _add = (type, listener) => {
  5665. platform.addEventListener(me, type, listener);
  5666. listeners[type] = listener;
  5667. };
  5668. const _remove = (type, listener) => {
  5669. if (listeners[type]) {
  5670. platform.removeEventListener(me, type, listener);
  5671. delete listeners[type];
  5672. }
  5673. };
  5674. let listener = function(e, x, y) {
  5675. e.offsetX = x;
  5676. e.offsetY = y;
  5677. me._eventHandler(e);
  5678. };
  5679. each(me.options.events, (type) => _add(type, listener));
  5680. if (me.options.responsive) {
  5681. listener = (width, height) => {
  5682. if (me.canvas) {
  5683. me.resize(width, height);
  5684. }
  5685. };
  5686. let detached;
  5687. const attached = () => {
  5688. _remove('attach', attached);
  5689. me.attached = true;
  5690. me.resize();
  5691. _add('resize', listener);
  5692. _add('detach', detached);
  5693. };
  5694. detached = () => {
  5695. me.attached = false;
  5696. _remove('resize', listener);
  5697. _add('attach', attached);
  5698. };
  5699. if (platform.isAttached(me.canvas)) {
  5700. attached();
  5701. } else {
  5702. detached();
  5703. }
  5704. } else {
  5705. me.attached = true;
  5706. }
  5707. }
  5708. unbindEvents() {
  5709. const me = this;
  5710. const listeners = me._listeners;
  5711. if (!listeners) {
  5712. return;
  5713. }
  5714. me._listeners = {};
  5715. each(listeners, (listener, type) => {
  5716. me.platform.removeEventListener(me, type, listener);
  5717. });
  5718. }
  5719. updateHoverStyle(items, mode, enabled) {
  5720. const prefix = enabled ? 'set' : 'remove';
  5721. let meta, item, i, ilen;
  5722. if (mode === 'dataset') {
  5723. meta = this.getDatasetMeta(items[0].datasetIndex);
  5724. meta.controller['_' + prefix + 'DatasetHoverStyle']();
  5725. }
  5726. for (i = 0, ilen = items.length; i < ilen; ++i) {
  5727. item = items[i];
  5728. const controller = item && this.getDatasetMeta(item.datasetIndex).controller;
  5729. if (controller) {
  5730. controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
  5731. }
  5732. }
  5733. }
  5734. getActiveElements() {
  5735. return this._active || [];
  5736. }
  5737. setActiveElements(activeElements) {
  5738. const me = this;
  5739. const lastActive = me._active || [];
  5740. const active = activeElements.map(({datasetIndex, index}) => {
  5741. const meta = me.getDatasetMeta(datasetIndex);
  5742. if (!meta) {
  5743. throw new Error('No dataset found at index ' + datasetIndex);
  5744. }
  5745. return {
  5746. datasetIndex,
  5747. element: meta.data[index],
  5748. index,
  5749. };
  5750. });
  5751. const changed = !_elementsEqual(active, lastActive);
  5752. if (changed) {
  5753. me._active = active;
  5754. me._updateHoverStyles(active, lastActive);
  5755. }
  5756. }
  5757. notifyPlugins(hook, args, filter) {
  5758. return this._plugins.notify(this, hook, args, filter);
  5759. }
  5760. _updateHoverStyles(active, lastActive, replay) {
  5761. const me = this;
  5762. const hoverOptions = me.options.hover;
  5763. const diff = (a, b) => a.filter(x => !b.some(y => x.datasetIndex === y.datasetIndex && x.index === y.index));
  5764. const deactivated = diff(lastActive, active);
  5765. const activated = replay ? active : diff(active, lastActive);
  5766. if (deactivated.length) {
  5767. me.updateHoverStyle(deactivated, hoverOptions.mode, false);
  5768. }
  5769. if (activated.length && hoverOptions.mode) {
  5770. me.updateHoverStyle(activated, hoverOptions.mode, true);
  5771. }
  5772. }
  5773. _eventHandler(e, replay) {
  5774. const me = this;
  5775. const args = {event: e, replay, cancelable: true};
  5776. const eventFilter = (plugin) => (plugin.options.events || this.options.events).includes(e.type);
  5777. if (me.notifyPlugins('beforeEvent', args, eventFilter) === false) {
  5778. return;
  5779. }
  5780. const changed = me._handleEvent(e, replay);
  5781. args.cancelable = false;
  5782. me.notifyPlugins('afterEvent', args, eventFilter);
  5783. if (changed || args.changed) {
  5784. me.render();
  5785. }
  5786. return me;
  5787. }
  5788. _handleEvent(e, replay) {
  5789. const me = this;
  5790. const {_active: lastActive = [], options} = me;
  5791. const hoverOptions = options.hover;
  5792. const useFinalPosition = replay;
  5793. let active = [];
  5794. let changed = false;
  5795. let lastEvent = null;
  5796. if (e.type !== 'mouseout') {
  5797. active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);
  5798. lastEvent = e.type === 'click' ? me._lastEvent : e;
  5799. }
  5800. me._lastEvent = null;
  5801. if (_isPointInArea(e, me.chartArea, me._minPadding)) {
  5802. callback(options.onHover, [e, active, me], me);
  5803. if (e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu') {
  5804. callback(options.onClick, [e, active, me], me);
  5805. }
  5806. }
  5807. changed = !_elementsEqual(active, lastActive);
  5808. if (changed || replay) {
  5809. me._active = active;
  5810. me._updateHoverStyles(active, lastActive, replay);
  5811. }
  5812. me._lastEvent = lastEvent;
  5813. return changed;
  5814. }
  5815. }
  5816. const invalidatePlugins = () => each(Chart.instances, (chart) => chart._plugins.invalidate());
  5817. const enumerable = true;
  5818. Object.defineProperties(Chart, {
  5819. defaults: {
  5820. enumerable,
  5821. value: defaults
  5822. },
  5823. instances: {
  5824. enumerable,
  5825. value: instances
  5826. },
  5827. overrides: {
  5828. enumerable,
  5829. value: overrides
  5830. },
  5831. registry: {
  5832. enumerable,
  5833. value: registry
  5834. },
  5835. version: {
  5836. enumerable,
  5837. value: version
  5838. },
  5839. getChart: {
  5840. enumerable,
  5841. value: getChart
  5842. },
  5843. register: {
  5844. enumerable,
  5845. value: (...items) => {
  5846. registry.add(...items);
  5847. invalidatePlugins();
  5848. }
  5849. },
  5850. unregister: {
  5851. enumerable,
  5852. value: (...items) => {
  5853. registry.remove(...items);
  5854. invalidatePlugins();
  5855. }
  5856. }
  5857. });
  5858. function clipArc(ctx, element) {
  5859. const {startAngle, endAngle, pixelMargin, x, y, outerRadius, innerRadius} = element;
  5860. let angleMargin = pixelMargin / outerRadius;
  5861. ctx.beginPath();
  5862. ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  5863. if (innerRadius > pixelMargin) {
  5864. angleMargin = pixelMargin / innerRadius;
  5865. ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);
  5866. } else {
  5867. ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI);
  5868. }
  5869. ctx.closePath();
  5870. ctx.clip();
  5871. }
  5872. function toRadiusCorners(value) {
  5873. return _readValueToProps(value, ['outerStart', 'outerEnd', 'innerStart', 'innerEnd']);
  5874. }
  5875. function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) {
  5876. const o = toRadiusCorners(arc.options.borderRadius);
  5877. const halfThickness = (outerRadius - innerRadius) / 2;
  5878. const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);
  5879. const computeOuterLimit = (val) => {
  5880. const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;
  5881. return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit));
  5882. };
  5883. return {
  5884. outerStart: computeOuterLimit(o.outerStart),
  5885. outerEnd: computeOuterLimit(o.outerEnd),
  5886. innerStart: _limitValue(o.innerStart, 0, innerLimit),
  5887. innerEnd: _limitValue(o.innerEnd, 0, innerLimit),
  5888. };
  5889. }
  5890. function rThetaToXY(r, theta, x, y) {
  5891. return {
  5892. x: x + r * Math.cos(theta),
  5893. y: y + r * Math.sin(theta),
  5894. };
  5895. }
  5896. function pathArc(ctx, element) {
  5897. const {x, y, startAngle, endAngle, pixelMargin} = element;
  5898. const outerRadius = Math.max(element.outerRadius - pixelMargin, 0);
  5899. const innerRadius = element.innerRadius + pixelMargin;
  5900. const {outerStart, outerEnd, innerStart, innerEnd} = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle);
  5901. const outerStartAdjustedRadius = outerRadius - outerStart;
  5902. const outerEndAdjustedRadius = outerRadius - outerEnd;
  5903. const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;
  5904. const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;
  5905. const innerStartAdjustedRadius = innerRadius + innerStart;
  5906. const innerEndAdjustedRadius = innerRadius + innerEnd;
  5907. const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;
  5908. const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;
  5909. ctx.beginPath();
  5910. ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerEndAdjustedAngle);
  5911. if (outerEnd > 0) {
  5912. const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);
  5913. ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);
  5914. }
  5915. const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);
  5916. ctx.lineTo(p4.x, p4.y);
  5917. if (innerEnd > 0) {
  5918. const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);
  5919. ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);
  5920. }
  5921. ctx.arc(x, y, innerRadius, endAngle - (innerEnd / innerRadius), startAngle + (innerStart / innerRadius), true);
  5922. if (innerStart > 0) {
  5923. const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);
  5924. ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);
  5925. }
  5926. const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);
  5927. ctx.lineTo(p8.x, p8.y);
  5928. if (outerStart > 0) {
  5929. const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);
  5930. ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);
  5931. }
  5932. ctx.closePath();
  5933. }
  5934. function drawArc(ctx, element) {
  5935. if (element.fullCircles) {
  5936. element.endAngle = element.startAngle + TAU;
  5937. pathArc(ctx, element);
  5938. for (let i = 0; i < element.fullCircles; ++i) {
  5939. ctx.fill();
  5940. }
  5941. }
  5942. if (!isNaN(element.circumference)) {
  5943. element.endAngle = element.startAngle + element.circumference % TAU;
  5944. }
  5945. pathArc(ctx, element);
  5946. ctx.fill();
  5947. }
  5948. function drawFullCircleBorders(ctx, element, inner) {
  5949. const {x, y, startAngle, endAngle, pixelMargin} = element;
  5950. const outerRadius = Math.max(element.outerRadius - pixelMargin, 0);
  5951. const innerRadius = element.innerRadius + pixelMargin;
  5952. let i;
  5953. if (inner) {
  5954. element.endAngle = element.startAngle + TAU;
  5955. clipArc(ctx, element);
  5956. element.endAngle = endAngle;
  5957. if (element.endAngle === element.startAngle) {
  5958. element.endAngle += TAU;
  5959. element.fullCircles--;
  5960. }
  5961. }
  5962. ctx.beginPath();
  5963. ctx.arc(x, y, innerRadius, startAngle + TAU, startAngle, true);
  5964. for (i = 0; i < element.fullCircles; ++i) {
  5965. ctx.stroke();
  5966. }
  5967. ctx.beginPath();
  5968. ctx.arc(x, y, outerRadius, startAngle, startAngle + TAU);
  5969. for (i = 0; i < element.fullCircles; ++i) {
  5970. ctx.stroke();
  5971. }
  5972. }
  5973. function drawBorder(ctx, element) {
  5974. const {options} = element;
  5975. const inner = options.borderAlign === 'inner';
  5976. if (!options.borderWidth) {
  5977. return;
  5978. }
  5979. if (inner) {
  5980. ctx.lineWidth = options.borderWidth * 2;
  5981. ctx.lineJoin = 'round';
  5982. } else {
  5983. ctx.lineWidth = options.borderWidth;
  5984. ctx.lineJoin = 'bevel';
  5985. }
  5986. if (element.fullCircles) {
  5987. drawFullCircleBorders(ctx, element, inner);
  5988. }
  5989. if (inner) {
  5990. clipArc(ctx, element);
  5991. }
  5992. pathArc(ctx, element);
  5993. ctx.stroke();
  5994. }
  5995. class ArcElement extends Element {
  5996. constructor(cfg) {
  5997. super();
  5998. this.options = undefined;
  5999. this.circumference = undefined;
  6000. this.startAngle = undefined;
  6001. this.endAngle = undefined;
  6002. this.innerRadius = undefined;
  6003. this.outerRadius = undefined;
  6004. this.pixelMargin = 0;
  6005. this.fullCircles = 0;
  6006. if (cfg) {
  6007. Object.assign(this, cfg);
  6008. }
  6009. }
  6010. inRange(chartX, chartY, useFinalPosition) {
  6011. const point = this.getProps(['x', 'y'], useFinalPosition);
  6012. const {angle, distance} = getAngleFromPoint(point, {x: chartX, y: chartY});
  6013. const {startAngle, endAngle, innerRadius, outerRadius, circumference} = this.getProps([
  6014. 'startAngle',
  6015. 'endAngle',
  6016. 'innerRadius',
  6017. 'outerRadius',
  6018. 'circumference'
  6019. ], useFinalPosition);
  6020. const betweenAngles = circumference >= TAU || _angleBetween(angle, startAngle, endAngle);
  6021. const withinRadius = (distance >= innerRadius && distance <= outerRadius);
  6022. return (betweenAngles && withinRadius);
  6023. }
  6024. getCenterPoint(useFinalPosition) {
  6025. const {x, y, startAngle, endAngle, innerRadius, outerRadius} = this.getProps([
  6026. 'x',
  6027. 'y',
  6028. 'startAngle',
  6029. 'endAngle',
  6030. 'innerRadius',
  6031. 'outerRadius'
  6032. ], useFinalPosition);
  6033. const halfAngle = (startAngle + endAngle) / 2;
  6034. const halfRadius = (innerRadius + outerRadius) / 2;
  6035. return {
  6036. x: x + Math.cos(halfAngle) * halfRadius,
  6037. y: y + Math.sin(halfAngle) * halfRadius
  6038. };
  6039. }
  6040. tooltipPosition(useFinalPosition) {
  6041. return this.getCenterPoint(useFinalPosition);
  6042. }
  6043. draw(ctx) {
  6044. const me = this;
  6045. const options = me.options;
  6046. const offset = options.offset || 0;
  6047. me.pixelMargin = (options.borderAlign === 'inner') ? 0.33 : 0;
  6048. me.fullCircles = Math.floor(me.circumference / TAU);
  6049. if (me.circumference === 0 || me.innerRadius < 0 || me.outerRadius < 0) {
  6050. return;
  6051. }
  6052. ctx.save();
  6053. if (offset && me.circumference < TAU) {
  6054. const halfAngle = (me.startAngle + me.endAngle) / 2;
  6055. ctx.translate(Math.cos(halfAngle) * offset, Math.sin(halfAngle) * offset);
  6056. }
  6057. ctx.fillStyle = options.backgroundColor;
  6058. ctx.strokeStyle = options.borderColor;
  6059. drawArc(ctx, me);
  6060. drawBorder(ctx, me);
  6061. ctx.restore();
  6062. }
  6063. }
  6064. ArcElement.id = 'arc';
  6065. ArcElement.defaults = {
  6066. borderAlign: 'center',
  6067. borderColor: '#fff',
  6068. borderRadius: 0,
  6069. borderWidth: 2,
  6070. offset: 0,
  6071. angle: undefined,
  6072. };
  6073. ArcElement.defaultRoutes = {
  6074. backgroundColor: 'backgroundColor'
  6075. };
  6076. function setStyle(ctx, options, style = options) {
  6077. ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle);
  6078. ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash));
  6079. ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset);
  6080. ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);
  6081. ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth);
  6082. ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor);
  6083. }
  6084. function lineTo(ctx, previous, target) {
  6085. ctx.lineTo(target.x, target.y);
  6086. }
  6087. function getLineMethod(options) {
  6088. if (options.stepped) {
  6089. return _steppedLineTo;
  6090. }
  6091. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  6092. return _bezierCurveTo;
  6093. }
  6094. return lineTo;
  6095. }
  6096. function pathVars(points, segment, params = {}) {
  6097. const count = points.length;
  6098. const {start: paramsStart = 0, end: paramsEnd = count - 1} = params;
  6099. const {start: segmentStart, end: segmentEnd} = segment;
  6100. const start = Math.max(paramsStart, segmentStart);
  6101. const end = Math.min(paramsEnd, segmentEnd);
  6102. const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;
  6103. return {
  6104. count,
  6105. start,
  6106. loop: segment.loop,
  6107. ilen: end < start && !outside ? count + end - start : end - start
  6108. };
  6109. }
  6110. function pathSegment(ctx, line, segment, params) {
  6111. const {points, options} = line;
  6112. const {count, start, loop, ilen} = pathVars(points, segment, params);
  6113. const lineMethod = getLineMethod(options);
  6114. let {move = true, reverse} = params || {};
  6115. let i, point, prev;
  6116. for (i = 0; i <= ilen; ++i) {
  6117. point = points[(start + (reverse ? ilen - i : i)) % count];
  6118. if (point.skip) {
  6119. continue;
  6120. } else if (move) {
  6121. ctx.moveTo(point.x, point.y);
  6122. move = false;
  6123. } else {
  6124. lineMethod(ctx, prev, point, reverse, options.stepped);
  6125. }
  6126. prev = point;
  6127. }
  6128. if (loop) {
  6129. point = points[(start + (reverse ? ilen : 0)) % count];
  6130. lineMethod(ctx, prev, point, reverse, options.stepped);
  6131. }
  6132. return !!loop;
  6133. }
  6134. function fastPathSegment(ctx, line, segment, params) {
  6135. const points = line.points;
  6136. const {count, start, ilen} = pathVars(points, segment, params);
  6137. const {move = true, reverse} = params || {};
  6138. let avgX = 0;
  6139. let countX = 0;
  6140. let i, point, prevX, minY, maxY, lastY;
  6141. const pointIndex = (index) => (start + (reverse ? ilen - index : index)) % count;
  6142. const drawX = () => {
  6143. if (minY !== maxY) {
  6144. ctx.lineTo(avgX, maxY);
  6145. ctx.lineTo(avgX, minY);
  6146. ctx.lineTo(avgX, lastY);
  6147. }
  6148. };
  6149. if (move) {
  6150. point = points[pointIndex(0)];
  6151. ctx.moveTo(point.x, point.y);
  6152. }
  6153. for (i = 0; i <= ilen; ++i) {
  6154. point = points[pointIndex(i)];
  6155. if (point.skip) {
  6156. continue;
  6157. }
  6158. const x = point.x;
  6159. const y = point.y;
  6160. const truncX = x | 0;
  6161. if (truncX === prevX) {
  6162. if (y < minY) {
  6163. minY = y;
  6164. } else if (y > maxY) {
  6165. maxY = y;
  6166. }
  6167. avgX = (countX * avgX + x) / ++countX;
  6168. } else {
  6169. drawX();
  6170. ctx.lineTo(x, y);
  6171. prevX = truncX;
  6172. countX = 0;
  6173. minY = maxY = y;
  6174. }
  6175. lastY = y;
  6176. }
  6177. drawX();
  6178. }
  6179. function _getSegmentMethod(line) {
  6180. const opts = line.options;
  6181. const borderDash = opts.borderDash && opts.borderDash.length;
  6182. const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;
  6183. return useFastPath ? fastPathSegment : pathSegment;
  6184. }
  6185. function _getInterpolationMethod(options) {
  6186. if (options.stepped) {
  6187. return _steppedInterpolation;
  6188. }
  6189. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  6190. return _bezierInterpolation;
  6191. }
  6192. return _pointInLine;
  6193. }
  6194. function strokePathWithCache(ctx, line, start, count) {
  6195. let path = line._path;
  6196. if (!path) {
  6197. path = line._path = new Path2D();
  6198. if (line.path(path, start, count)) {
  6199. path.closePath();
  6200. }
  6201. }
  6202. setStyle(ctx, line.options);
  6203. ctx.stroke(path);
  6204. }
  6205. function strokePathDirect(ctx, line, start, count) {
  6206. const {segments, options} = line;
  6207. const segmentMethod = _getSegmentMethod(line);
  6208. for (const segment of segments) {
  6209. setStyle(ctx, options, segment.style);
  6210. ctx.beginPath();
  6211. if (segmentMethod(ctx, line, segment, {start, end: start + count - 1})) {
  6212. ctx.closePath();
  6213. }
  6214. ctx.stroke();
  6215. }
  6216. }
  6217. const usePath2D = typeof Path2D === 'function';
  6218. function draw(ctx, line, start, count) {
  6219. if (usePath2D && line.segments.length === 1) {
  6220. strokePathWithCache(ctx, line, start, count);
  6221. } else {
  6222. strokePathDirect(ctx, line, start, count);
  6223. }
  6224. }
  6225. class LineElement extends Element {
  6226. constructor(cfg) {
  6227. super();
  6228. this.animated = true;
  6229. this.options = undefined;
  6230. this._loop = undefined;
  6231. this._fullLoop = undefined;
  6232. this._path = undefined;
  6233. this._points = undefined;
  6234. this._segments = undefined;
  6235. this._decimated = false;
  6236. this._pointsUpdated = false;
  6237. if (cfg) {
  6238. Object.assign(this, cfg);
  6239. }
  6240. }
  6241. updateControlPoints(chartArea) {
  6242. const me = this;
  6243. const options = me.options;
  6244. if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !me._pointsUpdated) {
  6245. const loop = options.spanGaps ? me._loop : me._fullLoop;
  6246. _updateBezierControlPoints(me._points, options, chartArea, loop);
  6247. me._pointsUpdated = true;
  6248. }
  6249. }
  6250. set points(points) {
  6251. const me = this;
  6252. me._points = points;
  6253. delete me._segments;
  6254. delete me._path;
  6255. me._pointsUpdated = false;
  6256. }
  6257. get points() {
  6258. return this._points;
  6259. }
  6260. get segments() {
  6261. return this._segments || (this._segments = _computeSegments(this, this.options.segment));
  6262. }
  6263. first() {
  6264. const segments = this.segments;
  6265. const points = this.points;
  6266. return segments.length && points[segments[0].start];
  6267. }
  6268. last() {
  6269. const segments = this.segments;
  6270. const points = this.points;
  6271. const count = segments.length;
  6272. return count && points[segments[count - 1].end];
  6273. }
  6274. interpolate(point, property) {
  6275. const me = this;
  6276. const options = me.options;
  6277. const value = point[property];
  6278. const points = me.points;
  6279. const segments = _boundSegments(me, {property, start: value, end: value});
  6280. if (!segments.length) {
  6281. return;
  6282. }
  6283. const result = [];
  6284. const _interpolate = _getInterpolationMethod(options);
  6285. let i, ilen;
  6286. for (i = 0, ilen = segments.length; i < ilen; ++i) {
  6287. const {start, end} = segments[i];
  6288. const p1 = points[start];
  6289. const p2 = points[end];
  6290. if (p1 === p2) {
  6291. result.push(p1);
  6292. continue;
  6293. }
  6294. const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));
  6295. const interpolated = _interpolate(p1, p2, t, options.stepped);
  6296. interpolated[property] = point[property];
  6297. result.push(interpolated);
  6298. }
  6299. return result.length === 1 ? result[0] : result;
  6300. }
  6301. pathSegment(ctx, segment, params) {
  6302. const segmentMethod = _getSegmentMethod(this);
  6303. return segmentMethod(ctx, this, segment, params);
  6304. }
  6305. path(ctx, start, count) {
  6306. const me = this;
  6307. const segments = me.segments;
  6308. const segmentMethod = _getSegmentMethod(me);
  6309. let loop = me._loop;
  6310. start = start || 0;
  6311. count = count || (me.points.length - start);
  6312. for (const segment of segments) {
  6313. loop &= segmentMethod(ctx, me, segment, {start, end: start + count - 1});
  6314. }
  6315. return !!loop;
  6316. }
  6317. draw(ctx, chartArea, start, count) {
  6318. const me = this;
  6319. const options = me.options || {};
  6320. const points = me.points || [];
  6321. if (!points.length || !options.borderWidth) {
  6322. return;
  6323. }
  6324. ctx.save();
  6325. draw(ctx, me, start, count);
  6326. ctx.restore();
  6327. if (me.animated) {
  6328. me._pointsUpdated = false;
  6329. me._path = undefined;
  6330. }
  6331. }
  6332. }
  6333. LineElement.id = 'line';
  6334. LineElement.defaults = {
  6335. borderCapStyle: 'butt',
  6336. borderDash: [],
  6337. borderDashOffset: 0,
  6338. borderJoinStyle: 'miter',
  6339. borderWidth: 3,
  6340. capBezierPoints: true,
  6341. cubicInterpolationMode: 'default',
  6342. fill: false,
  6343. spanGaps: false,
  6344. stepped: false,
  6345. tension: 0,
  6346. };
  6347. LineElement.defaultRoutes = {
  6348. backgroundColor: 'backgroundColor',
  6349. borderColor: 'borderColor'
  6350. };
  6351. LineElement.descriptors = {
  6352. _scriptable: true,
  6353. _indexable: (name) => name !== 'borderDash' && name !== 'fill',
  6354. };
  6355. function inRange$1(el, pos, axis, useFinalPosition) {
  6356. const options = el.options;
  6357. const {[axis]: value} = el.getProps([axis], useFinalPosition);
  6358. return (Math.abs(pos - value) < options.radius + options.hitRadius);
  6359. }
  6360. class PointElement extends Element {
  6361. constructor(cfg) {
  6362. super();
  6363. this.options = undefined;
  6364. this.parsed = undefined;
  6365. this.skip = undefined;
  6366. this.stop = undefined;
  6367. if (cfg) {
  6368. Object.assign(this, cfg);
  6369. }
  6370. }
  6371. inRange(mouseX, mouseY, useFinalPosition) {
  6372. const options = this.options;
  6373. const {x, y} = this.getProps(['x', 'y'], useFinalPosition);
  6374. return ((Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2)) < Math.pow(options.hitRadius + options.radius, 2));
  6375. }
  6376. inXRange(mouseX, useFinalPosition) {
  6377. return inRange$1(this, mouseX, 'x', useFinalPosition);
  6378. }
  6379. inYRange(mouseY, useFinalPosition) {
  6380. return inRange$1(this, mouseY, 'y', useFinalPosition);
  6381. }
  6382. getCenterPoint(useFinalPosition) {
  6383. const {x, y} = this.getProps(['x', 'y'], useFinalPosition);
  6384. return {x, y};
  6385. }
  6386. size(options) {
  6387. options = options || this.options || {};
  6388. let radius = options.radius || 0;
  6389. radius = Math.max(radius, radius && options.hoverRadius || 0);
  6390. const borderWidth = radius && options.borderWidth || 0;
  6391. return (radius + borderWidth) * 2;
  6392. }
  6393. draw(ctx) {
  6394. const me = this;
  6395. const options = me.options;
  6396. if (me.skip || options.radius < 0.1) {
  6397. return;
  6398. }
  6399. ctx.strokeStyle = options.borderColor;
  6400. ctx.lineWidth = options.borderWidth;
  6401. ctx.fillStyle = options.backgroundColor;
  6402. drawPoint(ctx, options, me.x, me.y);
  6403. }
  6404. getRange() {
  6405. const options = this.options || {};
  6406. return options.radius + options.hitRadius;
  6407. }
  6408. }
  6409. PointElement.id = 'point';
  6410. PointElement.defaults = {
  6411. borderWidth: 1,
  6412. hitRadius: 1,
  6413. hoverBorderWidth: 1,
  6414. hoverRadius: 4,
  6415. pointStyle: 'circle',
  6416. radius: 3,
  6417. rotation: 0
  6418. };
  6419. PointElement.defaultRoutes = {
  6420. backgroundColor: 'backgroundColor',
  6421. borderColor: 'borderColor'
  6422. };
  6423. function getBarBounds(bar, useFinalPosition) {
  6424. const {x, y, base, width, height} = bar.getProps(['x', 'y', 'base', 'width', 'height'], useFinalPosition);
  6425. let left, right, top, bottom, half;
  6426. if (bar.horizontal) {
  6427. half = height / 2;
  6428. left = Math.min(x, base);
  6429. right = Math.max(x, base);
  6430. top = y - half;
  6431. bottom = y + half;
  6432. } else {
  6433. half = width / 2;
  6434. left = x - half;
  6435. right = x + half;
  6436. top = Math.min(y, base);
  6437. bottom = Math.max(y, base);
  6438. }
  6439. return {left, top, right, bottom};
  6440. }
  6441. function parseBorderSkipped(bar) {
  6442. let edge = bar.options.borderSkipped;
  6443. const res = {};
  6444. if (!edge) {
  6445. return res;
  6446. }
  6447. edge = bar.horizontal
  6448. ? parseEdge(edge, 'left', 'right', bar.base > bar.x)
  6449. : parseEdge(edge, 'bottom', 'top', bar.base < bar.y);
  6450. res[edge] = true;
  6451. return res;
  6452. }
  6453. function parseEdge(edge, a, b, reverse) {
  6454. if (reverse) {
  6455. edge = swap(edge, a, b);
  6456. edge = startEnd(edge, b, a);
  6457. } else {
  6458. edge = startEnd(edge, a, b);
  6459. }
  6460. return edge;
  6461. }
  6462. function swap(orig, v1, v2) {
  6463. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  6464. }
  6465. function startEnd(v, start, end) {
  6466. return v === 'start' ? start : v === 'end' ? end : v;
  6467. }
  6468. function skipOrLimit(skip, value, min, max) {
  6469. return skip ? 0 : Math.max(Math.min(value, max), min);
  6470. }
  6471. function parseBorderWidth(bar, maxW, maxH) {
  6472. const value = bar.options.borderWidth;
  6473. const skip = parseBorderSkipped(bar);
  6474. const o = toTRBL(value);
  6475. return {
  6476. t: skipOrLimit(skip.top, o.top, 0, maxH),
  6477. r: skipOrLimit(skip.right, o.right, 0, maxW),
  6478. b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),
  6479. l: skipOrLimit(skip.left, o.left, 0, maxW)
  6480. };
  6481. }
  6482. function parseBorderRadius(bar, maxW, maxH) {
  6483. const {enableBorderRadius} = bar.getProps(['enableBorderRadius']);
  6484. const value = bar.options.borderRadius;
  6485. const o = toTRBLCorners(value);
  6486. const maxR = Math.min(maxW, maxH);
  6487. const skip = parseBorderSkipped(bar);
  6488. const enableBorder = enableBorderRadius || isObject(value);
  6489. return {
  6490. topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),
  6491. topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),
  6492. bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),
  6493. bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)
  6494. };
  6495. }
  6496. function boundingRects(bar) {
  6497. const bounds = getBarBounds(bar);
  6498. const width = bounds.right - bounds.left;
  6499. const height = bounds.bottom - bounds.top;
  6500. const border = parseBorderWidth(bar, width / 2, height / 2);
  6501. const radius = parseBorderRadius(bar, width / 2, height / 2);
  6502. return {
  6503. outer: {
  6504. x: bounds.left,
  6505. y: bounds.top,
  6506. w: width,
  6507. h: height,
  6508. radius
  6509. },
  6510. inner: {
  6511. x: bounds.left + border.l,
  6512. y: bounds.top + border.t,
  6513. w: width - border.l - border.r,
  6514. h: height - border.t - border.b,
  6515. radius: {
  6516. topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),
  6517. topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),
  6518. bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),
  6519. bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r)),
  6520. }
  6521. }
  6522. };
  6523. }
  6524. function inRange(bar, x, y, useFinalPosition) {
  6525. const skipX = x === null;
  6526. const skipY = y === null;
  6527. const skipBoth = skipX && skipY;
  6528. const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);
  6529. return bounds
  6530. && (skipX || x >= bounds.left && x <= bounds.right)
  6531. && (skipY || y >= bounds.top && y <= bounds.bottom);
  6532. }
  6533. function hasRadius(radius) {
  6534. return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;
  6535. }
  6536. function addNormalRectPath(ctx, rect) {
  6537. ctx.rect(rect.x, rect.y, rect.w, rect.h);
  6538. }
  6539. class BarElement extends Element {
  6540. constructor(cfg) {
  6541. super();
  6542. this.options = undefined;
  6543. this.horizontal = undefined;
  6544. this.base = undefined;
  6545. this.width = undefined;
  6546. this.height = undefined;
  6547. if (cfg) {
  6548. Object.assign(this, cfg);
  6549. }
  6550. }
  6551. draw(ctx) {
  6552. const options = this.options;
  6553. const {inner, outer} = boundingRects(this);
  6554. const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath;
  6555. ctx.save();
  6556. if (outer.w !== inner.w || outer.h !== inner.h) {
  6557. ctx.beginPath();
  6558. addRectPath(ctx, outer);
  6559. ctx.clip();
  6560. addRectPath(ctx, inner);
  6561. ctx.fillStyle = options.borderColor;
  6562. ctx.fill('evenodd');
  6563. }
  6564. ctx.beginPath();
  6565. addRectPath(ctx, inner);
  6566. ctx.fillStyle = options.backgroundColor;
  6567. ctx.fill();
  6568. ctx.restore();
  6569. }
  6570. inRange(mouseX, mouseY, useFinalPosition) {
  6571. return inRange(this, mouseX, mouseY, useFinalPosition);
  6572. }
  6573. inXRange(mouseX, useFinalPosition) {
  6574. return inRange(this, mouseX, null, useFinalPosition);
  6575. }
  6576. inYRange(mouseY, useFinalPosition) {
  6577. return inRange(this, null, mouseY, useFinalPosition);
  6578. }
  6579. getCenterPoint(useFinalPosition) {
  6580. const {x, y, base, horizontal} = this.getProps(['x', 'y', 'base', 'horizontal'], useFinalPosition);
  6581. return {
  6582. x: horizontal ? (x + base) / 2 : x,
  6583. y: horizontal ? y : (y + base) / 2
  6584. };
  6585. }
  6586. getRange(axis) {
  6587. return axis === 'x' ? this.width / 2 : this.height / 2;
  6588. }
  6589. }
  6590. BarElement.id = 'bar';
  6591. BarElement.defaults = {
  6592. borderSkipped: 'start',
  6593. borderWidth: 0,
  6594. borderRadius: 0,
  6595. enableBorderRadius: true,
  6596. pointStyle: undefined
  6597. };
  6598. BarElement.defaultRoutes = {
  6599. backgroundColor: 'backgroundColor',
  6600. borderColor: 'borderColor'
  6601. };
  6602. var elements = /*#__PURE__*/Object.freeze({
  6603. __proto__: null,
  6604. ArcElement: ArcElement,
  6605. LineElement: LineElement,
  6606. PointElement: PointElement,
  6607. BarElement: BarElement
  6608. });
  6609. function lttbDecimation(data, start, count, availableWidth, options) {
  6610. const samples = options.samples || availableWidth;
  6611. if (samples >= count) {
  6612. return data.slice(start, start + count);
  6613. }
  6614. const decimated = [];
  6615. const bucketWidth = (count - 2) / (samples - 2);
  6616. let sampledIndex = 0;
  6617. const endIndex = start + count - 1;
  6618. let a = start;
  6619. let i, maxAreaPoint, maxArea, area, nextA;
  6620. decimated[sampledIndex++] = data[a];
  6621. for (i = 0; i < samples - 2; i++) {
  6622. let avgX = 0;
  6623. let avgY = 0;
  6624. let j;
  6625. const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;
  6626. const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;
  6627. const avgRangeLength = avgRangeEnd - avgRangeStart;
  6628. for (j = avgRangeStart; j < avgRangeEnd; j++) {
  6629. avgX += data[j].x;
  6630. avgY += data[j].y;
  6631. }
  6632. avgX /= avgRangeLength;
  6633. avgY /= avgRangeLength;
  6634. const rangeOffs = Math.floor(i * bucketWidth) + 1 + start;
  6635. const rangeTo = Math.floor((i + 1) * bucketWidth) + 1 + start;
  6636. const {x: pointAx, y: pointAy} = data[a];
  6637. maxArea = area = -1;
  6638. for (j = rangeOffs; j < rangeTo; j++) {
  6639. area = 0.5 * Math.abs(
  6640. (pointAx - avgX) * (data[j].y - pointAy) -
  6641. (pointAx - data[j].x) * (avgY - pointAy)
  6642. );
  6643. if (area > maxArea) {
  6644. maxArea = area;
  6645. maxAreaPoint = data[j];
  6646. nextA = j;
  6647. }
  6648. }
  6649. decimated[sampledIndex++] = maxAreaPoint;
  6650. a = nextA;
  6651. }
  6652. decimated[sampledIndex++] = data[endIndex];
  6653. return decimated;
  6654. }
  6655. function minMaxDecimation(data, start, count, availableWidth) {
  6656. let avgX = 0;
  6657. let countX = 0;
  6658. let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;
  6659. const decimated = [];
  6660. const endIndex = start + count - 1;
  6661. const xMin = data[start].x;
  6662. const xMax = data[endIndex].x;
  6663. const dx = xMax - xMin;
  6664. for (i = start; i < start + count; ++i) {
  6665. point = data[i];
  6666. x = (point.x - xMin) / dx * availableWidth;
  6667. y = point.y;
  6668. const truncX = x | 0;
  6669. if (truncX === prevX) {
  6670. if (y < minY) {
  6671. minY = y;
  6672. minIndex = i;
  6673. } else if (y > maxY) {
  6674. maxY = y;
  6675. maxIndex = i;
  6676. }
  6677. avgX = (countX * avgX + point.x) / ++countX;
  6678. } else {
  6679. const lastIndex = i - 1;
  6680. if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) {
  6681. const intermediateIndex1 = Math.min(minIndex, maxIndex);
  6682. const intermediateIndex2 = Math.max(minIndex, maxIndex);
  6683. if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {
  6684. decimated.push({
  6685. ...data[intermediateIndex1],
  6686. x: avgX,
  6687. });
  6688. }
  6689. if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {
  6690. decimated.push({
  6691. ...data[intermediateIndex2],
  6692. x: avgX
  6693. });
  6694. }
  6695. }
  6696. if (i > 0 && lastIndex !== startIndex) {
  6697. decimated.push(data[lastIndex]);
  6698. }
  6699. decimated.push(point);
  6700. prevX = truncX;
  6701. countX = 0;
  6702. minY = maxY = y;
  6703. minIndex = maxIndex = startIndex = i;
  6704. }
  6705. }
  6706. return decimated;
  6707. }
  6708. function cleanDecimatedDataset(dataset) {
  6709. if (dataset._decimated) {
  6710. const data = dataset._data;
  6711. delete dataset._decimated;
  6712. delete dataset._data;
  6713. Object.defineProperty(dataset, 'data', {value: data});
  6714. }
  6715. }
  6716. function cleanDecimatedData(chart) {
  6717. chart.data.datasets.forEach((dataset) => {
  6718. cleanDecimatedDataset(dataset);
  6719. });
  6720. }
  6721. function getStartAndCountOfVisiblePointsSimplified(meta, points) {
  6722. const pointCount = points.length;
  6723. let start = 0;
  6724. let count;
  6725. const {iScale} = meta;
  6726. const {min, max, minDefined, maxDefined} = iScale.getUserBounds();
  6727. if (minDefined) {
  6728. start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);
  6729. }
  6730. if (maxDefined) {
  6731. count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;
  6732. } else {
  6733. count = pointCount - start;
  6734. }
  6735. return {start, count};
  6736. }
  6737. var plugin_decimation = {
  6738. id: 'decimation',
  6739. defaults: {
  6740. algorithm: 'min-max',
  6741. enabled: false,
  6742. },
  6743. beforeElementsUpdate: (chart, args, options) => {
  6744. if (!options.enabled) {
  6745. cleanDecimatedData(chart);
  6746. return;
  6747. }
  6748. const availableWidth = chart.width;
  6749. chart.data.datasets.forEach((dataset, datasetIndex) => {
  6750. const {_data, indexAxis} = dataset;
  6751. const meta = chart.getDatasetMeta(datasetIndex);
  6752. const data = _data || dataset.data;
  6753. if (resolve([indexAxis, chart.options.indexAxis]) === 'y') {
  6754. return;
  6755. }
  6756. if (meta.type !== 'line') {
  6757. return;
  6758. }
  6759. const xAxis = chart.scales[meta.xAxisID];
  6760. if (xAxis.type !== 'linear' && xAxis.type !== 'time') {
  6761. return;
  6762. }
  6763. if (chart.options.parsing) {
  6764. return;
  6765. }
  6766. let {start, count} = getStartAndCountOfVisiblePointsSimplified(meta, data);
  6767. if (count <= 4 * availableWidth) {
  6768. cleanDecimatedDataset(dataset);
  6769. return;
  6770. }
  6771. if (isNullOrUndef(_data)) {
  6772. dataset._data = data;
  6773. delete dataset.data;
  6774. Object.defineProperty(dataset, 'data', {
  6775. configurable: true,
  6776. enumerable: true,
  6777. get: function() {
  6778. return this._decimated;
  6779. },
  6780. set: function(d) {
  6781. this._data = d;
  6782. }
  6783. });
  6784. }
  6785. let decimated;
  6786. switch (options.algorithm) {
  6787. case 'lttb':
  6788. decimated = lttbDecimation(data, start, count, availableWidth, options);
  6789. break;
  6790. case 'min-max':
  6791. decimated = minMaxDecimation(data, start, count, availableWidth);
  6792. break;
  6793. default:
  6794. throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);
  6795. }
  6796. dataset._decimated = decimated;
  6797. });
  6798. },
  6799. destroy(chart) {
  6800. cleanDecimatedData(chart);
  6801. }
  6802. };
  6803. function getLineByIndex(chart, index) {
  6804. const meta = chart.getDatasetMeta(index);
  6805. const visible = meta && chart.isDatasetVisible(index);
  6806. return visible ? meta.dataset : null;
  6807. }
  6808. function parseFillOption(line) {
  6809. const options = line.options;
  6810. const fillOption = options.fill;
  6811. let fill = valueOrDefault(fillOption && fillOption.target, fillOption);
  6812. if (fill === undefined) {
  6813. fill = !!options.backgroundColor;
  6814. }
  6815. if (fill === false || fill === null) {
  6816. return false;
  6817. }
  6818. if (fill === true) {
  6819. return 'origin';
  6820. }
  6821. return fill;
  6822. }
  6823. function decodeFill(line, index, count) {
  6824. const fill = parseFillOption(line);
  6825. if (isObject(fill)) {
  6826. return isNaN(fill.value) ? false : fill;
  6827. }
  6828. let target = parseFloat(fill);
  6829. if (isNumberFinite(target) && Math.floor(target) === target) {
  6830. if (fill[0] === '-' || fill[0] === '+') {
  6831. target = index + target;
  6832. }
  6833. if (target === index || target < 0 || target >= count) {
  6834. return false;
  6835. }
  6836. return target;
  6837. }
  6838. return ['origin', 'start', 'end', 'stack'].indexOf(fill) >= 0 && fill;
  6839. }
  6840. function computeLinearBoundary(source) {
  6841. const {scale = {}, fill} = source;
  6842. let target = null;
  6843. let horizontal;
  6844. if (fill === 'start') {
  6845. target = scale.bottom;
  6846. } else if (fill === 'end') {
  6847. target = scale.top;
  6848. } else if (isObject(fill)) {
  6849. target = scale.getPixelForValue(fill.value);
  6850. } else if (scale.getBasePixel) {
  6851. target = scale.getBasePixel();
  6852. }
  6853. if (isNumberFinite(target)) {
  6854. horizontal = scale.isHorizontal();
  6855. return {
  6856. x: horizontal ? target : null,
  6857. y: horizontal ? null : target
  6858. };
  6859. }
  6860. return null;
  6861. }
  6862. class simpleArc {
  6863. constructor(opts) {
  6864. this.x = opts.x;
  6865. this.y = opts.y;
  6866. this.radius = opts.radius;
  6867. }
  6868. pathSegment(ctx, bounds, opts) {
  6869. const {x, y, radius} = this;
  6870. bounds = bounds || {start: 0, end: TAU};
  6871. ctx.arc(x, y, radius, bounds.end, bounds.start, true);
  6872. return !opts.bounds;
  6873. }
  6874. interpolate(point) {
  6875. const {x, y, radius} = this;
  6876. const angle = point.angle;
  6877. return {
  6878. x: x + Math.cos(angle) * radius,
  6879. y: y + Math.sin(angle) * radius,
  6880. angle
  6881. };
  6882. }
  6883. }
  6884. function computeCircularBoundary(source) {
  6885. const {scale, fill} = source;
  6886. const options = scale.options;
  6887. const length = scale.getLabels().length;
  6888. const target = [];
  6889. const start = options.reverse ? scale.max : scale.min;
  6890. const end = options.reverse ? scale.min : scale.max;
  6891. let i, center, value;
  6892. if (fill === 'start') {
  6893. value = start;
  6894. } else if (fill === 'end') {
  6895. value = end;
  6896. } else if (isObject(fill)) {
  6897. value = fill.value;
  6898. } else {
  6899. value = scale.getBaseValue();
  6900. }
  6901. if (options.grid.circular) {
  6902. center = scale.getPointPositionForValue(0, start);
  6903. return new simpleArc({
  6904. x: center.x,
  6905. y: center.y,
  6906. radius: scale.getDistanceFromCenterForValue(value)
  6907. });
  6908. }
  6909. for (i = 0; i < length; ++i) {
  6910. target.push(scale.getPointPositionForValue(i, value));
  6911. }
  6912. return target;
  6913. }
  6914. function computeBoundary(source) {
  6915. const scale = source.scale || {};
  6916. if (scale.getPointPositionForValue) {
  6917. return computeCircularBoundary(source);
  6918. }
  6919. return computeLinearBoundary(source);
  6920. }
  6921. function pointsFromSegments(boundary, line) {
  6922. const {x = null, y = null} = boundary || {};
  6923. const linePoints = line.points;
  6924. const points = [];
  6925. line.segments.forEach((segment) => {
  6926. const first = linePoints[segment.start];
  6927. const last = linePoints[segment.end];
  6928. if (y !== null) {
  6929. points.push({x: first.x, y});
  6930. points.push({x: last.x, y});
  6931. } else if (x !== null) {
  6932. points.push({x, y: first.y});
  6933. points.push({x, y: last.y});
  6934. }
  6935. });
  6936. return points;
  6937. }
  6938. function buildStackLine(source) {
  6939. const {chart, scale, index, line} = source;
  6940. const points = [];
  6941. const segments = line.segments;
  6942. const sourcePoints = line.points;
  6943. const linesBelow = getLinesBelow(chart, index);
  6944. linesBelow.push(createBoundaryLine({x: null, y: scale.bottom}, line));
  6945. for (let i = 0; i < segments.length; i++) {
  6946. const segment = segments[i];
  6947. for (let j = segment.start; j <= segment.end; j++) {
  6948. addPointsBelow(points, sourcePoints[j], linesBelow);
  6949. }
  6950. }
  6951. return new LineElement({points, options: {}});
  6952. }
  6953. const isLineAndNotInHideAnimation = (meta) => meta.type === 'line' && !meta.hidden;
  6954. function getLinesBelow(chart, index) {
  6955. const below = [];
  6956. const metas = chart.getSortedVisibleDatasetMetas();
  6957. for (let i = 0; i < metas.length; i++) {
  6958. const meta = metas[i];
  6959. if (meta.index === index) {
  6960. break;
  6961. }
  6962. if (isLineAndNotInHideAnimation(meta)) {
  6963. below.unshift(meta.dataset);
  6964. }
  6965. }
  6966. return below;
  6967. }
  6968. function addPointsBelow(points, sourcePoint, linesBelow) {
  6969. const postponed = [];
  6970. for (let j = 0; j < linesBelow.length; j++) {
  6971. const line = linesBelow[j];
  6972. const {first, last, point} = findPoint(line, sourcePoint, 'x');
  6973. if (!point || (first && last)) {
  6974. continue;
  6975. }
  6976. if (first) {
  6977. postponed.unshift(point);
  6978. } else {
  6979. points.push(point);
  6980. if (!last) {
  6981. break;
  6982. }
  6983. }
  6984. }
  6985. points.push(...postponed);
  6986. }
  6987. function findPoint(line, sourcePoint, property) {
  6988. const point = line.interpolate(sourcePoint, property);
  6989. if (!point) {
  6990. return {};
  6991. }
  6992. const pointValue = point[property];
  6993. const segments = line.segments;
  6994. const linePoints = line.points;
  6995. let first = false;
  6996. let last = false;
  6997. for (let i = 0; i < segments.length; i++) {
  6998. const segment = segments[i];
  6999. const firstValue = linePoints[segment.start][property];
  7000. const lastValue = linePoints[segment.end][property];
  7001. if (pointValue >= firstValue && pointValue <= lastValue) {
  7002. first = pointValue === firstValue;
  7003. last = pointValue === lastValue;
  7004. break;
  7005. }
  7006. }
  7007. return {first, last, point};
  7008. }
  7009. function getTarget(source) {
  7010. const {chart, fill, line} = source;
  7011. if (isNumberFinite(fill)) {
  7012. return getLineByIndex(chart, fill);
  7013. }
  7014. if (fill === 'stack') {
  7015. return buildStackLine(source);
  7016. }
  7017. const boundary = computeBoundary(source);
  7018. if (boundary instanceof simpleArc) {
  7019. return boundary;
  7020. }
  7021. return createBoundaryLine(boundary, line);
  7022. }
  7023. function createBoundaryLine(boundary, line) {
  7024. let points = [];
  7025. let _loop = false;
  7026. if (isArray(boundary)) {
  7027. _loop = true;
  7028. points = boundary;
  7029. } else {
  7030. points = pointsFromSegments(boundary, line);
  7031. }
  7032. return points.length ? new LineElement({
  7033. points,
  7034. options: {tension: 0},
  7035. _loop,
  7036. _fullLoop: _loop
  7037. }) : null;
  7038. }
  7039. function resolveTarget(sources, index, propagate) {
  7040. const source = sources[index];
  7041. let fill = source.fill;
  7042. const visited = [index];
  7043. let target;
  7044. if (!propagate) {
  7045. return fill;
  7046. }
  7047. while (fill !== false && visited.indexOf(fill) === -1) {
  7048. if (!isNumberFinite(fill)) {
  7049. return fill;
  7050. }
  7051. target = sources[fill];
  7052. if (!target) {
  7053. return false;
  7054. }
  7055. if (target.visible) {
  7056. return fill;
  7057. }
  7058. visited.push(fill);
  7059. fill = target.fill;
  7060. }
  7061. return false;
  7062. }
  7063. function _clip(ctx, target, clipY) {
  7064. ctx.beginPath();
  7065. target.path(ctx);
  7066. ctx.lineTo(target.last().x, clipY);
  7067. ctx.lineTo(target.first().x, clipY);
  7068. ctx.closePath();
  7069. ctx.clip();
  7070. }
  7071. function getBounds(property, first, last, loop) {
  7072. if (loop) {
  7073. return;
  7074. }
  7075. let start = first[property];
  7076. let end = last[property];
  7077. if (property === 'angle') {
  7078. start = _normalizeAngle(start);
  7079. end = _normalizeAngle(end);
  7080. }
  7081. return {property, start, end};
  7082. }
  7083. function _getEdge(a, b, prop, fn) {
  7084. if (a && b) {
  7085. return fn(a[prop], b[prop]);
  7086. }
  7087. return a ? a[prop] : b ? b[prop] : 0;
  7088. }
  7089. function _segments(line, target, property) {
  7090. const segments = line.segments;
  7091. const points = line.points;
  7092. const tpoints = target.points;
  7093. const parts = [];
  7094. for (const segment of segments) {
  7095. const bounds = getBounds(property, points[segment.start], points[segment.end], segment.loop);
  7096. if (!target.segments) {
  7097. parts.push({
  7098. source: segment,
  7099. target: bounds,
  7100. start: points[segment.start],
  7101. end: points[segment.end]
  7102. });
  7103. continue;
  7104. }
  7105. const targetSegments = _boundSegments(target, bounds);
  7106. for (const tgt of targetSegments) {
  7107. const subBounds = getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);
  7108. const fillSources = _boundSegment(segment, points, subBounds);
  7109. for (const fillSource of fillSources) {
  7110. parts.push({
  7111. source: fillSource,
  7112. target: tgt,
  7113. start: {
  7114. [property]: _getEdge(bounds, subBounds, 'start', Math.max)
  7115. },
  7116. end: {
  7117. [property]: _getEdge(bounds, subBounds, 'end', Math.min)
  7118. }
  7119. });
  7120. }
  7121. }
  7122. }
  7123. return parts;
  7124. }
  7125. function clipBounds(ctx, scale, bounds) {
  7126. const {top, bottom} = scale.chart.chartArea;
  7127. const {property, start, end} = bounds || {};
  7128. if (property === 'x') {
  7129. ctx.beginPath();
  7130. ctx.rect(start, top, end - start, bottom - top);
  7131. ctx.clip();
  7132. }
  7133. }
  7134. function interpolatedLineTo(ctx, target, point, property) {
  7135. const interpolatedPoint = target.interpolate(point, property);
  7136. if (interpolatedPoint) {
  7137. ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);
  7138. }
  7139. }
  7140. function _fill(ctx, cfg) {
  7141. const {line, target, property, color, scale} = cfg;
  7142. const segments = _segments(line, target, property);
  7143. for (const {source: src, target: tgt, start, end} of segments) {
  7144. const {style: {backgroundColor = color} = {}} = src;
  7145. ctx.save();
  7146. ctx.fillStyle = backgroundColor;
  7147. clipBounds(ctx, scale, getBounds(property, start, end));
  7148. ctx.beginPath();
  7149. const lineLoop = !!line.pathSegment(ctx, src);
  7150. if (lineLoop) {
  7151. ctx.closePath();
  7152. } else {
  7153. interpolatedLineTo(ctx, target, end, property);
  7154. }
  7155. const targetLoop = !!target.pathSegment(ctx, tgt, {move: lineLoop, reverse: true});
  7156. const loop = lineLoop && targetLoop;
  7157. if (!loop) {
  7158. interpolatedLineTo(ctx, target, start, property);
  7159. }
  7160. ctx.closePath();
  7161. ctx.fill(loop ? 'evenodd' : 'nonzero');
  7162. ctx.restore();
  7163. }
  7164. }
  7165. function doFill(ctx, cfg) {
  7166. const {line, target, above, below, area, scale} = cfg;
  7167. const property = line._loop ? 'angle' : cfg.axis;
  7168. ctx.save();
  7169. if (property === 'x' && below !== above) {
  7170. _clip(ctx, target, area.top);
  7171. _fill(ctx, {line, target, color: above, scale, property});
  7172. ctx.restore();
  7173. ctx.save();
  7174. _clip(ctx, target, area.bottom);
  7175. }
  7176. _fill(ctx, {line, target, color: below, scale, property});
  7177. ctx.restore();
  7178. }
  7179. function drawfill(ctx, source, area) {
  7180. const target = getTarget(source);
  7181. const {line, scale, axis} = source;
  7182. const lineOpts = line.options;
  7183. const fillOption = lineOpts.fill;
  7184. const color = lineOpts.backgroundColor;
  7185. const {above = color, below = color} = fillOption || {};
  7186. if (target && line.points.length) {
  7187. clipArea(ctx, area);
  7188. doFill(ctx, {line, target, above, below, area, scale, axis});
  7189. unclipArea(ctx);
  7190. }
  7191. }
  7192. var plugin_filler = {
  7193. id: 'filler',
  7194. afterDatasetsUpdate(chart, _args, options) {
  7195. const count = (chart.data.datasets || []).length;
  7196. const sources = [];
  7197. let meta, i, line, source;
  7198. for (i = 0; i < count; ++i) {
  7199. meta = chart.getDatasetMeta(i);
  7200. line = meta.dataset;
  7201. source = null;
  7202. if (line && line.options && line instanceof LineElement) {
  7203. source = {
  7204. visible: chart.isDatasetVisible(i),
  7205. index: i,
  7206. fill: decodeFill(line, i, count),
  7207. chart,
  7208. axis: meta.controller.options.indexAxis,
  7209. scale: meta.vScale,
  7210. line,
  7211. };
  7212. }
  7213. meta.$filler = source;
  7214. sources.push(source);
  7215. }
  7216. for (i = 0; i < count; ++i) {
  7217. source = sources[i];
  7218. if (!source || source.fill === false) {
  7219. continue;
  7220. }
  7221. source.fill = resolveTarget(sources, i, options.propagate);
  7222. }
  7223. },
  7224. beforeDraw(chart, _args, options) {
  7225. const draw = options.drawTime === 'beforeDraw';
  7226. const metasets = chart.getSortedVisibleDatasetMetas();
  7227. const area = chart.chartArea;
  7228. for (let i = metasets.length - 1; i >= 0; --i) {
  7229. const source = metasets[i].$filler;
  7230. if (!source) {
  7231. continue;
  7232. }
  7233. source.line.updateControlPoints(area);
  7234. if (draw) {
  7235. drawfill(chart.ctx, source, area);
  7236. }
  7237. }
  7238. },
  7239. beforeDatasetsDraw(chart, _args, options) {
  7240. if (options.drawTime !== 'beforeDatasetsDraw') {
  7241. return;
  7242. }
  7243. const metasets = chart.getSortedVisibleDatasetMetas();
  7244. for (let i = metasets.length - 1; i >= 0; --i) {
  7245. const source = metasets[i].$filler;
  7246. if (source) {
  7247. drawfill(chart.ctx, source, chart.chartArea);
  7248. }
  7249. }
  7250. },
  7251. beforeDatasetDraw(chart, args, options) {
  7252. const source = args.meta.$filler;
  7253. if (!source || source.fill === false || options.drawTime !== 'beforeDatasetDraw') {
  7254. return;
  7255. }
  7256. drawfill(chart.ctx, source, chart.chartArea);
  7257. },
  7258. defaults: {
  7259. propagate: true,
  7260. drawTime: 'beforeDatasetDraw'
  7261. }
  7262. };
  7263. const getBoxSize = (labelOpts, fontSize) => {
  7264. let {boxHeight = fontSize, boxWidth = fontSize} = labelOpts;
  7265. if (labelOpts.usePointStyle) {
  7266. boxHeight = Math.min(boxHeight, fontSize);
  7267. boxWidth = Math.min(boxWidth, fontSize);
  7268. }
  7269. return {
  7270. boxWidth,
  7271. boxHeight,
  7272. itemHeight: Math.max(fontSize, boxHeight)
  7273. };
  7274. };
  7275. const itemsEqual = (a, b) => a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;
  7276. class Legend extends Element {
  7277. constructor(config) {
  7278. super();
  7279. this._added = false;
  7280. this.legendHitBoxes = [];
  7281. this._hoveredItem = null;
  7282. this.doughnutMode = false;
  7283. this.chart = config.chart;
  7284. this.options = config.options;
  7285. this.ctx = config.ctx;
  7286. this.legendItems = undefined;
  7287. this.columnSizes = undefined;
  7288. this.lineWidths = undefined;
  7289. this.maxHeight = undefined;
  7290. this.maxWidth = undefined;
  7291. this.top = undefined;
  7292. this.bottom = undefined;
  7293. this.left = undefined;
  7294. this.right = undefined;
  7295. this.height = undefined;
  7296. this.width = undefined;
  7297. this._margins = undefined;
  7298. this.position = undefined;
  7299. this.weight = undefined;
  7300. this.fullSize = undefined;
  7301. }
  7302. update(maxWidth, maxHeight, margins) {
  7303. const me = this;
  7304. me.maxWidth = maxWidth;
  7305. me.maxHeight = maxHeight;
  7306. me._margins = margins;
  7307. me.setDimensions();
  7308. me.buildLabels();
  7309. me.fit();
  7310. }
  7311. setDimensions() {
  7312. const me = this;
  7313. if (me.isHorizontal()) {
  7314. me.width = me.maxWidth;
  7315. me.left = 0;
  7316. me.right = me.width;
  7317. } else {
  7318. me.height = me.maxHeight;
  7319. me.top = 0;
  7320. me.bottom = me.height;
  7321. }
  7322. }
  7323. buildLabels() {
  7324. const me = this;
  7325. const labelOpts = me.options.labels || {};
  7326. let legendItems = callback(labelOpts.generateLabels, [me.chart], me) || [];
  7327. if (labelOpts.filter) {
  7328. legendItems = legendItems.filter((item) => labelOpts.filter(item, me.chart.data));
  7329. }
  7330. if (labelOpts.sort) {
  7331. legendItems = legendItems.sort((a, b) => labelOpts.sort(a, b, me.chart.data));
  7332. }
  7333. if (me.options.reverse) {
  7334. legendItems.reverse();
  7335. }
  7336. me.legendItems = legendItems;
  7337. }
  7338. fit() {
  7339. const me = this;
  7340. const {options, ctx} = me;
  7341. if (!options.display) {
  7342. me.width = me.height = 0;
  7343. return;
  7344. }
  7345. const labelOpts = options.labels;
  7346. const labelFont = toFont(labelOpts.font);
  7347. const fontSize = labelFont.size;
  7348. const titleHeight = me._computeTitleHeight();
  7349. const {boxWidth, itemHeight} = getBoxSize(labelOpts, fontSize);
  7350. let width, height;
  7351. ctx.font = labelFont.string;
  7352. if (me.isHorizontal()) {
  7353. width = me.maxWidth;
  7354. height = me._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;
  7355. } else {
  7356. height = me.maxHeight;
  7357. width = me._fitCols(titleHeight, fontSize, boxWidth, itemHeight) + 10;
  7358. }
  7359. me.width = Math.min(width, options.maxWidth || me.maxWidth);
  7360. me.height = Math.min(height, options.maxHeight || me.maxHeight);
  7361. }
  7362. _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {
  7363. const me = this;
  7364. const {ctx, maxWidth, options: {labels: {padding}}} = me;
  7365. const hitboxes = me.legendHitBoxes = [];
  7366. const lineWidths = me.lineWidths = [0];
  7367. const lineHeight = itemHeight + padding;
  7368. let totalHeight = titleHeight;
  7369. ctx.textAlign = 'left';
  7370. ctx.textBaseline = 'middle';
  7371. let row = -1;
  7372. let top = -lineHeight;
  7373. me.legendItems.forEach((legendItem, i) => {
  7374. const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  7375. if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {
  7376. totalHeight += lineHeight;
  7377. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  7378. top += lineHeight;
  7379. row++;
  7380. }
  7381. hitboxes[i] = {left: 0, top, row, width: itemWidth, height: itemHeight};
  7382. lineWidths[lineWidths.length - 1] += itemWidth + padding;
  7383. });
  7384. return totalHeight;
  7385. }
  7386. _fitCols(titleHeight, fontSize, boxWidth, itemHeight) {
  7387. const me = this;
  7388. const {ctx, maxHeight, options: {labels: {padding}}} = me;
  7389. const hitboxes = me.legendHitBoxes = [];
  7390. const columnSizes = me.columnSizes = [];
  7391. const heightLimit = maxHeight - titleHeight;
  7392. let totalWidth = padding;
  7393. let currentColWidth = 0;
  7394. let currentColHeight = 0;
  7395. let left = 0;
  7396. let top = 0;
  7397. let col = 0;
  7398. me.legendItems.forEach((legendItem, i) => {
  7399. const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  7400. if (i > 0 && currentColHeight + fontSize + 2 * padding > heightLimit) {
  7401. totalWidth += currentColWidth + padding;
  7402. columnSizes.push({width: currentColWidth, height: currentColHeight});
  7403. left += currentColWidth + padding;
  7404. col++;
  7405. top = 0;
  7406. currentColWidth = currentColHeight = 0;
  7407. }
  7408. currentColWidth = Math.max(currentColWidth, itemWidth);
  7409. currentColHeight += fontSize + padding;
  7410. hitboxes[i] = {left, top, col, width: itemWidth, height: itemHeight};
  7411. top += itemHeight + padding;
  7412. });
  7413. totalWidth += currentColWidth;
  7414. columnSizes.push({width: currentColWidth, height: currentColHeight});
  7415. return totalWidth;
  7416. }
  7417. adjustHitBoxes() {
  7418. const me = this;
  7419. if (!me.options.display) {
  7420. return;
  7421. }
  7422. const titleHeight = me._computeTitleHeight();
  7423. const {legendHitBoxes: hitboxes, options: {align, labels: {padding}}} = me;
  7424. if (this.isHorizontal()) {
  7425. let row = 0;
  7426. let left = _alignStartEnd(align, me.left + padding, me.right - me.lineWidths[row]);
  7427. for (const hitbox of hitboxes) {
  7428. if (row !== hitbox.row) {
  7429. row = hitbox.row;
  7430. left = _alignStartEnd(align, me.left + padding, me.right - me.lineWidths[row]);
  7431. }
  7432. hitbox.top += me.top + titleHeight + padding;
  7433. hitbox.left = left;
  7434. left += hitbox.width + padding;
  7435. }
  7436. } else {
  7437. let col = 0;
  7438. let top = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - me.columnSizes[col].height);
  7439. for (const hitbox of hitboxes) {
  7440. if (hitbox.col !== col) {
  7441. col = hitbox.col;
  7442. top = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - me.columnSizes[col].height);
  7443. }
  7444. hitbox.top = top;
  7445. hitbox.left += me.left + padding;
  7446. top += hitbox.height + padding;
  7447. }
  7448. }
  7449. }
  7450. isHorizontal() {
  7451. return this.options.position === 'top' || this.options.position === 'bottom';
  7452. }
  7453. draw() {
  7454. const me = this;
  7455. if (me.options.display) {
  7456. const ctx = me.ctx;
  7457. clipArea(ctx, me);
  7458. me._draw();
  7459. unclipArea(ctx);
  7460. }
  7461. }
  7462. _draw() {
  7463. const me = this;
  7464. const {options: opts, columnSizes, lineWidths, ctx} = me;
  7465. const {align, labels: labelOpts} = opts;
  7466. const defaultColor = defaults.color;
  7467. const rtlHelper = getRtlAdapter(opts.rtl, me.left, me.width);
  7468. const labelFont = toFont(labelOpts.font);
  7469. const {color: fontColor, padding} = labelOpts;
  7470. const fontSize = labelFont.size;
  7471. const halfFontSize = fontSize / 2;
  7472. let cursor;
  7473. me.drawTitle();
  7474. ctx.textAlign = rtlHelper.textAlign('left');
  7475. ctx.textBaseline = 'middle';
  7476. ctx.lineWidth = 0.5;
  7477. ctx.font = labelFont.string;
  7478. const {boxWidth, boxHeight, itemHeight} = getBoxSize(labelOpts, fontSize);
  7479. const drawLegendBox = function(x, y, legendItem) {
  7480. if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {
  7481. return;
  7482. }
  7483. ctx.save();
  7484. const lineWidth = valueOrDefault(legendItem.lineWidth, 1);
  7485. ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);
  7486. ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt');
  7487. ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0);
  7488. ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter');
  7489. ctx.lineWidth = lineWidth;
  7490. ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor);
  7491. ctx.setLineDash(valueOrDefault(legendItem.lineDash, []));
  7492. if (labelOpts.usePointStyle) {
  7493. const drawOptions = {
  7494. radius: boxWidth * Math.SQRT2 / 2,
  7495. pointStyle: legendItem.pointStyle,
  7496. rotation: legendItem.rotation,
  7497. borderWidth: lineWidth
  7498. };
  7499. const centerX = rtlHelper.xPlus(x, boxWidth / 2);
  7500. const centerY = y + halfFontSize;
  7501. drawPoint(ctx, drawOptions, centerX, centerY);
  7502. } else {
  7503. const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);
  7504. const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);
  7505. const borderRadius = toTRBLCorners(legendItem.borderRadius);
  7506. ctx.beginPath();
  7507. if (Object.values(borderRadius).some(v => v !== 0)) {
  7508. addRoundedRectPath(ctx, {
  7509. x: xBoxLeft,
  7510. y: yBoxTop,
  7511. w: boxWidth,
  7512. h: boxHeight,
  7513. radius: borderRadius,
  7514. });
  7515. } else {
  7516. ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);
  7517. }
  7518. ctx.fill();
  7519. if (lineWidth !== 0) {
  7520. ctx.stroke();
  7521. }
  7522. }
  7523. ctx.restore();
  7524. };
  7525. const fillText = function(x, y, legendItem) {
  7526. renderText(ctx, legendItem.text, x, y + (itemHeight / 2), labelFont, {
  7527. strikethrough: legendItem.hidden,
  7528. textAlign: legendItem.textAlign
  7529. });
  7530. };
  7531. const isHorizontal = me.isHorizontal();
  7532. const titleHeight = this._computeTitleHeight();
  7533. if (isHorizontal) {
  7534. cursor = {
  7535. x: _alignStartEnd(align, me.left + padding, me.right - lineWidths[0]),
  7536. y: me.top + padding + titleHeight,
  7537. line: 0
  7538. };
  7539. } else {
  7540. cursor = {
  7541. x: me.left + padding,
  7542. y: _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - columnSizes[0].height),
  7543. line: 0
  7544. };
  7545. }
  7546. overrideTextDirection(me.ctx, opts.textDirection);
  7547. const lineHeight = itemHeight + padding;
  7548. me.legendItems.forEach((legendItem, i) => {
  7549. ctx.strokeStyle = legendItem.fontColor || fontColor;
  7550. ctx.fillStyle = legendItem.fontColor || fontColor;
  7551. const textWidth = ctx.measureText(legendItem.text).width;
  7552. const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));
  7553. const width = boxWidth + (fontSize / 2) + textWidth;
  7554. let x = cursor.x;
  7555. let y = cursor.y;
  7556. rtlHelper.setWidth(me.width);
  7557. if (isHorizontal) {
  7558. if (i > 0 && x + width + padding > me.right) {
  7559. y = cursor.y += lineHeight;
  7560. cursor.line++;
  7561. x = cursor.x = _alignStartEnd(align, me.left + padding, me.right - lineWidths[cursor.line]);
  7562. }
  7563. } else if (i > 0 && y + lineHeight > me.bottom) {
  7564. x = cursor.x = x + columnSizes[cursor.line].width + padding;
  7565. cursor.line++;
  7566. y = cursor.y = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - columnSizes[cursor.line].height);
  7567. }
  7568. const realX = rtlHelper.x(x);
  7569. drawLegendBox(realX, y, legendItem);
  7570. x = _textX(textAlign, x + boxWidth + halfFontSize, me.right);
  7571. fillText(rtlHelper.x(x), y, legendItem);
  7572. if (isHorizontal) {
  7573. cursor.x += width + padding;
  7574. } else {
  7575. cursor.y += lineHeight;
  7576. }
  7577. });
  7578. restoreTextDirection(me.ctx, opts.textDirection);
  7579. }
  7580. drawTitle() {
  7581. const me = this;
  7582. const opts = me.options;
  7583. const titleOpts = opts.title;
  7584. const titleFont = toFont(titleOpts.font);
  7585. const titlePadding = toPadding(titleOpts.padding);
  7586. if (!titleOpts.display) {
  7587. return;
  7588. }
  7589. const rtlHelper = getRtlAdapter(opts.rtl, me.left, me.width);
  7590. const ctx = me.ctx;
  7591. const position = titleOpts.position;
  7592. const halfFontSize = titleFont.size / 2;
  7593. const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;
  7594. let y;
  7595. let left = me.left;
  7596. let maxWidth = me.width;
  7597. if (this.isHorizontal()) {
  7598. maxWidth = Math.max(...me.lineWidths);
  7599. y = me.top + topPaddingPlusHalfFontSize;
  7600. left = _alignStartEnd(opts.align, left, me.right - maxWidth);
  7601. } else {
  7602. const maxHeight = me.columnSizes.reduce((acc, size) => Math.max(acc, size.height), 0);
  7603. y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, me.top, me.bottom - maxHeight - opts.labels.padding - me._computeTitleHeight());
  7604. }
  7605. const x = _alignStartEnd(position, left, left + maxWidth);
  7606. ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position));
  7607. ctx.textBaseline = 'middle';
  7608. ctx.strokeStyle = titleOpts.color;
  7609. ctx.fillStyle = titleOpts.color;
  7610. ctx.font = titleFont.string;
  7611. renderText(ctx, titleOpts.text, x, y, titleFont);
  7612. }
  7613. _computeTitleHeight() {
  7614. const titleOpts = this.options.title;
  7615. const titleFont = toFont(titleOpts.font);
  7616. const titlePadding = toPadding(titleOpts.padding);
  7617. return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
  7618. }
  7619. _getLegendItemAt(x, y) {
  7620. const me = this;
  7621. let i, hitBox, lh;
  7622. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  7623. lh = me.legendHitBoxes;
  7624. for (i = 0; i < lh.length; ++i) {
  7625. hitBox = lh[i];
  7626. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  7627. return me.legendItems[i];
  7628. }
  7629. }
  7630. }
  7631. return null;
  7632. }
  7633. handleEvent(e) {
  7634. const me = this;
  7635. const opts = me.options;
  7636. if (!isListened(e.type, opts)) {
  7637. return;
  7638. }
  7639. const hoveredItem = me._getLegendItemAt(e.x, e.y);
  7640. if (e.type === 'mousemove') {
  7641. const previous = me._hoveredItem;
  7642. const sameItem = itemsEqual(previous, hoveredItem);
  7643. if (previous && !sameItem) {
  7644. callback(opts.onLeave, [e, previous, me], me);
  7645. }
  7646. me._hoveredItem = hoveredItem;
  7647. if (hoveredItem && !sameItem) {
  7648. callback(opts.onHover, [e, hoveredItem, me], me);
  7649. }
  7650. } else if (hoveredItem) {
  7651. callback(opts.onClick, [e, hoveredItem, me], me);
  7652. }
  7653. }
  7654. }
  7655. function isListened(type, opts) {
  7656. if (type === 'mousemove' && (opts.onHover || opts.onLeave)) {
  7657. return true;
  7658. }
  7659. if (opts.onClick && (type === 'click' || type === 'mouseup')) {
  7660. return true;
  7661. }
  7662. return false;
  7663. }
  7664. var plugin_legend = {
  7665. id: 'legend',
  7666. _element: Legend,
  7667. start(chart, _args, options) {
  7668. const legend = chart.legend = new Legend({ctx: chart.ctx, options, chart});
  7669. layouts.configure(chart, legend, options);
  7670. layouts.addBox(chart, legend);
  7671. },
  7672. stop(chart) {
  7673. layouts.removeBox(chart, chart.legend);
  7674. delete chart.legend;
  7675. },
  7676. beforeUpdate(chart, _args, options) {
  7677. const legend = chart.legend;
  7678. layouts.configure(chart, legend, options);
  7679. legend.options = options;
  7680. },
  7681. afterUpdate(chart) {
  7682. const legend = chart.legend;
  7683. legend.buildLabels();
  7684. legend.adjustHitBoxes();
  7685. },
  7686. afterEvent(chart, args) {
  7687. if (!args.replay) {
  7688. chart.legend.handleEvent(args.event);
  7689. }
  7690. },
  7691. defaults: {
  7692. display: true,
  7693. position: 'top',
  7694. align: 'center',
  7695. fullSize: true,
  7696. reverse: false,
  7697. weight: 1000,
  7698. onClick(e, legendItem, legend) {
  7699. const index = legendItem.datasetIndex;
  7700. const ci = legend.chart;
  7701. if (ci.isDatasetVisible(index)) {
  7702. ci.hide(index);
  7703. legendItem.hidden = true;
  7704. } else {
  7705. ci.show(index);
  7706. legendItem.hidden = false;
  7707. }
  7708. },
  7709. onHover: null,
  7710. onLeave: null,
  7711. labels: {
  7712. color: (ctx) => ctx.chart.options.color,
  7713. boxWidth: 40,
  7714. padding: 10,
  7715. generateLabels(chart) {
  7716. const datasets = chart.data.datasets;
  7717. const {labels: {usePointStyle, pointStyle, textAlign, color}} = chart.legend.options;
  7718. return chart._getSortedDatasetMetas().map((meta) => {
  7719. const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  7720. const borderWidth = toPadding(style.borderWidth);
  7721. return {
  7722. text: datasets[meta.index].label,
  7723. fillStyle: style.backgroundColor,
  7724. fontColor: color,
  7725. hidden: !meta.visible,
  7726. lineCap: style.borderCapStyle,
  7727. lineDash: style.borderDash,
  7728. lineDashOffset: style.borderDashOffset,
  7729. lineJoin: style.borderJoinStyle,
  7730. lineWidth: (borderWidth.width + borderWidth.height) / 4,
  7731. strokeStyle: style.borderColor,
  7732. pointStyle: pointStyle || style.pointStyle,
  7733. rotation: style.rotation,
  7734. textAlign: textAlign || style.textAlign,
  7735. borderRadius: 0,
  7736. datasetIndex: meta.index
  7737. };
  7738. }, this);
  7739. }
  7740. },
  7741. title: {
  7742. color: (ctx) => ctx.chart.options.color,
  7743. display: false,
  7744. position: 'center',
  7745. text: '',
  7746. }
  7747. },
  7748. descriptors: {
  7749. _scriptable: (name) => !name.startsWith('on'),
  7750. labels: {
  7751. _scriptable: (name) => !['generateLabels', 'filter', 'sort'].includes(name),
  7752. }
  7753. },
  7754. };
  7755. class Title extends Element {
  7756. constructor(config) {
  7757. super();
  7758. this.chart = config.chart;
  7759. this.options = config.options;
  7760. this.ctx = config.ctx;
  7761. this._padding = undefined;
  7762. this.top = undefined;
  7763. this.bottom = undefined;
  7764. this.left = undefined;
  7765. this.right = undefined;
  7766. this.width = undefined;
  7767. this.height = undefined;
  7768. this.position = undefined;
  7769. this.weight = undefined;
  7770. this.fullSize = undefined;
  7771. }
  7772. update(maxWidth, maxHeight) {
  7773. const me = this;
  7774. const opts = me.options;
  7775. me.left = 0;
  7776. me.top = 0;
  7777. if (!opts.display) {
  7778. me.width = me.height = me.right = me.bottom = 0;
  7779. return;
  7780. }
  7781. me.width = me.right = maxWidth;
  7782. me.height = me.bottom = maxHeight;
  7783. const lineCount = isArray(opts.text) ? opts.text.length : 1;
  7784. me._padding = toPadding(opts.padding);
  7785. const textSize = lineCount * toFont(opts.font).lineHeight + me._padding.height;
  7786. if (me.isHorizontal()) {
  7787. me.height = textSize;
  7788. } else {
  7789. me.width = textSize;
  7790. }
  7791. }
  7792. isHorizontal() {
  7793. const pos = this.options.position;
  7794. return pos === 'top' || pos === 'bottom';
  7795. }
  7796. _drawArgs(offset) {
  7797. const {top, left, bottom, right, options} = this;
  7798. const align = options.align;
  7799. let rotation = 0;
  7800. let maxWidth, titleX, titleY;
  7801. if (this.isHorizontal()) {
  7802. titleX = _alignStartEnd(align, left, right);
  7803. titleY = top + offset;
  7804. maxWidth = right - left;
  7805. } else {
  7806. if (options.position === 'left') {
  7807. titleX = left + offset;
  7808. titleY = _alignStartEnd(align, bottom, top);
  7809. rotation = PI * -0.5;
  7810. } else {
  7811. titleX = right - offset;
  7812. titleY = _alignStartEnd(align, top, bottom);
  7813. rotation = PI * 0.5;
  7814. }
  7815. maxWidth = bottom - top;
  7816. }
  7817. return {titleX, titleY, maxWidth, rotation};
  7818. }
  7819. draw() {
  7820. const me = this;
  7821. const ctx = me.ctx;
  7822. const opts = me.options;
  7823. if (!opts.display) {
  7824. return;
  7825. }
  7826. const fontOpts = toFont(opts.font);
  7827. const lineHeight = fontOpts.lineHeight;
  7828. const offset = lineHeight / 2 + me._padding.top;
  7829. const {titleX, titleY, maxWidth, rotation} = me._drawArgs(offset);
  7830. renderText(ctx, opts.text, 0, 0, fontOpts, {
  7831. color: opts.color,
  7832. maxWidth,
  7833. rotation,
  7834. textAlign: _toLeftRightCenter(opts.align),
  7835. textBaseline: 'middle',
  7836. translation: [titleX, titleY],
  7837. });
  7838. }
  7839. }
  7840. function createTitle(chart, titleOpts) {
  7841. const title = new Title({
  7842. ctx: chart.ctx,
  7843. options: titleOpts,
  7844. chart
  7845. });
  7846. layouts.configure(chart, title, titleOpts);
  7847. layouts.addBox(chart, title);
  7848. chart.titleBlock = title;
  7849. }
  7850. var plugin_title = {
  7851. id: 'title',
  7852. _element: Title,
  7853. start(chart, _args, options) {
  7854. createTitle(chart, options);
  7855. },
  7856. stop(chart) {
  7857. const titleBlock = chart.titleBlock;
  7858. layouts.removeBox(chart, titleBlock);
  7859. delete chart.titleBlock;
  7860. },
  7861. beforeUpdate(chart, _args, options) {
  7862. const title = chart.titleBlock;
  7863. layouts.configure(chart, title, options);
  7864. title.options = options;
  7865. },
  7866. defaults: {
  7867. align: 'center',
  7868. display: false,
  7869. font: {
  7870. weight: 'bold',
  7871. },
  7872. fullSize: true,
  7873. padding: 10,
  7874. position: 'top',
  7875. text: '',
  7876. weight: 2000
  7877. },
  7878. defaultRoutes: {
  7879. color: 'color'
  7880. },
  7881. descriptors: {
  7882. _scriptable: true,
  7883. _indexable: false,
  7884. },
  7885. };
  7886. const positioners = {
  7887. average(items) {
  7888. if (!items.length) {
  7889. return false;
  7890. }
  7891. let i, len;
  7892. let x = 0;
  7893. let y = 0;
  7894. let count = 0;
  7895. for (i = 0, len = items.length; i < len; ++i) {
  7896. const el = items[i].element;
  7897. if (el && el.hasValue()) {
  7898. const pos = el.tooltipPosition();
  7899. x += pos.x;
  7900. y += pos.y;
  7901. ++count;
  7902. }
  7903. }
  7904. return {
  7905. x: x / count,
  7906. y: y / count
  7907. };
  7908. },
  7909. nearest(items, eventPosition) {
  7910. if (!items.length) {
  7911. return false;
  7912. }
  7913. let x = eventPosition.x;
  7914. let y = eventPosition.y;
  7915. let minDistance = Number.POSITIVE_INFINITY;
  7916. let i, len, nearestElement;
  7917. for (i = 0, len = items.length; i < len; ++i) {
  7918. const el = items[i].element;
  7919. if (el && el.hasValue()) {
  7920. const center = el.getCenterPoint();
  7921. const d = distanceBetweenPoints(eventPosition, center);
  7922. if (d < minDistance) {
  7923. minDistance = d;
  7924. nearestElement = el;
  7925. }
  7926. }
  7927. }
  7928. if (nearestElement) {
  7929. const tp = nearestElement.tooltipPosition();
  7930. x = tp.x;
  7931. y = tp.y;
  7932. }
  7933. return {
  7934. x,
  7935. y
  7936. };
  7937. }
  7938. };
  7939. function pushOrConcat(base, toPush) {
  7940. if (toPush) {
  7941. if (isArray(toPush)) {
  7942. Array.prototype.push.apply(base, toPush);
  7943. } else {
  7944. base.push(toPush);
  7945. }
  7946. }
  7947. return base;
  7948. }
  7949. function splitNewlines(str) {
  7950. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  7951. return str.split('\n');
  7952. }
  7953. return str;
  7954. }
  7955. function createTooltipItem(chart, item) {
  7956. const {element, datasetIndex, index} = item;
  7957. const controller = chart.getDatasetMeta(datasetIndex).controller;
  7958. const {label, value} = controller.getLabelAndValue(index);
  7959. return {
  7960. chart,
  7961. label,
  7962. parsed: controller.getParsed(index),
  7963. raw: chart.data.datasets[datasetIndex].data[index],
  7964. formattedValue: value,
  7965. dataset: controller.getDataset(),
  7966. dataIndex: index,
  7967. datasetIndex,
  7968. element
  7969. };
  7970. }
  7971. function getTooltipSize(tooltip, options) {
  7972. const ctx = tooltip._chart.ctx;
  7973. const {body, footer, title} = tooltip;
  7974. const {boxWidth, boxHeight} = options;
  7975. const bodyFont = toFont(options.bodyFont);
  7976. const titleFont = toFont(options.titleFont);
  7977. const footerFont = toFont(options.footerFont);
  7978. const titleLineCount = title.length;
  7979. const footerLineCount = footer.length;
  7980. const bodyLineItemCount = body.length;
  7981. const padding = toPadding(options.padding);
  7982. let height = padding.height;
  7983. let width = 0;
  7984. let combinedBodyLength = body.reduce((count, bodyItem) => count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);
  7985. combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;
  7986. if (titleLineCount) {
  7987. height += titleLineCount * titleFont.lineHeight
  7988. + (titleLineCount - 1) * options.titleSpacing
  7989. + options.titleMarginBottom;
  7990. }
  7991. if (combinedBodyLength) {
  7992. const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;
  7993. height += bodyLineItemCount * bodyLineHeight
  7994. + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight
  7995. + (combinedBodyLength - 1) * options.bodySpacing;
  7996. }
  7997. if (footerLineCount) {
  7998. height += options.footerMarginTop
  7999. + footerLineCount * footerFont.lineHeight
  8000. + (footerLineCount - 1) * options.footerSpacing;
  8001. }
  8002. let widthPadding = 0;
  8003. const maxLineWidth = function(line) {
  8004. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  8005. };
  8006. ctx.save();
  8007. ctx.font = titleFont.string;
  8008. each(tooltip.title, maxLineWidth);
  8009. ctx.font = bodyFont.string;
  8010. each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);
  8011. widthPadding = options.displayColors ? (boxWidth + 2) : 0;
  8012. each(body, (bodyItem) => {
  8013. each(bodyItem.before, maxLineWidth);
  8014. each(bodyItem.lines, maxLineWidth);
  8015. each(bodyItem.after, maxLineWidth);
  8016. });
  8017. widthPadding = 0;
  8018. ctx.font = footerFont.string;
  8019. each(tooltip.footer, maxLineWidth);
  8020. ctx.restore();
  8021. width += padding.width;
  8022. return {width, height};
  8023. }
  8024. function determineYAlign(chart, size) {
  8025. const {y, height} = size;
  8026. if (y < height / 2) {
  8027. return 'top';
  8028. } else if (y > (chart.height - height / 2)) {
  8029. return 'bottom';
  8030. }
  8031. return 'center';
  8032. }
  8033. function doesNotFitWithAlign(xAlign, chart, options, size) {
  8034. const {x, width} = size;
  8035. const caret = options.caretSize + options.caretPadding;
  8036. if (xAlign === 'left' && x + width + caret > chart.width) {
  8037. return true;
  8038. }
  8039. if (xAlign === 'right' && x - width - caret < 0) {
  8040. return true;
  8041. }
  8042. }
  8043. function determineXAlign(chart, options, size, yAlign) {
  8044. const {x, width} = size;
  8045. const {width: chartWidth, chartArea: {left, right}} = chart;
  8046. let xAlign = 'center';
  8047. if (yAlign === 'center') {
  8048. xAlign = x <= (left + right) / 2 ? 'left' : 'right';
  8049. } else if (x <= width / 2) {
  8050. xAlign = 'left';
  8051. } else if (x >= chartWidth - width / 2) {
  8052. xAlign = 'right';
  8053. }
  8054. if (doesNotFitWithAlign(xAlign, chart, options, size)) {
  8055. xAlign = 'center';
  8056. }
  8057. return xAlign;
  8058. }
  8059. function determineAlignment(chart, options, size) {
  8060. const yAlign = options.yAlign || determineYAlign(chart, size);
  8061. return {
  8062. xAlign: options.xAlign || determineXAlign(chart, options, size, yAlign),
  8063. yAlign
  8064. };
  8065. }
  8066. function alignX(size, xAlign) {
  8067. let {x, width} = size;
  8068. if (xAlign === 'right') {
  8069. x -= width;
  8070. } else if (xAlign === 'center') {
  8071. x -= (width / 2);
  8072. }
  8073. return x;
  8074. }
  8075. function alignY(size, yAlign, paddingAndSize) {
  8076. let {y, height} = size;
  8077. if (yAlign === 'top') {
  8078. y += paddingAndSize;
  8079. } else if (yAlign === 'bottom') {
  8080. y -= height + paddingAndSize;
  8081. } else {
  8082. y -= (height / 2);
  8083. }
  8084. return y;
  8085. }
  8086. function getBackgroundPoint(options, size, alignment, chart) {
  8087. const {caretSize, caretPadding, cornerRadius} = options;
  8088. const {xAlign, yAlign} = alignment;
  8089. const paddingAndSize = caretSize + caretPadding;
  8090. const radiusAndPadding = cornerRadius + caretPadding;
  8091. let x = alignX(size, xAlign);
  8092. const y = alignY(size, yAlign, paddingAndSize);
  8093. if (yAlign === 'center') {
  8094. if (xAlign === 'left') {
  8095. x += paddingAndSize;
  8096. } else if (xAlign === 'right') {
  8097. x -= paddingAndSize;
  8098. }
  8099. } else if (xAlign === 'left') {
  8100. x -= radiusAndPadding;
  8101. } else if (xAlign === 'right') {
  8102. x += radiusAndPadding;
  8103. }
  8104. return {
  8105. x: _limitValue(x, 0, chart.width - size.width),
  8106. y: _limitValue(y, 0, chart.height - size.height)
  8107. };
  8108. }
  8109. function getAlignedX(tooltip, align, options) {
  8110. const padding = toPadding(options.padding);
  8111. return align === 'center'
  8112. ? tooltip.x + tooltip.width / 2
  8113. : align === 'right'
  8114. ? tooltip.x + tooltip.width - padding.right
  8115. : tooltip.x + padding.left;
  8116. }
  8117. function getBeforeAfterBodyLines(callback) {
  8118. return pushOrConcat([], splitNewlines(callback));
  8119. }
  8120. function createTooltipContext(parent, tooltip, tooltipItems) {
  8121. return Object.assign(Object.create(parent), {
  8122. tooltip,
  8123. tooltipItems,
  8124. type: 'tooltip'
  8125. });
  8126. }
  8127. function overrideCallbacks(callbacks, context) {
  8128. const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;
  8129. return override ? callbacks.override(override) : callbacks;
  8130. }
  8131. class Tooltip extends Element {
  8132. constructor(config) {
  8133. super();
  8134. this.opacity = 0;
  8135. this._active = [];
  8136. this._chart = config._chart;
  8137. this._eventPosition = undefined;
  8138. this._size = undefined;
  8139. this._cachedAnimations = undefined;
  8140. this._tooltipItems = [];
  8141. this.$animations = undefined;
  8142. this.$context = undefined;
  8143. this.options = config.options;
  8144. this.dataPoints = undefined;
  8145. this.title = undefined;
  8146. this.beforeBody = undefined;
  8147. this.body = undefined;
  8148. this.afterBody = undefined;
  8149. this.footer = undefined;
  8150. this.xAlign = undefined;
  8151. this.yAlign = undefined;
  8152. this.x = undefined;
  8153. this.y = undefined;
  8154. this.height = undefined;
  8155. this.width = undefined;
  8156. this.caretX = undefined;
  8157. this.caretY = undefined;
  8158. this.labelColors = undefined;
  8159. this.labelPointStyles = undefined;
  8160. this.labelTextColors = undefined;
  8161. }
  8162. initialize(options) {
  8163. this.options = options;
  8164. this._cachedAnimations = undefined;
  8165. this.$context = undefined;
  8166. }
  8167. _resolveAnimations() {
  8168. const me = this;
  8169. const cached = me._cachedAnimations;
  8170. if (cached) {
  8171. return cached;
  8172. }
  8173. const chart = me._chart;
  8174. const options = me.options.setContext(me.getContext());
  8175. const opts = options.enabled && chart.options.animation && options.animations;
  8176. const animations = new Animations(me._chart, opts);
  8177. if (opts._cacheable) {
  8178. me._cachedAnimations = Object.freeze(animations);
  8179. }
  8180. return animations;
  8181. }
  8182. getContext() {
  8183. const me = this;
  8184. return me.$context ||
  8185. (me.$context = createTooltipContext(me._chart.getContext(), me, me._tooltipItems));
  8186. }
  8187. getTitle(context, options) {
  8188. const me = this;
  8189. const {callbacks} = options;
  8190. const beforeTitle = callbacks.beforeTitle.apply(me, [context]);
  8191. const title = callbacks.title.apply(me, [context]);
  8192. const afterTitle = callbacks.afterTitle.apply(me, [context]);
  8193. let lines = [];
  8194. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  8195. lines = pushOrConcat(lines, splitNewlines(title));
  8196. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  8197. return lines;
  8198. }
  8199. getBeforeBody(tooltipItems, options) {
  8200. return getBeforeAfterBodyLines(options.callbacks.beforeBody.apply(this, [tooltipItems]));
  8201. }
  8202. getBody(tooltipItems, options) {
  8203. const me = this;
  8204. const {callbacks} = options;
  8205. const bodyItems = [];
  8206. each(tooltipItems, (context) => {
  8207. const bodyItem = {
  8208. before: [],
  8209. lines: [],
  8210. after: []
  8211. };
  8212. const scoped = overrideCallbacks(callbacks, context);
  8213. pushOrConcat(bodyItem.before, splitNewlines(scoped.beforeLabel.call(me, context)));
  8214. pushOrConcat(bodyItem.lines, scoped.label.call(me, context));
  8215. pushOrConcat(bodyItem.after, splitNewlines(scoped.afterLabel.call(me, context)));
  8216. bodyItems.push(bodyItem);
  8217. });
  8218. return bodyItems;
  8219. }
  8220. getAfterBody(tooltipItems, options) {
  8221. return getBeforeAfterBodyLines(options.callbacks.afterBody.apply(this, [tooltipItems]));
  8222. }
  8223. getFooter(tooltipItems, options) {
  8224. const me = this;
  8225. const {callbacks} = options;
  8226. const beforeFooter = callbacks.beforeFooter.apply(me, [tooltipItems]);
  8227. const footer = callbacks.footer.apply(me, [tooltipItems]);
  8228. const afterFooter = callbacks.afterFooter.apply(me, [tooltipItems]);
  8229. let lines = [];
  8230. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  8231. lines = pushOrConcat(lines, splitNewlines(footer));
  8232. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  8233. return lines;
  8234. }
  8235. _createItems(options) {
  8236. const me = this;
  8237. const active = me._active;
  8238. const data = me._chart.data;
  8239. const labelColors = [];
  8240. const labelPointStyles = [];
  8241. const labelTextColors = [];
  8242. let tooltipItems = [];
  8243. let i, len;
  8244. for (i = 0, len = active.length; i < len; ++i) {
  8245. tooltipItems.push(createTooltipItem(me._chart, active[i]));
  8246. }
  8247. if (options.filter) {
  8248. tooltipItems = tooltipItems.filter((element, index, array) => options.filter(element, index, array, data));
  8249. }
  8250. if (options.itemSort) {
  8251. tooltipItems = tooltipItems.sort((a, b) => options.itemSort(a, b, data));
  8252. }
  8253. each(tooltipItems, (context) => {
  8254. const scoped = overrideCallbacks(options.callbacks, context);
  8255. labelColors.push(scoped.labelColor.call(me, context));
  8256. labelPointStyles.push(scoped.labelPointStyle.call(me, context));
  8257. labelTextColors.push(scoped.labelTextColor.call(me, context));
  8258. });
  8259. me.labelColors = labelColors;
  8260. me.labelPointStyles = labelPointStyles;
  8261. me.labelTextColors = labelTextColors;
  8262. me.dataPoints = tooltipItems;
  8263. return tooltipItems;
  8264. }
  8265. update(changed, replay) {
  8266. const me = this;
  8267. const options = me.options.setContext(me.getContext());
  8268. const active = me._active;
  8269. let properties;
  8270. let tooltipItems = [];
  8271. if (!active.length) {
  8272. if (me.opacity !== 0) {
  8273. properties = {
  8274. opacity: 0
  8275. };
  8276. }
  8277. } else {
  8278. const position = positioners[options.position].call(me, active, me._eventPosition);
  8279. tooltipItems = me._createItems(options);
  8280. me.title = me.getTitle(tooltipItems, options);
  8281. me.beforeBody = me.getBeforeBody(tooltipItems, options);
  8282. me.body = me.getBody(tooltipItems, options);
  8283. me.afterBody = me.getAfterBody(tooltipItems, options);
  8284. me.footer = me.getFooter(tooltipItems, options);
  8285. const size = me._size = getTooltipSize(me, options);
  8286. const positionAndSize = Object.assign({}, position, size);
  8287. const alignment = determineAlignment(me._chart, options, positionAndSize);
  8288. const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, me._chart);
  8289. me.xAlign = alignment.xAlign;
  8290. me.yAlign = alignment.yAlign;
  8291. properties = {
  8292. opacity: 1,
  8293. x: backgroundPoint.x,
  8294. y: backgroundPoint.y,
  8295. width: size.width,
  8296. height: size.height,
  8297. caretX: position.x,
  8298. caretY: position.y
  8299. };
  8300. }
  8301. me._tooltipItems = tooltipItems;
  8302. me.$context = undefined;
  8303. if (properties) {
  8304. me._resolveAnimations().update(me, properties);
  8305. }
  8306. if (changed && options.external) {
  8307. options.external.call(me, {chart: me._chart, tooltip: me, replay});
  8308. }
  8309. }
  8310. drawCaret(tooltipPoint, ctx, size, options) {
  8311. const caretPosition = this.getCaretPosition(tooltipPoint, size, options);
  8312. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  8313. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  8314. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  8315. }
  8316. getCaretPosition(tooltipPoint, size, options) {
  8317. const {xAlign, yAlign} = this;
  8318. const {cornerRadius, caretSize} = options;
  8319. const {x: ptX, y: ptY} = tooltipPoint;
  8320. const {width, height} = size;
  8321. let x1, x2, x3, y1, y2, y3;
  8322. if (yAlign === 'center') {
  8323. y2 = ptY + (height / 2);
  8324. if (xAlign === 'left') {
  8325. x1 = ptX;
  8326. x2 = x1 - caretSize;
  8327. y1 = y2 + caretSize;
  8328. y3 = y2 - caretSize;
  8329. } else {
  8330. x1 = ptX + width;
  8331. x2 = x1 + caretSize;
  8332. y1 = y2 - caretSize;
  8333. y3 = y2 + caretSize;
  8334. }
  8335. x3 = x1;
  8336. } else {
  8337. if (xAlign === 'left') {
  8338. x2 = ptX + cornerRadius + (caretSize);
  8339. } else if (xAlign === 'right') {
  8340. x2 = ptX + width - cornerRadius - caretSize;
  8341. } else {
  8342. x2 = this.caretX;
  8343. }
  8344. if (yAlign === 'top') {
  8345. y1 = ptY;
  8346. y2 = y1 - caretSize;
  8347. x1 = x2 - caretSize;
  8348. x3 = x2 + caretSize;
  8349. } else {
  8350. y1 = ptY + height;
  8351. y2 = y1 + caretSize;
  8352. x1 = x2 + caretSize;
  8353. x3 = x2 - caretSize;
  8354. }
  8355. y3 = y1;
  8356. }
  8357. return {x1, x2, x3, y1, y2, y3};
  8358. }
  8359. drawTitle(pt, ctx, options) {
  8360. const me = this;
  8361. const title = me.title;
  8362. const length = title.length;
  8363. let titleFont, titleSpacing, i;
  8364. if (length) {
  8365. const rtlHelper = getRtlAdapter(options.rtl, me.x, me.width);
  8366. pt.x = getAlignedX(me, options.titleAlign, options);
  8367. ctx.textAlign = rtlHelper.textAlign(options.titleAlign);
  8368. ctx.textBaseline = 'middle';
  8369. titleFont = toFont(options.titleFont);
  8370. titleSpacing = options.titleSpacing;
  8371. ctx.fillStyle = options.titleColor;
  8372. ctx.font = titleFont.string;
  8373. for (i = 0; i < length; ++i) {
  8374. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);
  8375. pt.y += titleFont.lineHeight + titleSpacing;
  8376. if (i + 1 === length) {
  8377. pt.y += options.titleMarginBottom - titleSpacing;
  8378. }
  8379. }
  8380. }
  8381. }
  8382. _drawColorBox(ctx, pt, i, rtlHelper, options) {
  8383. const me = this;
  8384. const labelColors = me.labelColors[i];
  8385. const labelPointStyle = me.labelPointStyles[i];
  8386. const {boxHeight, boxWidth} = options;
  8387. const bodyFont = toFont(options.bodyFont);
  8388. const colorX = getAlignedX(me, 'left', options);
  8389. const rtlColorX = rtlHelper.x(colorX);
  8390. const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;
  8391. const colorY = pt.y + yOffSet;
  8392. if (options.usePointStyle) {
  8393. const drawOptions = {
  8394. radius: Math.min(boxWidth, boxHeight) / 2,
  8395. pointStyle: labelPointStyle.pointStyle,
  8396. rotation: labelPointStyle.rotation,
  8397. borderWidth: 1
  8398. };
  8399. const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;
  8400. const centerY = colorY + boxHeight / 2;
  8401. ctx.strokeStyle = options.multiKeyBackground;
  8402. ctx.fillStyle = options.multiKeyBackground;
  8403. drawPoint(ctx, drawOptions, centerX, centerY);
  8404. ctx.strokeStyle = labelColors.borderColor;
  8405. ctx.fillStyle = labelColors.backgroundColor;
  8406. drawPoint(ctx, drawOptions, centerX, centerY);
  8407. } else {
  8408. ctx.lineWidth = labelColors.borderWidth || 1;
  8409. ctx.strokeStyle = labelColors.borderColor;
  8410. ctx.setLineDash(labelColors.borderDash || []);
  8411. ctx.lineDashOffset = labelColors.borderDashOffset || 0;
  8412. const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth);
  8413. const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2);
  8414. const borderRadius = toTRBLCorners(labelColors.borderRadius);
  8415. if (Object.values(borderRadius).some(v => v !== 0)) {
  8416. ctx.beginPath();
  8417. ctx.fillStyle = options.multiKeyBackground;
  8418. addRoundedRectPath(ctx, {
  8419. x: outerX,
  8420. y: colorY,
  8421. w: boxWidth,
  8422. h: boxHeight,
  8423. radius: borderRadius,
  8424. });
  8425. ctx.fill();
  8426. ctx.stroke();
  8427. ctx.fillStyle = labelColors.backgroundColor;
  8428. ctx.beginPath();
  8429. addRoundedRectPath(ctx, {
  8430. x: innerX,
  8431. y: colorY + 1,
  8432. w: boxWidth - 2,
  8433. h: boxHeight - 2,
  8434. radius: borderRadius,
  8435. });
  8436. ctx.fill();
  8437. } else {
  8438. ctx.fillStyle = options.multiKeyBackground;
  8439. ctx.fillRect(outerX, colorY, boxWidth, boxHeight);
  8440. ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);
  8441. ctx.fillStyle = labelColors.backgroundColor;
  8442. ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);
  8443. }
  8444. }
  8445. ctx.fillStyle = me.labelTextColors[i];
  8446. }
  8447. drawBody(pt, ctx, options) {
  8448. const me = this;
  8449. const {body} = me;
  8450. const {bodySpacing, bodyAlign, displayColors, boxHeight, boxWidth} = options;
  8451. const bodyFont = toFont(options.bodyFont);
  8452. let bodyLineHeight = bodyFont.lineHeight;
  8453. let xLinePadding = 0;
  8454. const rtlHelper = getRtlAdapter(options.rtl, me.x, me.width);
  8455. const fillLineOfText = function(line) {
  8456. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);
  8457. pt.y += bodyLineHeight + bodySpacing;
  8458. };
  8459. const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  8460. let bodyItem, textColor, lines, i, j, ilen, jlen;
  8461. ctx.textAlign = bodyAlign;
  8462. ctx.textBaseline = 'middle';
  8463. ctx.font = bodyFont.string;
  8464. pt.x = getAlignedX(me, bodyAlignForCalculation, options);
  8465. ctx.fillStyle = options.bodyColor;
  8466. each(me.beforeBody, fillLineOfText);
  8467. xLinePadding = displayColors && bodyAlignForCalculation !== 'right'
  8468. ? bodyAlign === 'center' ? (boxWidth / 2 + 1) : (boxWidth + 2)
  8469. : 0;
  8470. for (i = 0, ilen = body.length; i < ilen; ++i) {
  8471. bodyItem = body[i];
  8472. textColor = me.labelTextColors[i];
  8473. ctx.fillStyle = textColor;
  8474. each(bodyItem.before, fillLineOfText);
  8475. lines = bodyItem.lines;
  8476. if (displayColors && lines.length) {
  8477. me._drawColorBox(ctx, pt, i, rtlHelper, options);
  8478. bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);
  8479. }
  8480. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  8481. fillLineOfText(lines[j]);
  8482. bodyLineHeight = bodyFont.lineHeight;
  8483. }
  8484. each(bodyItem.after, fillLineOfText);
  8485. }
  8486. xLinePadding = 0;
  8487. bodyLineHeight = bodyFont.lineHeight;
  8488. each(me.afterBody, fillLineOfText);
  8489. pt.y -= bodySpacing;
  8490. }
  8491. drawFooter(pt, ctx, options) {
  8492. const me = this;
  8493. const footer = me.footer;
  8494. const length = footer.length;
  8495. let footerFont, i;
  8496. if (length) {
  8497. const rtlHelper = getRtlAdapter(options.rtl, me.x, me.width);
  8498. pt.x = getAlignedX(me, options.footerAlign, options);
  8499. pt.y += options.footerMarginTop;
  8500. ctx.textAlign = rtlHelper.textAlign(options.footerAlign);
  8501. ctx.textBaseline = 'middle';
  8502. footerFont = toFont(options.footerFont);
  8503. ctx.fillStyle = options.footerColor;
  8504. ctx.font = footerFont.string;
  8505. for (i = 0; i < length; ++i) {
  8506. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);
  8507. pt.y += footerFont.lineHeight + options.footerSpacing;
  8508. }
  8509. }
  8510. }
  8511. drawBackground(pt, ctx, tooltipSize, options) {
  8512. const {xAlign, yAlign} = this;
  8513. const {x, y} = pt;
  8514. const {width, height} = tooltipSize;
  8515. const radius = options.cornerRadius;
  8516. ctx.fillStyle = options.backgroundColor;
  8517. ctx.strokeStyle = options.borderColor;
  8518. ctx.lineWidth = options.borderWidth;
  8519. ctx.beginPath();
  8520. ctx.moveTo(x + radius, y);
  8521. if (yAlign === 'top') {
  8522. this.drawCaret(pt, ctx, tooltipSize, options);
  8523. }
  8524. ctx.lineTo(x + width - radius, y);
  8525. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  8526. if (yAlign === 'center' && xAlign === 'right') {
  8527. this.drawCaret(pt, ctx, tooltipSize, options);
  8528. }
  8529. ctx.lineTo(x + width, y + height - radius);
  8530. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  8531. if (yAlign === 'bottom') {
  8532. this.drawCaret(pt, ctx, tooltipSize, options);
  8533. }
  8534. ctx.lineTo(x + radius, y + height);
  8535. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  8536. if (yAlign === 'center' && xAlign === 'left') {
  8537. this.drawCaret(pt, ctx, tooltipSize, options);
  8538. }
  8539. ctx.lineTo(x, y + radius);
  8540. ctx.quadraticCurveTo(x, y, x + radius, y);
  8541. ctx.closePath();
  8542. ctx.fill();
  8543. if (options.borderWidth > 0) {
  8544. ctx.stroke();
  8545. }
  8546. }
  8547. _updateAnimationTarget(options) {
  8548. const me = this;
  8549. const chart = me._chart;
  8550. const anims = me.$animations;
  8551. const animX = anims && anims.x;
  8552. const animY = anims && anims.y;
  8553. if (animX || animY) {
  8554. const position = positioners[options.position].call(me, me._active, me._eventPosition);
  8555. if (!position) {
  8556. return;
  8557. }
  8558. const size = me._size = getTooltipSize(me, options);
  8559. const positionAndSize = Object.assign({}, position, me._size);
  8560. const alignment = determineAlignment(chart, options, positionAndSize);
  8561. const point = getBackgroundPoint(options, positionAndSize, alignment, chart);
  8562. if (animX._to !== point.x || animY._to !== point.y) {
  8563. me.xAlign = alignment.xAlign;
  8564. me.yAlign = alignment.yAlign;
  8565. me.width = size.width;
  8566. me.height = size.height;
  8567. me.caretX = position.x;
  8568. me.caretY = position.y;
  8569. me._resolveAnimations().update(me, point);
  8570. }
  8571. }
  8572. }
  8573. draw(ctx) {
  8574. const me = this;
  8575. const options = me.options.setContext(me.getContext());
  8576. let opacity = me.opacity;
  8577. if (!opacity) {
  8578. return;
  8579. }
  8580. me._updateAnimationTarget(options);
  8581. const tooltipSize = {
  8582. width: me.width,
  8583. height: me.height
  8584. };
  8585. const pt = {
  8586. x: me.x,
  8587. y: me.y
  8588. };
  8589. opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
  8590. const padding = toPadding(options.padding);
  8591. const hasTooltipContent = me.title.length || me.beforeBody.length || me.body.length || me.afterBody.length || me.footer.length;
  8592. if (options.enabled && hasTooltipContent) {
  8593. ctx.save();
  8594. ctx.globalAlpha = opacity;
  8595. me.drawBackground(pt, ctx, tooltipSize, options);
  8596. overrideTextDirection(ctx, options.textDirection);
  8597. pt.y += padding.top;
  8598. me.drawTitle(pt, ctx, options);
  8599. me.drawBody(pt, ctx, options);
  8600. me.drawFooter(pt, ctx, options);
  8601. restoreTextDirection(ctx, options.textDirection);
  8602. ctx.restore();
  8603. }
  8604. }
  8605. getActiveElements() {
  8606. return this._active || [];
  8607. }
  8608. setActiveElements(activeElements, eventPosition) {
  8609. const me = this;
  8610. const lastActive = me._active;
  8611. const active = activeElements.map(({datasetIndex, index}) => {
  8612. const meta = me._chart.getDatasetMeta(datasetIndex);
  8613. if (!meta) {
  8614. throw new Error('Cannot find a dataset at index ' + datasetIndex);
  8615. }
  8616. return {
  8617. datasetIndex,
  8618. element: meta.data[index],
  8619. index,
  8620. };
  8621. });
  8622. const changed = !_elementsEqual(lastActive, active);
  8623. const positionChanged = me._positionChanged(active, eventPosition);
  8624. if (changed || positionChanged) {
  8625. me._active = active;
  8626. me._eventPosition = eventPosition;
  8627. me.update(true);
  8628. }
  8629. }
  8630. handleEvent(e, replay) {
  8631. const me = this;
  8632. const options = me.options;
  8633. const lastActive = me._active || [];
  8634. let changed = false;
  8635. let active = [];
  8636. if (e.type !== 'mouseout') {
  8637. active = me._chart.getElementsAtEventForMode(e, options.mode, options, replay);
  8638. if (options.reverse) {
  8639. active.reverse();
  8640. }
  8641. }
  8642. const positionChanged = me._positionChanged(active, e);
  8643. changed = replay || !_elementsEqual(active, lastActive) || positionChanged;
  8644. if (changed) {
  8645. me._active = active;
  8646. if (options.enabled || options.external) {
  8647. me._eventPosition = {
  8648. x: e.x,
  8649. y: e.y
  8650. };
  8651. me.update(true, replay);
  8652. }
  8653. }
  8654. return changed;
  8655. }
  8656. _positionChanged(active, e) {
  8657. const {caretX, caretY, options} = this;
  8658. const position = positioners[options.position].call(this, active, e);
  8659. return position !== false && (caretX !== position.x || caretY !== position.y);
  8660. }
  8661. }
  8662. Tooltip.positioners = positioners;
  8663. var plugin_tooltip = {
  8664. id: 'tooltip',
  8665. _element: Tooltip,
  8666. positioners,
  8667. afterInit(chart, _args, options) {
  8668. if (options) {
  8669. chart.tooltip = new Tooltip({_chart: chart, options});
  8670. }
  8671. },
  8672. beforeUpdate(chart, _args, options) {
  8673. if (chart.tooltip) {
  8674. chart.tooltip.initialize(options);
  8675. }
  8676. },
  8677. reset(chart, _args, options) {
  8678. if (chart.tooltip) {
  8679. chart.tooltip.initialize(options);
  8680. }
  8681. },
  8682. afterDraw(chart) {
  8683. const tooltip = chart.tooltip;
  8684. const args = {
  8685. tooltip
  8686. };
  8687. if (chart.notifyPlugins('beforeTooltipDraw', args) === false) {
  8688. return;
  8689. }
  8690. if (tooltip) {
  8691. tooltip.draw(chart.ctx);
  8692. }
  8693. chart.notifyPlugins('afterTooltipDraw', args);
  8694. },
  8695. afterEvent(chart, args) {
  8696. if (chart.tooltip) {
  8697. const useFinalPosition = args.replay;
  8698. if (chart.tooltip.handleEvent(args.event, useFinalPosition)) {
  8699. args.changed = true;
  8700. }
  8701. }
  8702. },
  8703. defaults: {
  8704. enabled: true,
  8705. external: null,
  8706. position: 'average',
  8707. backgroundColor: 'rgba(0,0,0,0.8)',
  8708. titleColor: '#fff',
  8709. titleFont: {
  8710. weight: 'bold',
  8711. },
  8712. titleSpacing: 2,
  8713. titleMarginBottom: 6,
  8714. titleAlign: 'left',
  8715. bodyColor: '#fff',
  8716. bodySpacing: 2,
  8717. bodyFont: {
  8718. },
  8719. bodyAlign: 'left',
  8720. footerColor: '#fff',
  8721. footerSpacing: 2,
  8722. footerMarginTop: 6,
  8723. footerFont: {
  8724. weight: 'bold',
  8725. },
  8726. footerAlign: 'left',
  8727. padding: 6,
  8728. caretPadding: 2,
  8729. caretSize: 5,
  8730. cornerRadius: 6,
  8731. boxHeight: (ctx, opts) => opts.bodyFont.size,
  8732. boxWidth: (ctx, opts) => opts.bodyFont.size,
  8733. multiKeyBackground: '#fff',
  8734. displayColors: true,
  8735. borderColor: 'rgba(0,0,0,0)',
  8736. borderWidth: 0,
  8737. animation: {
  8738. duration: 400,
  8739. easing: 'easeOutQuart',
  8740. },
  8741. animations: {
  8742. numbers: {
  8743. type: 'number',
  8744. properties: ['x', 'y', 'width', 'height', 'caretX', 'caretY'],
  8745. },
  8746. opacity: {
  8747. easing: 'linear',
  8748. duration: 200
  8749. }
  8750. },
  8751. callbacks: {
  8752. beforeTitle: noop,
  8753. title(tooltipItems) {
  8754. if (tooltipItems.length > 0) {
  8755. const item = tooltipItems[0];
  8756. const labels = item.chart.data.labels;
  8757. const labelCount = labels ? labels.length : 0;
  8758. if (this && this.options && this.options.mode === 'dataset') {
  8759. return item.dataset.label || '';
  8760. } else if (item.label) {
  8761. return item.label;
  8762. } else if (labelCount > 0 && item.dataIndex < labelCount) {
  8763. return labels[item.dataIndex];
  8764. }
  8765. }
  8766. return '';
  8767. },
  8768. afterTitle: noop,
  8769. beforeBody: noop,
  8770. beforeLabel: noop,
  8771. label(tooltipItem) {
  8772. if (this && this.options && this.options.mode === 'dataset') {
  8773. return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;
  8774. }
  8775. let label = tooltipItem.dataset.label || '';
  8776. if (label) {
  8777. label += ': ';
  8778. }
  8779. const value = tooltipItem.formattedValue;
  8780. if (!isNullOrUndef(value)) {
  8781. label += value;
  8782. }
  8783. return label;
  8784. },
  8785. labelColor(tooltipItem) {
  8786. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  8787. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  8788. return {
  8789. borderColor: options.borderColor,
  8790. backgroundColor: options.backgroundColor,
  8791. borderWidth: options.borderWidth,
  8792. borderDash: options.borderDash,
  8793. borderDashOffset: options.borderDashOffset,
  8794. borderRadius: 0,
  8795. };
  8796. },
  8797. labelTextColor() {
  8798. return this.options.bodyColor;
  8799. },
  8800. labelPointStyle(tooltipItem) {
  8801. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  8802. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  8803. return {
  8804. pointStyle: options.pointStyle,
  8805. rotation: options.rotation,
  8806. };
  8807. },
  8808. afterLabel: noop,
  8809. afterBody: noop,
  8810. beforeFooter: noop,
  8811. footer: noop,
  8812. afterFooter: noop
  8813. }
  8814. },
  8815. defaultRoutes: {
  8816. bodyFont: 'font',
  8817. footerFont: 'font',
  8818. titleFont: 'font'
  8819. },
  8820. descriptors: {
  8821. _scriptable: (name) => name !== 'filter' && name !== 'itemSort' && name !== 'external',
  8822. _indexable: false,
  8823. callbacks: {
  8824. _scriptable: false,
  8825. _indexable: false,
  8826. },
  8827. animation: {
  8828. _fallback: false
  8829. },
  8830. animations: {
  8831. _fallback: 'animation'
  8832. }
  8833. },
  8834. additionalOptionScopes: ['interaction']
  8835. };
  8836. var plugins = /*#__PURE__*/Object.freeze({
  8837. __proto__: null,
  8838. Decimation: plugin_decimation,
  8839. Filler: plugin_filler,
  8840. Legend: plugin_legend,
  8841. Title: plugin_title,
  8842. Tooltip: plugin_tooltip
  8843. });
  8844. const addIfString = (labels, raw, index) => typeof raw === 'string'
  8845. ? labels.push(raw) - 1
  8846. : isNaN(raw) ? null : index;
  8847. function findOrAddLabel(labels, raw, index) {
  8848. const first = labels.indexOf(raw);
  8849. if (first === -1) {
  8850. return addIfString(labels, raw, index);
  8851. }
  8852. const last = labels.lastIndexOf(raw);
  8853. return first !== last ? index : first;
  8854. }
  8855. const validIndex = (index, max) => index === null ? null : _limitValue(Math.round(index), 0, max);
  8856. class CategoryScale extends Scale {
  8857. constructor(cfg) {
  8858. super(cfg);
  8859. this._startValue = undefined;
  8860. this._valueRange = 0;
  8861. }
  8862. parse(raw, index) {
  8863. if (isNullOrUndef(raw)) {
  8864. return null;
  8865. }
  8866. const labels = this.getLabels();
  8867. index = isFinite(index) && labels[index] === raw ? index
  8868. : findOrAddLabel(labels, raw, valueOrDefault(index, raw));
  8869. return validIndex(index, labels.length - 1);
  8870. }
  8871. determineDataLimits() {
  8872. const me = this;
  8873. const {minDefined, maxDefined} = me.getUserBounds();
  8874. let {min, max} = me.getMinMax(true);
  8875. if (me.options.bounds === 'ticks') {
  8876. if (!minDefined) {
  8877. min = 0;
  8878. }
  8879. if (!maxDefined) {
  8880. max = me.getLabels().length - 1;
  8881. }
  8882. }
  8883. me.min = min;
  8884. me.max = max;
  8885. }
  8886. buildTicks() {
  8887. const me = this;
  8888. const min = me.min;
  8889. const max = me.max;
  8890. const offset = me.options.offset;
  8891. const ticks = [];
  8892. let labels = me.getLabels();
  8893. labels = (min === 0 && max === labels.length - 1) ? labels : labels.slice(min, max + 1);
  8894. me._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);
  8895. me._startValue = me.min - (offset ? 0.5 : 0);
  8896. for (let value = min; value <= max; value++) {
  8897. ticks.push({value});
  8898. }
  8899. return ticks;
  8900. }
  8901. getLabelForValue(value) {
  8902. const me = this;
  8903. const labels = me.getLabels();
  8904. if (value >= 0 && value < labels.length) {
  8905. return labels[value];
  8906. }
  8907. return value;
  8908. }
  8909. configure() {
  8910. const me = this;
  8911. super.configure();
  8912. if (!me.isHorizontal()) {
  8913. me._reversePixels = !me._reversePixels;
  8914. }
  8915. }
  8916. getPixelForValue(value) {
  8917. const me = this;
  8918. if (typeof value !== 'number') {
  8919. value = me.parse(value);
  8920. }
  8921. return value === null ? NaN : me.getPixelForDecimal((value - me._startValue) / me._valueRange);
  8922. }
  8923. getPixelForTick(index) {
  8924. const me = this;
  8925. const ticks = me.ticks;
  8926. if (index < 0 || index > ticks.length - 1) {
  8927. return null;
  8928. }
  8929. return me.getPixelForValue(ticks[index].value);
  8930. }
  8931. getValueForPixel(pixel) {
  8932. const me = this;
  8933. return Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
  8934. }
  8935. getBasePixel() {
  8936. return this.bottom;
  8937. }
  8938. }
  8939. CategoryScale.id = 'category';
  8940. CategoryScale.defaults = {
  8941. ticks: {
  8942. callback: CategoryScale.prototype.getLabelForValue
  8943. }
  8944. };
  8945. function generateTicks$1(generationOptions, dataRange) {
  8946. const ticks = [];
  8947. const MIN_SPACING = 1e-14;
  8948. const {step, min, max, precision, count, maxTicks, maxDigits, horizontal} = generationOptions;
  8949. const unit = step || 1;
  8950. const maxSpaces = maxTicks - 1;
  8951. const {min: rmin, max: rmax} = dataRange;
  8952. const minDefined = !isNullOrUndef(min);
  8953. const maxDefined = !isNullOrUndef(max);
  8954. const countDefined = !isNullOrUndef(count);
  8955. const minSpacing = (rmax - rmin) / maxDigits;
  8956. let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit;
  8957. let factor, niceMin, niceMax, numSpaces;
  8958. if (spacing < MIN_SPACING && !minDefined && !maxDefined) {
  8959. return [{value: rmin}, {value: rmax}];
  8960. }
  8961. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  8962. if (numSpaces > maxSpaces) {
  8963. spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit;
  8964. }
  8965. if (!isNullOrUndef(precision)) {
  8966. factor = Math.pow(10, precision);
  8967. spacing = Math.ceil(spacing * factor) / factor;
  8968. }
  8969. niceMin = Math.floor(rmin / spacing) * spacing;
  8970. niceMax = Math.ceil(rmax / spacing) * spacing;
  8971. if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) {
  8972. numSpaces = Math.min((max - min) / spacing, maxTicks);
  8973. spacing = (max - min) / numSpaces;
  8974. niceMin = min;
  8975. niceMax = max;
  8976. } else if (countDefined) {
  8977. niceMin = minDefined ? min : niceMin;
  8978. niceMax = maxDefined ? max : niceMax;
  8979. numSpaces = count - 1;
  8980. spacing = (niceMax - niceMin) / numSpaces;
  8981. } else {
  8982. numSpaces = (niceMax - niceMin) / spacing;
  8983. if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  8984. numSpaces = Math.round(numSpaces);
  8985. } else {
  8986. numSpaces = Math.ceil(numSpaces);
  8987. }
  8988. }
  8989. factor = Math.pow(10, isNullOrUndef(precision) ? _decimalPlaces(spacing) : precision);
  8990. niceMin = Math.round(niceMin * factor) / factor;
  8991. niceMax = Math.round(niceMax * factor) / factor;
  8992. let j = 0;
  8993. if (minDefined) {
  8994. ticks.push({value: min});
  8995. if (niceMin <= min) {
  8996. j++;
  8997. }
  8998. if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, minSpacing * (horizontal ? ('' + min).length : 1))) {
  8999. j++;
  9000. }
  9001. }
  9002. for (; j < numSpaces; ++j) {
  9003. ticks.push({value: Math.round((niceMin + j * spacing) * factor) / factor});
  9004. }
  9005. if (maxDefined) {
  9006. if (almostEquals(ticks[ticks.length - 1].value, max, minSpacing * (horizontal ? ('' + max).length : 1))) {
  9007. ticks[ticks.length - 1].value = max;
  9008. } else {
  9009. ticks.push({value: max});
  9010. }
  9011. } else {
  9012. ticks.push({value: niceMax});
  9013. }
  9014. return ticks;
  9015. }
  9016. class LinearScaleBase extends Scale {
  9017. constructor(cfg) {
  9018. super(cfg);
  9019. this.start = undefined;
  9020. this.end = undefined;
  9021. this._startValue = undefined;
  9022. this._endValue = undefined;
  9023. this._valueRange = 0;
  9024. }
  9025. parse(raw, index) {
  9026. if (isNullOrUndef(raw)) {
  9027. return null;
  9028. }
  9029. if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {
  9030. return null;
  9031. }
  9032. return +raw;
  9033. }
  9034. handleTickRangeOptions() {
  9035. const me = this;
  9036. const {beginAtZero, stacked} = me.options;
  9037. const {minDefined, maxDefined} = me.getUserBounds();
  9038. let {min, max} = me;
  9039. const setMin = v => (min = minDefined ? min : v);
  9040. const setMax = v => (max = maxDefined ? max : v);
  9041. if (beginAtZero || stacked) {
  9042. const minSign = sign(min);
  9043. const maxSign = sign(max);
  9044. if (minSign < 0 && maxSign < 0) {
  9045. setMax(0);
  9046. } else if (minSign > 0 && maxSign > 0) {
  9047. setMin(0);
  9048. }
  9049. }
  9050. if (min === max) {
  9051. setMax(max + 1);
  9052. if (!beginAtZero) {
  9053. setMin(min - 1);
  9054. }
  9055. }
  9056. me.min = min;
  9057. me.max = max;
  9058. }
  9059. getTickLimit() {
  9060. const me = this;
  9061. const tickOpts = me.options.ticks;
  9062. let {maxTicksLimit, stepSize} = tickOpts;
  9063. let maxTicks;
  9064. if (stepSize) {
  9065. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  9066. } else {
  9067. maxTicks = me.computeTickLimit();
  9068. maxTicksLimit = maxTicksLimit || 11;
  9069. }
  9070. if (maxTicksLimit) {
  9071. maxTicks = Math.min(maxTicksLimit, maxTicks);
  9072. }
  9073. return maxTicks;
  9074. }
  9075. computeTickLimit() {
  9076. return Number.POSITIVE_INFINITY;
  9077. }
  9078. buildTicks() {
  9079. const me = this;
  9080. const opts = me.options;
  9081. const tickOpts = opts.ticks;
  9082. let maxTicks = me.getTickLimit();
  9083. maxTicks = Math.max(2, maxTicks);
  9084. const numericGeneratorOptions = {
  9085. maxTicks,
  9086. min: opts.min,
  9087. max: opts.max,
  9088. precision: tickOpts.precision,
  9089. step: tickOpts.stepSize,
  9090. count: tickOpts.count,
  9091. maxDigits: me._maxDigits(),
  9092. horizontal: me.isHorizontal()
  9093. };
  9094. const dataRange = me._range || me;
  9095. const ticks = generateTicks$1(numericGeneratorOptions, dataRange);
  9096. if (opts.bounds === 'ticks') {
  9097. _setMinAndMaxByKey(ticks, me, 'value');
  9098. }
  9099. if (opts.reverse) {
  9100. ticks.reverse();
  9101. me.start = me.max;
  9102. me.end = me.min;
  9103. } else {
  9104. me.start = me.min;
  9105. me.end = me.max;
  9106. }
  9107. return ticks;
  9108. }
  9109. configure() {
  9110. const me = this;
  9111. const ticks = me.ticks;
  9112. let start = me.min;
  9113. let end = me.max;
  9114. super.configure();
  9115. if (me.options.offset && ticks.length) {
  9116. const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  9117. start -= offset;
  9118. end += offset;
  9119. }
  9120. me._startValue = start;
  9121. me._endValue = end;
  9122. me._valueRange = end - start;
  9123. }
  9124. getLabelForValue(value) {
  9125. return formatNumber(value, this.chart.options.locale);
  9126. }
  9127. }
  9128. class LinearScale extends LinearScaleBase {
  9129. determineDataLimits() {
  9130. const me = this;
  9131. const {min, max} = me.getMinMax(true);
  9132. me.min = isNumberFinite(min) ? min : 0;
  9133. me.max = isNumberFinite(max) ? max : 1;
  9134. me.handleTickRangeOptions();
  9135. }
  9136. computeTickLimit() {
  9137. const me = this;
  9138. if (me.isHorizontal()) {
  9139. return Math.ceil(me.width / 40);
  9140. }
  9141. const tickFont = me._resolveTickFontOptions(0);
  9142. return Math.ceil(me.height / tickFont.lineHeight);
  9143. }
  9144. getPixelForValue(value) {
  9145. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  9146. }
  9147. getValueForPixel(pixel) {
  9148. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  9149. }
  9150. }
  9151. LinearScale.id = 'linear';
  9152. LinearScale.defaults = {
  9153. ticks: {
  9154. callback: Ticks.formatters.numeric
  9155. }
  9156. };
  9157. function isMajor(tickVal) {
  9158. const remain = tickVal / (Math.pow(10, Math.floor(log10(tickVal))));
  9159. return remain === 1;
  9160. }
  9161. function generateTicks(generationOptions, dataRange) {
  9162. const endExp = Math.floor(log10(dataRange.max));
  9163. const endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  9164. const ticks = [];
  9165. let tickVal = finiteOrDefault(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  9166. let exp = Math.floor(log10(tickVal));
  9167. let significand = Math.floor(tickVal / Math.pow(10, exp));
  9168. let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  9169. do {
  9170. ticks.push({value: tickVal, major: isMajor(tickVal)});
  9171. ++significand;
  9172. if (significand === 10) {
  9173. significand = 1;
  9174. ++exp;
  9175. precision = exp >= 0 ? 1 : precision;
  9176. }
  9177. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  9178. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  9179. const lastTick = finiteOrDefault(generationOptions.max, tickVal);
  9180. ticks.push({value: lastTick, major: isMajor(tickVal)});
  9181. return ticks;
  9182. }
  9183. class LogarithmicScale extends Scale {
  9184. constructor(cfg) {
  9185. super(cfg);
  9186. this.start = undefined;
  9187. this.end = undefined;
  9188. this._startValue = undefined;
  9189. this._valueRange = 0;
  9190. }
  9191. parse(raw, index) {
  9192. const value = LinearScaleBase.prototype.parse.apply(this, [raw, index]);
  9193. if (value === 0) {
  9194. this._zero = true;
  9195. return undefined;
  9196. }
  9197. return isNumberFinite(value) && value > 0 ? value : null;
  9198. }
  9199. determineDataLimits() {
  9200. const me = this;
  9201. const {min, max} = me.getMinMax(true);
  9202. me.min = isNumberFinite(min) ? Math.max(0, min) : null;
  9203. me.max = isNumberFinite(max) ? Math.max(0, max) : null;
  9204. if (me.options.beginAtZero) {
  9205. me._zero = true;
  9206. }
  9207. me.handleTickRangeOptions();
  9208. }
  9209. handleTickRangeOptions() {
  9210. const me = this;
  9211. const {minDefined, maxDefined} = me.getUserBounds();
  9212. let min = me.min;
  9213. let max = me.max;
  9214. const setMin = v => (min = minDefined ? min : v);
  9215. const setMax = v => (max = maxDefined ? max : v);
  9216. const exp = (v, m) => Math.pow(10, Math.floor(log10(v)) + m);
  9217. if (min === max) {
  9218. if (min <= 0) {
  9219. setMin(1);
  9220. setMax(10);
  9221. } else {
  9222. setMin(exp(min, -1));
  9223. setMax(exp(max, +1));
  9224. }
  9225. }
  9226. if (min <= 0) {
  9227. setMin(exp(max, -1));
  9228. }
  9229. if (max <= 0) {
  9230. setMax(exp(min, +1));
  9231. }
  9232. if (me._zero && me.min !== me._suggestedMin && min === exp(me.min, 0)) {
  9233. setMin(exp(min, -1));
  9234. }
  9235. me.min = min;
  9236. me.max = max;
  9237. }
  9238. buildTicks() {
  9239. const me = this;
  9240. const opts = me.options;
  9241. const generationOptions = {
  9242. min: me._userMin,
  9243. max: me._userMax
  9244. };
  9245. const ticks = generateTicks(generationOptions, me);
  9246. if (opts.bounds === 'ticks') {
  9247. _setMinAndMaxByKey(ticks, me, 'value');
  9248. }
  9249. if (opts.reverse) {
  9250. ticks.reverse();
  9251. me.start = me.max;
  9252. me.end = me.min;
  9253. } else {
  9254. me.start = me.min;
  9255. me.end = me.max;
  9256. }
  9257. return ticks;
  9258. }
  9259. getLabelForValue(value) {
  9260. return value === undefined ? '0' : formatNumber(value, this.chart.options.locale);
  9261. }
  9262. configure() {
  9263. const me = this;
  9264. const start = me.min;
  9265. super.configure();
  9266. me._startValue = log10(start);
  9267. me._valueRange = log10(me.max) - log10(start);
  9268. }
  9269. getPixelForValue(value) {
  9270. const me = this;
  9271. if (value === undefined || value === 0) {
  9272. value = me.min;
  9273. }
  9274. if (value === null || isNaN(value)) {
  9275. return NaN;
  9276. }
  9277. return me.getPixelForDecimal(value === me.min
  9278. ? 0
  9279. : (log10(value) - me._startValue) / me._valueRange);
  9280. }
  9281. getValueForPixel(pixel) {
  9282. const me = this;
  9283. const decimal = me.getDecimalForPixel(pixel);
  9284. return Math.pow(10, me._startValue + decimal * me._valueRange);
  9285. }
  9286. }
  9287. LogarithmicScale.id = 'logarithmic';
  9288. LogarithmicScale.defaults = {
  9289. ticks: {
  9290. callback: Ticks.formatters.logarithmic,
  9291. major: {
  9292. enabled: true
  9293. }
  9294. }
  9295. };
  9296. function getTickBackdropHeight(opts) {
  9297. const tickOpts = opts.ticks;
  9298. if (tickOpts.display && opts.display) {
  9299. const padding = toPadding(tickOpts.backdropPadding);
  9300. return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height;
  9301. }
  9302. return 0;
  9303. }
  9304. function measureLabelSize(ctx, lineHeight, label) {
  9305. if (isArray(label)) {
  9306. return {
  9307. w: _longestText(ctx, ctx.font, label),
  9308. h: label.length * lineHeight
  9309. };
  9310. }
  9311. return {
  9312. w: ctx.measureText(label).width,
  9313. h: lineHeight
  9314. };
  9315. }
  9316. function determineLimits(angle, pos, size, min, max) {
  9317. if (angle === min || angle === max) {
  9318. return {
  9319. start: pos - (size / 2),
  9320. end: pos + (size / 2)
  9321. };
  9322. } else if (angle < min || angle > max) {
  9323. return {
  9324. start: pos - size,
  9325. end: pos
  9326. };
  9327. }
  9328. return {
  9329. start: pos,
  9330. end: pos + size
  9331. };
  9332. }
  9333. function fitWithPointLabels(scale) {
  9334. const furthestLimits = {
  9335. l: 0,
  9336. r: scale.width,
  9337. t: 0,
  9338. b: scale.height - scale.paddingTop
  9339. };
  9340. const furthestAngles = {};
  9341. let i, textSize, pointPosition;
  9342. const labelSizes = [];
  9343. const padding = [];
  9344. const valueCount = scale.getLabels().length;
  9345. for (i = 0; i < valueCount; i++) {
  9346. const opts = scale.options.pointLabels.setContext(scale.getContext(i));
  9347. padding[i] = opts.padding;
  9348. pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i]);
  9349. const plFont = toFont(opts.font);
  9350. scale.ctx.font = plFont.string;
  9351. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale._pointLabels[i]);
  9352. labelSizes[i] = textSize;
  9353. const angleRadians = scale.getIndexAngle(i);
  9354. const angle = toDegrees(angleRadians);
  9355. const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  9356. const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  9357. if (hLimits.start < furthestLimits.l) {
  9358. furthestLimits.l = hLimits.start;
  9359. furthestAngles.l = angleRadians;
  9360. }
  9361. if (hLimits.end > furthestLimits.r) {
  9362. furthestLimits.r = hLimits.end;
  9363. furthestAngles.r = angleRadians;
  9364. }
  9365. if (vLimits.start < furthestLimits.t) {
  9366. furthestLimits.t = vLimits.start;
  9367. furthestAngles.t = angleRadians;
  9368. }
  9369. if (vLimits.end > furthestLimits.b) {
  9370. furthestLimits.b = vLimits.end;
  9371. furthestAngles.b = angleRadians;
  9372. }
  9373. }
  9374. scale._setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  9375. scale._pointLabelItems = [];
  9376. const opts = scale.options;
  9377. const tickBackdropHeight = getTickBackdropHeight(opts);
  9378. const outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  9379. for (i = 0; i < valueCount; i++) {
  9380. const extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  9381. const pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + padding[i]);
  9382. const angle = toDegrees(scale.getIndexAngle(i));
  9383. const size = labelSizes[i];
  9384. adjustPointPositionForLabelHeight(angle, size, pointLabelPosition);
  9385. const textAlign = getTextAlignForAngle(angle);
  9386. let left;
  9387. if (textAlign === 'left') {
  9388. left = pointLabelPosition.x;
  9389. } else if (textAlign === 'center') {
  9390. left = pointLabelPosition.x - (size.w / 2);
  9391. } else {
  9392. left = pointLabelPosition.x - size.w;
  9393. }
  9394. const right = left + size.w;
  9395. scale._pointLabelItems[i] = {
  9396. x: pointLabelPosition.x,
  9397. y: pointLabelPosition.y,
  9398. textAlign,
  9399. left,
  9400. top: pointLabelPosition.y,
  9401. right,
  9402. bottom: pointLabelPosition.y + size.h,
  9403. };
  9404. }
  9405. }
  9406. function getTextAlignForAngle(angle) {
  9407. if (angle === 0 || angle === 180) {
  9408. return 'center';
  9409. } else if (angle < 180) {
  9410. return 'left';
  9411. }
  9412. return 'right';
  9413. }
  9414. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  9415. if (angle === 90 || angle === 270) {
  9416. position.y -= (textSize.h / 2);
  9417. } else if (angle > 270 || angle < 90) {
  9418. position.y -= textSize.h;
  9419. }
  9420. }
  9421. function drawPointLabels(scale, labelCount) {
  9422. const {ctx, options: {pointLabels}} = scale;
  9423. for (let i = labelCount - 1; i >= 0; i--) {
  9424. const optsAtIndex = pointLabels.setContext(scale.getContext(i));
  9425. const plFont = toFont(optsAtIndex.font);
  9426. const {x, y, textAlign, left, top, right, bottom} = scale._pointLabelItems[i];
  9427. const {backdropColor} = optsAtIndex;
  9428. if (!isNullOrUndef(backdropColor)) {
  9429. const padding = toPadding(optsAtIndex.backdropPadding);
  9430. ctx.fillStyle = backdropColor;
  9431. ctx.fillRect(left - padding.left, top - padding.top, right - left + padding.width, bottom - top + padding.height);
  9432. }
  9433. renderText(
  9434. ctx,
  9435. scale._pointLabels[i],
  9436. x,
  9437. y + (plFont.lineHeight / 2),
  9438. plFont,
  9439. {
  9440. color: optsAtIndex.color,
  9441. textAlign: textAlign,
  9442. textBaseline: 'middle'
  9443. }
  9444. );
  9445. }
  9446. }
  9447. function pathRadiusLine(scale, radius, circular, labelCount) {
  9448. const {ctx} = scale;
  9449. if (circular) {
  9450. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU);
  9451. } else {
  9452. let pointPosition = scale.getPointPosition(0, radius);
  9453. ctx.moveTo(pointPosition.x, pointPosition.y);
  9454. for (let i = 1; i < labelCount; i++) {
  9455. pointPosition = scale.getPointPosition(i, radius);
  9456. ctx.lineTo(pointPosition.x, pointPosition.y);
  9457. }
  9458. }
  9459. }
  9460. function drawRadiusLine(scale, gridLineOpts, radius, labelCount) {
  9461. const ctx = scale.ctx;
  9462. const circular = gridLineOpts.circular;
  9463. const {color, lineWidth} = gridLineOpts;
  9464. if ((!circular && !labelCount) || !color || !lineWidth || radius < 0) {
  9465. return;
  9466. }
  9467. ctx.save();
  9468. ctx.strokeStyle = color;
  9469. ctx.lineWidth = lineWidth;
  9470. ctx.setLineDash(gridLineOpts.borderDash);
  9471. ctx.lineDashOffset = gridLineOpts.borderDashOffset;
  9472. ctx.beginPath();
  9473. pathRadiusLine(scale, radius, circular, labelCount);
  9474. ctx.closePath();
  9475. ctx.stroke();
  9476. ctx.restore();
  9477. }
  9478. function numberOrZero(param) {
  9479. return isNumber(param) ? param : 0;
  9480. }
  9481. class RadialLinearScale extends LinearScaleBase {
  9482. constructor(cfg) {
  9483. super(cfg);
  9484. this.xCenter = undefined;
  9485. this.yCenter = undefined;
  9486. this.drawingArea = undefined;
  9487. this._pointLabels = [];
  9488. this._pointLabelItems = [];
  9489. }
  9490. setDimensions() {
  9491. const me = this;
  9492. me.width = me.maxWidth;
  9493. me.height = me.maxHeight;
  9494. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  9495. me.xCenter = Math.floor(me.width / 2);
  9496. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  9497. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  9498. }
  9499. determineDataLimits() {
  9500. const me = this;
  9501. const {min, max} = me.getMinMax(false);
  9502. me.min = isNumberFinite(min) && !isNaN(min) ? min : 0;
  9503. me.max = isNumberFinite(max) && !isNaN(max) ? max : 0;
  9504. me.handleTickRangeOptions();
  9505. }
  9506. computeTickLimit() {
  9507. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  9508. }
  9509. generateTickLabels(ticks) {
  9510. const me = this;
  9511. LinearScaleBase.prototype.generateTickLabels.call(me, ticks);
  9512. me._pointLabels = me.getLabels().map((value, index) => {
  9513. const label = callback(me.options.pointLabels.callback, [value, index], me);
  9514. return label || label === 0 ? label : '';
  9515. });
  9516. }
  9517. fit() {
  9518. const me = this;
  9519. const opts = me.options;
  9520. if (opts.display && opts.pointLabels.display) {
  9521. fitWithPointLabels(me);
  9522. } else {
  9523. me.setCenterPoint(0, 0, 0, 0);
  9524. }
  9525. }
  9526. _setReductions(largestPossibleRadius, furthestLimits, furthestAngles) {
  9527. const me = this;
  9528. let radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  9529. let radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  9530. let radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  9531. let radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  9532. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  9533. radiusReductionRight = numberOrZero(radiusReductionRight);
  9534. radiusReductionTop = numberOrZero(radiusReductionTop);
  9535. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  9536. me.drawingArea = Math.max(largestPossibleRadius / 2, Math.min(
  9537. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  9538. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2)));
  9539. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  9540. }
  9541. setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {
  9542. const me = this;
  9543. const maxRight = me.width - rightMovement - me.drawingArea;
  9544. const maxLeft = leftMovement + me.drawingArea;
  9545. const maxTop = topMovement + me.drawingArea;
  9546. const maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  9547. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  9548. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  9549. }
  9550. getIndexAngle(index) {
  9551. const angleMultiplier = TAU / this.getLabels().length;
  9552. const startAngle = this.options.startAngle || 0;
  9553. return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));
  9554. }
  9555. getDistanceFromCenterForValue(value) {
  9556. const me = this;
  9557. if (isNullOrUndef(value)) {
  9558. return NaN;
  9559. }
  9560. const scalingFactor = me.drawingArea / (me.max - me.min);
  9561. if (me.options.reverse) {
  9562. return (me.max - value) * scalingFactor;
  9563. }
  9564. return (value - me.min) * scalingFactor;
  9565. }
  9566. getValueForDistanceFromCenter(distance) {
  9567. if (isNullOrUndef(distance)) {
  9568. return NaN;
  9569. }
  9570. const me = this;
  9571. const scaledDistance = distance / (me.drawingArea / (me.max - me.min));
  9572. return me.options.reverse ? me.max - scaledDistance : me.min + scaledDistance;
  9573. }
  9574. getPointPosition(index, distanceFromCenter) {
  9575. const me = this;
  9576. const angle = me.getIndexAngle(index) - HALF_PI;
  9577. return {
  9578. x: Math.cos(angle) * distanceFromCenter + me.xCenter,
  9579. y: Math.sin(angle) * distanceFromCenter + me.yCenter,
  9580. angle
  9581. };
  9582. }
  9583. getPointPositionForValue(index, value) {
  9584. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  9585. }
  9586. getBasePosition(index) {
  9587. return this.getPointPositionForValue(index || 0, this.getBaseValue());
  9588. }
  9589. getPointLabelPosition(index) {
  9590. const {left, top, right, bottom} = this._pointLabelItems[index];
  9591. return {
  9592. left,
  9593. top,
  9594. right,
  9595. bottom,
  9596. };
  9597. }
  9598. drawBackground() {
  9599. const me = this;
  9600. const {backgroundColor, grid: {circular}} = me.options;
  9601. if (backgroundColor) {
  9602. const ctx = me.ctx;
  9603. ctx.save();
  9604. ctx.beginPath();
  9605. pathRadiusLine(me, me.getDistanceFromCenterForValue(me._endValue), circular, me.getLabels().length);
  9606. ctx.closePath();
  9607. ctx.fillStyle = backgroundColor;
  9608. ctx.fill();
  9609. ctx.restore();
  9610. }
  9611. }
  9612. drawGrid() {
  9613. const me = this;
  9614. const ctx = me.ctx;
  9615. const opts = me.options;
  9616. const {angleLines, grid} = opts;
  9617. const labelCount = me.getLabels().length;
  9618. let i, offset, position;
  9619. if (opts.pointLabels.display) {
  9620. drawPointLabels(me, labelCount);
  9621. }
  9622. if (grid.display) {
  9623. me.ticks.forEach((tick, index) => {
  9624. if (index !== 0) {
  9625. offset = me.getDistanceFromCenterForValue(tick.value);
  9626. const optsAtIndex = grid.setContext(me.getContext(index - 1));
  9627. drawRadiusLine(me, optsAtIndex, offset, labelCount);
  9628. }
  9629. });
  9630. }
  9631. if (angleLines.display) {
  9632. ctx.save();
  9633. for (i = me.getLabels().length - 1; i >= 0; i--) {
  9634. const optsAtIndex = angleLines.setContext(me.getContext(i));
  9635. const {color, lineWidth} = optsAtIndex;
  9636. if (!lineWidth || !color) {
  9637. continue;
  9638. }
  9639. ctx.lineWidth = lineWidth;
  9640. ctx.strokeStyle = color;
  9641. ctx.setLineDash(optsAtIndex.borderDash);
  9642. ctx.lineDashOffset = optsAtIndex.borderDashOffset;
  9643. offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
  9644. position = me.getPointPosition(i, offset);
  9645. ctx.beginPath();
  9646. ctx.moveTo(me.xCenter, me.yCenter);
  9647. ctx.lineTo(position.x, position.y);
  9648. ctx.stroke();
  9649. }
  9650. ctx.restore();
  9651. }
  9652. }
  9653. drawBorder() {}
  9654. drawLabels() {
  9655. const me = this;
  9656. const ctx = me.ctx;
  9657. const opts = me.options;
  9658. const tickOpts = opts.ticks;
  9659. if (!tickOpts.display) {
  9660. return;
  9661. }
  9662. const startAngle = me.getIndexAngle(0);
  9663. let offset, width;
  9664. ctx.save();
  9665. ctx.translate(me.xCenter, me.yCenter);
  9666. ctx.rotate(startAngle);
  9667. ctx.textAlign = 'center';
  9668. ctx.textBaseline = 'middle';
  9669. me.ticks.forEach((tick, index) => {
  9670. if (index === 0 && !opts.reverse) {
  9671. return;
  9672. }
  9673. const optsAtIndex = tickOpts.setContext(me.getContext(index));
  9674. const tickFont = toFont(optsAtIndex.font);
  9675. offset = me.getDistanceFromCenterForValue(me.ticks[index].value);
  9676. if (optsAtIndex.showLabelBackdrop) {
  9677. width = ctx.measureText(tick.label).width;
  9678. ctx.fillStyle = optsAtIndex.backdropColor;
  9679. const padding = toPadding(optsAtIndex.backdropPadding);
  9680. ctx.fillRect(
  9681. -width / 2 - padding.left,
  9682. -offset - tickFont.size / 2 - padding.top,
  9683. width + padding.width,
  9684. tickFont.size + padding.height
  9685. );
  9686. }
  9687. renderText(ctx, tick.label, 0, -offset, tickFont, {
  9688. color: optsAtIndex.color,
  9689. });
  9690. });
  9691. ctx.restore();
  9692. }
  9693. drawTitle() {}
  9694. }
  9695. RadialLinearScale.id = 'radialLinear';
  9696. RadialLinearScale.defaults = {
  9697. display: true,
  9698. animate: true,
  9699. position: 'chartArea',
  9700. angleLines: {
  9701. display: true,
  9702. lineWidth: 1,
  9703. borderDash: [],
  9704. borderDashOffset: 0.0
  9705. },
  9706. grid: {
  9707. circular: false
  9708. },
  9709. startAngle: 0,
  9710. ticks: {
  9711. showLabelBackdrop: true,
  9712. callback: Ticks.formatters.numeric
  9713. },
  9714. pointLabels: {
  9715. backdropColor: undefined,
  9716. backdropPadding: 2,
  9717. display: true,
  9718. font: {
  9719. size: 10
  9720. },
  9721. callback(label) {
  9722. return label;
  9723. },
  9724. padding: 5
  9725. }
  9726. };
  9727. RadialLinearScale.defaultRoutes = {
  9728. 'angleLines.color': 'borderColor',
  9729. 'pointLabels.color': 'color',
  9730. 'ticks.color': 'color'
  9731. };
  9732. RadialLinearScale.descriptors = {
  9733. angleLines: {
  9734. _fallback: 'grid'
  9735. }
  9736. };
  9737. const INTERVALS = {
  9738. millisecond: {common: true, size: 1, steps: 1000},
  9739. second: {common: true, size: 1000, steps: 60},
  9740. minute: {common: true, size: 60000, steps: 60},
  9741. hour: {common: true, size: 3600000, steps: 24},
  9742. day: {common: true, size: 86400000, steps: 30},
  9743. week: {common: false, size: 604800000, steps: 4},
  9744. month: {common: true, size: 2.628e9, steps: 12},
  9745. quarter: {common: false, size: 7.884e9, steps: 4},
  9746. year: {common: true, size: 3.154e10}
  9747. };
  9748. const UNITS = (Object.keys(INTERVALS));
  9749. function sorter(a, b) {
  9750. return a - b;
  9751. }
  9752. function parse(scale, input) {
  9753. if (isNullOrUndef(input)) {
  9754. return null;
  9755. }
  9756. const adapter = scale._adapter;
  9757. const {parser, round, isoWeekday} = scale._parseOpts;
  9758. let value = input;
  9759. if (typeof parser === 'function') {
  9760. value = parser(value);
  9761. }
  9762. if (!isNumberFinite(value)) {
  9763. value = typeof parser === 'string'
  9764. ? adapter.parse(value, parser)
  9765. : adapter.parse(value);
  9766. }
  9767. if (value === null) {
  9768. return null;
  9769. }
  9770. if (round) {
  9771. value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true)
  9772. ? adapter.startOf(value, 'isoWeek', isoWeekday)
  9773. : adapter.startOf(value, round);
  9774. }
  9775. return +value;
  9776. }
  9777. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  9778. const ilen = UNITS.length;
  9779. for (let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  9780. const interval = INTERVALS[UNITS[i]];
  9781. const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;
  9782. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  9783. return UNITS[i];
  9784. }
  9785. }
  9786. return UNITS[ilen - 1];
  9787. }
  9788. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  9789. for (let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  9790. const unit = UNITS[i];
  9791. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  9792. return unit;
  9793. }
  9794. }
  9795. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  9796. }
  9797. function determineMajorUnit(unit) {
  9798. for (let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  9799. if (INTERVALS[UNITS[i]].common) {
  9800. return UNITS[i];
  9801. }
  9802. }
  9803. }
  9804. function addTick(ticks, time, timestamps) {
  9805. if (!timestamps) {
  9806. ticks[time] = true;
  9807. } else if (timestamps.length) {
  9808. const {lo, hi} = _lookup(timestamps, time);
  9809. const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];
  9810. ticks[timestamp] = true;
  9811. }
  9812. }
  9813. function setMajorTicks(scale, ticks, map, majorUnit) {
  9814. const adapter = scale._adapter;
  9815. const first = +adapter.startOf(ticks[0].value, majorUnit);
  9816. const last = ticks[ticks.length - 1].value;
  9817. let major, index;
  9818. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  9819. index = map[major];
  9820. if (index >= 0) {
  9821. ticks[index].major = true;
  9822. }
  9823. }
  9824. return ticks;
  9825. }
  9826. function ticksFromTimestamps(scale, values, majorUnit) {
  9827. const ticks = [];
  9828. const map = {};
  9829. const ilen = values.length;
  9830. let i, value;
  9831. for (i = 0; i < ilen; ++i) {
  9832. value = values[i];
  9833. map[value] = i;
  9834. ticks.push({
  9835. value,
  9836. major: false
  9837. });
  9838. }
  9839. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  9840. }
  9841. class TimeScale extends Scale {
  9842. constructor(props) {
  9843. super(props);
  9844. this._cache = {
  9845. data: [],
  9846. labels: [],
  9847. all: []
  9848. };
  9849. this._unit = 'day';
  9850. this._majorUnit = undefined;
  9851. this._offsets = {};
  9852. this._normalized = false;
  9853. this._parseOpts = undefined;
  9854. }
  9855. init(scaleOpts, opts) {
  9856. const time = scaleOpts.time || (scaleOpts.time = {});
  9857. const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);
  9858. mergeIf(time.displayFormats, adapter.formats());
  9859. this._parseOpts = {
  9860. parser: time.parser,
  9861. round: time.round,
  9862. isoWeekday: time.isoWeekday
  9863. };
  9864. super.init(scaleOpts);
  9865. this._normalized = opts.normalized;
  9866. }
  9867. parse(raw, index) {
  9868. if (raw === undefined) {
  9869. return null;
  9870. }
  9871. return parse(this, raw);
  9872. }
  9873. beforeLayout() {
  9874. super.beforeLayout();
  9875. this._cache = {
  9876. data: [],
  9877. labels: [],
  9878. all: []
  9879. };
  9880. }
  9881. determineDataLimits() {
  9882. const me = this;
  9883. const options = me.options;
  9884. const adapter = me._adapter;
  9885. const unit = options.time.unit || 'day';
  9886. let {min, max, minDefined, maxDefined} = me.getUserBounds();
  9887. function _applyBounds(bounds) {
  9888. if (!minDefined && !isNaN(bounds.min)) {
  9889. min = Math.min(min, bounds.min);
  9890. }
  9891. if (!maxDefined && !isNaN(bounds.max)) {
  9892. max = Math.max(max, bounds.max);
  9893. }
  9894. }
  9895. if (!minDefined || !maxDefined) {
  9896. _applyBounds(me._getLabelBounds());
  9897. if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {
  9898. _applyBounds(me.getMinMax(false));
  9899. }
  9900. }
  9901. min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);
  9902. max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;
  9903. me.min = Math.min(min, max - 1);
  9904. me.max = Math.max(min + 1, max);
  9905. }
  9906. _getLabelBounds() {
  9907. const arr = this.getLabelTimestamps();
  9908. let min = Number.POSITIVE_INFINITY;
  9909. let max = Number.NEGATIVE_INFINITY;
  9910. if (arr.length) {
  9911. min = arr[0];
  9912. max = arr[arr.length - 1];
  9913. }
  9914. return {min, max};
  9915. }
  9916. buildTicks() {
  9917. const me = this;
  9918. const options = me.options;
  9919. const timeOpts = options.time;
  9920. const tickOpts = options.ticks;
  9921. const timestamps = tickOpts.source === 'labels' ? me.getLabelTimestamps() : me._generate();
  9922. if (options.bounds === 'ticks' && timestamps.length) {
  9923. me.min = me._userMin || timestamps[0];
  9924. me.max = me._userMax || timestamps[timestamps.length - 1];
  9925. }
  9926. const min = me.min;
  9927. const max = me.max;
  9928. const ticks = _filterBetween(timestamps, min, max);
  9929. me._unit = timeOpts.unit || (tickOpts.autoSkip
  9930. ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, me._getLabelCapacity(min))
  9931. : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
  9932. me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
  9933. : determineMajorUnit(me._unit);
  9934. me.initOffsets(timestamps);
  9935. if (options.reverse) {
  9936. ticks.reverse();
  9937. }
  9938. return ticksFromTimestamps(me, ticks, me._majorUnit);
  9939. }
  9940. initOffsets(timestamps) {
  9941. const me = this;
  9942. let start = 0;
  9943. let end = 0;
  9944. let first, last;
  9945. if (me.options.offset && timestamps.length) {
  9946. first = me.getDecimalForValue(timestamps[0]);
  9947. if (timestamps.length === 1) {
  9948. start = 1 - first;
  9949. } else {
  9950. start = (me.getDecimalForValue(timestamps[1]) - first) / 2;
  9951. }
  9952. last = me.getDecimalForValue(timestamps[timestamps.length - 1]);
  9953. if (timestamps.length === 1) {
  9954. end = last;
  9955. } else {
  9956. end = (last - me.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;
  9957. }
  9958. }
  9959. const limit = timestamps.length < 3 ? 0.5 : 0.25;
  9960. start = _limitValue(start, 0, limit);
  9961. end = _limitValue(end, 0, limit);
  9962. me._offsets = {start, end, factor: 1 / (start + 1 + end)};
  9963. }
  9964. _generate() {
  9965. const me = this;
  9966. const adapter = me._adapter;
  9967. const min = me.min;
  9968. const max = me.max;
  9969. const options = me.options;
  9970. const timeOpts = options.time;
  9971. const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, me._getLabelCapacity(min));
  9972. const stepSize = valueOrDefault(timeOpts.stepSize, 1);
  9973. const weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  9974. const hasWeekday = isNumber(weekday) || weekday === true;
  9975. const ticks = {};
  9976. let first = min;
  9977. let time, count;
  9978. if (hasWeekday) {
  9979. first = +adapter.startOf(first, 'isoWeek', weekday);
  9980. }
  9981. first = +adapter.startOf(first, hasWeekday ? 'day' : minor);
  9982. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  9983. throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);
  9984. }
  9985. const timestamps = options.ticks.source === 'data' && me.getDataTimestamps();
  9986. for (time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++) {
  9987. addTick(ticks, time, timestamps);
  9988. }
  9989. if (time === max || options.bounds === 'ticks' || count === 1) {
  9990. addTick(ticks, time, timestamps);
  9991. }
  9992. return Object.keys(ticks).sort((a, b) => a - b).map(x => +x);
  9993. }
  9994. getLabelForValue(value) {
  9995. const me = this;
  9996. const adapter = me._adapter;
  9997. const timeOpts = me.options.time;
  9998. if (timeOpts.tooltipFormat) {
  9999. return adapter.format(value, timeOpts.tooltipFormat);
  10000. }
  10001. return adapter.format(value, timeOpts.displayFormats.datetime);
  10002. }
  10003. _tickFormatFunction(time, index, ticks, format) {
  10004. const me = this;
  10005. const options = me.options;
  10006. const formats = options.time.displayFormats;
  10007. const unit = me._unit;
  10008. const majorUnit = me._majorUnit;
  10009. const minorFormat = unit && formats[unit];
  10010. const majorFormat = majorUnit && formats[majorUnit];
  10011. const tick = ticks[index];
  10012. const major = majorUnit && majorFormat && tick && tick.major;
  10013. const label = me._adapter.format(time, format || (major ? majorFormat : minorFormat));
  10014. const formatter = options.ticks.callback;
  10015. return formatter ? callback(formatter, [label, index, ticks], me) : label;
  10016. }
  10017. generateTickLabels(ticks) {
  10018. let i, ilen, tick;
  10019. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10020. tick = ticks[i];
  10021. tick.label = this._tickFormatFunction(tick.value, i, ticks);
  10022. }
  10023. }
  10024. getDecimalForValue(value) {
  10025. const me = this;
  10026. return value === null ? NaN : (value - me.min) / (me.max - me.min);
  10027. }
  10028. getPixelForValue(value) {
  10029. const me = this;
  10030. const offsets = me._offsets;
  10031. const pos = me.getDecimalForValue(value);
  10032. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  10033. }
  10034. getValueForPixel(pixel) {
  10035. const me = this;
  10036. const offsets = me._offsets;
  10037. const pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  10038. return me.min + pos * (me.max - me.min);
  10039. }
  10040. _getLabelSize(label) {
  10041. const me = this;
  10042. const ticksOpts = me.options.ticks;
  10043. const tickLabelWidth = me.ctx.measureText(label).width;
  10044. const angle = toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  10045. const cosRotation = Math.cos(angle);
  10046. const sinRotation = Math.sin(angle);
  10047. const tickFontSize = me._resolveTickFontOptions(0).size;
  10048. return {
  10049. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  10050. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  10051. };
  10052. }
  10053. _getLabelCapacity(exampleTime) {
  10054. const me = this;
  10055. const timeOpts = me.options.time;
  10056. const displayFormats = timeOpts.displayFormats;
  10057. const format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  10058. const exampleLabel = me._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
  10059. const size = me._getLabelSize(exampleLabel);
  10060. const capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h) - 1;
  10061. return capacity > 0 ? capacity : 1;
  10062. }
  10063. getDataTimestamps() {
  10064. const me = this;
  10065. let timestamps = me._cache.data || [];
  10066. let i, ilen;
  10067. if (timestamps.length) {
  10068. return timestamps;
  10069. }
  10070. const metas = me.getMatchingVisibleMetas();
  10071. if (me._normalized && metas.length) {
  10072. return (me._cache.data = metas[0].controller.getAllParsedValues(me));
  10073. }
  10074. for (i = 0, ilen = metas.length; i < ilen; ++i) {
  10075. timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(me));
  10076. }
  10077. return (me._cache.data = me.normalize(timestamps));
  10078. }
  10079. getLabelTimestamps() {
  10080. const me = this;
  10081. const timestamps = me._cache.labels || [];
  10082. let i, ilen;
  10083. if (timestamps.length) {
  10084. return timestamps;
  10085. }
  10086. const labels = me.getLabels();
  10087. for (i = 0, ilen = labels.length; i < ilen; ++i) {
  10088. timestamps.push(parse(me, labels[i]));
  10089. }
  10090. return (me._cache.labels = me._normalized ? timestamps : me.normalize(timestamps));
  10091. }
  10092. normalize(values) {
  10093. return _arrayUnique(values.sort(sorter));
  10094. }
  10095. }
  10096. TimeScale.id = 'time';
  10097. TimeScale.defaults = {
  10098. bounds: 'data',
  10099. adapters: {},
  10100. time: {
  10101. parser: false,
  10102. unit: false,
  10103. round: false,
  10104. isoWeekday: false,
  10105. minUnit: 'millisecond',
  10106. displayFormats: {}
  10107. },
  10108. ticks: {
  10109. source: 'auto',
  10110. major: {
  10111. enabled: false
  10112. }
  10113. }
  10114. };
  10115. function interpolate(table, val, reverse) {
  10116. let prevSource, nextSource, prevTarget, nextTarget;
  10117. if (reverse) {
  10118. prevSource = Math.floor(val);
  10119. nextSource = Math.ceil(val);
  10120. prevTarget = table[prevSource];
  10121. nextTarget = table[nextSource];
  10122. } else {
  10123. const result = _lookup(table, val);
  10124. prevTarget = result.lo;
  10125. nextTarget = result.hi;
  10126. prevSource = table[prevTarget];
  10127. nextSource = table[nextTarget];
  10128. }
  10129. const span = nextSource - prevSource;
  10130. return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;
  10131. }
  10132. class TimeSeriesScale extends TimeScale {
  10133. constructor(props) {
  10134. super(props);
  10135. this._table = [];
  10136. this._maxIndex = undefined;
  10137. }
  10138. initOffsets() {
  10139. const me = this;
  10140. const timestamps = me._getTimestampsForTable();
  10141. me._table = me.buildLookupTable(timestamps);
  10142. me._maxIndex = me._table.length - 1;
  10143. super.initOffsets(timestamps);
  10144. }
  10145. buildLookupTable(timestamps) {
  10146. const me = this;
  10147. const {min, max} = me;
  10148. if (!timestamps.length) {
  10149. return [
  10150. {time: min, pos: 0},
  10151. {time: max, pos: 1}
  10152. ];
  10153. }
  10154. const items = [min];
  10155. let i, ilen, curr;
  10156. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  10157. curr = timestamps[i];
  10158. if (curr > min && curr < max) {
  10159. items.push(curr);
  10160. }
  10161. }
  10162. items.push(max);
  10163. return items;
  10164. }
  10165. _getTimestampsForTable() {
  10166. const me = this;
  10167. let timestamps = me._cache.all || [];
  10168. if (timestamps.length) {
  10169. return timestamps;
  10170. }
  10171. const data = me.getDataTimestamps();
  10172. const label = me.getLabelTimestamps();
  10173. if (data.length && label.length) {
  10174. timestamps = me.normalize(data.concat(label));
  10175. } else {
  10176. timestamps = data.length ? data : label;
  10177. }
  10178. timestamps = me._cache.all = timestamps;
  10179. return timestamps;
  10180. }
  10181. getPixelForValue(value, index) {
  10182. const me = this;
  10183. const offsets = me._offsets;
  10184. const pos = me._normalized && me._maxIndex > 0 && !isNullOrUndef(index)
  10185. ? index / me._maxIndex : me.getDecimalForValue(value);
  10186. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  10187. }
  10188. getDecimalForValue(value) {
  10189. return interpolate(this._table, value) / this._maxIndex;
  10190. }
  10191. getValueForPixel(pixel) {
  10192. const me = this;
  10193. const offsets = me._offsets;
  10194. const decimal = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  10195. return interpolate(me._table, decimal * this._maxIndex, true);
  10196. }
  10197. }
  10198. TimeSeriesScale.id = 'timeseries';
  10199. TimeSeriesScale.defaults = TimeScale.defaults;
  10200. var scales = /*#__PURE__*/Object.freeze({
  10201. __proto__: null,
  10202. CategoryScale: CategoryScale,
  10203. LinearScale: LinearScale,
  10204. LogarithmicScale: LogarithmicScale,
  10205. RadialLinearScale: RadialLinearScale,
  10206. TimeScale: TimeScale,
  10207. TimeSeriesScale: TimeSeriesScale
  10208. });
  10209. const registerables = [
  10210. controllers,
  10211. elements,
  10212. plugins,
  10213. scales,
  10214. ];
  10215. export { Animation, Animations, ArcElement, BarController, BarElement, BasePlatform, BasicPlatform, BubbleController, CategoryScale, Chart, DatasetController, plugin_decimation as Decimation, DomPlatform, DoughnutController, Element, plugin_filler as Filler, Interaction, plugin_legend as Legend, LineController, LineElement, LinearScale, LogarithmicScale, PieController, PointElement, PolarAreaController, RadarController, RadialLinearScale, Scale, ScatterController, Ticks, TimeScale, TimeSeriesScale, plugin_title as Title, plugin_tooltip as Tooltip, adapters as _adapters, animator, controllers, elements, layouts, plugins, registerables, registry, scales };