Node-Red configuration
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

chart.js 393KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472
  1. /*!
  2. * Chart.js v4.4.4
  3. * https://www.chartjs.org
  4. * (c) 2024 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, d as defaults, b as isArray, v as valueOrDefault, u as unlistenArrayEvents, l as listenArrayEvents, f as resolveObjectKey, g as isNumberFinite, h as defined, s as sign, j as createContext, k as isNullOrUndef, _ as _arrayUnique, t as toRadians, m as toPercentage, n as toDimension, T as TAU, o as formatNumber, p as _angleBetween, H as HALF_PI, P as PI, q as _getStartAndCountOfVisiblePoints, w as _scaleRangesChanged, x as isNumber, y as _parseObjectDataRadialScale, z as getRelativePosition, A as _rlookupByKey, B as _lookupByKey, C as _isPointInArea, D as getAngleFromPoint, E as toPadding, F as each, G as getMaximumSize, I as _getParentNode, J as readUsedSize, K as supportsEventListenerOptions, L as throttled, M as _isDomSupported, N as _factorize, O as finiteOrDefault, Q as callback, R as _addGrace, S as _limitValue, U as toDegrees, V as _measureText, W as _int16Range, X as _alignPixel, Y as clipArea, Z as renderText, $ as unclipArea, a0 as toFont, a1 as _toLeftRightCenter, a2 as _alignStartEnd, a3 as overrides, a4 as merge, a5 as _capitalize, a6 as descriptors, a7 as isFunction, a8 as _attachContext, a9 as _createResolver, aa as _descriptors, ab as mergeIf, ac as uid, ad as debounce, ae as retinaScale, af as clearCanvas, ag as setsEqual, ah as _elementsEqual, ai as _isClickEvent, aj as _isBetween, ak as _readValueToProps, al as _updateBezierControlPoints, am as _computeSegments, an as _boundSegments, ao as _steppedInterpolation, ap as _bezierInterpolation, aq as _pointInLine, ar as _steppedLineTo, as as _bezierCurveTo, at as drawPoint, au as addRoundedRectPath, av as toTRBL, aw as toTRBLCorners, ax as _boundSegment, ay as _normalizeAngle, az as getRtlAdapter, aA as overrideTextDirection, aB as _textX, aC as restoreTextDirection, aD as drawPointLegend, aE as distanceBetweenPoints, aF as noop, aG as _setMinAndMaxByKey, aH as niceNum, aI as almostWhole, aJ as almostEquals, aK as _decimalPlaces, aL as Ticks, aM as log10, aN as _longestText, aO as _filterBetween, aP as _lookup } from './chunks/helpers.segment.js';
  8. import '@kurkle/color';
  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. if (this._request) {
  28. return;
  29. }
  30. this._running = true;
  31. this._request = requestAnimFrame.call(window, ()=>{
  32. this._update();
  33. this._request = null;
  34. if (this._running) {
  35. this._refresh();
  36. }
  37. });
  38. }
  39. _update(date = Date.now()) {
  40. let remaining = 0;
  41. this._charts.forEach((anims, chart)=>{
  42. if (!anims.running || !anims.items.length) {
  43. return;
  44. }
  45. const items = anims.items;
  46. let i = items.length - 1;
  47. let draw = false;
  48. let item;
  49. for(; i >= 0; --i){
  50. item = items[i];
  51. if (item._active) {
  52. if (item._total > anims.duration) {
  53. anims.duration = item._total;
  54. }
  55. item.tick(date);
  56. draw = true;
  57. } else {
  58. items[i] = items[items.length - 1];
  59. items.pop();
  60. }
  61. }
  62. if (draw) {
  63. chart.draw();
  64. this._notify(chart, anims, date, 'progress');
  65. }
  66. if (!items.length) {
  67. anims.running = false;
  68. this._notify(chart, anims, date, 'complete');
  69. anims.initial = false;
  70. }
  71. remaining += items.length;
  72. });
  73. this._lastDate = date;
  74. if (remaining === 0) {
  75. this._running = false;
  76. }
  77. }
  78. _getAnims(chart) {
  79. const charts = this._charts;
  80. let anims = charts.get(chart);
  81. if (!anims) {
  82. anims = {
  83. running: false,
  84. initial: true,
  85. items: [],
  86. listeners: {
  87. complete: [],
  88. progress: []
  89. }
  90. };
  91. charts.set(chart, anims);
  92. }
  93. return anims;
  94. }
  95. listen(chart, event, cb) {
  96. this._getAnims(chart).listeners[event].push(cb);
  97. }
  98. add(chart, items) {
  99. if (!items || !items.length) {
  100. return;
  101. }
  102. this._getAnims(chart).items.push(...items);
  103. }
  104. has(chart) {
  105. return this._getAnims(chart).items.length > 0;
  106. }
  107. start(chart) {
  108. const anims = this._charts.get(chart);
  109. if (!anims) {
  110. return;
  111. }
  112. anims.running = true;
  113. anims.start = Date.now();
  114. anims.duration = anims.items.reduce((acc, cur)=>Math.max(acc, cur._duration), 0);
  115. this._refresh();
  116. }
  117. running(chart) {
  118. if (!this._running) {
  119. return false;
  120. }
  121. const anims = this._charts.get(chart);
  122. if (!anims || !anims.running || !anims.items.length) {
  123. return false;
  124. }
  125. return true;
  126. }
  127. stop(chart) {
  128. const anims = this._charts.get(chart);
  129. if (!anims || !anims.items.length) {
  130. return;
  131. }
  132. const items = anims.items;
  133. let i = items.length - 1;
  134. for(; i >= 0; --i){
  135. items[i].cancel();
  136. }
  137. anims.items = [];
  138. this._notify(chart, anims, Date.now(), 'complete');
  139. }
  140. remove(chart) {
  141. return this._charts.delete(chart);
  142. }
  143. }
  144. var animator = /* #__PURE__ */ new Animator();
  145. const transparent = 'transparent';
  146. const interpolators = {
  147. boolean (from, to, factor) {
  148. return factor > 0.5 ? to : from;
  149. },
  150. color (from, to, factor) {
  151. const c0 = color(from || transparent);
  152. const c1 = c0.valid && color(to || transparent);
  153. return c1 && c1.valid ? c1.mix(c0, factor).hexString() : to;
  154. },
  155. number (from, to, factor) {
  156. return from + (to - from) * factor;
  157. }
  158. };
  159. class Animation {
  160. constructor(cfg, target, prop, to){
  161. const currentValue = target[prop];
  162. to = resolve([
  163. cfg.to,
  164. to,
  165. currentValue,
  166. cfg.from
  167. ]);
  168. const from = resolve([
  169. cfg.from,
  170. currentValue,
  171. to
  172. ]);
  173. this._active = true;
  174. this._fn = cfg.fn || interpolators[cfg.type || typeof from];
  175. this._easing = effects[cfg.easing] || effects.linear;
  176. this._start = Math.floor(Date.now() + (cfg.delay || 0));
  177. this._duration = this._total = Math.floor(cfg.duration);
  178. this._loop = !!cfg.loop;
  179. this._target = target;
  180. this._prop = prop;
  181. this._from = from;
  182. this._to = to;
  183. this._promises = undefined;
  184. }
  185. active() {
  186. return this._active;
  187. }
  188. update(cfg, to, date) {
  189. if (this._active) {
  190. this._notify(false);
  191. const currentValue = this._target[this._prop];
  192. const elapsed = date - this._start;
  193. const remain = this._duration - elapsed;
  194. this._start = date;
  195. this._duration = Math.floor(Math.max(remain, cfg.duration));
  196. this._total += elapsed;
  197. this._loop = !!cfg.loop;
  198. this._to = resolve([
  199. cfg.to,
  200. to,
  201. currentValue,
  202. cfg.from
  203. ]);
  204. this._from = resolve([
  205. cfg.from,
  206. currentValue,
  207. to
  208. ]);
  209. }
  210. }
  211. cancel() {
  212. if (this._active) {
  213. this.tick(Date.now());
  214. this._active = false;
  215. this._notify(false);
  216. }
  217. }
  218. tick(date) {
  219. const elapsed = date - this._start;
  220. const duration = this._duration;
  221. const prop = this._prop;
  222. const from = this._from;
  223. const loop = this._loop;
  224. const to = this._to;
  225. let factor;
  226. this._active = from !== to && (loop || elapsed < duration);
  227. if (!this._active) {
  228. this._target[prop] = to;
  229. this._notify(true);
  230. return;
  231. }
  232. if (elapsed < 0) {
  233. this._target[prop] = from;
  234. return;
  235. }
  236. factor = elapsed / duration % 2;
  237. factor = loop && factor > 1 ? 2 - factor : factor;
  238. factor = this._easing(Math.min(1, Math.max(0, factor)));
  239. this._target[prop] = this._fn(from, to, factor);
  240. }
  241. wait() {
  242. const promises = this._promises || (this._promises = []);
  243. return new Promise((res, rej)=>{
  244. promises.push({
  245. res,
  246. rej
  247. });
  248. });
  249. }
  250. _notify(resolved) {
  251. const method = resolved ? 'res' : 'rej';
  252. const promises = this._promises || [];
  253. for(let i = 0; i < promises.length; i++){
  254. promises[i][method]();
  255. }
  256. }
  257. }
  258. class Animations {
  259. constructor(chart, config){
  260. this._chart = chart;
  261. this._properties = new Map();
  262. this.configure(config);
  263. }
  264. configure(config) {
  265. if (!isObject(config)) {
  266. return;
  267. }
  268. const animationOptions = Object.keys(defaults.animation);
  269. const animatedProps = this._properties;
  270. Object.getOwnPropertyNames(config).forEach((key)=>{
  271. const cfg = config[key];
  272. if (!isObject(cfg)) {
  273. return;
  274. }
  275. const resolved = {};
  276. for (const option of animationOptions){
  277. resolved[option] = cfg[option];
  278. }
  279. (isArray(cfg.properties) && cfg.properties || [
  280. key
  281. ]).forEach((prop)=>{
  282. if (prop === key || !animatedProps.has(prop)) {
  283. animatedProps.set(prop, resolved);
  284. }
  285. });
  286. });
  287. }
  288. _animateOptions(target, values) {
  289. const newOptions = values.options;
  290. const options = resolveTargetOptions(target, newOptions);
  291. if (!options) {
  292. return [];
  293. }
  294. const animations = this._createAnimations(options, newOptions);
  295. if (newOptions.$shared) {
  296. awaitAll(target.options.$animations, newOptions).then(()=>{
  297. target.options = newOptions;
  298. }, ()=>{
  299. });
  300. }
  301. return animations;
  302. }
  303. _createAnimations(target, values) {
  304. const animatedProps = this._properties;
  305. const animations = [];
  306. const running = target.$animations || (target.$animations = {});
  307. const props = Object.keys(values);
  308. const date = Date.now();
  309. let i;
  310. for(i = props.length - 1; i >= 0; --i){
  311. const prop = props[i];
  312. if (prop.charAt(0) === '$') {
  313. continue;
  314. }
  315. if (prop === 'options') {
  316. animations.push(...this._animateOptions(target, values));
  317. continue;
  318. }
  319. const value = values[prop];
  320. let animation = running[prop];
  321. const cfg = animatedProps.get(prop);
  322. if (animation) {
  323. if (cfg && animation.active()) {
  324. animation.update(cfg, value, date);
  325. continue;
  326. } else {
  327. animation.cancel();
  328. }
  329. }
  330. if (!cfg || !cfg.duration) {
  331. target[prop] = value;
  332. continue;
  333. }
  334. running[prop] = animation = new Animation(cfg, target, prop, value);
  335. animations.push(animation);
  336. }
  337. return animations;
  338. }
  339. update(target, values) {
  340. if (this._properties.size === 0) {
  341. Object.assign(target, values);
  342. return;
  343. }
  344. const animations = this._createAnimations(target, values);
  345. if (animations.length) {
  346. animator.add(this._chart, animations);
  347. return true;
  348. }
  349. }
  350. }
  351. function awaitAll(animations, properties) {
  352. const running = [];
  353. const keys = Object.keys(properties);
  354. for(let i = 0; i < keys.length; i++){
  355. const anim = animations[keys[i]];
  356. if (anim && anim.active()) {
  357. running.push(anim.wait());
  358. }
  359. }
  360. return Promise.all(running);
  361. }
  362. function resolveTargetOptions(target, newOptions) {
  363. if (!newOptions) {
  364. return;
  365. }
  366. let options = target.options;
  367. if (!options) {
  368. target.options = newOptions;
  369. return;
  370. }
  371. if (options.$shared) {
  372. target.options = options = Object.assign({}, options, {
  373. $shared: false,
  374. $animations: {}
  375. });
  376. }
  377. return options;
  378. }
  379. function scaleClip(scale, allowedOverflow) {
  380. const opts = scale && scale.options || {};
  381. const reverse = opts.reverse;
  382. const min = opts.min === undefined ? allowedOverflow : 0;
  383. const max = opts.max === undefined ? allowedOverflow : 0;
  384. return {
  385. start: reverse ? max : min,
  386. end: reverse ? min : max
  387. };
  388. }
  389. function defaultClip(xScale, yScale, allowedOverflow) {
  390. if (allowedOverflow === false) {
  391. return false;
  392. }
  393. const x = scaleClip(xScale, allowedOverflow);
  394. const y = scaleClip(yScale, allowedOverflow);
  395. return {
  396. top: y.end,
  397. right: x.end,
  398. bottom: y.start,
  399. left: x.start
  400. };
  401. }
  402. function toClip(value) {
  403. let t, r, b, l;
  404. if (isObject(value)) {
  405. t = value.top;
  406. r = value.right;
  407. b = value.bottom;
  408. l = value.left;
  409. } else {
  410. t = r = b = l = value;
  411. }
  412. return {
  413. top: t,
  414. right: r,
  415. bottom: b,
  416. left: l,
  417. disabled: value === false
  418. };
  419. }
  420. function getSortedDatasetIndices(chart, filterVisible) {
  421. const keys = [];
  422. const metasets = chart._getSortedDatasetMetas(filterVisible);
  423. let i, ilen;
  424. for(i = 0, ilen = metasets.length; i < ilen; ++i){
  425. keys.push(metasets[i].index);
  426. }
  427. return keys;
  428. }
  429. function applyStack(stack, value, dsIndex, options = {}) {
  430. const keys = stack.keys;
  431. const singleMode = options.mode === 'single';
  432. let i, ilen, datasetIndex, otherValue;
  433. if (value === null) {
  434. return;
  435. }
  436. for(i = 0, ilen = keys.length; i < ilen; ++i){
  437. datasetIndex = +keys[i];
  438. if (datasetIndex === dsIndex) {
  439. if (options.all) {
  440. continue;
  441. }
  442. break;
  443. }
  444. otherValue = stack.values[datasetIndex];
  445. if (isNumberFinite(otherValue) && (singleMode || value === 0 || sign(value) === sign(otherValue))) {
  446. value += otherValue;
  447. }
  448. }
  449. return value;
  450. }
  451. function convertObjectDataToArray(data, meta) {
  452. const { iScale , vScale } = meta;
  453. const iAxisKey = iScale.axis === 'x' ? 'x' : 'y';
  454. const vAxisKey = vScale.axis === 'x' ? 'x' : 'y';
  455. const keys = Object.keys(data);
  456. const adata = new Array(keys.length);
  457. let i, ilen, key;
  458. for(i = 0, ilen = keys.length; i < ilen; ++i){
  459. key = keys[i];
  460. adata[i] = {
  461. [iAxisKey]: key,
  462. [vAxisKey]: data[key]
  463. };
  464. }
  465. return adata;
  466. }
  467. function isStacked(scale, meta) {
  468. const stacked = scale && scale.options.stacked;
  469. return stacked || stacked === undefined && meta.stack !== undefined;
  470. }
  471. function getStackKey(indexScale, valueScale, meta) {
  472. return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;
  473. }
  474. function getUserBounds(scale) {
  475. const { min , max , minDefined , maxDefined } = scale.getUserBounds();
  476. return {
  477. min: minDefined ? min : Number.NEGATIVE_INFINITY,
  478. max: maxDefined ? max : Number.POSITIVE_INFINITY
  479. };
  480. }
  481. function getOrCreateStack(stacks, stackKey, indexValue) {
  482. const subStack = stacks[stackKey] || (stacks[stackKey] = {});
  483. return subStack[indexValue] || (subStack[indexValue] = {});
  484. }
  485. function getLastIndexInStack(stack, vScale, positive, type) {
  486. for (const meta of vScale.getMatchingVisibleMetas(type).reverse()){
  487. const value = stack[meta.index];
  488. if (positive && value > 0 || !positive && value < 0) {
  489. return meta.index;
  490. }
  491. }
  492. return null;
  493. }
  494. function updateStacks(controller, parsed) {
  495. const { chart , _cachedMeta: meta } = controller;
  496. const stacks = chart._stacks || (chart._stacks = {});
  497. const { iScale , vScale , index: datasetIndex } = meta;
  498. const iAxis = iScale.axis;
  499. const vAxis = vScale.axis;
  500. const key = getStackKey(iScale, vScale, meta);
  501. const ilen = parsed.length;
  502. let stack;
  503. for(let i = 0; i < ilen; ++i){
  504. const item = parsed[i];
  505. const { [iAxis]: index , [vAxis]: value } = item;
  506. const itemStacks = item._stacks || (item._stacks = {});
  507. stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);
  508. stack[datasetIndex] = value;
  509. stack._top = getLastIndexInStack(stack, vScale, true, meta.type);
  510. stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type);
  511. const visualValues = stack._visualValues || (stack._visualValues = {});
  512. visualValues[datasetIndex] = value;
  513. }
  514. }
  515. function getFirstScaleId(chart, axis) {
  516. const scales = chart.scales;
  517. return Object.keys(scales).filter((key)=>scales[key].axis === axis).shift();
  518. }
  519. function createDatasetContext(parent, index) {
  520. return createContext(parent, {
  521. active: false,
  522. dataset: undefined,
  523. datasetIndex: index,
  524. index,
  525. mode: 'default',
  526. type: 'dataset'
  527. });
  528. }
  529. function createDataContext(parent, index, element) {
  530. return createContext(parent, {
  531. active: false,
  532. dataIndex: index,
  533. parsed: undefined,
  534. raw: undefined,
  535. element,
  536. index,
  537. mode: 'default',
  538. type: 'data'
  539. });
  540. }
  541. function clearStacks(meta, items) {
  542. const datasetIndex = meta.controller.index;
  543. const axis = meta.vScale && meta.vScale.axis;
  544. if (!axis) {
  545. return;
  546. }
  547. items = items || meta._parsed;
  548. for (const parsed of items){
  549. const stacks = parsed._stacks;
  550. if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {
  551. return;
  552. }
  553. delete stacks[axis][datasetIndex];
  554. if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) {
  555. delete stacks[axis]._visualValues[datasetIndex];
  556. }
  557. }
  558. }
  559. const isDirectUpdateMode = (mode)=>mode === 'reset' || mode === 'none';
  560. const cloneIfNotShared = (cached, shared)=>shared ? cached : Object.assign({}, cached);
  561. const createStack = (canStack, meta, chart)=>canStack && !meta.hidden && meta._stacked && {
  562. keys: getSortedDatasetIndices(chart, true),
  563. values: null
  564. };
  565. class DatasetController {
  566. static defaults = {};
  567. static datasetElementType = null;
  568. static dataElementType = null;
  569. constructor(chart, datasetIndex){
  570. this.chart = chart;
  571. this._ctx = chart.ctx;
  572. this.index = datasetIndex;
  573. this._cachedDataOpts = {};
  574. this._cachedMeta = this.getMeta();
  575. this._type = this._cachedMeta.type;
  576. this.options = undefined;
  577. this._parsing = false;
  578. this._data = undefined;
  579. this._objectData = undefined;
  580. this._sharedOptions = undefined;
  581. this._drawStart = undefined;
  582. this._drawCount = undefined;
  583. this.enableOptionSharing = false;
  584. this.supportsDecimation = false;
  585. this.$context = undefined;
  586. this._syncList = [];
  587. this.datasetElementType = new.target.datasetElementType;
  588. this.dataElementType = new.target.dataElementType;
  589. this.initialize();
  590. }
  591. initialize() {
  592. const meta = this._cachedMeta;
  593. this.configure();
  594. this.linkScales();
  595. meta._stacked = isStacked(meta.vScale, meta);
  596. this.addElements();
  597. if (this.options.fill && !this.chart.isPluginEnabled('filler')) {
  598. console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options");
  599. }
  600. }
  601. updateIndex(datasetIndex) {
  602. if (this.index !== datasetIndex) {
  603. clearStacks(this._cachedMeta);
  604. }
  605. this.index = datasetIndex;
  606. }
  607. linkScales() {
  608. const chart = this.chart;
  609. const meta = this._cachedMeta;
  610. const dataset = this.getDataset();
  611. const chooseId = (axis, x, y, r)=>axis === 'x' ? x : axis === 'r' ? r : y;
  612. const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));
  613. const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));
  614. const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));
  615. const indexAxis = meta.indexAxis;
  616. const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);
  617. const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);
  618. meta.xScale = this.getScaleForId(xid);
  619. meta.yScale = this.getScaleForId(yid);
  620. meta.rScale = this.getScaleForId(rid);
  621. meta.iScale = this.getScaleForId(iid);
  622. meta.vScale = this.getScaleForId(vid);
  623. }
  624. getDataset() {
  625. return this.chart.data.datasets[this.index];
  626. }
  627. getMeta() {
  628. return this.chart.getDatasetMeta(this.index);
  629. }
  630. getScaleForId(scaleID) {
  631. return this.chart.scales[scaleID];
  632. }
  633. _getOtherScale(scale) {
  634. const meta = this._cachedMeta;
  635. return scale === meta.iScale ? meta.vScale : meta.iScale;
  636. }
  637. reset() {
  638. this._update('reset');
  639. }
  640. _destroy() {
  641. const meta = this._cachedMeta;
  642. if (this._data) {
  643. unlistenArrayEvents(this._data, this);
  644. }
  645. if (meta._stacked) {
  646. clearStacks(meta);
  647. }
  648. }
  649. _dataCheck() {
  650. const dataset = this.getDataset();
  651. const data = dataset.data || (dataset.data = []);
  652. const _data = this._data;
  653. if (isObject(data)) {
  654. const meta = this._cachedMeta;
  655. this._data = convertObjectDataToArray(data, meta);
  656. } else if (_data !== data) {
  657. if (_data) {
  658. unlistenArrayEvents(_data, this);
  659. const meta = this._cachedMeta;
  660. clearStacks(meta);
  661. meta._parsed = [];
  662. }
  663. if (data && Object.isExtensible(data)) {
  664. listenArrayEvents(data, this);
  665. }
  666. this._syncList = [];
  667. this._data = data;
  668. }
  669. }
  670. addElements() {
  671. const meta = this._cachedMeta;
  672. this._dataCheck();
  673. if (this.datasetElementType) {
  674. meta.dataset = new this.datasetElementType();
  675. }
  676. }
  677. buildOrUpdateElements(resetNewElements) {
  678. const meta = this._cachedMeta;
  679. const dataset = this.getDataset();
  680. let stackChanged = false;
  681. this._dataCheck();
  682. const oldStacked = meta._stacked;
  683. meta._stacked = isStacked(meta.vScale, meta);
  684. if (meta.stack !== dataset.stack) {
  685. stackChanged = true;
  686. clearStacks(meta);
  687. meta.stack = dataset.stack;
  688. }
  689. this._resyncElements(resetNewElements);
  690. if (stackChanged || oldStacked !== meta._stacked) {
  691. updateStacks(this, meta._parsed);
  692. }
  693. }
  694. configure() {
  695. const config = this.chart.config;
  696. const scopeKeys = config.datasetScopeKeys(this._type);
  697. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true);
  698. this.options = config.createResolver(scopes, this.getContext());
  699. this._parsing = this.options.parsing;
  700. this._cachedDataOpts = {};
  701. }
  702. parse(start, count) {
  703. const { _cachedMeta: meta , _data: data } = this;
  704. const { iScale , _stacked } = meta;
  705. const iAxis = iScale.axis;
  706. let sorted = start === 0 && count === data.length ? true : meta._sorted;
  707. let prev = start > 0 && meta._parsed[start - 1];
  708. let i, cur, parsed;
  709. if (this._parsing === false) {
  710. meta._parsed = data;
  711. meta._sorted = true;
  712. parsed = data;
  713. } else {
  714. if (isArray(data[start])) {
  715. parsed = this.parseArrayData(meta, data, start, count);
  716. } else if (isObject(data[start])) {
  717. parsed = this.parseObjectData(meta, data, start, count);
  718. } else {
  719. parsed = this.parsePrimitiveData(meta, data, start, count);
  720. }
  721. const isNotInOrderComparedToPrev = ()=>cur[iAxis] === null || prev && cur[iAxis] < prev[iAxis];
  722. for(i = 0; i < count; ++i){
  723. meta._parsed[i + start] = cur = parsed[i];
  724. if (sorted) {
  725. if (isNotInOrderComparedToPrev()) {
  726. sorted = false;
  727. }
  728. prev = cur;
  729. }
  730. }
  731. meta._sorted = sorted;
  732. }
  733. if (_stacked) {
  734. updateStacks(this, parsed);
  735. }
  736. }
  737. parsePrimitiveData(meta, data, start, count) {
  738. const { iScale , vScale } = meta;
  739. const iAxis = iScale.axis;
  740. const vAxis = vScale.axis;
  741. const labels = iScale.getLabels();
  742. const singleScale = iScale === vScale;
  743. const parsed = new Array(count);
  744. let i, ilen, index;
  745. for(i = 0, ilen = count; i < ilen; ++i){
  746. index = i + start;
  747. parsed[i] = {
  748. [iAxis]: singleScale || iScale.parse(labels[index], index),
  749. [vAxis]: vScale.parse(data[index], index)
  750. };
  751. }
  752. return parsed;
  753. }
  754. parseArrayData(meta, data, start, count) {
  755. const { xScale , yScale } = meta;
  756. const parsed = new Array(count);
  757. let i, ilen, index, item;
  758. for(i = 0, ilen = count; i < ilen; ++i){
  759. index = i + start;
  760. item = data[index];
  761. parsed[i] = {
  762. x: xScale.parse(item[0], index),
  763. y: yScale.parse(item[1], index)
  764. };
  765. }
  766. return parsed;
  767. }
  768. parseObjectData(meta, data, start, count) {
  769. const { xScale , yScale } = meta;
  770. const { xAxisKey ='x' , yAxisKey ='y' } = this._parsing;
  771. const parsed = new Array(count);
  772. let i, ilen, index, item;
  773. for(i = 0, ilen = count; i < ilen; ++i){
  774. index = i + start;
  775. item = data[index];
  776. parsed[i] = {
  777. x: xScale.parse(resolveObjectKey(item, xAxisKey), index),
  778. y: yScale.parse(resolveObjectKey(item, yAxisKey), index)
  779. };
  780. }
  781. return parsed;
  782. }
  783. getParsed(index) {
  784. return this._cachedMeta._parsed[index];
  785. }
  786. getDataElement(index) {
  787. return this._cachedMeta.data[index];
  788. }
  789. applyStack(scale, parsed, mode) {
  790. const chart = this.chart;
  791. const meta = this._cachedMeta;
  792. const value = parsed[scale.axis];
  793. const stack = {
  794. keys: getSortedDatasetIndices(chart, true),
  795. values: parsed._stacks[scale.axis]._visualValues
  796. };
  797. return applyStack(stack, value, meta.index, {
  798. mode
  799. });
  800. }
  801. updateRangeFromParsed(range, scale, parsed, stack) {
  802. const parsedValue = parsed[scale.axis];
  803. let value = parsedValue === null ? NaN : parsedValue;
  804. const values = stack && parsed._stacks[scale.axis];
  805. if (stack && values) {
  806. stack.values = values;
  807. value = applyStack(stack, parsedValue, this._cachedMeta.index);
  808. }
  809. range.min = Math.min(range.min, value);
  810. range.max = Math.max(range.max, value);
  811. }
  812. getMinMax(scale, canStack) {
  813. const meta = this._cachedMeta;
  814. const _parsed = meta._parsed;
  815. const sorted = meta._sorted && scale === meta.iScale;
  816. const ilen = _parsed.length;
  817. const otherScale = this._getOtherScale(scale);
  818. const stack = createStack(canStack, meta, this.chart);
  819. const range = {
  820. min: Number.POSITIVE_INFINITY,
  821. max: Number.NEGATIVE_INFINITY
  822. };
  823. const { min: otherMin , max: otherMax } = getUserBounds(otherScale);
  824. let i, parsed;
  825. function _skip() {
  826. parsed = _parsed[i];
  827. const otherValue = parsed[otherScale.axis];
  828. return !isNumberFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue;
  829. }
  830. for(i = 0; i < ilen; ++i){
  831. if (_skip()) {
  832. continue;
  833. }
  834. this.updateRangeFromParsed(range, scale, parsed, stack);
  835. if (sorted) {
  836. break;
  837. }
  838. }
  839. if (sorted) {
  840. for(i = ilen - 1; i >= 0; --i){
  841. if (_skip()) {
  842. continue;
  843. }
  844. this.updateRangeFromParsed(range, scale, parsed, stack);
  845. break;
  846. }
  847. }
  848. return range;
  849. }
  850. getAllParsedValues(scale) {
  851. const parsed = this._cachedMeta._parsed;
  852. const values = [];
  853. let i, ilen, value;
  854. for(i = 0, ilen = parsed.length; i < ilen; ++i){
  855. value = parsed[i][scale.axis];
  856. if (isNumberFinite(value)) {
  857. values.push(value);
  858. }
  859. }
  860. return values;
  861. }
  862. getMaxOverflow() {
  863. return false;
  864. }
  865. getLabelAndValue(index) {
  866. const meta = this._cachedMeta;
  867. const iScale = meta.iScale;
  868. const vScale = meta.vScale;
  869. const parsed = this.getParsed(index);
  870. return {
  871. label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',
  872. value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''
  873. };
  874. }
  875. _update(mode) {
  876. const meta = this._cachedMeta;
  877. this.update(mode || 'default');
  878. meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow())));
  879. }
  880. update(mode) {}
  881. draw() {
  882. const ctx = this._ctx;
  883. const chart = this.chart;
  884. const meta = this._cachedMeta;
  885. const elements = meta.data || [];
  886. const area = chart.chartArea;
  887. const active = [];
  888. const start = this._drawStart || 0;
  889. const count = this._drawCount || elements.length - start;
  890. const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop;
  891. let i;
  892. if (meta.dataset) {
  893. meta.dataset.draw(ctx, area, start, count);
  894. }
  895. for(i = start; i < start + count; ++i){
  896. const element = elements[i];
  897. if (element.hidden) {
  898. continue;
  899. }
  900. if (element.active && drawActiveElementsOnTop) {
  901. active.push(element);
  902. } else {
  903. element.draw(ctx, area);
  904. }
  905. }
  906. for(i = 0; i < active.length; ++i){
  907. active[i].draw(ctx, area);
  908. }
  909. }
  910. getStyle(index, active) {
  911. const mode = active ? 'active' : 'default';
  912. return index === undefined && this._cachedMeta.dataset ? this.resolveDatasetElementOptions(mode) : this.resolveDataElementOptions(index || 0, mode);
  913. }
  914. getContext(index, active, mode) {
  915. const dataset = this.getDataset();
  916. let context;
  917. if (index >= 0 && index < this._cachedMeta.data.length) {
  918. const element = this._cachedMeta.data[index];
  919. context = element.$context || (element.$context = createDataContext(this.getContext(), index, element));
  920. context.parsed = this.getParsed(index);
  921. context.raw = dataset.data[index];
  922. context.index = context.dataIndex = index;
  923. } else {
  924. context = this.$context || (this.$context = createDatasetContext(this.chart.getContext(), this.index));
  925. context.dataset = dataset;
  926. context.index = context.datasetIndex = this.index;
  927. }
  928. context.active = !!active;
  929. context.mode = mode;
  930. return context;
  931. }
  932. resolveDatasetElementOptions(mode) {
  933. return this._resolveElementOptions(this.datasetElementType.id, mode);
  934. }
  935. resolveDataElementOptions(index, mode) {
  936. return this._resolveElementOptions(this.dataElementType.id, mode, index);
  937. }
  938. _resolveElementOptions(elementType, mode = 'default', index) {
  939. const active = mode === 'active';
  940. const cache = this._cachedDataOpts;
  941. const cacheKey = elementType + '-' + mode;
  942. const cached = cache[cacheKey];
  943. const sharing = this.enableOptionSharing && defined(index);
  944. if (cached) {
  945. return cloneIfNotShared(cached, sharing);
  946. }
  947. const config = this.chart.config;
  948. const scopeKeys = config.datasetElementScopeKeys(this._type, elementType);
  949. const prefixes = active ? [
  950. `${elementType}Hover`,
  951. 'hover',
  952. elementType,
  953. ''
  954. ] : [
  955. elementType,
  956. ''
  957. ];
  958. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);
  959. const names = Object.keys(defaults.elements[elementType]);
  960. const context = ()=>this.getContext(index, active, mode);
  961. const values = config.resolveNamedOptions(scopes, names, context, prefixes);
  962. if (values.$shared) {
  963. values.$shared = sharing;
  964. cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));
  965. }
  966. return values;
  967. }
  968. _resolveAnimations(index, transition, active) {
  969. const chart = this.chart;
  970. const cache = this._cachedDataOpts;
  971. const cacheKey = `animation-${transition}`;
  972. const cached = cache[cacheKey];
  973. if (cached) {
  974. return cached;
  975. }
  976. let options;
  977. if (chart.options.animation !== false) {
  978. const config = this.chart.config;
  979. const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition);
  980. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);
  981. options = config.createResolver(scopes, this.getContext(index, active, transition));
  982. }
  983. const animations = new Animations(chart, options && options.animations);
  984. if (options && options._cacheable) {
  985. cache[cacheKey] = Object.freeze(animations);
  986. }
  987. return animations;
  988. }
  989. getSharedOptions(options) {
  990. if (!options.$shared) {
  991. return;
  992. }
  993. return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));
  994. }
  995. includeOptions(mode, sharedOptions) {
  996. return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;
  997. }
  998. _getSharedOptions(start, mode) {
  999. const firstOpts = this.resolveDataElementOptions(start, mode);
  1000. const previouslySharedOptions = this._sharedOptions;
  1001. const sharedOptions = this.getSharedOptions(firstOpts);
  1002. const includeOptions = this.includeOptions(mode, sharedOptions) || sharedOptions !== previouslySharedOptions;
  1003. this.updateSharedOptions(sharedOptions, mode, firstOpts);
  1004. return {
  1005. sharedOptions,
  1006. includeOptions
  1007. };
  1008. }
  1009. updateElement(element, index, properties, mode) {
  1010. if (isDirectUpdateMode(mode)) {
  1011. Object.assign(element, properties);
  1012. } else {
  1013. this._resolveAnimations(index, mode).update(element, properties);
  1014. }
  1015. }
  1016. updateSharedOptions(sharedOptions, mode, newOptions) {
  1017. if (sharedOptions && !isDirectUpdateMode(mode)) {
  1018. this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);
  1019. }
  1020. }
  1021. _setStyle(element, index, mode, active) {
  1022. element.active = active;
  1023. const options = this.getStyle(index, active);
  1024. this._resolveAnimations(index, mode, active).update(element, {
  1025. options: !active && this.getSharedOptions(options) || options
  1026. });
  1027. }
  1028. removeHoverStyle(element, datasetIndex, index) {
  1029. this._setStyle(element, index, 'active', false);
  1030. }
  1031. setHoverStyle(element, datasetIndex, index) {
  1032. this._setStyle(element, index, 'active', true);
  1033. }
  1034. _removeDatasetHoverStyle() {
  1035. const element = this._cachedMeta.dataset;
  1036. if (element) {
  1037. this._setStyle(element, undefined, 'active', false);
  1038. }
  1039. }
  1040. _setDatasetHoverStyle() {
  1041. const element = this._cachedMeta.dataset;
  1042. if (element) {
  1043. this._setStyle(element, undefined, 'active', true);
  1044. }
  1045. }
  1046. _resyncElements(resetNewElements) {
  1047. const data = this._data;
  1048. const elements = this._cachedMeta.data;
  1049. for (const [method, arg1, arg2] of this._syncList){
  1050. this[method](arg1, arg2);
  1051. }
  1052. this._syncList = [];
  1053. const numMeta = elements.length;
  1054. const numData = data.length;
  1055. const count = Math.min(numData, numMeta);
  1056. if (count) {
  1057. this.parse(0, count);
  1058. }
  1059. if (numData > numMeta) {
  1060. this._insertElements(numMeta, numData - numMeta, resetNewElements);
  1061. } else if (numData < numMeta) {
  1062. this._removeElements(numData, numMeta - numData);
  1063. }
  1064. }
  1065. _insertElements(start, count, resetNewElements = true) {
  1066. const meta = this._cachedMeta;
  1067. const data = meta.data;
  1068. const end = start + count;
  1069. let i;
  1070. const move = (arr)=>{
  1071. arr.length += count;
  1072. for(i = arr.length - 1; i >= end; i--){
  1073. arr[i] = arr[i - count];
  1074. }
  1075. };
  1076. move(data);
  1077. for(i = start; i < end; ++i){
  1078. data[i] = new this.dataElementType();
  1079. }
  1080. if (this._parsing) {
  1081. move(meta._parsed);
  1082. }
  1083. this.parse(start, count);
  1084. if (resetNewElements) {
  1085. this.updateElements(data, start, count, 'reset');
  1086. }
  1087. }
  1088. updateElements(element, start, count, mode) {}
  1089. _removeElements(start, count) {
  1090. const meta = this._cachedMeta;
  1091. if (this._parsing) {
  1092. const removed = meta._parsed.splice(start, count);
  1093. if (meta._stacked) {
  1094. clearStacks(meta, removed);
  1095. }
  1096. }
  1097. meta.data.splice(start, count);
  1098. }
  1099. _sync(args) {
  1100. if (this._parsing) {
  1101. this._syncList.push(args);
  1102. } else {
  1103. const [method, arg1, arg2] = args;
  1104. this[method](arg1, arg2);
  1105. }
  1106. this.chart._dataChanges.push([
  1107. this.index,
  1108. ...args
  1109. ]);
  1110. }
  1111. _onDataPush() {
  1112. const count = arguments.length;
  1113. this._sync([
  1114. '_insertElements',
  1115. this.getDataset().data.length - count,
  1116. count
  1117. ]);
  1118. }
  1119. _onDataPop() {
  1120. this._sync([
  1121. '_removeElements',
  1122. this._cachedMeta.data.length - 1,
  1123. 1
  1124. ]);
  1125. }
  1126. _onDataShift() {
  1127. this._sync([
  1128. '_removeElements',
  1129. 0,
  1130. 1
  1131. ]);
  1132. }
  1133. _onDataSplice(start, count) {
  1134. if (count) {
  1135. this._sync([
  1136. '_removeElements',
  1137. start,
  1138. count
  1139. ]);
  1140. }
  1141. const newCount = arguments.length - 2;
  1142. if (newCount) {
  1143. this._sync([
  1144. '_insertElements',
  1145. start,
  1146. newCount
  1147. ]);
  1148. }
  1149. }
  1150. _onDataUnshift() {
  1151. this._sync([
  1152. '_insertElements',
  1153. 0,
  1154. arguments.length
  1155. ]);
  1156. }
  1157. }
  1158. function getAllScaleValues(scale, type) {
  1159. if (!scale._cache.$bar) {
  1160. const visibleMetas = scale.getMatchingVisibleMetas(type);
  1161. let values = [];
  1162. for(let i = 0, ilen = visibleMetas.length; i < ilen; i++){
  1163. values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale));
  1164. }
  1165. scale._cache.$bar = _arrayUnique(values.sort((a, b)=>a - b));
  1166. }
  1167. return scale._cache.$bar;
  1168. }
  1169. function computeMinSampleSize(meta) {
  1170. const scale = meta.iScale;
  1171. const values = getAllScaleValues(scale, meta.type);
  1172. let min = scale._length;
  1173. let i, ilen, curr, prev;
  1174. const updateMinAndPrev = ()=>{
  1175. if (curr === 32767 || curr === -32768) {
  1176. return;
  1177. }
  1178. if (defined(prev)) {
  1179. min = Math.min(min, Math.abs(curr - prev) || min);
  1180. }
  1181. prev = curr;
  1182. };
  1183. for(i = 0, ilen = values.length; i < ilen; ++i){
  1184. curr = scale.getPixelForValue(values[i]);
  1185. updateMinAndPrev();
  1186. }
  1187. prev = undefined;
  1188. for(i = 0, ilen = scale.ticks.length; i < ilen; ++i){
  1189. curr = scale.getPixelForTick(i);
  1190. updateMinAndPrev();
  1191. }
  1192. return min;
  1193. }
  1194. function computeFitCategoryTraits(index, ruler, options, stackCount) {
  1195. const thickness = options.barThickness;
  1196. let size, ratio;
  1197. if (isNullOrUndef(thickness)) {
  1198. size = ruler.min * options.categoryPercentage;
  1199. ratio = options.barPercentage;
  1200. } else {
  1201. size = thickness * stackCount;
  1202. ratio = 1;
  1203. }
  1204. return {
  1205. chunk: size / stackCount,
  1206. ratio,
  1207. start: ruler.pixels[index] - size / 2
  1208. };
  1209. }
  1210. function computeFlexCategoryTraits(index, ruler, options, stackCount) {
  1211. const pixels = ruler.pixels;
  1212. const curr = pixels[index];
  1213. let prev = index > 0 ? pixels[index - 1] : null;
  1214. let next = index < pixels.length - 1 ? pixels[index + 1] : null;
  1215. const percent = options.categoryPercentage;
  1216. if (prev === null) {
  1217. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  1218. }
  1219. if (next === null) {
  1220. next = curr + curr - prev;
  1221. }
  1222. const start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  1223. const size = Math.abs(next - prev) / 2 * percent;
  1224. return {
  1225. chunk: size / stackCount,
  1226. ratio: options.barPercentage,
  1227. start
  1228. };
  1229. }
  1230. function parseFloatBar(entry, item, vScale, i) {
  1231. const startValue = vScale.parse(entry[0], i);
  1232. const endValue = vScale.parse(entry[1], i);
  1233. const min = Math.min(startValue, endValue);
  1234. const max = Math.max(startValue, endValue);
  1235. let barStart = min;
  1236. let barEnd = max;
  1237. if (Math.abs(min) > Math.abs(max)) {
  1238. barStart = max;
  1239. barEnd = min;
  1240. }
  1241. item[vScale.axis] = barEnd;
  1242. item._custom = {
  1243. barStart,
  1244. barEnd,
  1245. start: startValue,
  1246. end: endValue,
  1247. min,
  1248. max
  1249. };
  1250. }
  1251. function parseValue(entry, item, vScale, i) {
  1252. if (isArray(entry)) {
  1253. parseFloatBar(entry, item, vScale, i);
  1254. } else {
  1255. item[vScale.axis] = vScale.parse(entry, i);
  1256. }
  1257. return item;
  1258. }
  1259. function parseArrayOrPrimitive(meta, data, start, count) {
  1260. const iScale = meta.iScale;
  1261. const vScale = meta.vScale;
  1262. const labels = iScale.getLabels();
  1263. const singleScale = iScale === vScale;
  1264. const parsed = [];
  1265. let i, ilen, item, entry;
  1266. for(i = start, ilen = start + count; i < ilen; ++i){
  1267. entry = data[i];
  1268. item = {};
  1269. item[iScale.axis] = singleScale || iScale.parse(labels[i], i);
  1270. parsed.push(parseValue(entry, item, vScale, i));
  1271. }
  1272. return parsed;
  1273. }
  1274. function isFloatBar(custom) {
  1275. return custom && custom.barStart !== undefined && custom.barEnd !== undefined;
  1276. }
  1277. function barSign(size, vScale, actualBase) {
  1278. if (size !== 0) {
  1279. return sign(size);
  1280. }
  1281. return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);
  1282. }
  1283. function borderProps(properties) {
  1284. let reverse, start, end, top, bottom;
  1285. if (properties.horizontal) {
  1286. reverse = properties.base > properties.x;
  1287. start = 'left';
  1288. end = 'right';
  1289. } else {
  1290. reverse = properties.base < properties.y;
  1291. start = 'bottom';
  1292. end = 'top';
  1293. }
  1294. if (reverse) {
  1295. top = 'end';
  1296. bottom = 'start';
  1297. } else {
  1298. top = 'start';
  1299. bottom = 'end';
  1300. }
  1301. return {
  1302. start,
  1303. end,
  1304. reverse,
  1305. top,
  1306. bottom
  1307. };
  1308. }
  1309. function setBorderSkipped(properties, options, stack, index) {
  1310. let edge = options.borderSkipped;
  1311. const res = {};
  1312. if (!edge) {
  1313. properties.borderSkipped = res;
  1314. return;
  1315. }
  1316. if (edge === true) {
  1317. properties.borderSkipped = {
  1318. top: true,
  1319. right: true,
  1320. bottom: true,
  1321. left: true
  1322. };
  1323. return;
  1324. }
  1325. const { start , end , reverse , top , bottom } = borderProps(properties);
  1326. if (edge === 'middle' && stack) {
  1327. properties.enableBorderRadius = true;
  1328. if ((stack._top || 0) === index) {
  1329. edge = top;
  1330. } else if ((stack._bottom || 0) === index) {
  1331. edge = bottom;
  1332. } else {
  1333. res[parseEdge(bottom, start, end, reverse)] = true;
  1334. edge = top;
  1335. }
  1336. }
  1337. res[parseEdge(edge, start, end, reverse)] = true;
  1338. properties.borderSkipped = res;
  1339. }
  1340. function parseEdge(edge, a, b, reverse) {
  1341. if (reverse) {
  1342. edge = swap(edge, a, b);
  1343. edge = startEnd(edge, b, a);
  1344. } else {
  1345. edge = startEnd(edge, a, b);
  1346. }
  1347. return edge;
  1348. }
  1349. function swap(orig, v1, v2) {
  1350. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  1351. }
  1352. function startEnd(v, start, end) {
  1353. return v === 'start' ? start : v === 'end' ? end : v;
  1354. }
  1355. function setInflateAmount(properties, { inflateAmount }, ratio) {
  1356. properties.inflateAmount = inflateAmount === 'auto' ? ratio === 1 ? 0.33 : 0 : inflateAmount;
  1357. }
  1358. class BarController extends DatasetController {
  1359. static id = 'bar';
  1360. static defaults = {
  1361. datasetElementType: false,
  1362. dataElementType: 'bar',
  1363. categoryPercentage: 0.8,
  1364. barPercentage: 0.9,
  1365. grouped: true,
  1366. animations: {
  1367. numbers: {
  1368. type: 'number',
  1369. properties: [
  1370. 'x',
  1371. 'y',
  1372. 'base',
  1373. 'width',
  1374. 'height'
  1375. ]
  1376. }
  1377. }
  1378. };
  1379. static overrides = {
  1380. scales: {
  1381. _index_: {
  1382. type: 'category',
  1383. offset: true,
  1384. grid: {
  1385. offset: true
  1386. }
  1387. },
  1388. _value_: {
  1389. type: 'linear',
  1390. beginAtZero: true
  1391. }
  1392. }
  1393. };
  1394. parsePrimitiveData(meta, data, start, count) {
  1395. return parseArrayOrPrimitive(meta, data, start, count);
  1396. }
  1397. parseArrayData(meta, data, start, count) {
  1398. return parseArrayOrPrimitive(meta, data, start, count);
  1399. }
  1400. parseObjectData(meta, data, start, count) {
  1401. const { iScale , vScale } = meta;
  1402. const { xAxisKey ='x' , yAxisKey ='y' } = this._parsing;
  1403. const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;
  1404. const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;
  1405. const parsed = [];
  1406. let i, ilen, item, obj;
  1407. for(i = start, ilen = start + count; i < ilen; ++i){
  1408. obj = data[i];
  1409. item = {};
  1410. item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);
  1411. parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));
  1412. }
  1413. return parsed;
  1414. }
  1415. updateRangeFromParsed(range, scale, parsed, stack) {
  1416. super.updateRangeFromParsed(range, scale, parsed, stack);
  1417. const custom = parsed._custom;
  1418. if (custom && scale === this._cachedMeta.vScale) {
  1419. range.min = Math.min(range.min, custom.min);
  1420. range.max = Math.max(range.max, custom.max);
  1421. }
  1422. }
  1423. getMaxOverflow() {
  1424. return 0;
  1425. }
  1426. getLabelAndValue(index) {
  1427. const meta = this._cachedMeta;
  1428. const { iScale , vScale } = meta;
  1429. const parsed = this.getParsed(index);
  1430. const custom = parsed._custom;
  1431. const value = isFloatBar(custom) ? '[' + custom.start + ', ' + custom.end + ']' : '' + vScale.getLabelForValue(parsed[vScale.axis]);
  1432. return {
  1433. label: '' + iScale.getLabelForValue(parsed[iScale.axis]),
  1434. value
  1435. };
  1436. }
  1437. initialize() {
  1438. this.enableOptionSharing = true;
  1439. super.initialize();
  1440. const meta = this._cachedMeta;
  1441. meta.stack = this.getDataset().stack;
  1442. }
  1443. update(mode) {
  1444. const meta = this._cachedMeta;
  1445. this.updateElements(meta.data, 0, meta.data.length, mode);
  1446. }
  1447. updateElements(bars, start, count, mode) {
  1448. const reset = mode === 'reset';
  1449. const { index , _cachedMeta: { vScale } } = this;
  1450. const base = vScale.getBasePixel();
  1451. const horizontal = vScale.isHorizontal();
  1452. const ruler = this._getRuler();
  1453. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  1454. for(let i = start; i < start + count; i++){
  1455. const parsed = this.getParsed(i);
  1456. const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {
  1457. base,
  1458. head: base
  1459. } : this._calculateBarValuePixels(i);
  1460. const ipixels = this._calculateBarIndexPixels(i, ruler);
  1461. const stack = (parsed._stacks || {})[vScale.axis];
  1462. const properties = {
  1463. horizontal,
  1464. base: vpixels.base,
  1465. enableBorderRadius: !stack || isFloatBar(parsed._custom) || index === stack._top || index === stack._bottom,
  1466. x: horizontal ? vpixels.head : ipixels.center,
  1467. y: horizontal ? ipixels.center : vpixels.head,
  1468. height: horizontal ? ipixels.size : Math.abs(vpixels.size),
  1469. width: horizontal ? Math.abs(vpixels.size) : ipixels.size
  1470. };
  1471. if (includeOptions) {
  1472. properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);
  1473. }
  1474. const options = properties.options || bars[i].options;
  1475. setBorderSkipped(properties, options, stack, index);
  1476. setInflateAmount(properties, options, ruler.ratio);
  1477. this.updateElement(bars[i], i, properties, mode);
  1478. }
  1479. }
  1480. _getStacks(last, dataIndex) {
  1481. const { iScale } = this._cachedMeta;
  1482. const metasets = iScale.getMatchingVisibleMetas(this._type).filter((meta)=>meta.controller.options.grouped);
  1483. const stacked = iScale.options.stacked;
  1484. const stacks = [];
  1485. const currentParsed = this._cachedMeta.controller.getParsed(dataIndex);
  1486. const iScaleValue = currentParsed && currentParsed[iScale.axis];
  1487. const skipNull = (meta)=>{
  1488. const parsed = meta._parsed.find((item)=>item[iScale.axis] === iScaleValue);
  1489. const val = parsed && parsed[meta.vScale.axis];
  1490. if (isNullOrUndef(val) || isNaN(val)) {
  1491. return true;
  1492. }
  1493. };
  1494. for (const meta of metasets){
  1495. if (dataIndex !== undefined && skipNull(meta)) {
  1496. continue;
  1497. }
  1498. if (stacked === false || stacks.indexOf(meta.stack) === -1 || stacked === undefined && meta.stack === undefined) {
  1499. stacks.push(meta.stack);
  1500. }
  1501. if (meta.index === last) {
  1502. break;
  1503. }
  1504. }
  1505. if (!stacks.length) {
  1506. stacks.push(undefined);
  1507. }
  1508. return stacks;
  1509. }
  1510. _getStackCount(index) {
  1511. return this._getStacks(undefined, index).length;
  1512. }
  1513. _getStackIndex(datasetIndex, name, dataIndex) {
  1514. const stacks = this._getStacks(datasetIndex, dataIndex);
  1515. const index = name !== undefined ? stacks.indexOf(name) : -1;
  1516. return index === -1 ? stacks.length - 1 : index;
  1517. }
  1518. _getRuler() {
  1519. const opts = this.options;
  1520. const meta = this._cachedMeta;
  1521. const iScale = meta.iScale;
  1522. const pixels = [];
  1523. let i, ilen;
  1524. for(i = 0, ilen = meta.data.length; i < ilen; ++i){
  1525. pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i));
  1526. }
  1527. const barThickness = opts.barThickness;
  1528. const min = barThickness || computeMinSampleSize(meta);
  1529. return {
  1530. min,
  1531. pixels,
  1532. start: iScale._startPixel,
  1533. end: iScale._endPixel,
  1534. stackCount: this._getStackCount(),
  1535. scale: iScale,
  1536. grouped: opts.grouped,
  1537. ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage
  1538. };
  1539. }
  1540. _calculateBarValuePixels(index) {
  1541. const { _cachedMeta: { vScale , _stacked , index: datasetIndex } , options: { base: baseValue , minBarLength } } = this;
  1542. const actualBase = baseValue || 0;
  1543. const parsed = this.getParsed(index);
  1544. const custom = parsed._custom;
  1545. const floating = isFloatBar(custom);
  1546. let value = parsed[vScale.axis];
  1547. let start = 0;
  1548. let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value;
  1549. let head, size;
  1550. if (length !== value) {
  1551. start = length - value;
  1552. length = value;
  1553. }
  1554. if (floating) {
  1555. value = custom.barStart;
  1556. length = custom.barEnd - custom.barStart;
  1557. if (value !== 0 && sign(value) !== sign(custom.barEnd)) {
  1558. start = 0;
  1559. }
  1560. start += value;
  1561. }
  1562. const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;
  1563. let base = vScale.getPixelForValue(startValue);
  1564. if (this.chart.getDataVisibility(index)) {
  1565. head = vScale.getPixelForValue(start + length);
  1566. } else {
  1567. head = base;
  1568. }
  1569. size = head - base;
  1570. if (Math.abs(size) < minBarLength) {
  1571. size = barSign(size, vScale, actualBase) * minBarLength;
  1572. if (value === actualBase) {
  1573. base -= size / 2;
  1574. }
  1575. const startPixel = vScale.getPixelForDecimal(0);
  1576. const endPixel = vScale.getPixelForDecimal(1);
  1577. const min = Math.min(startPixel, endPixel);
  1578. const max = Math.max(startPixel, endPixel);
  1579. base = Math.max(Math.min(base, max), min);
  1580. head = base + size;
  1581. if (_stacked && !floating) {
  1582. parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base);
  1583. }
  1584. }
  1585. if (base === vScale.getPixelForValue(actualBase)) {
  1586. const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2;
  1587. base += halfGrid;
  1588. size -= halfGrid;
  1589. }
  1590. return {
  1591. size,
  1592. base,
  1593. head,
  1594. center: head + size / 2
  1595. };
  1596. }
  1597. _calculateBarIndexPixels(index, ruler) {
  1598. const scale = ruler.scale;
  1599. const options = this.options;
  1600. const skipNull = options.skipNull;
  1601. const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);
  1602. let center, size;
  1603. if (ruler.grouped) {
  1604. const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount;
  1605. const range = options.barThickness === 'flex' ? computeFlexCategoryTraits(index, ruler, options, stackCount) : computeFitCategoryTraits(index, ruler, options, stackCount);
  1606. const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined);
  1607. center = range.start + range.chunk * stackIndex + range.chunk / 2;
  1608. size = Math.min(maxBarThickness, range.chunk * range.ratio);
  1609. } else {
  1610. center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index);
  1611. size = Math.min(maxBarThickness, ruler.min * ruler.ratio);
  1612. }
  1613. return {
  1614. base: center - size / 2,
  1615. head: center + size / 2,
  1616. center,
  1617. size
  1618. };
  1619. }
  1620. draw() {
  1621. const meta = this._cachedMeta;
  1622. const vScale = meta.vScale;
  1623. const rects = meta.data;
  1624. const ilen = rects.length;
  1625. let i = 0;
  1626. for(; i < ilen; ++i){
  1627. if (this.getParsed(i)[vScale.axis] !== null && !rects[i].hidden) {
  1628. rects[i].draw(this._ctx);
  1629. }
  1630. }
  1631. }
  1632. }
  1633. class BubbleController extends DatasetController {
  1634. static id = 'bubble';
  1635. static defaults = {
  1636. datasetElementType: false,
  1637. dataElementType: 'point',
  1638. animations: {
  1639. numbers: {
  1640. type: 'number',
  1641. properties: [
  1642. 'x',
  1643. 'y',
  1644. 'borderWidth',
  1645. 'radius'
  1646. ]
  1647. }
  1648. }
  1649. };
  1650. static overrides = {
  1651. scales: {
  1652. x: {
  1653. type: 'linear'
  1654. },
  1655. y: {
  1656. type: 'linear'
  1657. }
  1658. }
  1659. };
  1660. initialize() {
  1661. this.enableOptionSharing = true;
  1662. super.initialize();
  1663. }
  1664. parsePrimitiveData(meta, data, start, count) {
  1665. const parsed = super.parsePrimitiveData(meta, data, start, count);
  1666. for(let i = 0; i < parsed.length; i++){
  1667. parsed[i]._custom = this.resolveDataElementOptions(i + start).radius;
  1668. }
  1669. return parsed;
  1670. }
  1671. parseArrayData(meta, data, start, count) {
  1672. const parsed = super.parseArrayData(meta, data, start, count);
  1673. for(let i = 0; i < parsed.length; i++){
  1674. const item = data[start + i];
  1675. parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius);
  1676. }
  1677. return parsed;
  1678. }
  1679. parseObjectData(meta, data, start, count) {
  1680. const parsed = super.parseObjectData(meta, data, start, count);
  1681. for(let i = 0; i < parsed.length; i++){
  1682. const item = data[start + i];
  1683. parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius);
  1684. }
  1685. return parsed;
  1686. }
  1687. getMaxOverflow() {
  1688. const data = this._cachedMeta.data;
  1689. let max = 0;
  1690. for(let i = data.length - 1; i >= 0; --i){
  1691. max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);
  1692. }
  1693. return max > 0 && max;
  1694. }
  1695. getLabelAndValue(index) {
  1696. const meta = this._cachedMeta;
  1697. const labels = this.chart.data.labels || [];
  1698. const { xScale , yScale } = meta;
  1699. const parsed = this.getParsed(index);
  1700. const x = xScale.getLabelForValue(parsed.x);
  1701. const y = yScale.getLabelForValue(parsed.y);
  1702. const r = parsed._custom;
  1703. return {
  1704. label: labels[index] || '',
  1705. value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'
  1706. };
  1707. }
  1708. update(mode) {
  1709. const points = this._cachedMeta.data;
  1710. this.updateElements(points, 0, points.length, mode);
  1711. }
  1712. updateElements(points, start, count, mode) {
  1713. const reset = mode === 'reset';
  1714. const { iScale , vScale } = this._cachedMeta;
  1715. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  1716. const iAxis = iScale.axis;
  1717. const vAxis = vScale.axis;
  1718. for(let i = start; i < start + count; i++){
  1719. const point = points[i];
  1720. const parsed = !reset && this.getParsed(i);
  1721. const properties = {};
  1722. const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);
  1723. const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);
  1724. properties.skip = isNaN(iPixel) || isNaN(vPixel);
  1725. if (includeOptions) {
  1726. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  1727. if (reset) {
  1728. properties.options.radius = 0;
  1729. }
  1730. }
  1731. this.updateElement(point, i, properties, mode);
  1732. }
  1733. }
  1734. resolveDataElementOptions(index, mode) {
  1735. const parsed = this.getParsed(index);
  1736. let values = super.resolveDataElementOptions(index, mode);
  1737. if (values.$shared) {
  1738. values = Object.assign({}, values, {
  1739. $shared: false
  1740. });
  1741. }
  1742. const radius = values.radius;
  1743. if (mode !== 'active') {
  1744. values.radius = 0;
  1745. }
  1746. values.radius += valueOrDefault(parsed && parsed._custom, radius);
  1747. return values;
  1748. }
  1749. }
  1750. function getRatioAndOffset(rotation, circumference, cutout) {
  1751. let ratioX = 1;
  1752. let ratioY = 1;
  1753. let offsetX = 0;
  1754. let offsetY = 0;
  1755. if (circumference < TAU) {
  1756. const startAngle = rotation;
  1757. const endAngle = startAngle + circumference;
  1758. const startX = Math.cos(startAngle);
  1759. const startY = Math.sin(startAngle);
  1760. const endX = Math.cos(endAngle);
  1761. const endY = Math.sin(endAngle);
  1762. const calcMax = (angle, a, b)=>_angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);
  1763. const calcMin = (angle, a, b)=>_angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);
  1764. const maxX = calcMax(0, startX, endX);
  1765. const maxY = calcMax(HALF_PI, startY, endY);
  1766. const minX = calcMin(PI, startX, endX);
  1767. const minY = calcMin(PI + HALF_PI, startY, endY);
  1768. ratioX = (maxX - minX) / 2;
  1769. ratioY = (maxY - minY) / 2;
  1770. offsetX = -(maxX + minX) / 2;
  1771. offsetY = -(maxY + minY) / 2;
  1772. }
  1773. return {
  1774. ratioX,
  1775. ratioY,
  1776. offsetX,
  1777. offsetY
  1778. };
  1779. }
  1780. class DoughnutController extends DatasetController {
  1781. static id = 'doughnut';
  1782. static defaults = {
  1783. datasetElementType: false,
  1784. dataElementType: 'arc',
  1785. animation: {
  1786. animateRotate: true,
  1787. animateScale: false
  1788. },
  1789. animations: {
  1790. numbers: {
  1791. type: 'number',
  1792. properties: [
  1793. 'circumference',
  1794. 'endAngle',
  1795. 'innerRadius',
  1796. 'outerRadius',
  1797. 'startAngle',
  1798. 'x',
  1799. 'y',
  1800. 'offset',
  1801. 'borderWidth',
  1802. 'spacing'
  1803. ]
  1804. }
  1805. },
  1806. cutout: '50%',
  1807. rotation: 0,
  1808. circumference: 360,
  1809. radius: '100%',
  1810. spacing: 0,
  1811. indexAxis: 'r'
  1812. };
  1813. static descriptors = {
  1814. _scriptable: (name)=>name !== 'spacing',
  1815. _indexable: (name)=>name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash')
  1816. };
  1817. static overrides = {
  1818. aspectRatio: 1,
  1819. plugins: {
  1820. legend: {
  1821. labels: {
  1822. generateLabels (chart) {
  1823. const data = chart.data;
  1824. if (data.labels.length && data.datasets.length) {
  1825. const { labels: { pointStyle , color } } = chart.legend.options;
  1826. return data.labels.map((label, i)=>{
  1827. const meta = chart.getDatasetMeta(0);
  1828. const style = meta.controller.getStyle(i);
  1829. return {
  1830. text: label,
  1831. fillStyle: style.backgroundColor,
  1832. strokeStyle: style.borderColor,
  1833. fontColor: color,
  1834. lineWidth: style.borderWidth,
  1835. pointStyle: pointStyle,
  1836. hidden: !chart.getDataVisibility(i),
  1837. index: i
  1838. };
  1839. });
  1840. }
  1841. return [];
  1842. }
  1843. },
  1844. onClick (e, legendItem, legend) {
  1845. legend.chart.toggleDataVisibility(legendItem.index);
  1846. legend.chart.update();
  1847. }
  1848. }
  1849. }
  1850. };
  1851. constructor(chart, datasetIndex){
  1852. super(chart, datasetIndex);
  1853. this.enableOptionSharing = true;
  1854. this.innerRadius = undefined;
  1855. this.outerRadius = undefined;
  1856. this.offsetX = undefined;
  1857. this.offsetY = undefined;
  1858. }
  1859. linkScales() {}
  1860. parse(start, count) {
  1861. const data = this.getDataset().data;
  1862. const meta = this._cachedMeta;
  1863. if (this._parsing === false) {
  1864. meta._parsed = data;
  1865. } else {
  1866. let getter = (i)=>+data[i];
  1867. if (isObject(data[start])) {
  1868. const { key ='value' } = this._parsing;
  1869. getter = (i)=>+resolveObjectKey(data[i], key);
  1870. }
  1871. let i, ilen;
  1872. for(i = start, ilen = start + count; i < ilen; ++i){
  1873. meta._parsed[i] = getter(i);
  1874. }
  1875. }
  1876. }
  1877. _getRotation() {
  1878. return toRadians(this.options.rotation - 90);
  1879. }
  1880. _getCircumference() {
  1881. return toRadians(this.options.circumference);
  1882. }
  1883. _getRotationExtents() {
  1884. let min = TAU;
  1885. let max = -TAU;
  1886. for(let i = 0; i < this.chart.data.datasets.length; ++i){
  1887. if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) {
  1888. const controller = this.chart.getDatasetMeta(i).controller;
  1889. const rotation = controller._getRotation();
  1890. const circumference = controller._getCircumference();
  1891. min = Math.min(min, rotation);
  1892. max = Math.max(max, rotation + circumference);
  1893. }
  1894. }
  1895. return {
  1896. rotation: min,
  1897. circumference: max - min
  1898. };
  1899. }
  1900. update(mode) {
  1901. const chart = this.chart;
  1902. const { chartArea } = chart;
  1903. const meta = this._cachedMeta;
  1904. const arcs = meta.data;
  1905. const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;
  1906. const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);
  1907. const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1);
  1908. const chartWeight = this._getRingWeight(this.index);
  1909. const { circumference , rotation } = this._getRotationExtents();
  1910. const { ratioX , ratioY , offsetX , offsetY } = getRatioAndOffset(rotation, circumference, cutout);
  1911. const maxWidth = (chartArea.width - spacing) / ratioX;
  1912. const maxHeight = (chartArea.height - spacing) / ratioY;
  1913. const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  1914. const outerRadius = toDimension(this.options.radius, maxRadius);
  1915. const innerRadius = Math.max(outerRadius * cutout, 0);
  1916. const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();
  1917. this.offsetX = offsetX * outerRadius;
  1918. this.offsetY = offsetY * outerRadius;
  1919. meta.total = this.calculateTotal();
  1920. this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);
  1921. this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);
  1922. this.updateElements(arcs, 0, arcs.length, mode);
  1923. }
  1924. _circumference(i, reset) {
  1925. const opts = this.options;
  1926. const meta = this._cachedMeta;
  1927. const circumference = this._getCircumference();
  1928. if (reset && opts.animation.animateRotate || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {
  1929. return 0;
  1930. }
  1931. return this.calculateCircumference(meta._parsed[i] * circumference / TAU);
  1932. }
  1933. updateElements(arcs, start, count, mode) {
  1934. const reset = mode === 'reset';
  1935. const chart = this.chart;
  1936. const chartArea = chart.chartArea;
  1937. const opts = chart.options;
  1938. const animationOpts = opts.animation;
  1939. const centerX = (chartArea.left + chartArea.right) / 2;
  1940. const centerY = (chartArea.top + chartArea.bottom) / 2;
  1941. const animateScale = reset && animationOpts.animateScale;
  1942. const innerRadius = animateScale ? 0 : this.innerRadius;
  1943. const outerRadius = animateScale ? 0 : this.outerRadius;
  1944. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  1945. let startAngle = this._getRotation();
  1946. let i;
  1947. for(i = 0; i < start; ++i){
  1948. startAngle += this._circumference(i, reset);
  1949. }
  1950. for(i = start; i < start + count; ++i){
  1951. const circumference = this._circumference(i, reset);
  1952. const arc = arcs[i];
  1953. const properties = {
  1954. x: centerX + this.offsetX,
  1955. y: centerY + this.offsetY,
  1956. startAngle,
  1957. endAngle: startAngle + circumference,
  1958. circumference,
  1959. outerRadius,
  1960. innerRadius
  1961. };
  1962. if (includeOptions) {
  1963. properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);
  1964. }
  1965. startAngle += circumference;
  1966. this.updateElement(arc, i, properties, mode);
  1967. }
  1968. }
  1969. calculateTotal() {
  1970. const meta = this._cachedMeta;
  1971. const metaData = meta.data;
  1972. let total = 0;
  1973. let i;
  1974. for(i = 0; i < metaData.length; i++){
  1975. const value = meta._parsed[i];
  1976. if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {
  1977. total += Math.abs(value);
  1978. }
  1979. }
  1980. return total;
  1981. }
  1982. calculateCircumference(value) {
  1983. const total = this._cachedMeta.total;
  1984. if (total > 0 && !isNaN(value)) {
  1985. return TAU * (Math.abs(value) / total);
  1986. }
  1987. return 0;
  1988. }
  1989. getLabelAndValue(index) {
  1990. const meta = this._cachedMeta;
  1991. const chart = this.chart;
  1992. const labels = chart.data.labels || [];
  1993. const value = formatNumber(meta._parsed[index], chart.options.locale);
  1994. return {
  1995. label: labels[index] || '',
  1996. value
  1997. };
  1998. }
  1999. getMaxBorderWidth(arcs) {
  2000. let max = 0;
  2001. const chart = this.chart;
  2002. let i, ilen, meta, controller, options;
  2003. if (!arcs) {
  2004. for(i = 0, ilen = chart.data.datasets.length; i < ilen; ++i){
  2005. if (chart.isDatasetVisible(i)) {
  2006. meta = chart.getDatasetMeta(i);
  2007. arcs = meta.data;
  2008. controller = meta.controller;
  2009. break;
  2010. }
  2011. }
  2012. }
  2013. if (!arcs) {
  2014. return 0;
  2015. }
  2016. for(i = 0, ilen = arcs.length; i < ilen; ++i){
  2017. options = controller.resolveDataElementOptions(i);
  2018. if (options.borderAlign !== 'inner') {
  2019. max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);
  2020. }
  2021. }
  2022. return max;
  2023. }
  2024. getMaxOffset(arcs) {
  2025. let max = 0;
  2026. for(let i = 0, ilen = arcs.length; i < ilen; ++i){
  2027. const options = this.resolveDataElementOptions(i);
  2028. max = Math.max(max, options.offset || 0, options.hoverOffset || 0);
  2029. }
  2030. return max;
  2031. }
  2032. _getRingWeightOffset(datasetIndex) {
  2033. let ringWeightOffset = 0;
  2034. for(let i = 0; i < datasetIndex; ++i){
  2035. if (this.chart.isDatasetVisible(i)) {
  2036. ringWeightOffset += this._getRingWeight(i);
  2037. }
  2038. }
  2039. return ringWeightOffset;
  2040. }
  2041. _getRingWeight(datasetIndex) {
  2042. return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);
  2043. }
  2044. _getVisibleDatasetWeightTotal() {
  2045. return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;
  2046. }
  2047. }
  2048. class LineController extends DatasetController {
  2049. static id = 'line';
  2050. static defaults = {
  2051. datasetElementType: 'line',
  2052. dataElementType: 'point',
  2053. showLine: true,
  2054. spanGaps: false
  2055. };
  2056. static overrides = {
  2057. scales: {
  2058. _index_: {
  2059. type: 'category'
  2060. },
  2061. _value_: {
  2062. type: 'linear'
  2063. }
  2064. }
  2065. };
  2066. initialize() {
  2067. this.enableOptionSharing = true;
  2068. this.supportsDecimation = true;
  2069. super.initialize();
  2070. }
  2071. update(mode) {
  2072. const meta = this._cachedMeta;
  2073. const { dataset: line , data: points = [] , _dataset } = meta;
  2074. const animationsDisabled = this.chart._animationsDisabled;
  2075. let { start , count } = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
  2076. this._drawStart = start;
  2077. this._drawCount = count;
  2078. if (_scaleRangesChanged(meta)) {
  2079. start = 0;
  2080. count = points.length;
  2081. }
  2082. line._chart = this.chart;
  2083. line._datasetIndex = this.index;
  2084. line._decimated = !!_dataset._decimated;
  2085. line.points = points;
  2086. const options = this.resolveDatasetElementOptions(mode);
  2087. if (!this.options.showLine) {
  2088. options.borderWidth = 0;
  2089. }
  2090. options.segment = this.options.segment;
  2091. this.updateElement(line, undefined, {
  2092. animated: !animationsDisabled,
  2093. options
  2094. }, mode);
  2095. this.updateElements(points, start, count, mode);
  2096. }
  2097. updateElements(points, start, count, mode) {
  2098. const reset = mode === 'reset';
  2099. const { iScale , vScale , _stacked , _dataset } = this._cachedMeta;
  2100. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  2101. const iAxis = iScale.axis;
  2102. const vAxis = vScale.axis;
  2103. const { spanGaps , segment } = this.options;
  2104. const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
  2105. const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';
  2106. const end = start + count;
  2107. const pointsCount = points.length;
  2108. let prevParsed = start > 0 && this.getParsed(start - 1);
  2109. for(let i = 0; i < pointsCount; ++i){
  2110. const point = points[i];
  2111. const properties = directUpdate ? point : {};
  2112. if (i < start || i >= end) {
  2113. properties.skip = true;
  2114. continue;
  2115. }
  2116. const parsed = this.getParsed(i);
  2117. const nullData = isNullOrUndef(parsed[vAxis]);
  2118. const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
  2119. const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
  2120. properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
  2121. properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;
  2122. if (segment) {
  2123. properties.parsed = parsed;
  2124. properties.raw = _dataset.data[i];
  2125. }
  2126. if (includeOptions) {
  2127. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2128. }
  2129. if (!directUpdate) {
  2130. this.updateElement(point, i, properties, mode);
  2131. }
  2132. prevParsed = parsed;
  2133. }
  2134. }
  2135. getMaxOverflow() {
  2136. const meta = this._cachedMeta;
  2137. const dataset = meta.dataset;
  2138. const border = dataset.options && dataset.options.borderWidth || 0;
  2139. const data = meta.data || [];
  2140. if (!data.length) {
  2141. return border;
  2142. }
  2143. const firstPoint = data[0].size(this.resolveDataElementOptions(0));
  2144. const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));
  2145. return Math.max(border, firstPoint, lastPoint) / 2;
  2146. }
  2147. draw() {
  2148. const meta = this._cachedMeta;
  2149. meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);
  2150. super.draw();
  2151. }
  2152. }
  2153. class PolarAreaController extends DatasetController {
  2154. static id = 'polarArea';
  2155. static defaults = {
  2156. dataElementType: 'arc',
  2157. animation: {
  2158. animateRotate: true,
  2159. animateScale: true
  2160. },
  2161. animations: {
  2162. numbers: {
  2163. type: 'number',
  2164. properties: [
  2165. 'x',
  2166. 'y',
  2167. 'startAngle',
  2168. 'endAngle',
  2169. 'innerRadius',
  2170. 'outerRadius'
  2171. ]
  2172. }
  2173. },
  2174. indexAxis: 'r',
  2175. startAngle: 0
  2176. };
  2177. static overrides = {
  2178. aspectRatio: 1,
  2179. plugins: {
  2180. legend: {
  2181. labels: {
  2182. generateLabels (chart) {
  2183. const data = chart.data;
  2184. if (data.labels.length && data.datasets.length) {
  2185. const { labels: { pointStyle , color } } = chart.legend.options;
  2186. return data.labels.map((label, i)=>{
  2187. const meta = chart.getDatasetMeta(0);
  2188. const style = meta.controller.getStyle(i);
  2189. return {
  2190. text: label,
  2191. fillStyle: style.backgroundColor,
  2192. strokeStyle: style.borderColor,
  2193. fontColor: color,
  2194. lineWidth: style.borderWidth,
  2195. pointStyle: pointStyle,
  2196. hidden: !chart.getDataVisibility(i),
  2197. index: i
  2198. };
  2199. });
  2200. }
  2201. return [];
  2202. }
  2203. },
  2204. onClick (e, legendItem, legend) {
  2205. legend.chart.toggleDataVisibility(legendItem.index);
  2206. legend.chart.update();
  2207. }
  2208. }
  2209. },
  2210. scales: {
  2211. r: {
  2212. type: 'radialLinear',
  2213. angleLines: {
  2214. display: false
  2215. },
  2216. beginAtZero: true,
  2217. grid: {
  2218. circular: true
  2219. },
  2220. pointLabels: {
  2221. display: false
  2222. },
  2223. startAngle: 0
  2224. }
  2225. }
  2226. };
  2227. constructor(chart, datasetIndex){
  2228. super(chart, datasetIndex);
  2229. this.innerRadius = undefined;
  2230. this.outerRadius = undefined;
  2231. }
  2232. getLabelAndValue(index) {
  2233. const meta = this._cachedMeta;
  2234. const chart = this.chart;
  2235. const labels = chart.data.labels || [];
  2236. const value = formatNumber(meta._parsed[index].r, chart.options.locale);
  2237. return {
  2238. label: labels[index] || '',
  2239. value
  2240. };
  2241. }
  2242. parseObjectData(meta, data, start, count) {
  2243. return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);
  2244. }
  2245. update(mode) {
  2246. const arcs = this._cachedMeta.data;
  2247. this._updateRadius();
  2248. this.updateElements(arcs, 0, arcs.length, mode);
  2249. }
  2250. getMinMax() {
  2251. const meta = this._cachedMeta;
  2252. const range = {
  2253. min: Number.POSITIVE_INFINITY,
  2254. max: Number.NEGATIVE_INFINITY
  2255. };
  2256. meta.data.forEach((element, index)=>{
  2257. const parsed = this.getParsed(index).r;
  2258. if (!isNaN(parsed) && this.chart.getDataVisibility(index)) {
  2259. if (parsed < range.min) {
  2260. range.min = parsed;
  2261. }
  2262. if (parsed > range.max) {
  2263. range.max = parsed;
  2264. }
  2265. }
  2266. });
  2267. return range;
  2268. }
  2269. _updateRadius() {
  2270. const chart = this.chart;
  2271. const chartArea = chart.chartArea;
  2272. const opts = chart.options;
  2273. const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  2274. const outerRadius = Math.max(minSize / 2, 0);
  2275. const innerRadius = Math.max(opts.cutoutPercentage ? outerRadius / 100 * opts.cutoutPercentage : 1, 0);
  2276. const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();
  2277. this.outerRadius = outerRadius - radiusLength * this.index;
  2278. this.innerRadius = this.outerRadius - radiusLength;
  2279. }
  2280. updateElements(arcs, start, count, mode) {
  2281. const reset = mode === 'reset';
  2282. const chart = this.chart;
  2283. const opts = chart.options;
  2284. const animationOpts = opts.animation;
  2285. const scale = this._cachedMeta.rScale;
  2286. const centerX = scale.xCenter;
  2287. const centerY = scale.yCenter;
  2288. const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;
  2289. let angle = datasetStartAngle;
  2290. let i;
  2291. const defaultAngle = 360 / this.countVisibleElements();
  2292. for(i = 0; i < start; ++i){
  2293. angle += this._computeAngle(i, mode, defaultAngle);
  2294. }
  2295. for(i = start; i < start + count; i++){
  2296. const arc = arcs[i];
  2297. let startAngle = angle;
  2298. let endAngle = angle + this._computeAngle(i, mode, defaultAngle);
  2299. let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0;
  2300. angle = endAngle;
  2301. if (reset) {
  2302. if (animationOpts.animateScale) {
  2303. outerRadius = 0;
  2304. }
  2305. if (animationOpts.animateRotate) {
  2306. startAngle = endAngle = datasetStartAngle;
  2307. }
  2308. }
  2309. const properties = {
  2310. x: centerX,
  2311. y: centerY,
  2312. innerRadius: 0,
  2313. outerRadius,
  2314. startAngle,
  2315. endAngle,
  2316. options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode)
  2317. };
  2318. this.updateElement(arc, i, properties, mode);
  2319. }
  2320. }
  2321. countVisibleElements() {
  2322. const meta = this._cachedMeta;
  2323. let count = 0;
  2324. meta.data.forEach((element, index)=>{
  2325. if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) {
  2326. count++;
  2327. }
  2328. });
  2329. return count;
  2330. }
  2331. _computeAngle(index, mode, defaultAngle) {
  2332. return this.chart.getDataVisibility(index) ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle) : 0;
  2333. }
  2334. }
  2335. class PieController extends DoughnutController {
  2336. static id = 'pie';
  2337. static defaults = {
  2338. cutout: 0,
  2339. rotation: 0,
  2340. circumference: 360,
  2341. radius: '100%'
  2342. };
  2343. }
  2344. class RadarController extends DatasetController {
  2345. static id = 'radar';
  2346. static defaults = {
  2347. datasetElementType: 'line',
  2348. dataElementType: 'point',
  2349. indexAxis: 'r',
  2350. showLine: true,
  2351. elements: {
  2352. line: {
  2353. fill: 'start'
  2354. }
  2355. }
  2356. };
  2357. static overrides = {
  2358. aspectRatio: 1,
  2359. scales: {
  2360. r: {
  2361. type: 'radialLinear'
  2362. }
  2363. }
  2364. };
  2365. getLabelAndValue(index) {
  2366. const vScale = this._cachedMeta.vScale;
  2367. const parsed = this.getParsed(index);
  2368. return {
  2369. label: vScale.getLabels()[index],
  2370. value: '' + vScale.getLabelForValue(parsed[vScale.axis])
  2371. };
  2372. }
  2373. parseObjectData(meta, data, start, count) {
  2374. return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);
  2375. }
  2376. update(mode) {
  2377. const meta = this._cachedMeta;
  2378. const line = meta.dataset;
  2379. const points = meta.data || [];
  2380. const labels = meta.iScale.getLabels();
  2381. line.points = points;
  2382. if (mode !== 'resize') {
  2383. const options = this.resolveDatasetElementOptions(mode);
  2384. if (!this.options.showLine) {
  2385. options.borderWidth = 0;
  2386. }
  2387. const properties = {
  2388. _loop: true,
  2389. _fullLoop: labels.length === points.length,
  2390. options
  2391. };
  2392. this.updateElement(line, undefined, properties, mode);
  2393. }
  2394. this.updateElements(points, 0, points.length, mode);
  2395. }
  2396. updateElements(points, start, count, mode) {
  2397. const scale = this._cachedMeta.rScale;
  2398. const reset = mode === 'reset';
  2399. for(let i = start; i < start + count; i++){
  2400. const point = points[i];
  2401. const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2402. const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r);
  2403. const x = reset ? scale.xCenter : pointPosition.x;
  2404. const y = reset ? scale.yCenter : pointPosition.y;
  2405. const properties = {
  2406. x,
  2407. y,
  2408. angle: pointPosition.angle,
  2409. skip: isNaN(x) || isNaN(y),
  2410. options
  2411. };
  2412. this.updateElement(point, i, properties, mode);
  2413. }
  2414. }
  2415. }
  2416. class ScatterController extends DatasetController {
  2417. static id = 'scatter';
  2418. static defaults = {
  2419. datasetElementType: false,
  2420. dataElementType: 'point',
  2421. showLine: false,
  2422. fill: false
  2423. };
  2424. static overrides = {
  2425. interaction: {
  2426. mode: 'point'
  2427. },
  2428. scales: {
  2429. x: {
  2430. type: 'linear'
  2431. },
  2432. y: {
  2433. type: 'linear'
  2434. }
  2435. }
  2436. };
  2437. getLabelAndValue(index) {
  2438. const meta = this._cachedMeta;
  2439. const labels = this.chart.data.labels || [];
  2440. const { xScale , yScale } = meta;
  2441. const parsed = this.getParsed(index);
  2442. const x = xScale.getLabelForValue(parsed.x);
  2443. const y = yScale.getLabelForValue(parsed.y);
  2444. return {
  2445. label: labels[index] || '',
  2446. value: '(' + x + ', ' + y + ')'
  2447. };
  2448. }
  2449. update(mode) {
  2450. const meta = this._cachedMeta;
  2451. const { data: points = [] } = meta;
  2452. const animationsDisabled = this.chart._animationsDisabled;
  2453. let { start , count } = _getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
  2454. this._drawStart = start;
  2455. this._drawCount = count;
  2456. if (_scaleRangesChanged(meta)) {
  2457. start = 0;
  2458. count = points.length;
  2459. }
  2460. if (this.options.showLine) {
  2461. if (!this.datasetElementType) {
  2462. this.addElements();
  2463. }
  2464. const { dataset: line , _dataset } = meta;
  2465. line._chart = this.chart;
  2466. line._datasetIndex = this.index;
  2467. line._decimated = !!_dataset._decimated;
  2468. line.points = points;
  2469. const options = this.resolveDatasetElementOptions(mode);
  2470. options.segment = this.options.segment;
  2471. this.updateElement(line, undefined, {
  2472. animated: !animationsDisabled,
  2473. options
  2474. }, mode);
  2475. } else if (this.datasetElementType) {
  2476. delete meta.dataset;
  2477. this.datasetElementType = false;
  2478. }
  2479. this.updateElements(points, start, count, mode);
  2480. }
  2481. addElements() {
  2482. const { showLine } = this.options;
  2483. if (!this.datasetElementType && showLine) {
  2484. this.datasetElementType = this.chart.registry.getElement('line');
  2485. }
  2486. super.addElements();
  2487. }
  2488. updateElements(points, start, count, mode) {
  2489. const reset = mode === 'reset';
  2490. const { iScale , vScale , _stacked , _dataset } = this._cachedMeta;
  2491. const firstOpts = this.resolveDataElementOptions(start, mode);
  2492. const sharedOptions = this.getSharedOptions(firstOpts);
  2493. const includeOptions = this.includeOptions(mode, sharedOptions);
  2494. const iAxis = iScale.axis;
  2495. const vAxis = vScale.axis;
  2496. const { spanGaps , segment } = this.options;
  2497. const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
  2498. const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';
  2499. let prevParsed = start > 0 && this.getParsed(start - 1);
  2500. for(let i = start; i < start + count; ++i){
  2501. const point = points[i];
  2502. const parsed = this.getParsed(i);
  2503. const properties = directUpdate ? point : {};
  2504. const nullData = isNullOrUndef(parsed[vAxis]);
  2505. const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
  2506. const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
  2507. properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
  2508. properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;
  2509. if (segment) {
  2510. properties.parsed = parsed;
  2511. properties.raw = _dataset.data[i];
  2512. }
  2513. if (includeOptions) {
  2514. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2515. }
  2516. if (!directUpdate) {
  2517. this.updateElement(point, i, properties, mode);
  2518. }
  2519. prevParsed = parsed;
  2520. }
  2521. this.updateSharedOptions(sharedOptions, mode, firstOpts);
  2522. }
  2523. getMaxOverflow() {
  2524. const meta = this._cachedMeta;
  2525. const data = meta.data || [];
  2526. if (!this.options.showLine) {
  2527. let max = 0;
  2528. for(let i = data.length - 1; i >= 0; --i){
  2529. max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);
  2530. }
  2531. return max > 0 && max;
  2532. }
  2533. const dataset = meta.dataset;
  2534. const border = dataset.options && dataset.options.borderWidth || 0;
  2535. if (!data.length) {
  2536. return border;
  2537. }
  2538. const firstPoint = data[0].size(this.resolveDataElementOptions(0));
  2539. const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));
  2540. return Math.max(border, firstPoint, lastPoint) / 2;
  2541. }
  2542. }
  2543. var controllers = /*#__PURE__*/Object.freeze({
  2544. __proto__: null,
  2545. BarController: BarController,
  2546. BubbleController: BubbleController,
  2547. DoughnutController: DoughnutController,
  2548. LineController: LineController,
  2549. PieController: PieController,
  2550. PolarAreaController: PolarAreaController,
  2551. RadarController: RadarController,
  2552. ScatterController: ScatterController
  2553. });
  2554. /**
  2555. * @namespace Chart._adapters
  2556. * @since 2.8.0
  2557. * @private
  2558. */ function abstract() {
  2559. throw new Error('This method is not implemented: Check that a complete date adapter is provided.');
  2560. }
  2561. /**
  2562. * Date adapter (current used by the time scale)
  2563. * @namespace Chart._adapters._date
  2564. * @memberof Chart._adapters
  2565. * @private
  2566. */ class DateAdapterBase {
  2567. /**
  2568. * Override default date adapter methods.
  2569. * Accepts type parameter to define options type.
  2570. * @example
  2571. * Chart._adapters._date.override<{myAdapterOption: string}>({
  2572. * init() {
  2573. * console.log(this.options.myAdapterOption);
  2574. * }
  2575. * })
  2576. */ static override(members) {
  2577. Object.assign(DateAdapterBase.prototype, members);
  2578. }
  2579. options;
  2580. constructor(options){
  2581. this.options = options || {};
  2582. }
  2583. // eslint-disable-next-line @typescript-eslint/no-empty-function
  2584. init() {}
  2585. formats() {
  2586. return abstract();
  2587. }
  2588. parse() {
  2589. return abstract();
  2590. }
  2591. format() {
  2592. return abstract();
  2593. }
  2594. add() {
  2595. return abstract();
  2596. }
  2597. diff() {
  2598. return abstract();
  2599. }
  2600. startOf() {
  2601. return abstract();
  2602. }
  2603. endOf() {
  2604. return abstract();
  2605. }
  2606. }
  2607. var adapters = {
  2608. _date: DateAdapterBase
  2609. };
  2610. function binarySearch(metaset, axis, value, intersect) {
  2611. const { controller , data , _sorted } = metaset;
  2612. const iScale = controller._cachedMeta.iScale;
  2613. if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) {
  2614. const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;
  2615. if (!intersect) {
  2616. return lookupMethod(data, axis, value);
  2617. } else if (controller._sharedOptions) {
  2618. const el = data[0];
  2619. const range = typeof el.getRange === 'function' && el.getRange(axis);
  2620. if (range) {
  2621. const start = lookupMethod(data, axis, value - range);
  2622. const end = lookupMethod(data, axis, value + range);
  2623. return {
  2624. lo: start.lo,
  2625. hi: end.hi
  2626. };
  2627. }
  2628. }
  2629. }
  2630. return {
  2631. lo: 0,
  2632. hi: data.length - 1
  2633. };
  2634. }
  2635. function evaluateInteractionItems(chart, axis, position, handler, intersect) {
  2636. const metasets = chart.getSortedVisibleDatasetMetas();
  2637. const value = position[axis];
  2638. for(let i = 0, ilen = metasets.length; i < ilen; ++i){
  2639. const { index , data } = metasets[i];
  2640. const { lo , hi } = binarySearch(metasets[i], axis, value, intersect);
  2641. for(let j = lo; j <= hi; ++j){
  2642. const element = data[j];
  2643. if (!element.skip) {
  2644. handler(element, index, j);
  2645. }
  2646. }
  2647. }
  2648. }
  2649. function getDistanceMetricForAxis(axis) {
  2650. const useX = axis.indexOf('x') !== -1;
  2651. const useY = axis.indexOf('y') !== -1;
  2652. return function(pt1, pt2) {
  2653. const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  2654. const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  2655. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  2656. };
  2657. }
  2658. function getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) {
  2659. const items = [];
  2660. if (!includeInvisible && !chart.isPointInArea(position)) {
  2661. return items;
  2662. }
  2663. const evaluationFunc = function(element, datasetIndex, index) {
  2664. if (!includeInvisible && !_isPointInArea(element, chart.chartArea, 0)) {
  2665. return;
  2666. }
  2667. if (element.inRange(position.x, position.y, useFinalPosition)) {
  2668. items.push({
  2669. element,
  2670. datasetIndex,
  2671. index
  2672. });
  2673. }
  2674. };
  2675. evaluateInteractionItems(chart, axis, position, evaluationFunc, true);
  2676. return items;
  2677. }
  2678. function getNearestRadialItems(chart, position, axis, useFinalPosition) {
  2679. let items = [];
  2680. function evaluationFunc(element, datasetIndex, index) {
  2681. const { startAngle , endAngle } = element.getProps([
  2682. 'startAngle',
  2683. 'endAngle'
  2684. ], useFinalPosition);
  2685. const { angle } = getAngleFromPoint(element, {
  2686. x: position.x,
  2687. y: position.y
  2688. });
  2689. if (_angleBetween(angle, startAngle, endAngle)) {
  2690. items.push({
  2691. element,
  2692. datasetIndex,
  2693. index
  2694. });
  2695. }
  2696. }
  2697. evaluateInteractionItems(chart, axis, position, evaluationFunc);
  2698. return items;
  2699. }
  2700. function getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {
  2701. let items = [];
  2702. const distanceMetric = getDistanceMetricForAxis(axis);
  2703. let minDistance = Number.POSITIVE_INFINITY;
  2704. function evaluationFunc(element, datasetIndex, index) {
  2705. const inRange = element.inRange(position.x, position.y, useFinalPosition);
  2706. if (intersect && !inRange) {
  2707. return;
  2708. }
  2709. const center = element.getCenterPoint(useFinalPosition);
  2710. const pointInArea = !!includeInvisible || chart.isPointInArea(center);
  2711. if (!pointInArea && !inRange) {
  2712. return;
  2713. }
  2714. const distance = distanceMetric(position, center);
  2715. if (distance < minDistance) {
  2716. items = [
  2717. {
  2718. element,
  2719. datasetIndex,
  2720. index
  2721. }
  2722. ];
  2723. minDistance = distance;
  2724. } else if (distance === minDistance) {
  2725. items.push({
  2726. element,
  2727. datasetIndex,
  2728. index
  2729. });
  2730. }
  2731. }
  2732. evaluateInteractionItems(chart, axis, position, evaluationFunc);
  2733. return items;
  2734. }
  2735. function getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {
  2736. if (!includeInvisible && !chart.isPointInArea(position)) {
  2737. return [];
  2738. }
  2739. return axis === 'r' && !intersect ? getNearestRadialItems(chart, position, axis, useFinalPosition) : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible);
  2740. }
  2741. function getAxisItems(chart, position, axis, intersect, useFinalPosition) {
  2742. const items = [];
  2743. const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';
  2744. let intersectsItem = false;
  2745. evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index)=>{
  2746. if (element[rangeMethod] && element[rangeMethod](position[axis], useFinalPosition)) {
  2747. items.push({
  2748. element,
  2749. datasetIndex,
  2750. index
  2751. });
  2752. intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition);
  2753. }
  2754. });
  2755. if (intersect && !intersectsItem) {
  2756. return [];
  2757. }
  2758. return items;
  2759. }
  2760. var Interaction = {
  2761. evaluateInteractionItems,
  2762. modes: {
  2763. index (chart, e, options, useFinalPosition) {
  2764. const position = getRelativePosition(e, chart);
  2765. const axis = options.axis || 'x';
  2766. const includeInvisible = options.includeInvisible || false;
  2767. const items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);
  2768. const elements = [];
  2769. if (!items.length) {
  2770. return [];
  2771. }
  2772. chart.getSortedVisibleDatasetMetas().forEach((meta)=>{
  2773. const index = items[0].index;
  2774. const element = meta.data[index];
  2775. if (element && !element.skip) {
  2776. elements.push({
  2777. element,
  2778. datasetIndex: meta.index,
  2779. index
  2780. });
  2781. }
  2782. });
  2783. return elements;
  2784. },
  2785. dataset (chart, e, options, useFinalPosition) {
  2786. const position = getRelativePosition(e, chart);
  2787. const axis = options.axis || 'xy';
  2788. const includeInvisible = options.includeInvisible || false;
  2789. let items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);
  2790. if (items.length > 0) {
  2791. const datasetIndex = items[0].datasetIndex;
  2792. const data = chart.getDatasetMeta(datasetIndex).data;
  2793. items = [];
  2794. for(let i = 0; i < data.length; ++i){
  2795. items.push({
  2796. element: data[i],
  2797. datasetIndex,
  2798. index: i
  2799. });
  2800. }
  2801. }
  2802. return items;
  2803. },
  2804. point (chart, e, options, useFinalPosition) {
  2805. const position = getRelativePosition(e, chart);
  2806. const axis = options.axis || 'xy';
  2807. const includeInvisible = options.includeInvisible || false;
  2808. return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible);
  2809. },
  2810. nearest (chart, e, options, useFinalPosition) {
  2811. const position = getRelativePosition(e, chart);
  2812. const axis = options.axis || 'xy';
  2813. const includeInvisible = options.includeInvisible || false;
  2814. return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible);
  2815. },
  2816. x (chart, e, options, useFinalPosition) {
  2817. const position = getRelativePosition(e, chart);
  2818. return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition);
  2819. },
  2820. y (chart, e, options, useFinalPosition) {
  2821. const position = getRelativePosition(e, chart);
  2822. return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition);
  2823. }
  2824. }
  2825. };
  2826. const STATIC_POSITIONS = [
  2827. 'left',
  2828. 'top',
  2829. 'right',
  2830. 'bottom'
  2831. ];
  2832. function filterByPosition(array, position) {
  2833. return array.filter((v)=>v.pos === position);
  2834. }
  2835. function filterDynamicPositionByAxis(array, axis) {
  2836. return array.filter((v)=>STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);
  2837. }
  2838. function sortByWeight(array, reverse) {
  2839. return array.sort((a, b)=>{
  2840. const v0 = reverse ? b : a;
  2841. const v1 = reverse ? a : b;
  2842. return v0.weight === v1.weight ? v0.index - v1.index : v0.weight - v1.weight;
  2843. });
  2844. }
  2845. function wrapBoxes(boxes) {
  2846. const layoutBoxes = [];
  2847. let i, ilen, box, pos, stack, stackWeight;
  2848. for(i = 0, ilen = (boxes || []).length; i < ilen; ++i){
  2849. box = boxes[i];
  2850. ({ position: pos , options: { stack , stackWeight =1 } } = box);
  2851. layoutBoxes.push({
  2852. index: i,
  2853. box,
  2854. pos,
  2855. horizontal: box.isHorizontal(),
  2856. weight: box.weight,
  2857. stack: stack && pos + stack,
  2858. stackWeight
  2859. });
  2860. }
  2861. return layoutBoxes;
  2862. }
  2863. function buildStacks(layouts) {
  2864. const stacks = {};
  2865. for (const wrap of layouts){
  2866. const { stack , pos , stackWeight } = wrap;
  2867. if (!stack || !STATIC_POSITIONS.includes(pos)) {
  2868. continue;
  2869. }
  2870. const _stack = stacks[stack] || (stacks[stack] = {
  2871. count: 0,
  2872. placed: 0,
  2873. weight: 0,
  2874. size: 0
  2875. });
  2876. _stack.count++;
  2877. _stack.weight += stackWeight;
  2878. }
  2879. return stacks;
  2880. }
  2881. function setLayoutDims(layouts, params) {
  2882. const stacks = buildStacks(layouts);
  2883. const { vBoxMaxWidth , hBoxMaxHeight } = params;
  2884. let i, ilen, layout;
  2885. for(i = 0, ilen = layouts.length; i < ilen; ++i){
  2886. layout = layouts[i];
  2887. const { fullSize } = layout.box;
  2888. const stack = stacks[layout.stack];
  2889. const factor = stack && layout.stackWeight / stack.weight;
  2890. if (layout.horizontal) {
  2891. layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;
  2892. layout.height = hBoxMaxHeight;
  2893. } else {
  2894. layout.width = vBoxMaxWidth;
  2895. layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;
  2896. }
  2897. }
  2898. return stacks;
  2899. }
  2900. function buildLayoutBoxes(boxes) {
  2901. const layoutBoxes = wrapBoxes(boxes);
  2902. const fullSize = sortByWeight(layoutBoxes.filter((wrap)=>wrap.box.fullSize), true);
  2903. const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  2904. const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  2905. const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  2906. const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  2907. const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');
  2908. const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');
  2909. return {
  2910. fullSize,
  2911. leftAndTop: left.concat(top),
  2912. rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),
  2913. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  2914. vertical: left.concat(right).concat(centerVertical),
  2915. horizontal: top.concat(bottom).concat(centerHorizontal)
  2916. };
  2917. }
  2918. function getCombinedMax(maxPadding, chartArea, a, b) {
  2919. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  2920. }
  2921. function updateMaxPadding(maxPadding, boxPadding) {
  2922. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  2923. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  2924. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  2925. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  2926. }
  2927. function updateDims(chartArea, params, layout, stacks) {
  2928. const { pos , box } = layout;
  2929. const maxPadding = chartArea.maxPadding;
  2930. if (!isObject(pos)) {
  2931. if (layout.size) {
  2932. chartArea[pos] -= layout.size;
  2933. }
  2934. const stack = stacks[layout.stack] || {
  2935. size: 0,
  2936. count: 1
  2937. };
  2938. stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);
  2939. layout.size = stack.size / stack.count;
  2940. chartArea[pos] += layout.size;
  2941. }
  2942. if (box.getPadding) {
  2943. updateMaxPadding(maxPadding, box.getPadding());
  2944. }
  2945. const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));
  2946. const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));
  2947. const widthChanged = newWidth !== chartArea.w;
  2948. const heightChanged = newHeight !== chartArea.h;
  2949. chartArea.w = newWidth;
  2950. chartArea.h = newHeight;
  2951. return layout.horizontal ? {
  2952. same: widthChanged,
  2953. other: heightChanged
  2954. } : {
  2955. same: heightChanged,
  2956. other: widthChanged
  2957. };
  2958. }
  2959. function handleMaxPadding(chartArea) {
  2960. const maxPadding = chartArea.maxPadding;
  2961. function updatePos(pos) {
  2962. const change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  2963. chartArea[pos] += change;
  2964. return change;
  2965. }
  2966. chartArea.y += updatePos('top');
  2967. chartArea.x += updatePos('left');
  2968. updatePos('right');
  2969. updatePos('bottom');
  2970. }
  2971. function getMargins(horizontal, chartArea) {
  2972. const maxPadding = chartArea.maxPadding;
  2973. function marginForPositions(positions) {
  2974. const margin = {
  2975. left: 0,
  2976. top: 0,
  2977. right: 0,
  2978. bottom: 0
  2979. };
  2980. positions.forEach((pos)=>{
  2981. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  2982. });
  2983. return margin;
  2984. }
  2985. return horizontal ? marginForPositions([
  2986. 'left',
  2987. 'right'
  2988. ]) : marginForPositions([
  2989. 'top',
  2990. 'bottom'
  2991. ]);
  2992. }
  2993. function fitBoxes(boxes, chartArea, params, stacks) {
  2994. const refitBoxes = [];
  2995. let i, ilen, layout, box, refit, changed;
  2996. for(i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i){
  2997. layout = boxes[i];
  2998. box = layout.box;
  2999. box.update(layout.width || chartArea.w, layout.height || chartArea.h, getMargins(layout.horizontal, chartArea));
  3000. const { same , other } = updateDims(chartArea, params, layout, stacks);
  3001. refit |= same && refitBoxes.length;
  3002. changed = changed || other;
  3003. if (!box.fullSize) {
  3004. refitBoxes.push(layout);
  3005. }
  3006. }
  3007. return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;
  3008. }
  3009. function setBoxDims(box, left, top, width, height) {
  3010. box.top = top;
  3011. box.left = left;
  3012. box.right = left + width;
  3013. box.bottom = top + height;
  3014. box.width = width;
  3015. box.height = height;
  3016. }
  3017. function placeBoxes(boxes, chartArea, params, stacks) {
  3018. const userPadding = params.padding;
  3019. let { x , y } = chartArea;
  3020. for (const layout of boxes){
  3021. const box = layout.box;
  3022. const stack = stacks[layout.stack] || {
  3023. count: 1,
  3024. placed: 0,
  3025. weight: 1
  3026. };
  3027. const weight = layout.stackWeight / stack.weight || 1;
  3028. if (layout.horizontal) {
  3029. const width = chartArea.w * weight;
  3030. const height = stack.size || box.height;
  3031. if (defined(stack.start)) {
  3032. y = stack.start;
  3033. }
  3034. if (box.fullSize) {
  3035. setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);
  3036. } else {
  3037. setBoxDims(box, chartArea.left + stack.placed, y, width, height);
  3038. }
  3039. stack.start = y;
  3040. stack.placed += width;
  3041. y = box.bottom;
  3042. } else {
  3043. const height = chartArea.h * weight;
  3044. const width = stack.size || box.width;
  3045. if (defined(stack.start)) {
  3046. x = stack.start;
  3047. }
  3048. if (box.fullSize) {
  3049. setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);
  3050. } else {
  3051. setBoxDims(box, x, chartArea.top + stack.placed, width, height);
  3052. }
  3053. stack.start = x;
  3054. stack.placed += height;
  3055. x = box.right;
  3056. }
  3057. }
  3058. chartArea.x = x;
  3059. chartArea.y = y;
  3060. }
  3061. var layouts = {
  3062. addBox (chart, item) {
  3063. if (!chart.boxes) {
  3064. chart.boxes = [];
  3065. }
  3066. item.fullSize = item.fullSize || false;
  3067. item.position = item.position || 'top';
  3068. item.weight = item.weight || 0;
  3069. item._layers = item._layers || function() {
  3070. return [
  3071. {
  3072. z: 0,
  3073. draw (chartArea) {
  3074. item.draw(chartArea);
  3075. }
  3076. }
  3077. ];
  3078. };
  3079. chart.boxes.push(item);
  3080. },
  3081. removeBox (chart, layoutItem) {
  3082. const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  3083. if (index !== -1) {
  3084. chart.boxes.splice(index, 1);
  3085. }
  3086. },
  3087. configure (chart, item, options) {
  3088. item.fullSize = options.fullSize;
  3089. item.position = options.position;
  3090. item.weight = options.weight;
  3091. },
  3092. update (chart, width, height, minPadding) {
  3093. if (!chart) {
  3094. return;
  3095. }
  3096. const padding = toPadding(chart.options.layout.padding);
  3097. const availableWidth = Math.max(width - padding.width, 0);
  3098. const availableHeight = Math.max(height - padding.height, 0);
  3099. const boxes = buildLayoutBoxes(chart.boxes);
  3100. const verticalBoxes = boxes.vertical;
  3101. const horizontalBoxes = boxes.horizontal;
  3102. each(chart.boxes, (box)=>{
  3103. if (typeof box.beforeLayout === 'function') {
  3104. box.beforeLayout();
  3105. }
  3106. });
  3107. const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap)=>wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;
  3108. const params = Object.freeze({
  3109. outerWidth: width,
  3110. outerHeight: height,
  3111. padding,
  3112. availableWidth,
  3113. availableHeight,
  3114. vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,
  3115. hBoxMaxHeight: availableHeight / 2
  3116. });
  3117. const maxPadding = Object.assign({}, padding);
  3118. updateMaxPadding(maxPadding, toPadding(minPadding));
  3119. const chartArea = Object.assign({
  3120. maxPadding,
  3121. w: availableWidth,
  3122. h: availableHeight,
  3123. x: padding.left,
  3124. y: padding.top
  3125. }, padding);
  3126. const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  3127. fitBoxes(boxes.fullSize, chartArea, params, stacks);
  3128. fitBoxes(verticalBoxes, chartArea, params, stacks);
  3129. if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {
  3130. fitBoxes(verticalBoxes, chartArea, params, stacks);
  3131. }
  3132. handleMaxPadding(chartArea);
  3133. placeBoxes(boxes.leftAndTop, chartArea, params, stacks);
  3134. chartArea.x += chartArea.w;
  3135. chartArea.y += chartArea.h;
  3136. placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);
  3137. chart.chartArea = {
  3138. left: chartArea.left,
  3139. top: chartArea.top,
  3140. right: chartArea.left + chartArea.w,
  3141. bottom: chartArea.top + chartArea.h,
  3142. height: chartArea.h,
  3143. width: chartArea.w
  3144. };
  3145. each(boxes.chartArea, (layout)=>{
  3146. const box = layout.box;
  3147. Object.assign(box, chart.chartArea);
  3148. box.update(chartArea.w, chartArea.h, {
  3149. left: 0,
  3150. top: 0,
  3151. right: 0,
  3152. bottom: 0
  3153. });
  3154. });
  3155. }
  3156. };
  3157. class BasePlatform {
  3158. acquireContext(canvas, aspectRatio) {}
  3159. releaseContext(context) {
  3160. return false;
  3161. }
  3162. addEventListener(chart, type, listener) {}
  3163. removeEventListener(chart, type, listener) {}
  3164. getDevicePixelRatio() {
  3165. return 1;
  3166. }
  3167. getMaximumSize(element, width, height, aspectRatio) {
  3168. width = Math.max(0, width || element.width);
  3169. height = height || element.height;
  3170. return {
  3171. width,
  3172. height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)
  3173. };
  3174. }
  3175. isAttached(canvas) {
  3176. return true;
  3177. }
  3178. updateConfig(config) {
  3179. }
  3180. }
  3181. class BasicPlatform extends BasePlatform {
  3182. acquireContext(item) {
  3183. return item && item.getContext && item.getContext('2d') || null;
  3184. }
  3185. updateConfig(config) {
  3186. config.options.animation = false;
  3187. }
  3188. }
  3189. const EXPANDO_KEY = '$chartjs';
  3190. const EVENT_TYPES = {
  3191. touchstart: 'mousedown',
  3192. touchmove: 'mousemove',
  3193. touchend: 'mouseup',
  3194. pointerenter: 'mouseenter',
  3195. pointerdown: 'mousedown',
  3196. pointermove: 'mousemove',
  3197. pointerup: 'mouseup',
  3198. pointerleave: 'mouseout',
  3199. pointerout: 'mouseout'
  3200. };
  3201. const isNullOrEmpty = (value)=>value === null || value === '';
  3202. function initCanvas(canvas, aspectRatio) {
  3203. const style = canvas.style;
  3204. const renderHeight = canvas.getAttribute('height');
  3205. const renderWidth = canvas.getAttribute('width');
  3206. canvas[EXPANDO_KEY] = {
  3207. initial: {
  3208. height: renderHeight,
  3209. width: renderWidth,
  3210. style: {
  3211. display: style.display,
  3212. height: style.height,
  3213. width: style.width
  3214. }
  3215. }
  3216. };
  3217. style.display = style.display || 'block';
  3218. style.boxSizing = style.boxSizing || 'border-box';
  3219. if (isNullOrEmpty(renderWidth)) {
  3220. const displayWidth = readUsedSize(canvas, 'width');
  3221. if (displayWidth !== undefined) {
  3222. canvas.width = displayWidth;
  3223. }
  3224. }
  3225. if (isNullOrEmpty(renderHeight)) {
  3226. if (canvas.style.height === '') {
  3227. canvas.height = canvas.width / (aspectRatio || 2);
  3228. } else {
  3229. const displayHeight = readUsedSize(canvas, 'height');
  3230. if (displayHeight !== undefined) {
  3231. canvas.height = displayHeight;
  3232. }
  3233. }
  3234. }
  3235. return canvas;
  3236. }
  3237. const eventListenerOptions = supportsEventListenerOptions ? {
  3238. passive: true
  3239. } : false;
  3240. function addListener(node, type, listener) {
  3241. if (node) {
  3242. node.addEventListener(type, listener, eventListenerOptions);
  3243. }
  3244. }
  3245. function removeListener(chart, type, listener) {
  3246. if (chart && chart.canvas) {
  3247. chart.canvas.removeEventListener(type, listener, eventListenerOptions);
  3248. }
  3249. }
  3250. function fromNativeEvent(event, chart) {
  3251. const type = EVENT_TYPES[event.type] || event.type;
  3252. const { x , y } = getRelativePosition(event, chart);
  3253. return {
  3254. type,
  3255. chart,
  3256. native: event,
  3257. x: x !== undefined ? x : null,
  3258. y: y !== undefined ? y : null
  3259. };
  3260. }
  3261. function nodeListContains(nodeList, canvas) {
  3262. for (const node of nodeList){
  3263. if (node === canvas || node.contains(canvas)) {
  3264. return true;
  3265. }
  3266. }
  3267. }
  3268. function createAttachObserver(chart, type, listener) {
  3269. const canvas = chart.canvas;
  3270. const observer = new MutationObserver((entries)=>{
  3271. let trigger = false;
  3272. for (const entry of entries){
  3273. trigger = trigger || nodeListContains(entry.addedNodes, canvas);
  3274. trigger = trigger && !nodeListContains(entry.removedNodes, canvas);
  3275. }
  3276. if (trigger) {
  3277. listener();
  3278. }
  3279. });
  3280. observer.observe(document, {
  3281. childList: true,
  3282. subtree: true
  3283. });
  3284. return observer;
  3285. }
  3286. function createDetachObserver(chart, type, listener) {
  3287. const canvas = chart.canvas;
  3288. const observer = new MutationObserver((entries)=>{
  3289. let trigger = false;
  3290. for (const entry of entries){
  3291. trigger = trigger || nodeListContains(entry.removedNodes, canvas);
  3292. trigger = trigger && !nodeListContains(entry.addedNodes, canvas);
  3293. }
  3294. if (trigger) {
  3295. listener();
  3296. }
  3297. });
  3298. observer.observe(document, {
  3299. childList: true,
  3300. subtree: true
  3301. });
  3302. return observer;
  3303. }
  3304. const drpListeningCharts = new Map();
  3305. let oldDevicePixelRatio = 0;
  3306. function onWindowResize() {
  3307. const dpr = window.devicePixelRatio;
  3308. if (dpr === oldDevicePixelRatio) {
  3309. return;
  3310. }
  3311. oldDevicePixelRatio = dpr;
  3312. drpListeningCharts.forEach((resize, chart)=>{
  3313. if (chart.currentDevicePixelRatio !== dpr) {
  3314. resize();
  3315. }
  3316. });
  3317. }
  3318. function listenDevicePixelRatioChanges(chart, resize) {
  3319. if (!drpListeningCharts.size) {
  3320. window.addEventListener('resize', onWindowResize);
  3321. }
  3322. drpListeningCharts.set(chart, resize);
  3323. }
  3324. function unlistenDevicePixelRatioChanges(chart) {
  3325. drpListeningCharts.delete(chart);
  3326. if (!drpListeningCharts.size) {
  3327. window.removeEventListener('resize', onWindowResize);
  3328. }
  3329. }
  3330. function createResizeObserver(chart, type, listener) {
  3331. const canvas = chart.canvas;
  3332. const container = canvas && _getParentNode(canvas);
  3333. if (!container) {
  3334. return;
  3335. }
  3336. const resize = throttled((width, height)=>{
  3337. const w = container.clientWidth;
  3338. listener(width, height);
  3339. if (w < container.clientWidth) {
  3340. listener();
  3341. }
  3342. }, window);
  3343. const observer = new ResizeObserver((entries)=>{
  3344. const entry = entries[0];
  3345. const width = entry.contentRect.width;
  3346. const height = entry.contentRect.height;
  3347. if (width === 0 && height === 0) {
  3348. return;
  3349. }
  3350. resize(width, height);
  3351. });
  3352. observer.observe(container);
  3353. listenDevicePixelRatioChanges(chart, resize);
  3354. return observer;
  3355. }
  3356. function releaseObserver(chart, type, observer) {
  3357. if (observer) {
  3358. observer.disconnect();
  3359. }
  3360. if (type === 'resize') {
  3361. unlistenDevicePixelRatioChanges(chart);
  3362. }
  3363. }
  3364. function createProxyAndListen(chart, type, listener) {
  3365. const canvas = chart.canvas;
  3366. const proxy = throttled((event)=>{
  3367. if (chart.ctx !== null) {
  3368. listener(fromNativeEvent(event, chart));
  3369. }
  3370. }, chart);
  3371. addListener(canvas, type, proxy);
  3372. return proxy;
  3373. }
  3374. class DomPlatform extends BasePlatform {
  3375. acquireContext(canvas, aspectRatio) {
  3376. const context = canvas && canvas.getContext && canvas.getContext('2d');
  3377. if (context && context.canvas === canvas) {
  3378. initCanvas(canvas, aspectRatio);
  3379. return context;
  3380. }
  3381. return null;
  3382. }
  3383. releaseContext(context) {
  3384. const canvas = context.canvas;
  3385. if (!canvas[EXPANDO_KEY]) {
  3386. return false;
  3387. }
  3388. const initial = canvas[EXPANDO_KEY].initial;
  3389. [
  3390. 'height',
  3391. 'width'
  3392. ].forEach((prop)=>{
  3393. const value = initial[prop];
  3394. if (isNullOrUndef(value)) {
  3395. canvas.removeAttribute(prop);
  3396. } else {
  3397. canvas.setAttribute(prop, value);
  3398. }
  3399. });
  3400. const style = initial.style || {};
  3401. Object.keys(style).forEach((key)=>{
  3402. canvas.style[key] = style[key];
  3403. });
  3404. canvas.width = canvas.width;
  3405. delete canvas[EXPANDO_KEY];
  3406. return true;
  3407. }
  3408. addEventListener(chart, type, listener) {
  3409. this.removeEventListener(chart, type);
  3410. const proxies = chart.$proxies || (chart.$proxies = {});
  3411. const handlers = {
  3412. attach: createAttachObserver,
  3413. detach: createDetachObserver,
  3414. resize: createResizeObserver
  3415. };
  3416. const handler = handlers[type] || createProxyAndListen;
  3417. proxies[type] = handler(chart, type, listener);
  3418. }
  3419. removeEventListener(chart, type) {
  3420. const proxies = chart.$proxies || (chart.$proxies = {});
  3421. const proxy = proxies[type];
  3422. if (!proxy) {
  3423. return;
  3424. }
  3425. const handlers = {
  3426. attach: releaseObserver,
  3427. detach: releaseObserver,
  3428. resize: releaseObserver
  3429. };
  3430. const handler = handlers[type] || removeListener;
  3431. handler(chart, type, proxy);
  3432. proxies[type] = undefined;
  3433. }
  3434. getDevicePixelRatio() {
  3435. return window.devicePixelRatio;
  3436. }
  3437. getMaximumSize(canvas, width, height, aspectRatio) {
  3438. return getMaximumSize(canvas, width, height, aspectRatio);
  3439. }
  3440. isAttached(canvas) {
  3441. const container = canvas && _getParentNode(canvas);
  3442. return !!(container && container.isConnected);
  3443. }
  3444. }
  3445. function _detectPlatform(canvas) {
  3446. if (!_isDomSupported() || typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) {
  3447. return BasicPlatform;
  3448. }
  3449. return DomPlatform;
  3450. }
  3451. class Element {
  3452. static defaults = {};
  3453. static defaultRoutes = undefined;
  3454. x;
  3455. y;
  3456. active = false;
  3457. options;
  3458. $animations;
  3459. tooltipPosition(useFinalPosition) {
  3460. const { x , y } = this.getProps([
  3461. 'x',
  3462. 'y'
  3463. ], useFinalPosition);
  3464. return {
  3465. x,
  3466. y
  3467. };
  3468. }
  3469. hasValue() {
  3470. return isNumber(this.x) && isNumber(this.y);
  3471. }
  3472. getProps(props, final) {
  3473. const anims = this.$animations;
  3474. if (!final || !anims) {
  3475. // let's not create an object, if not needed
  3476. return this;
  3477. }
  3478. const ret = {};
  3479. props.forEach((prop)=>{
  3480. ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop];
  3481. });
  3482. return ret;
  3483. }
  3484. }
  3485. function autoSkip(scale, ticks) {
  3486. const tickOpts = scale.options.ticks;
  3487. const determinedMaxTicks = determineMaxTicks(scale);
  3488. const ticksLimit = Math.min(tickOpts.maxTicksLimit || determinedMaxTicks, determinedMaxTicks);
  3489. const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  3490. const numMajorIndices = majorIndices.length;
  3491. const first = majorIndices[0];
  3492. const last = majorIndices[numMajorIndices - 1];
  3493. const newTicks = [];
  3494. if (numMajorIndices > ticksLimit) {
  3495. skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);
  3496. return newTicks;
  3497. }
  3498. const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);
  3499. if (numMajorIndices > 0) {
  3500. let i, ilen;
  3501. const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
  3502. skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  3503. for(i = 0, ilen = numMajorIndices - 1; i < ilen; i++){
  3504. skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
  3505. }
  3506. skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  3507. return newTicks;
  3508. }
  3509. skip(ticks, newTicks, spacing);
  3510. return newTicks;
  3511. }
  3512. function determineMaxTicks(scale) {
  3513. const offset = scale.options.offset;
  3514. const tickLength = scale._tickSize();
  3515. const maxScale = scale._length / tickLength + (offset ? 0 : 1);
  3516. const maxChart = scale._maxLength / tickLength;
  3517. return Math.floor(Math.min(maxScale, maxChart));
  3518. }
  3519. function calculateSpacing(majorIndices, ticks, ticksLimit) {
  3520. const evenMajorSpacing = getEvenSpacing(majorIndices);
  3521. const spacing = ticks.length / ticksLimit;
  3522. if (!evenMajorSpacing) {
  3523. return Math.max(spacing, 1);
  3524. }
  3525. const factors = _factorize(evenMajorSpacing);
  3526. for(let i = 0, ilen = factors.length - 1; i < ilen; i++){
  3527. const factor = factors[i];
  3528. if (factor > spacing) {
  3529. return factor;
  3530. }
  3531. }
  3532. return Math.max(spacing, 1);
  3533. }
  3534. function getMajorIndices(ticks) {
  3535. const result = [];
  3536. let i, ilen;
  3537. for(i = 0, ilen = ticks.length; i < ilen; i++){
  3538. if (ticks[i].major) {
  3539. result.push(i);
  3540. }
  3541. }
  3542. return result;
  3543. }
  3544. function skipMajors(ticks, newTicks, majorIndices, spacing) {
  3545. let count = 0;
  3546. let next = majorIndices[0];
  3547. let i;
  3548. spacing = Math.ceil(spacing);
  3549. for(i = 0; i < ticks.length; i++){
  3550. if (i === next) {
  3551. newTicks.push(ticks[i]);
  3552. count++;
  3553. next = majorIndices[count * spacing];
  3554. }
  3555. }
  3556. }
  3557. function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
  3558. const start = valueOrDefault(majorStart, 0);
  3559. const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);
  3560. let count = 0;
  3561. let length, i, next;
  3562. spacing = Math.ceil(spacing);
  3563. if (majorEnd) {
  3564. length = majorEnd - majorStart;
  3565. spacing = length / Math.floor(length / spacing);
  3566. }
  3567. next = start;
  3568. while(next < 0){
  3569. count++;
  3570. next = Math.round(start + count * spacing);
  3571. }
  3572. for(i = Math.max(start, 0); i < end; i++){
  3573. if (i === next) {
  3574. newTicks.push(ticks[i]);
  3575. count++;
  3576. next = Math.round(start + count * spacing);
  3577. }
  3578. }
  3579. }
  3580. function getEvenSpacing(arr) {
  3581. const len = arr.length;
  3582. let i, diff;
  3583. if (len < 2) {
  3584. return false;
  3585. }
  3586. for(diff = arr[0], i = 1; i < len; ++i){
  3587. if (arr[i] - arr[i - 1] !== diff) {
  3588. return false;
  3589. }
  3590. }
  3591. return diff;
  3592. }
  3593. const reverseAlign = (align)=>align === 'left' ? 'right' : align === 'right' ? 'left' : align;
  3594. const offsetFromEdge = (scale, edge, offset)=>edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;
  3595. const getTicksLimit = (ticksLength, maxTicksLimit)=>Math.min(maxTicksLimit || ticksLength, ticksLength);
  3596. function sample(arr, numItems) {
  3597. const result = [];
  3598. const increment = arr.length / numItems;
  3599. const len = arr.length;
  3600. let i = 0;
  3601. for(; i < len; i += increment){
  3602. result.push(arr[Math.floor(i)]);
  3603. }
  3604. return result;
  3605. }
  3606. function getPixelForGridLine(scale, index, offsetGridLines) {
  3607. const length = scale.ticks.length;
  3608. const validIndex = Math.min(index, length - 1);
  3609. const start = scale._startPixel;
  3610. const end = scale._endPixel;
  3611. const epsilon = 1e-6;
  3612. let lineValue = scale.getPixelForTick(validIndex);
  3613. let offset;
  3614. if (offsetGridLines) {
  3615. if (length === 1) {
  3616. offset = Math.max(lineValue - start, end - lineValue);
  3617. } else if (index === 0) {
  3618. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  3619. } else {
  3620. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  3621. }
  3622. lineValue += validIndex < index ? offset : -offset;
  3623. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  3624. return;
  3625. }
  3626. }
  3627. return lineValue;
  3628. }
  3629. function garbageCollect(caches, length) {
  3630. each(caches, (cache)=>{
  3631. const gc = cache.gc;
  3632. const gcLen = gc.length / 2;
  3633. let i;
  3634. if (gcLen > length) {
  3635. for(i = 0; i < gcLen; ++i){
  3636. delete cache.data[gc[i]];
  3637. }
  3638. gc.splice(0, gcLen);
  3639. }
  3640. });
  3641. }
  3642. function getTickMarkLength(options) {
  3643. return options.drawTicks ? options.tickLength : 0;
  3644. }
  3645. function getTitleHeight(options, fallback) {
  3646. if (!options.display) {
  3647. return 0;
  3648. }
  3649. const font = toFont(options.font, fallback);
  3650. const padding = toPadding(options.padding);
  3651. const lines = isArray(options.text) ? options.text.length : 1;
  3652. return lines * font.lineHeight + padding.height;
  3653. }
  3654. function createScaleContext(parent, scale) {
  3655. return createContext(parent, {
  3656. scale,
  3657. type: 'scale'
  3658. });
  3659. }
  3660. function createTickContext(parent, index, tick) {
  3661. return createContext(parent, {
  3662. tick,
  3663. index,
  3664. type: 'tick'
  3665. });
  3666. }
  3667. function titleAlign(align, position, reverse) {
  3668. let ret = _toLeftRightCenter(align);
  3669. if (reverse && position !== 'right' || !reverse && position === 'right') {
  3670. ret = reverseAlign(ret);
  3671. }
  3672. return ret;
  3673. }
  3674. function titleArgs(scale, offset, position, align) {
  3675. const { top , left , bottom , right , chart } = scale;
  3676. const { chartArea , scales } = chart;
  3677. let rotation = 0;
  3678. let maxWidth, titleX, titleY;
  3679. const height = bottom - top;
  3680. const width = right - left;
  3681. if (scale.isHorizontal()) {
  3682. titleX = _alignStartEnd(align, left, right);
  3683. if (isObject(position)) {
  3684. const positionAxisID = Object.keys(position)[0];
  3685. const value = position[positionAxisID];
  3686. titleY = scales[positionAxisID].getPixelForValue(value) + height - offset;
  3687. } else if (position === 'center') {
  3688. titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset;
  3689. } else {
  3690. titleY = offsetFromEdge(scale, position, offset);
  3691. }
  3692. maxWidth = right - left;
  3693. } else {
  3694. if (isObject(position)) {
  3695. const positionAxisID = Object.keys(position)[0];
  3696. const value = position[positionAxisID];
  3697. titleX = scales[positionAxisID].getPixelForValue(value) - width + offset;
  3698. } else if (position === 'center') {
  3699. titleX = (chartArea.left + chartArea.right) / 2 - width + offset;
  3700. } else {
  3701. titleX = offsetFromEdge(scale, position, offset);
  3702. }
  3703. titleY = _alignStartEnd(align, bottom, top);
  3704. rotation = position === 'left' ? -HALF_PI : HALF_PI;
  3705. }
  3706. return {
  3707. titleX,
  3708. titleY,
  3709. maxWidth,
  3710. rotation
  3711. };
  3712. }
  3713. class Scale extends Element {
  3714. constructor(cfg){
  3715. super();
  3716. this.id = cfg.id;
  3717. this.type = cfg.type;
  3718. this.options = undefined;
  3719. this.ctx = cfg.ctx;
  3720. this.chart = cfg.chart;
  3721. this.top = undefined;
  3722. this.bottom = undefined;
  3723. this.left = undefined;
  3724. this.right = undefined;
  3725. this.width = undefined;
  3726. this.height = undefined;
  3727. this._margins = {
  3728. left: 0,
  3729. right: 0,
  3730. top: 0,
  3731. bottom: 0
  3732. };
  3733. this.maxWidth = undefined;
  3734. this.maxHeight = undefined;
  3735. this.paddingTop = undefined;
  3736. this.paddingBottom = undefined;
  3737. this.paddingLeft = undefined;
  3738. this.paddingRight = undefined;
  3739. this.axis = undefined;
  3740. this.labelRotation = undefined;
  3741. this.min = undefined;
  3742. this.max = undefined;
  3743. this._range = undefined;
  3744. this.ticks = [];
  3745. this._gridLineItems = null;
  3746. this._labelItems = null;
  3747. this._labelSizes = null;
  3748. this._length = 0;
  3749. this._maxLength = 0;
  3750. this._longestTextCache = {};
  3751. this._startPixel = undefined;
  3752. this._endPixel = undefined;
  3753. this._reversePixels = false;
  3754. this._userMax = undefined;
  3755. this._userMin = undefined;
  3756. this._suggestedMax = undefined;
  3757. this._suggestedMin = undefined;
  3758. this._ticksLength = 0;
  3759. this._borderValue = 0;
  3760. this._cache = {};
  3761. this._dataLimitsCached = false;
  3762. this.$context = undefined;
  3763. }
  3764. init(options) {
  3765. this.options = options.setContext(this.getContext());
  3766. this.axis = options.axis;
  3767. this._userMin = this.parse(options.min);
  3768. this._userMax = this.parse(options.max);
  3769. this._suggestedMin = this.parse(options.suggestedMin);
  3770. this._suggestedMax = this.parse(options.suggestedMax);
  3771. }
  3772. parse(raw, index) {
  3773. return raw;
  3774. }
  3775. getUserBounds() {
  3776. let { _userMin , _userMax , _suggestedMin , _suggestedMax } = this;
  3777. _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);
  3778. _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);
  3779. _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);
  3780. _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);
  3781. return {
  3782. min: finiteOrDefault(_userMin, _suggestedMin),
  3783. max: finiteOrDefault(_userMax, _suggestedMax),
  3784. minDefined: isNumberFinite(_userMin),
  3785. maxDefined: isNumberFinite(_userMax)
  3786. };
  3787. }
  3788. getMinMax(canStack) {
  3789. let { min , max , minDefined , maxDefined } = this.getUserBounds();
  3790. let range;
  3791. if (minDefined && maxDefined) {
  3792. return {
  3793. min,
  3794. max
  3795. };
  3796. }
  3797. const metas = this.getMatchingVisibleMetas();
  3798. for(let i = 0, ilen = metas.length; i < ilen; ++i){
  3799. range = metas[i].controller.getMinMax(this, canStack);
  3800. if (!minDefined) {
  3801. min = Math.min(min, range.min);
  3802. }
  3803. if (!maxDefined) {
  3804. max = Math.max(max, range.max);
  3805. }
  3806. }
  3807. min = maxDefined && min > max ? max : min;
  3808. max = minDefined && min > max ? min : max;
  3809. return {
  3810. min: finiteOrDefault(min, finiteOrDefault(max, min)),
  3811. max: finiteOrDefault(max, finiteOrDefault(min, max))
  3812. };
  3813. }
  3814. getPadding() {
  3815. return {
  3816. left: this.paddingLeft || 0,
  3817. top: this.paddingTop || 0,
  3818. right: this.paddingRight || 0,
  3819. bottom: this.paddingBottom || 0
  3820. };
  3821. }
  3822. getTicks() {
  3823. return this.ticks;
  3824. }
  3825. getLabels() {
  3826. const data = this.chart.data;
  3827. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  3828. }
  3829. getLabelItems(chartArea = this.chart.chartArea) {
  3830. const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea));
  3831. return items;
  3832. }
  3833. beforeLayout() {
  3834. this._cache = {};
  3835. this._dataLimitsCached = false;
  3836. }
  3837. beforeUpdate() {
  3838. callback(this.options.beforeUpdate, [
  3839. this
  3840. ]);
  3841. }
  3842. update(maxWidth, maxHeight, margins) {
  3843. const { beginAtZero , grace , ticks: tickOpts } = this.options;
  3844. const sampleSize = tickOpts.sampleSize;
  3845. this.beforeUpdate();
  3846. this.maxWidth = maxWidth;
  3847. this.maxHeight = maxHeight;
  3848. this._margins = margins = Object.assign({
  3849. left: 0,
  3850. right: 0,
  3851. top: 0,
  3852. bottom: 0
  3853. }, margins);
  3854. this.ticks = null;
  3855. this._labelSizes = null;
  3856. this._gridLineItems = null;
  3857. this._labelItems = null;
  3858. this.beforeSetDimensions();
  3859. this.setDimensions();
  3860. this.afterSetDimensions();
  3861. this._maxLength = this.isHorizontal() ? this.width + margins.left + margins.right : this.height + margins.top + margins.bottom;
  3862. if (!this._dataLimitsCached) {
  3863. this.beforeDataLimits();
  3864. this.determineDataLimits();
  3865. this.afterDataLimits();
  3866. this._range = _addGrace(this, grace, beginAtZero);
  3867. this._dataLimitsCached = true;
  3868. }
  3869. this.beforeBuildTicks();
  3870. this.ticks = this.buildTicks() || [];
  3871. this.afterBuildTicks();
  3872. const samplingEnabled = sampleSize < this.ticks.length;
  3873. this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks);
  3874. this.configure();
  3875. this.beforeCalculateLabelRotation();
  3876. this.calculateLabelRotation();
  3877. this.afterCalculateLabelRotation();
  3878. if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {
  3879. this.ticks = autoSkip(this, this.ticks);
  3880. this._labelSizes = null;
  3881. this.afterAutoSkip();
  3882. }
  3883. if (samplingEnabled) {
  3884. this._convertTicksToLabels(this.ticks);
  3885. }
  3886. this.beforeFit();
  3887. this.fit();
  3888. this.afterFit();
  3889. this.afterUpdate();
  3890. }
  3891. configure() {
  3892. let reversePixels = this.options.reverse;
  3893. let startPixel, endPixel;
  3894. if (this.isHorizontal()) {
  3895. startPixel = this.left;
  3896. endPixel = this.right;
  3897. } else {
  3898. startPixel = this.top;
  3899. endPixel = this.bottom;
  3900. reversePixels = !reversePixels;
  3901. }
  3902. this._startPixel = startPixel;
  3903. this._endPixel = endPixel;
  3904. this._reversePixels = reversePixels;
  3905. this._length = endPixel - startPixel;
  3906. this._alignToPixels = this.options.alignToPixels;
  3907. }
  3908. afterUpdate() {
  3909. callback(this.options.afterUpdate, [
  3910. this
  3911. ]);
  3912. }
  3913. beforeSetDimensions() {
  3914. callback(this.options.beforeSetDimensions, [
  3915. this
  3916. ]);
  3917. }
  3918. setDimensions() {
  3919. if (this.isHorizontal()) {
  3920. this.width = this.maxWidth;
  3921. this.left = 0;
  3922. this.right = this.width;
  3923. } else {
  3924. this.height = this.maxHeight;
  3925. this.top = 0;
  3926. this.bottom = this.height;
  3927. }
  3928. this.paddingLeft = 0;
  3929. this.paddingTop = 0;
  3930. this.paddingRight = 0;
  3931. this.paddingBottom = 0;
  3932. }
  3933. afterSetDimensions() {
  3934. callback(this.options.afterSetDimensions, [
  3935. this
  3936. ]);
  3937. }
  3938. _callHooks(name) {
  3939. this.chart.notifyPlugins(name, this.getContext());
  3940. callback(this.options[name], [
  3941. this
  3942. ]);
  3943. }
  3944. beforeDataLimits() {
  3945. this._callHooks('beforeDataLimits');
  3946. }
  3947. determineDataLimits() {}
  3948. afterDataLimits() {
  3949. this._callHooks('afterDataLimits');
  3950. }
  3951. beforeBuildTicks() {
  3952. this._callHooks('beforeBuildTicks');
  3953. }
  3954. buildTicks() {
  3955. return [];
  3956. }
  3957. afterBuildTicks() {
  3958. this._callHooks('afterBuildTicks');
  3959. }
  3960. beforeTickToLabelConversion() {
  3961. callback(this.options.beforeTickToLabelConversion, [
  3962. this
  3963. ]);
  3964. }
  3965. generateTickLabels(ticks) {
  3966. const tickOpts = this.options.ticks;
  3967. let i, ilen, tick;
  3968. for(i = 0, ilen = ticks.length; i < ilen; i++){
  3969. tick = ticks[i];
  3970. tick.label = callback(tickOpts.callback, [
  3971. tick.value,
  3972. i,
  3973. ticks
  3974. ], this);
  3975. }
  3976. }
  3977. afterTickToLabelConversion() {
  3978. callback(this.options.afterTickToLabelConversion, [
  3979. this
  3980. ]);
  3981. }
  3982. beforeCalculateLabelRotation() {
  3983. callback(this.options.beforeCalculateLabelRotation, [
  3984. this
  3985. ]);
  3986. }
  3987. calculateLabelRotation() {
  3988. const options = this.options;
  3989. const tickOpts = options.ticks;
  3990. const numTicks = getTicksLimit(this.ticks.length, options.ticks.maxTicksLimit);
  3991. const minRotation = tickOpts.minRotation || 0;
  3992. const maxRotation = tickOpts.maxRotation;
  3993. let labelRotation = minRotation;
  3994. let tickWidth, maxHeight, maxLabelDiagonal;
  3995. if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) {
  3996. this.labelRotation = minRotation;
  3997. return;
  3998. }
  3999. const labelSizes = this._getLabelSizes();
  4000. const maxLabelWidth = labelSizes.widest.width;
  4001. const maxLabelHeight = labelSizes.highest.height;
  4002. const maxWidth = _limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth);
  4003. tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1);
  4004. if (maxLabelWidth + 6 > tickWidth) {
  4005. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  4006. maxHeight = this.maxHeight - getTickMarkLength(options.grid) - tickOpts.padding - getTitleHeight(options.title, this.chart.options.font);
  4007. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  4008. labelRotation = toDegrees(Math.min(Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)), Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))));
  4009. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  4010. }
  4011. this.labelRotation = labelRotation;
  4012. }
  4013. afterCalculateLabelRotation() {
  4014. callback(this.options.afterCalculateLabelRotation, [
  4015. this
  4016. ]);
  4017. }
  4018. afterAutoSkip() {}
  4019. beforeFit() {
  4020. callback(this.options.beforeFit, [
  4021. this
  4022. ]);
  4023. }
  4024. fit() {
  4025. const minSize = {
  4026. width: 0,
  4027. height: 0
  4028. };
  4029. const { chart , options: { ticks: tickOpts , title: titleOpts , grid: gridOpts } } = this;
  4030. const display = this._isVisible();
  4031. const isHorizontal = this.isHorizontal();
  4032. if (display) {
  4033. const titleHeight = getTitleHeight(titleOpts, chart.options.font);
  4034. if (isHorizontal) {
  4035. minSize.width = this.maxWidth;
  4036. minSize.height = getTickMarkLength(gridOpts) + titleHeight;
  4037. } else {
  4038. minSize.height = this.maxHeight;
  4039. minSize.width = getTickMarkLength(gridOpts) + titleHeight;
  4040. }
  4041. if (tickOpts.display && this.ticks.length) {
  4042. const { first , last , widest , highest } = this._getLabelSizes();
  4043. const tickPadding = tickOpts.padding * 2;
  4044. const angleRadians = toRadians(this.labelRotation);
  4045. const cos = Math.cos(angleRadians);
  4046. const sin = Math.sin(angleRadians);
  4047. if (isHorizontal) {
  4048. const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;
  4049. minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding);
  4050. } else {
  4051. const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;
  4052. minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding);
  4053. }
  4054. this._calculatePadding(first, last, sin, cos);
  4055. }
  4056. }
  4057. this._handleMargins();
  4058. if (isHorizontal) {
  4059. this.width = this._length = chart.width - this._margins.left - this._margins.right;
  4060. this.height = minSize.height;
  4061. } else {
  4062. this.width = minSize.width;
  4063. this.height = this._length = chart.height - this._margins.top - this._margins.bottom;
  4064. }
  4065. }
  4066. _calculatePadding(first, last, sin, cos) {
  4067. const { ticks: { align , padding } , position } = this.options;
  4068. const isRotated = this.labelRotation !== 0;
  4069. const labelsBelowTicks = position !== 'top' && this.axis === 'x';
  4070. if (this.isHorizontal()) {
  4071. const offsetLeft = this.getPixelForTick(0) - this.left;
  4072. const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1);
  4073. let paddingLeft = 0;
  4074. let paddingRight = 0;
  4075. if (isRotated) {
  4076. if (labelsBelowTicks) {
  4077. paddingLeft = cos * first.width;
  4078. paddingRight = sin * last.height;
  4079. } else {
  4080. paddingLeft = sin * first.height;
  4081. paddingRight = cos * last.width;
  4082. }
  4083. } else if (align === 'start') {
  4084. paddingRight = last.width;
  4085. } else if (align === 'end') {
  4086. paddingLeft = first.width;
  4087. } else if (align !== 'inner') {
  4088. paddingLeft = first.width / 2;
  4089. paddingRight = last.width / 2;
  4090. }
  4091. this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0);
  4092. this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0);
  4093. } else {
  4094. let paddingTop = last.height / 2;
  4095. let paddingBottom = first.height / 2;
  4096. if (align === 'start') {
  4097. paddingTop = 0;
  4098. paddingBottom = first.height;
  4099. } else if (align === 'end') {
  4100. paddingTop = last.height;
  4101. paddingBottom = 0;
  4102. }
  4103. this.paddingTop = paddingTop + padding;
  4104. this.paddingBottom = paddingBottom + padding;
  4105. }
  4106. }
  4107. _handleMargins() {
  4108. if (this._margins) {
  4109. this._margins.left = Math.max(this.paddingLeft, this._margins.left);
  4110. this._margins.top = Math.max(this.paddingTop, this._margins.top);
  4111. this._margins.right = Math.max(this.paddingRight, this._margins.right);
  4112. this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom);
  4113. }
  4114. }
  4115. afterFit() {
  4116. callback(this.options.afterFit, [
  4117. this
  4118. ]);
  4119. }
  4120. isHorizontal() {
  4121. const { axis , position } = this.options;
  4122. return position === 'top' || position === 'bottom' || axis === 'x';
  4123. }
  4124. isFullSize() {
  4125. return this.options.fullSize;
  4126. }
  4127. _convertTicksToLabels(ticks) {
  4128. this.beforeTickToLabelConversion();
  4129. this.generateTickLabels(ticks);
  4130. let i, ilen;
  4131. for(i = 0, ilen = ticks.length; i < ilen; i++){
  4132. if (isNullOrUndef(ticks[i].label)) {
  4133. ticks.splice(i, 1);
  4134. ilen--;
  4135. i--;
  4136. }
  4137. }
  4138. this.afterTickToLabelConversion();
  4139. }
  4140. _getLabelSizes() {
  4141. let labelSizes = this._labelSizes;
  4142. if (!labelSizes) {
  4143. const sampleSize = this.options.ticks.sampleSize;
  4144. let ticks = this.ticks;
  4145. if (sampleSize < ticks.length) {
  4146. ticks = sample(ticks, sampleSize);
  4147. }
  4148. this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length, this.options.ticks.maxTicksLimit);
  4149. }
  4150. return labelSizes;
  4151. }
  4152. _computeLabelSizes(ticks, length, maxTicksLimit) {
  4153. const { ctx , _longestTextCache: caches } = this;
  4154. const widths = [];
  4155. const heights = [];
  4156. const increment = Math.floor(length / getTicksLimit(length, maxTicksLimit));
  4157. let widestLabelSize = 0;
  4158. let highestLabelSize = 0;
  4159. let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;
  4160. for(i = 0; i < length; i += increment){
  4161. label = ticks[i].label;
  4162. tickFont = this._resolveTickFontOptions(i);
  4163. ctx.font = fontString = tickFont.string;
  4164. cache = caches[fontString] = caches[fontString] || {
  4165. data: {},
  4166. gc: []
  4167. };
  4168. lineHeight = tickFont.lineHeight;
  4169. width = height = 0;
  4170. if (!isNullOrUndef(label) && !isArray(label)) {
  4171. width = _measureText(ctx, cache.data, cache.gc, width, label);
  4172. height = lineHeight;
  4173. } else if (isArray(label)) {
  4174. for(j = 0, jlen = label.length; j < jlen; ++j){
  4175. nestedLabel = label[j];
  4176. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  4177. width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  4178. height += lineHeight;
  4179. }
  4180. }
  4181. }
  4182. widths.push(width);
  4183. heights.push(height);
  4184. widestLabelSize = Math.max(width, widestLabelSize);
  4185. highestLabelSize = Math.max(height, highestLabelSize);
  4186. }
  4187. garbageCollect(caches, length);
  4188. const widest = widths.indexOf(widestLabelSize);
  4189. const highest = heights.indexOf(highestLabelSize);
  4190. const valueAt = (idx)=>({
  4191. width: widths[idx] || 0,
  4192. height: heights[idx] || 0
  4193. });
  4194. return {
  4195. first: valueAt(0),
  4196. last: valueAt(length - 1),
  4197. widest: valueAt(widest),
  4198. highest: valueAt(highest),
  4199. widths,
  4200. heights
  4201. };
  4202. }
  4203. getLabelForValue(value) {
  4204. return value;
  4205. }
  4206. getPixelForValue(value, index) {
  4207. return NaN;
  4208. }
  4209. getValueForPixel(pixel) {}
  4210. getPixelForTick(index) {
  4211. const ticks = this.ticks;
  4212. if (index < 0 || index > ticks.length - 1) {
  4213. return null;
  4214. }
  4215. return this.getPixelForValue(ticks[index].value);
  4216. }
  4217. getPixelForDecimal(decimal) {
  4218. if (this._reversePixels) {
  4219. decimal = 1 - decimal;
  4220. }
  4221. const pixel = this._startPixel + decimal * this._length;
  4222. return _int16Range(this._alignToPixels ? _alignPixel(this.chart, pixel, 0) : pixel);
  4223. }
  4224. getDecimalForPixel(pixel) {
  4225. const decimal = (pixel - this._startPixel) / this._length;
  4226. return this._reversePixels ? 1 - decimal : decimal;
  4227. }
  4228. getBasePixel() {
  4229. return this.getPixelForValue(this.getBaseValue());
  4230. }
  4231. getBaseValue() {
  4232. const { min , max } = this;
  4233. return min < 0 && max < 0 ? max : min > 0 && max > 0 ? min : 0;
  4234. }
  4235. getContext(index) {
  4236. const ticks = this.ticks || [];
  4237. if (index >= 0 && index < ticks.length) {
  4238. const tick = ticks[index];
  4239. return tick.$context || (tick.$context = createTickContext(this.getContext(), index, tick));
  4240. }
  4241. return this.$context || (this.$context = createScaleContext(this.chart.getContext(), this));
  4242. }
  4243. _tickSize() {
  4244. const optionTicks = this.options.ticks;
  4245. const rot = toRadians(this.labelRotation);
  4246. const cos = Math.abs(Math.cos(rot));
  4247. const sin = Math.abs(Math.sin(rot));
  4248. const labelSizes = this._getLabelSizes();
  4249. const padding = optionTicks.autoSkipPadding || 0;
  4250. const w = labelSizes ? labelSizes.widest.width + padding : 0;
  4251. const h = labelSizes ? labelSizes.highest.height + padding : 0;
  4252. return this.isHorizontal() ? h * cos > w * sin ? w / cos : h / sin : h * sin < w * cos ? h / cos : w / sin;
  4253. }
  4254. _isVisible() {
  4255. const display = this.options.display;
  4256. if (display !== 'auto') {
  4257. return !!display;
  4258. }
  4259. return this.getMatchingVisibleMetas().length > 0;
  4260. }
  4261. _computeGridLineItems(chartArea) {
  4262. const axis = this.axis;
  4263. const chart = this.chart;
  4264. const options = this.options;
  4265. const { grid , position , border } = options;
  4266. const offset = grid.offset;
  4267. const isHorizontal = this.isHorizontal();
  4268. const ticks = this.ticks;
  4269. const ticksLength = ticks.length + (offset ? 1 : 0);
  4270. const tl = getTickMarkLength(grid);
  4271. const items = [];
  4272. const borderOpts = border.setContext(this.getContext());
  4273. const axisWidth = borderOpts.display ? borderOpts.width : 0;
  4274. const axisHalfWidth = axisWidth / 2;
  4275. const alignBorderValue = function(pixel) {
  4276. return _alignPixel(chart, pixel, axisWidth);
  4277. };
  4278. let borderValue, i, lineValue, alignedLineValue;
  4279. let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
  4280. if (position === 'top') {
  4281. borderValue = alignBorderValue(this.bottom);
  4282. ty1 = this.bottom - tl;
  4283. ty2 = borderValue - axisHalfWidth;
  4284. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  4285. y2 = chartArea.bottom;
  4286. } else if (position === 'bottom') {
  4287. borderValue = alignBorderValue(this.top);
  4288. y1 = chartArea.top;
  4289. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  4290. ty1 = borderValue + axisHalfWidth;
  4291. ty2 = this.top + tl;
  4292. } else if (position === 'left') {
  4293. borderValue = alignBorderValue(this.right);
  4294. tx1 = this.right - tl;
  4295. tx2 = borderValue - axisHalfWidth;
  4296. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  4297. x2 = chartArea.right;
  4298. } else if (position === 'right') {
  4299. borderValue = alignBorderValue(this.left);
  4300. x1 = chartArea.left;
  4301. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  4302. tx1 = borderValue + axisHalfWidth;
  4303. tx2 = this.left + tl;
  4304. } else if (axis === 'x') {
  4305. if (position === 'center') {
  4306. borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);
  4307. } else if (isObject(position)) {
  4308. const positionAxisID = Object.keys(position)[0];
  4309. const value = position[positionAxisID];
  4310. borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));
  4311. }
  4312. y1 = chartArea.top;
  4313. y2 = chartArea.bottom;
  4314. ty1 = borderValue + axisHalfWidth;
  4315. ty2 = ty1 + tl;
  4316. } else if (axis === 'y') {
  4317. if (position === 'center') {
  4318. borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
  4319. } else if (isObject(position)) {
  4320. const positionAxisID = Object.keys(position)[0];
  4321. const value = position[positionAxisID];
  4322. borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));
  4323. }
  4324. tx1 = borderValue - axisHalfWidth;
  4325. tx2 = tx1 - tl;
  4326. x1 = chartArea.left;
  4327. x2 = chartArea.right;
  4328. }
  4329. const limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength);
  4330. const step = Math.max(1, Math.ceil(ticksLength / limit));
  4331. for(i = 0; i < ticksLength; i += step){
  4332. const context = this.getContext(i);
  4333. const optsAtIndex = grid.setContext(context);
  4334. const optsAtIndexBorder = border.setContext(context);
  4335. const lineWidth = optsAtIndex.lineWidth;
  4336. const lineColor = optsAtIndex.color;
  4337. const borderDash = optsAtIndexBorder.dash || [];
  4338. const borderDashOffset = optsAtIndexBorder.dashOffset;
  4339. const tickWidth = optsAtIndex.tickWidth;
  4340. const tickColor = optsAtIndex.tickColor;
  4341. const tickBorderDash = optsAtIndex.tickBorderDash || [];
  4342. const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;
  4343. lineValue = getPixelForGridLine(this, i, offset);
  4344. if (lineValue === undefined) {
  4345. continue;
  4346. }
  4347. alignedLineValue = _alignPixel(chart, lineValue, lineWidth);
  4348. if (isHorizontal) {
  4349. tx1 = tx2 = x1 = x2 = alignedLineValue;
  4350. } else {
  4351. ty1 = ty2 = y1 = y2 = alignedLineValue;
  4352. }
  4353. items.push({
  4354. tx1,
  4355. ty1,
  4356. tx2,
  4357. ty2,
  4358. x1,
  4359. y1,
  4360. x2,
  4361. y2,
  4362. width: lineWidth,
  4363. color: lineColor,
  4364. borderDash,
  4365. borderDashOffset,
  4366. tickWidth,
  4367. tickColor,
  4368. tickBorderDash,
  4369. tickBorderDashOffset
  4370. });
  4371. }
  4372. this._ticksLength = ticksLength;
  4373. this._borderValue = borderValue;
  4374. return items;
  4375. }
  4376. _computeLabelItems(chartArea) {
  4377. const axis = this.axis;
  4378. const options = this.options;
  4379. const { position , ticks: optionTicks } = options;
  4380. const isHorizontal = this.isHorizontal();
  4381. const ticks = this.ticks;
  4382. const { align , crossAlign , padding , mirror } = optionTicks;
  4383. const tl = getTickMarkLength(options.grid);
  4384. const tickAndPadding = tl + padding;
  4385. const hTickAndPadding = mirror ? -padding : tickAndPadding;
  4386. const rotation = -toRadians(this.labelRotation);
  4387. const items = [];
  4388. let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  4389. let textBaseline = 'middle';
  4390. if (position === 'top') {
  4391. y = this.bottom - hTickAndPadding;
  4392. textAlign = this._getXAxisLabelAlignment();
  4393. } else if (position === 'bottom') {
  4394. y = this.top + hTickAndPadding;
  4395. textAlign = this._getXAxisLabelAlignment();
  4396. } else if (position === 'left') {
  4397. const ret = this._getYAxisLabelAlignment(tl);
  4398. textAlign = ret.textAlign;
  4399. x = ret.x;
  4400. } else if (position === 'right') {
  4401. const ret = this._getYAxisLabelAlignment(tl);
  4402. textAlign = ret.textAlign;
  4403. x = ret.x;
  4404. } else if (axis === 'x') {
  4405. if (position === 'center') {
  4406. y = (chartArea.top + chartArea.bottom) / 2 + tickAndPadding;
  4407. } else if (isObject(position)) {
  4408. const positionAxisID = Object.keys(position)[0];
  4409. const value = position[positionAxisID];
  4410. y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;
  4411. }
  4412. textAlign = this._getXAxisLabelAlignment();
  4413. } else if (axis === 'y') {
  4414. if (position === 'center') {
  4415. x = (chartArea.left + chartArea.right) / 2 - tickAndPadding;
  4416. } else if (isObject(position)) {
  4417. const positionAxisID = Object.keys(position)[0];
  4418. const value = position[positionAxisID];
  4419. x = this.chart.scales[positionAxisID].getPixelForValue(value);
  4420. }
  4421. textAlign = this._getYAxisLabelAlignment(tl).textAlign;
  4422. }
  4423. if (axis === 'y') {
  4424. if (align === 'start') {
  4425. textBaseline = 'top';
  4426. } else if (align === 'end') {
  4427. textBaseline = 'bottom';
  4428. }
  4429. }
  4430. const labelSizes = this._getLabelSizes();
  4431. for(i = 0, ilen = ticks.length; i < ilen; ++i){
  4432. tick = ticks[i];
  4433. label = tick.label;
  4434. const optsAtIndex = optionTicks.setContext(this.getContext(i));
  4435. pixel = this.getPixelForTick(i) + optionTicks.labelOffset;
  4436. font = this._resolveTickFontOptions(i);
  4437. lineHeight = font.lineHeight;
  4438. lineCount = isArray(label) ? label.length : 1;
  4439. const halfCount = lineCount / 2;
  4440. const color = optsAtIndex.color;
  4441. const strokeColor = optsAtIndex.textStrokeColor;
  4442. const strokeWidth = optsAtIndex.textStrokeWidth;
  4443. let tickTextAlign = textAlign;
  4444. if (isHorizontal) {
  4445. x = pixel;
  4446. if (textAlign === 'inner') {
  4447. if (i === ilen - 1) {
  4448. tickTextAlign = !this.options.reverse ? 'right' : 'left';
  4449. } else if (i === 0) {
  4450. tickTextAlign = !this.options.reverse ? 'left' : 'right';
  4451. } else {
  4452. tickTextAlign = 'center';
  4453. }
  4454. }
  4455. if (position === 'top') {
  4456. if (crossAlign === 'near' || rotation !== 0) {
  4457. textOffset = -lineCount * lineHeight + lineHeight / 2;
  4458. } else if (crossAlign === 'center') {
  4459. textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;
  4460. } else {
  4461. textOffset = -labelSizes.highest.height + lineHeight / 2;
  4462. }
  4463. } else {
  4464. if (crossAlign === 'near' || rotation !== 0) {
  4465. textOffset = lineHeight / 2;
  4466. } else if (crossAlign === 'center') {
  4467. textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;
  4468. } else {
  4469. textOffset = labelSizes.highest.height - lineCount * lineHeight;
  4470. }
  4471. }
  4472. if (mirror) {
  4473. textOffset *= -1;
  4474. }
  4475. if (rotation !== 0 && !optsAtIndex.showLabelBackdrop) {
  4476. x += lineHeight / 2 * Math.sin(rotation);
  4477. }
  4478. } else {
  4479. y = pixel;
  4480. textOffset = (1 - lineCount) * lineHeight / 2;
  4481. }
  4482. let backdrop;
  4483. if (optsAtIndex.showLabelBackdrop) {
  4484. const labelPadding = toPadding(optsAtIndex.backdropPadding);
  4485. const height = labelSizes.heights[i];
  4486. const width = labelSizes.widths[i];
  4487. let top = textOffset - labelPadding.top;
  4488. let left = 0 - labelPadding.left;
  4489. switch(textBaseline){
  4490. case 'middle':
  4491. top -= height / 2;
  4492. break;
  4493. case 'bottom':
  4494. top -= height;
  4495. break;
  4496. }
  4497. switch(textAlign){
  4498. case 'center':
  4499. left -= width / 2;
  4500. break;
  4501. case 'right':
  4502. left -= width;
  4503. break;
  4504. case 'inner':
  4505. if (i === ilen - 1) {
  4506. left -= width;
  4507. } else if (i > 0) {
  4508. left -= width / 2;
  4509. }
  4510. break;
  4511. }
  4512. backdrop = {
  4513. left,
  4514. top,
  4515. width: width + labelPadding.width,
  4516. height: height + labelPadding.height,
  4517. color: optsAtIndex.backdropColor
  4518. };
  4519. }
  4520. items.push({
  4521. label,
  4522. font,
  4523. textOffset,
  4524. options: {
  4525. rotation,
  4526. color,
  4527. strokeColor,
  4528. strokeWidth,
  4529. textAlign: tickTextAlign,
  4530. textBaseline,
  4531. translation: [
  4532. x,
  4533. y
  4534. ],
  4535. backdrop
  4536. }
  4537. });
  4538. }
  4539. return items;
  4540. }
  4541. _getXAxisLabelAlignment() {
  4542. const { position , ticks } = this.options;
  4543. const rotation = -toRadians(this.labelRotation);
  4544. if (rotation) {
  4545. return position === 'top' ? 'left' : 'right';
  4546. }
  4547. let align = 'center';
  4548. if (ticks.align === 'start') {
  4549. align = 'left';
  4550. } else if (ticks.align === 'end') {
  4551. align = 'right';
  4552. } else if (ticks.align === 'inner') {
  4553. align = 'inner';
  4554. }
  4555. return align;
  4556. }
  4557. _getYAxisLabelAlignment(tl) {
  4558. const { position , ticks: { crossAlign , mirror , padding } } = this.options;
  4559. const labelSizes = this._getLabelSizes();
  4560. const tickAndPadding = tl + padding;
  4561. const widest = labelSizes.widest.width;
  4562. let textAlign;
  4563. let x;
  4564. if (position === 'left') {
  4565. if (mirror) {
  4566. x = this.right + padding;
  4567. if (crossAlign === 'near') {
  4568. textAlign = 'left';
  4569. } else if (crossAlign === 'center') {
  4570. textAlign = 'center';
  4571. x += widest / 2;
  4572. } else {
  4573. textAlign = 'right';
  4574. x += widest;
  4575. }
  4576. } else {
  4577. x = this.right - tickAndPadding;
  4578. if (crossAlign === 'near') {
  4579. textAlign = 'right';
  4580. } else if (crossAlign === 'center') {
  4581. textAlign = 'center';
  4582. x -= widest / 2;
  4583. } else {
  4584. textAlign = 'left';
  4585. x = this.left;
  4586. }
  4587. }
  4588. } else if (position === 'right') {
  4589. if (mirror) {
  4590. x = this.left + padding;
  4591. if (crossAlign === 'near') {
  4592. textAlign = 'right';
  4593. } else if (crossAlign === 'center') {
  4594. textAlign = 'center';
  4595. x -= widest / 2;
  4596. } else {
  4597. textAlign = 'left';
  4598. x -= widest;
  4599. }
  4600. } else {
  4601. x = this.left + tickAndPadding;
  4602. if (crossAlign === 'near') {
  4603. textAlign = 'left';
  4604. } else if (crossAlign === 'center') {
  4605. textAlign = 'center';
  4606. x += widest / 2;
  4607. } else {
  4608. textAlign = 'right';
  4609. x = this.right;
  4610. }
  4611. }
  4612. } else {
  4613. textAlign = 'right';
  4614. }
  4615. return {
  4616. textAlign,
  4617. x
  4618. };
  4619. }
  4620. _computeLabelArea() {
  4621. if (this.options.ticks.mirror) {
  4622. return;
  4623. }
  4624. const chart = this.chart;
  4625. const position = this.options.position;
  4626. if (position === 'left' || position === 'right') {
  4627. return {
  4628. top: 0,
  4629. left: this.left,
  4630. bottom: chart.height,
  4631. right: this.right
  4632. };
  4633. }
  4634. if (position === 'top' || position === 'bottom') {
  4635. return {
  4636. top: this.top,
  4637. left: 0,
  4638. bottom: this.bottom,
  4639. right: chart.width
  4640. };
  4641. }
  4642. }
  4643. drawBackground() {
  4644. const { ctx , options: { backgroundColor } , left , top , width , height } = this;
  4645. if (backgroundColor) {
  4646. ctx.save();
  4647. ctx.fillStyle = backgroundColor;
  4648. ctx.fillRect(left, top, width, height);
  4649. ctx.restore();
  4650. }
  4651. }
  4652. getLineWidthForValue(value) {
  4653. const grid = this.options.grid;
  4654. if (!this._isVisible() || !grid.display) {
  4655. return 0;
  4656. }
  4657. const ticks = this.ticks;
  4658. const index = ticks.findIndex((t)=>t.value === value);
  4659. if (index >= 0) {
  4660. const opts = grid.setContext(this.getContext(index));
  4661. return opts.lineWidth;
  4662. }
  4663. return 0;
  4664. }
  4665. drawGrid(chartArea) {
  4666. const grid = this.options.grid;
  4667. const ctx = this.ctx;
  4668. const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea));
  4669. let i, ilen;
  4670. const drawLine = (p1, p2, style)=>{
  4671. if (!style.width || !style.color) {
  4672. return;
  4673. }
  4674. ctx.save();
  4675. ctx.lineWidth = style.width;
  4676. ctx.strokeStyle = style.color;
  4677. ctx.setLineDash(style.borderDash || []);
  4678. ctx.lineDashOffset = style.borderDashOffset;
  4679. ctx.beginPath();
  4680. ctx.moveTo(p1.x, p1.y);
  4681. ctx.lineTo(p2.x, p2.y);
  4682. ctx.stroke();
  4683. ctx.restore();
  4684. };
  4685. if (grid.display) {
  4686. for(i = 0, ilen = items.length; i < ilen; ++i){
  4687. const item = items[i];
  4688. if (grid.drawOnChartArea) {
  4689. drawLine({
  4690. x: item.x1,
  4691. y: item.y1
  4692. }, {
  4693. x: item.x2,
  4694. y: item.y2
  4695. }, item);
  4696. }
  4697. if (grid.drawTicks) {
  4698. drawLine({
  4699. x: item.tx1,
  4700. y: item.ty1
  4701. }, {
  4702. x: item.tx2,
  4703. y: item.ty2
  4704. }, {
  4705. color: item.tickColor,
  4706. width: item.tickWidth,
  4707. borderDash: item.tickBorderDash,
  4708. borderDashOffset: item.tickBorderDashOffset
  4709. });
  4710. }
  4711. }
  4712. }
  4713. }
  4714. drawBorder() {
  4715. const { chart , ctx , options: { border , grid } } = this;
  4716. const borderOpts = border.setContext(this.getContext());
  4717. const axisWidth = border.display ? borderOpts.width : 0;
  4718. if (!axisWidth) {
  4719. return;
  4720. }
  4721. const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth;
  4722. const borderValue = this._borderValue;
  4723. let x1, x2, y1, y2;
  4724. if (this.isHorizontal()) {
  4725. x1 = _alignPixel(chart, this.left, axisWidth) - axisWidth / 2;
  4726. x2 = _alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2;
  4727. y1 = y2 = borderValue;
  4728. } else {
  4729. y1 = _alignPixel(chart, this.top, axisWidth) - axisWidth / 2;
  4730. y2 = _alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2;
  4731. x1 = x2 = borderValue;
  4732. }
  4733. ctx.save();
  4734. ctx.lineWidth = borderOpts.width;
  4735. ctx.strokeStyle = borderOpts.color;
  4736. ctx.beginPath();
  4737. ctx.moveTo(x1, y1);
  4738. ctx.lineTo(x2, y2);
  4739. ctx.stroke();
  4740. ctx.restore();
  4741. }
  4742. drawLabels(chartArea) {
  4743. const optionTicks = this.options.ticks;
  4744. if (!optionTicks.display) {
  4745. return;
  4746. }
  4747. const ctx = this.ctx;
  4748. const area = this._computeLabelArea();
  4749. if (area) {
  4750. clipArea(ctx, area);
  4751. }
  4752. const items = this.getLabelItems(chartArea);
  4753. for (const item of items){
  4754. const renderTextOptions = item.options;
  4755. const tickFont = item.font;
  4756. const label = item.label;
  4757. const y = item.textOffset;
  4758. renderText(ctx, label, 0, y, tickFont, renderTextOptions);
  4759. }
  4760. if (area) {
  4761. unclipArea(ctx);
  4762. }
  4763. }
  4764. drawTitle() {
  4765. const { ctx , options: { position , title , reverse } } = this;
  4766. if (!title.display) {
  4767. return;
  4768. }
  4769. const font = toFont(title.font);
  4770. const padding = toPadding(title.padding);
  4771. const align = title.align;
  4772. let offset = font.lineHeight / 2;
  4773. if (position === 'bottom' || position === 'center' || isObject(position)) {
  4774. offset += padding.bottom;
  4775. if (isArray(title.text)) {
  4776. offset += font.lineHeight * (title.text.length - 1);
  4777. }
  4778. } else {
  4779. offset += padding.top;
  4780. }
  4781. const { titleX , titleY , maxWidth , rotation } = titleArgs(this, offset, position, align);
  4782. renderText(ctx, title.text, 0, 0, font, {
  4783. color: title.color,
  4784. maxWidth,
  4785. rotation,
  4786. textAlign: titleAlign(align, position, reverse),
  4787. textBaseline: 'middle',
  4788. translation: [
  4789. titleX,
  4790. titleY
  4791. ]
  4792. });
  4793. }
  4794. draw(chartArea) {
  4795. if (!this._isVisible()) {
  4796. return;
  4797. }
  4798. this.drawBackground();
  4799. this.drawGrid(chartArea);
  4800. this.drawBorder();
  4801. this.drawTitle();
  4802. this.drawLabels(chartArea);
  4803. }
  4804. _layers() {
  4805. const opts = this.options;
  4806. const tz = opts.ticks && opts.ticks.z || 0;
  4807. const gz = valueOrDefault(opts.grid && opts.grid.z, -1);
  4808. const bz = valueOrDefault(opts.border && opts.border.z, 0);
  4809. if (!this._isVisible() || this.draw !== Scale.prototype.draw) {
  4810. return [
  4811. {
  4812. z: tz,
  4813. draw: (chartArea)=>{
  4814. this.draw(chartArea);
  4815. }
  4816. }
  4817. ];
  4818. }
  4819. return [
  4820. {
  4821. z: gz,
  4822. draw: (chartArea)=>{
  4823. this.drawBackground();
  4824. this.drawGrid(chartArea);
  4825. this.drawTitle();
  4826. }
  4827. },
  4828. {
  4829. z: bz,
  4830. draw: ()=>{
  4831. this.drawBorder();
  4832. }
  4833. },
  4834. {
  4835. z: tz,
  4836. draw: (chartArea)=>{
  4837. this.drawLabels(chartArea);
  4838. }
  4839. }
  4840. ];
  4841. }
  4842. getMatchingVisibleMetas(type) {
  4843. const metas = this.chart.getSortedVisibleDatasetMetas();
  4844. const axisID = this.axis + 'AxisID';
  4845. const result = [];
  4846. let i, ilen;
  4847. for(i = 0, ilen = metas.length; i < ilen; ++i){
  4848. const meta = metas[i];
  4849. if (meta[axisID] === this.id && (!type || meta.type === type)) {
  4850. result.push(meta);
  4851. }
  4852. }
  4853. return result;
  4854. }
  4855. _resolveTickFontOptions(index) {
  4856. const opts = this.options.ticks.setContext(this.getContext(index));
  4857. return toFont(opts.font);
  4858. }
  4859. _maxDigits() {
  4860. const fontSize = this._resolveTickFontOptions(0).lineHeight;
  4861. return (this.isHorizontal() ? this.width : this.height) / fontSize;
  4862. }
  4863. }
  4864. class TypedRegistry {
  4865. constructor(type, scope, override){
  4866. this.type = type;
  4867. this.scope = scope;
  4868. this.override = override;
  4869. this.items = Object.create(null);
  4870. }
  4871. isForType(type) {
  4872. return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);
  4873. }
  4874. register(item) {
  4875. const proto = Object.getPrototypeOf(item);
  4876. let parentScope;
  4877. if (isIChartComponent(proto)) {
  4878. parentScope = this.register(proto);
  4879. }
  4880. const items = this.items;
  4881. const id = item.id;
  4882. const scope = this.scope + '.' + id;
  4883. if (!id) {
  4884. throw new Error('class does not have id: ' + item);
  4885. }
  4886. if (id in items) {
  4887. return scope;
  4888. }
  4889. items[id] = item;
  4890. registerDefaults(item, scope, parentScope);
  4891. if (this.override) {
  4892. defaults.override(item.id, item.overrides);
  4893. }
  4894. return scope;
  4895. }
  4896. get(id) {
  4897. return this.items[id];
  4898. }
  4899. unregister(item) {
  4900. const items = this.items;
  4901. const id = item.id;
  4902. const scope = this.scope;
  4903. if (id in items) {
  4904. delete items[id];
  4905. }
  4906. if (scope && id in defaults[scope]) {
  4907. delete defaults[scope][id];
  4908. if (this.override) {
  4909. delete overrides[id];
  4910. }
  4911. }
  4912. }
  4913. }
  4914. function registerDefaults(item, scope, parentScope) {
  4915. const itemDefaults = merge(Object.create(null), [
  4916. parentScope ? defaults.get(parentScope) : {},
  4917. defaults.get(scope),
  4918. item.defaults
  4919. ]);
  4920. defaults.set(scope, itemDefaults);
  4921. if (item.defaultRoutes) {
  4922. routeDefaults(scope, item.defaultRoutes);
  4923. }
  4924. if (item.descriptors) {
  4925. defaults.describe(scope, item.descriptors);
  4926. }
  4927. }
  4928. function routeDefaults(scope, routes) {
  4929. Object.keys(routes).forEach((property)=>{
  4930. const propertyParts = property.split('.');
  4931. const sourceName = propertyParts.pop();
  4932. const sourceScope = [
  4933. scope
  4934. ].concat(propertyParts).join('.');
  4935. const parts = routes[property].split('.');
  4936. const targetName = parts.pop();
  4937. const targetScope = parts.join('.');
  4938. defaults.route(sourceScope, sourceName, targetScope, targetName);
  4939. });
  4940. }
  4941. function isIChartComponent(proto) {
  4942. return 'id' in proto && 'defaults' in proto;
  4943. }
  4944. class Registry {
  4945. constructor(){
  4946. this.controllers = new TypedRegistry(DatasetController, 'datasets', true);
  4947. this.elements = new TypedRegistry(Element, 'elements');
  4948. this.plugins = new TypedRegistry(Object, 'plugins');
  4949. this.scales = new TypedRegistry(Scale, 'scales');
  4950. this._typedRegistries = [
  4951. this.controllers,
  4952. this.scales,
  4953. this.elements
  4954. ];
  4955. }
  4956. add(...args) {
  4957. this._each('register', args);
  4958. }
  4959. remove(...args) {
  4960. this._each('unregister', args);
  4961. }
  4962. addControllers(...args) {
  4963. this._each('register', args, this.controllers);
  4964. }
  4965. addElements(...args) {
  4966. this._each('register', args, this.elements);
  4967. }
  4968. addPlugins(...args) {
  4969. this._each('register', args, this.plugins);
  4970. }
  4971. addScales(...args) {
  4972. this._each('register', args, this.scales);
  4973. }
  4974. getController(id) {
  4975. return this._get(id, this.controllers, 'controller');
  4976. }
  4977. getElement(id) {
  4978. return this._get(id, this.elements, 'element');
  4979. }
  4980. getPlugin(id) {
  4981. return this._get(id, this.plugins, 'plugin');
  4982. }
  4983. getScale(id) {
  4984. return this._get(id, this.scales, 'scale');
  4985. }
  4986. removeControllers(...args) {
  4987. this._each('unregister', args, this.controllers);
  4988. }
  4989. removeElements(...args) {
  4990. this._each('unregister', args, this.elements);
  4991. }
  4992. removePlugins(...args) {
  4993. this._each('unregister', args, this.plugins);
  4994. }
  4995. removeScales(...args) {
  4996. this._each('unregister', args, this.scales);
  4997. }
  4998. _each(method, args, typedRegistry) {
  4999. [
  5000. ...args
  5001. ].forEach((arg)=>{
  5002. const reg = typedRegistry || this._getRegistryForType(arg);
  5003. if (typedRegistry || reg.isForType(arg) || reg === this.plugins && arg.id) {
  5004. this._exec(method, reg, arg);
  5005. } else {
  5006. each(arg, (item)=>{
  5007. const itemReg = typedRegistry || this._getRegistryForType(item);
  5008. this._exec(method, itemReg, item);
  5009. });
  5010. }
  5011. });
  5012. }
  5013. _exec(method, registry, component) {
  5014. const camelMethod = _capitalize(method);
  5015. callback(component['before' + camelMethod], [], component);
  5016. registry[method](component);
  5017. callback(component['after' + camelMethod], [], component);
  5018. }
  5019. _getRegistryForType(type) {
  5020. for(let i = 0; i < this._typedRegistries.length; i++){
  5021. const reg = this._typedRegistries[i];
  5022. if (reg.isForType(type)) {
  5023. return reg;
  5024. }
  5025. }
  5026. return this.plugins;
  5027. }
  5028. _get(id, typedRegistry, type) {
  5029. const item = typedRegistry.get(id);
  5030. if (item === undefined) {
  5031. throw new Error('"' + id + '" is not a registered ' + type + '.');
  5032. }
  5033. return item;
  5034. }
  5035. }
  5036. var registry = /* #__PURE__ */ new Registry();
  5037. class PluginService {
  5038. constructor(){
  5039. this._init = [];
  5040. }
  5041. notify(chart, hook, args, filter) {
  5042. if (hook === 'beforeInit') {
  5043. this._init = this._createDescriptors(chart, true);
  5044. this._notify(this._init, chart, 'install');
  5045. }
  5046. const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart);
  5047. const result = this._notify(descriptors, chart, hook, args);
  5048. if (hook === 'afterDestroy') {
  5049. this._notify(descriptors, chart, 'stop');
  5050. this._notify(this._init, chart, 'uninstall');
  5051. }
  5052. return result;
  5053. }
  5054. _notify(descriptors, chart, hook, args) {
  5055. args = args || {};
  5056. for (const descriptor of descriptors){
  5057. const plugin = descriptor.plugin;
  5058. const method = plugin[hook];
  5059. const params = [
  5060. chart,
  5061. args,
  5062. descriptor.options
  5063. ];
  5064. if (callback(method, params, plugin) === false && args.cancelable) {
  5065. return false;
  5066. }
  5067. }
  5068. return true;
  5069. }
  5070. invalidate() {
  5071. if (!isNullOrUndef(this._cache)) {
  5072. this._oldCache = this._cache;
  5073. this._cache = undefined;
  5074. }
  5075. }
  5076. _descriptors(chart) {
  5077. if (this._cache) {
  5078. return this._cache;
  5079. }
  5080. const descriptors = this._cache = this._createDescriptors(chart);
  5081. this._notifyStateChanges(chart);
  5082. return descriptors;
  5083. }
  5084. _createDescriptors(chart, all) {
  5085. const config = chart && chart.config;
  5086. const options = valueOrDefault(config.options && config.options.plugins, {});
  5087. const plugins = allPlugins(config);
  5088. return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);
  5089. }
  5090. _notifyStateChanges(chart) {
  5091. const previousDescriptors = this._oldCache || [];
  5092. const descriptors = this._cache;
  5093. const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.plugin.id === y.plugin.id));
  5094. this._notify(diff(previousDescriptors, descriptors), chart, 'stop');
  5095. this._notify(diff(descriptors, previousDescriptors), chart, 'start');
  5096. }
  5097. }
  5098. function allPlugins(config) {
  5099. const localIds = {};
  5100. const plugins = [];
  5101. const keys = Object.keys(registry.plugins.items);
  5102. for(let i = 0; i < keys.length; i++){
  5103. plugins.push(registry.getPlugin(keys[i]));
  5104. }
  5105. const local = config.plugins || [];
  5106. for(let i = 0; i < local.length; i++){
  5107. const plugin = local[i];
  5108. if (plugins.indexOf(plugin) === -1) {
  5109. plugins.push(plugin);
  5110. localIds[plugin.id] = true;
  5111. }
  5112. }
  5113. return {
  5114. plugins,
  5115. localIds
  5116. };
  5117. }
  5118. function getOpts(options, all) {
  5119. if (!all && options === false) {
  5120. return null;
  5121. }
  5122. if (options === true) {
  5123. return {};
  5124. }
  5125. return options;
  5126. }
  5127. function createDescriptors(chart, { plugins , localIds }, options, all) {
  5128. const result = [];
  5129. const context = chart.getContext();
  5130. for (const plugin of plugins){
  5131. const id = plugin.id;
  5132. const opts = getOpts(options[id], all);
  5133. if (opts === null) {
  5134. continue;
  5135. }
  5136. result.push({
  5137. plugin,
  5138. options: pluginOpts(chart.config, {
  5139. plugin,
  5140. local: localIds[id]
  5141. }, opts, context)
  5142. });
  5143. }
  5144. return result;
  5145. }
  5146. function pluginOpts(config, { plugin , local }, opts, context) {
  5147. const keys = config.pluginScopeKeys(plugin);
  5148. const scopes = config.getOptionScopes(opts, keys);
  5149. if (local && plugin.defaults) {
  5150. scopes.push(plugin.defaults);
  5151. }
  5152. return config.createResolver(scopes, context, [
  5153. ''
  5154. ], {
  5155. scriptable: false,
  5156. indexable: false,
  5157. allKeys: true
  5158. });
  5159. }
  5160. function getIndexAxis(type, options) {
  5161. const datasetDefaults = defaults.datasets[type] || {};
  5162. const datasetOptions = (options.datasets || {})[type] || {};
  5163. return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';
  5164. }
  5165. function getAxisFromDefaultScaleID(id, indexAxis) {
  5166. let axis = id;
  5167. if (id === '_index_') {
  5168. axis = indexAxis;
  5169. } else if (id === '_value_') {
  5170. axis = indexAxis === 'x' ? 'y' : 'x';
  5171. }
  5172. return axis;
  5173. }
  5174. function getDefaultScaleIDFromAxis(axis, indexAxis) {
  5175. return axis === indexAxis ? '_index_' : '_value_';
  5176. }
  5177. function idMatchesAxis(id) {
  5178. if (id === 'x' || id === 'y' || id === 'r') {
  5179. return id;
  5180. }
  5181. }
  5182. function axisFromPosition(position) {
  5183. if (position === 'top' || position === 'bottom') {
  5184. return 'x';
  5185. }
  5186. if (position === 'left' || position === 'right') {
  5187. return 'y';
  5188. }
  5189. }
  5190. function determineAxis(id, ...scaleOptions) {
  5191. if (idMatchesAxis(id)) {
  5192. return id;
  5193. }
  5194. for (const opts of scaleOptions){
  5195. const axis = opts.axis || axisFromPosition(opts.position) || id.length > 1 && idMatchesAxis(id[0].toLowerCase());
  5196. if (axis) {
  5197. return axis;
  5198. }
  5199. }
  5200. throw new Error(`Cannot determine type of '${id}' axis. Please provide 'axis' or 'position' option.`);
  5201. }
  5202. function getAxisFromDataset(id, axis, dataset) {
  5203. if (dataset[axis + 'AxisID'] === id) {
  5204. return {
  5205. axis
  5206. };
  5207. }
  5208. }
  5209. function retrieveAxisFromDatasets(id, config) {
  5210. if (config.data && config.data.datasets) {
  5211. const boundDs = config.data.datasets.filter((d)=>d.xAxisID === id || d.yAxisID === id);
  5212. if (boundDs.length) {
  5213. return getAxisFromDataset(id, 'x', boundDs[0]) || getAxisFromDataset(id, 'y', boundDs[0]);
  5214. }
  5215. }
  5216. return {};
  5217. }
  5218. function mergeScaleConfig(config, options) {
  5219. const chartDefaults = overrides[config.type] || {
  5220. scales: {}
  5221. };
  5222. const configScales = options.scales || {};
  5223. const chartIndexAxis = getIndexAxis(config.type, options);
  5224. const scales = Object.create(null);
  5225. Object.keys(configScales).forEach((id)=>{
  5226. const scaleConf = configScales[id];
  5227. if (!isObject(scaleConf)) {
  5228. return console.error(`Invalid scale configuration for scale: ${id}`);
  5229. }
  5230. if (scaleConf._proxy) {
  5231. return console.warn(`Ignoring resolver passed as options for scale: ${id}`);
  5232. }
  5233. const axis = determineAxis(id, scaleConf, retrieveAxisFromDatasets(id, config), defaults.scales[scaleConf.type]);
  5234. const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
  5235. const defaultScaleOptions = chartDefaults.scales || {};
  5236. scales[id] = mergeIf(Object.create(null), [
  5237. {
  5238. axis
  5239. },
  5240. scaleConf,
  5241. defaultScaleOptions[axis],
  5242. defaultScaleOptions[defaultId]
  5243. ]);
  5244. });
  5245. config.data.datasets.forEach((dataset)=>{
  5246. const type = dataset.type || config.type;
  5247. const indexAxis = dataset.indexAxis || getIndexAxis(type, options);
  5248. const datasetDefaults = overrides[type] || {};
  5249. const defaultScaleOptions = datasetDefaults.scales || {};
  5250. Object.keys(defaultScaleOptions).forEach((defaultID)=>{
  5251. const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
  5252. const id = dataset[axis + 'AxisID'] || axis;
  5253. scales[id] = scales[id] || Object.create(null);
  5254. mergeIf(scales[id], [
  5255. {
  5256. axis
  5257. },
  5258. configScales[id],
  5259. defaultScaleOptions[defaultID]
  5260. ]);
  5261. });
  5262. });
  5263. Object.keys(scales).forEach((key)=>{
  5264. const scale = scales[key];
  5265. mergeIf(scale, [
  5266. defaults.scales[scale.type],
  5267. defaults.scale
  5268. ]);
  5269. });
  5270. return scales;
  5271. }
  5272. function initOptions(config) {
  5273. const options = config.options || (config.options = {});
  5274. options.plugins = valueOrDefault(options.plugins, {});
  5275. options.scales = mergeScaleConfig(config, options);
  5276. }
  5277. function initData(data) {
  5278. data = data || {};
  5279. data.datasets = data.datasets || [];
  5280. data.labels = data.labels || [];
  5281. return data;
  5282. }
  5283. function initConfig(config) {
  5284. config = config || {};
  5285. config.data = initData(config.data);
  5286. initOptions(config);
  5287. return config;
  5288. }
  5289. const keyCache = new Map();
  5290. const keysCached = new Set();
  5291. function cachedKeys(cacheKey, generate) {
  5292. let keys = keyCache.get(cacheKey);
  5293. if (!keys) {
  5294. keys = generate();
  5295. keyCache.set(cacheKey, keys);
  5296. keysCached.add(keys);
  5297. }
  5298. return keys;
  5299. }
  5300. const addIfFound = (set, obj, key)=>{
  5301. const opts = resolveObjectKey(obj, key);
  5302. if (opts !== undefined) {
  5303. set.add(opts);
  5304. }
  5305. };
  5306. class Config {
  5307. constructor(config){
  5308. this._config = initConfig(config);
  5309. this._scopeCache = new Map();
  5310. this._resolverCache = new Map();
  5311. }
  5312. get platform() {
  5313. return this._config.platform;
  5314. }
  5315. get type() {
  5316. return this._config.type;
  5317. }
  5318. set type(type) {
  5319. this._config.type = type;
  5320. }
  5321. get data() {
  5322. return this._config.data;
  5323. }
  5324. set data(data) {
  5325. this._config.data = initData(data);
  5326. }
  5327. get options() {
  5328. return this._config.options;
  5329. }
  5330. set options(options) {
  5331. this._config.options = options;
  5332. }
  5333. get plugins() {
  5334. return this._config.plugins;
  5335. }
  5336. update() {
  5337. const config = this._config;
  5338. this.clearCache();
  5339. initOptions(config);
  5340. }
  5341. clearCache() {
  5342. this._scopeCache.clear();
  5343. this._resolverCache.clear();
  5344. }
  5345. datasetScopeKeys(datasetType) {
  5346. return cachedKeys(datasetType, ()=>[
  5347. [
  5348. `datasets.${datasetType}`,
  5349. ''
  5350. ]
  5351. ]);
  5352. }
  5353. datasetAnimationScopeKeys(datasetType, transition) {
  5354. return cachedKeys(`${datasetType}.transition.${transition}`, ()=>[
  5355. [
  5356. `datasets.${datasetType}.transitions.${transition}`,
  5357. `transitions.${transition}`
  5358. ],
  5359. [
  5360. `datasets.${datasetType}`,
  5361. ''
  5362. ]
  5363. ]);
  5364. }
  5365. datasetElementScopeKeys(datasetType, elementType) {
  5366. return cachedKeys(`${datasetType}-${elementType}`, ()=>[
  5367. [
  5368. `datasets.${datasetType}.elements.${elementType}`,
  5369. `datasets.${datasetType}`,
  5370. `elements.${elementType}`,
  5371. ''
  5372. ]
  5373. ]);
  5374. }
  5375. pluginScopeKeys(plugin) {
  5376. const id = plugin.id;
  5377. const type = this.type;
  5378. return cachedKeys(`${type}-plugin-${id}`, ()=>[
  5379. [
  5380. `plugins.${id}`,
  5381. ...plugin.additionalOptionScopes || []
  5382. ]
  5383. ]);
  5384. }
  5385. _cachedScopes(mainScope, resetCache) {
  5386. const _scopeCache = this._scopeCache;
  5387. let cache = _scopeCache.get(mainScope);
  5388. if (!cache || resetCache) {
  5389. cache = new Map();
  5390. _scopeCache.set(mainScope, cache);
  5391. }
  5392. return cache;
  5393. }
  5394. getOptionScopes(mainScope, keyLists, resetCache) {
  5395. const { options , type } = this;
  5396. const cache = this._cachedScopes(mainScope, resetCache);
  5397. const cached = cache.get(keyLists);
  5398. if (cached) {
  5399. return cached;
  5400. }
  5401. const scopes = new Set();
  5402. keyLists.forEach((keys)=>{
  5403. if (mainScope) {
  5404. scopes.add(mainScope);
  5405. keys.forEach((key)=>addIfFound(scopes, mainScope, key));
  5406. }
  5407. keys.forEach((key)=>addIfFound(scopes, options, key));
  5408. keys.forEach((key)=>addIfFound(scopes, overrides[type] || {}, key));
  5409. keys.forEach((key)=>addIfFound(scopes, defaults, key));
  5410. keys.forEach((key)=>addIfFound(scopes, descriptors, key));
  5411. });
  5412. const array = Array.from(scopes);
  5413. if (array.length === 0) {
  5414. array.push(Object.create(null));
  5415. }
  5416. if (keysCached.has(keyLists)) {
  5417. cache.set(keyLists, array);
  5418. }
  5419. return array;
  5420. }
  5421. chartOptionScopes() {
  5422. const { options , type } = this;
  5423. return [
  5424. options,
  5425. overrides[type] || {},
  5426. defaults.datasets[type] || {},
  5427. {
  5428. type
  5429. },
  5430. defaults,
  5431. descriptors
  5432. ];
  5433. }
  5434. resolveNamedOptions(scopes, names, context, prefixes = [
  5435. ''
  5436. ]) {
  5437. const result = {
  5438. $shared: true
  5439. };
  5440. const { resolver , subPrefixes } = getResolver(this._resolverCache, scopes, prefixes);
  5441. let options = resolver;
  5442. if (needContext(resolver, names)) {
  5443. result.$shared = false;
  5444. context = isFunction(context) ? context() : context;
  5445. const subResolver = this.createResolver(scopes, context, subPrefixes);
  5446. options = _attachContext(resolver, context, subResolver);
  5447. }
  5448. for (const prop of names){
  5449. result[prop] = options[prop];
  5450. }
  5451. return result;
  5452. }
  5453. createResolver(scopes, context, prefixes = [
  5454. ''
  5455. ], descriptorDefaults) {
  5456. const { resolver } = getResolver(this._resolverCache, scopes, prefixes);
  5457. return isObject(context) ? _attachContext(resolver, context, undefined, descriptorDefaults) : resolver;
  5458. }
  5459. }
  5460. function getResolver(resolverCache, scopes, prefixes) {
  5461. let cache = resolverCache.get(scopes);
  5462. if (!cache) {
  5463. cache = new Map();
  5464. resolverCache.set(scopes, cache);
  5465. }
  5466. const cacheKey = prefixes.join();
  5467. let cached = cache.get(cacheKey);
  5468. if (!cached) {
  5469. const resolver = _createResolver(scopes, prefixes);
  5470. cached = {
  5471. resolver,
  5472. subPrefixes: prefixes.filter((p)=>!p.toLowerCase().includes('hover'))
  5473. };
  5474. cache.set(cacheKey, cached);
  5475. }
  5476. return cached;
  5477. }
  5478. const hasFunction = (value)=>isObject(value) && Object.getOwnPropertyNames(value).some((key)=>isFunction(value[key]));
  5479. function needContext(proxy, names) {
  5480. const { isScriptable , isIndexable } = _descriptors(proxy);
  5481. for (const prop of names){
  5482. const scriptable = isScriptable(prop);
  5483. const indexable = isIndexable(prop);
  5484. const value = (indexable || scriptable) && proxy[prop];
  5485. if (scriptable && (isFunction(value) || hasFunction(value)) || indexable && isArray(value)) {
  5486. return true;
  5487. }
  5488. }
  5489. return false;
  5490. }
  5491. var version = "4.4.4";
  5492. const KNOWN_POSITIONS = [
  5493. 'top',
  5494. 'bottom',
  5495. 'left',
  5496. 'right',
  5497. 'chartArea'
  5498. ];
  5499. function positionIsHorizontal(position, axis) {
  5500. return position === 'top' || position === 'bottom' || KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x';
  5501. }
  5502. function compare2Level(l1, l2) {
  5503. return function(a, b) {
  5504. return a[l1] === b[l1] ? a[l2] - b[l2] : a[l1] - b[l1];
  5505. };
  5506. }
  5507. function onAnimationsComplete(context) {
  5508. const chart = context.chart;
  5509. const animationOptions = chart.options.animation;
  5510. chart.notifyPlugins('afterRender');
  5511. callback(animationOptions && animationOptions.onComplete, [
  5512. context
  5513. ], chart);
  5514. }
  5515. function onAnimationProgress(context) {
  5516. const chart = context.chart;
  5517. const animationOptions = chart.options.animation;
  5518. callback(animationOptions && animationOptions.onProgress, [
  5519. context
  5520. ], chart);
  5521. }
  5522. function getCanvas(item) {
  5523. if (_isDomSupported() && typeof item === 'string') {
  5524. item = document.getElementById(item);
  5525. } else if (item && item.length) {
  5526. item = item[0];
  5527. }
  5528. if (item && item.canvas) {
  5529. item = item.canvas;
  5530. }
  5531. return item;
  5532. }
  5533. const instances = {};
  5534. const getChart = (key)=>{
  5535. const canvas = getCanvas(key);
  5536. return Object.values(instances).filter((c)=>c.canvas === canvas).pop();
  5537. };
  5538. function moveNumericKeys(obj, start, move) {
  5539. const keys = Object.keys(obj);
  5540. for (const key of keys){
  5541. const intKey = +key;
  5542. if (intKey >= start) {
  5543. const value = obj[key];
  5544. delete obj[key];
  5545. if (move > 0 || intKey > start) {
  5546. obj[intKey + move] = value;
  5547. }
  5548. }
  5549. }
  5550. }
  5551. function determineLastEvent(e, lastEvent, inChartArea, isClick) {
  5552. if (!inChartArea || e.type === 'mouseout') {
  5553. return null;
  5554. }
  5555. if (isClick) {
  5556. return lastEvent;
  5557. }
  5558. return e;
  5559. }
  5560. function getSizeForArea(scale, chartArea, field) {
  5561. return scale.options.clip ? scale[field] : chartArea[field];
  5562. }
  5563. function getDatasetArea(meta, chartArea) {
  5564. const { xScale , yScale } = meta;
  5565. if (xScale && yScale) {
  5566. return {
  5567. left: getSizeForArea(xScale, chartArea, 'left'),
  5568. right: getSizeForArea(xScale, chartArea, 'right'),
  5569. top: getSizeForArea(yScale, chartArea, 'top'),
  5570. bottom: getSizeForArea(yScale, chartArea, 'bottom')
  5571. };
  5572. }
  5573. return chartArea;
  5574. }
  5575. class Chart {
  5576. static defaults = defaults;
  5577. static instances = instances;
  5578. static overrides = overrides;
  5579. static registry = registry;
  5580. static version = version;
  5581. static getChart = getChart;
  5582. static register(...items) {
  5583. registry.add(...items);
  5584. invalidatePlugins();
  5585. }
  5586. static unregister(...items) {
  5587. registry.remove(...items);
  5588. invalidatePlugins();
  5589. }
  5590. constructor(item, userConfig){
  5591. const config = this.config = new Config(userConfig);
  5592. const initialCanvas = getCanvas(item);
  5593. const existingChart = getChart(initialCanvas);
  5594. if (existingChart) {
  5595. throw new Error('Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' + ' must be destroyed before the canvas with ID \'' + existingChart.canvas.id + '\' can be reused.');
  5596. }
  5597. const options = config.createResolver(config.chartOptionScopes(), this.getContext());
  5598. this.platform = new (config.platform || _detectPlatform(initialCanvas))();
  5599. this.platform.updateConfig(config);
  5600. const context = this.platform.acquireContext(initialCanvas, options.aspectRatio);
  5601. const canvas = context && context.canvas;
  5602. const height = canvas && canvas.height;
  5603. const width = canvas && canvas.width;
  5604. this.id = uid();
  5605. this.ctx = context;
  5606. this.canvas = canvas;
  5607. this.width = width;
  5608. this.height = height;
  5609. this._options = options;
  5610. this._aspectRatio = this.aspectRatio;
  5611. this._layers = [];
  5612. this._metasets = [];
  5613. this._stacks = undefined;
  5614. this.boxes = [];
  5615. this.currentDevicePixelRatio = undefined;
  5616. this.chartArea = undefined;
  5617. this._active = [];
  5618. this._lastEvent = undefined;
  5619. this._listeners = {};
  5620. this._responsiveListeners = undefined;
  5621. this._sortedMetasets = [];
  5622. this.scales = {};
  5623. this._plugins = new PluginService();
  5624. this.$proxies = {};
  5625. this._hiddenIndices = {};
  5626. this.attached = false;
  5627. this._animationsDisabled = undefined;
  5628. this.$context = undefined;
  5629. this._doResize = debounce((mode)=>this.update(mode), options.resizeDelay || 0);
  5630. this._dataChanges = [];
  5631. instances[this.id] = this;
  5632. if (!context || !canvas) {
  5633. console.error("Failed to create chart: can't acquire context from the given item");
  5634. return;
  5635. }
  5636. animator.listen(this, 'complete', onAnimationsComplete);
  5637. animator.listen(this, 'progress', onAnimationProgress);
  5638. this._initialize();
  5639. if (this.attached) {
  5640. this.update();
  5641. }
  5642. }
  5643. get aspectRatio() {
  5644. const { options: { aspectRatio , maintainAspectRatio } , width , height , _aspectRatio } = this;
  5645. if (!isNullOrUndef(aspectRatio)) {
  5646. return aspectRatio;
  5647. }
  5648. if (maintainAspectRatio && _aspectRatio) {
  5649. return _aspectRatio;
  5650. }
  5651. return height ? width / height : null;
  5652. }
  5653. get data() {
  5654. return this.config.data;
  5655. }
  5656. set data(data) {
  5657. this.config.data = data;
  5658. }
  5659. get options() {
  5660. return this._options;
  5661. }
  5662. set options(options) {
  5663. this.config.options = options;
  5664. }
  5665. get registry() {
  5666. return registry;
  5667. }
  5668. _initialize() {
  5669. this.notifyPlugins('beforeInit');
  5670. if (this.options.responsive) {
  5671. this.resize();
  5672. } else {
  5673. retinaScale(this, this.options.devicePixelRatio);
  5674. }
  5675. this.bindEvents();
  5676. this.notifyPlugins('afterInit');
  5677. return this;
  5678. }
  5679. clear() {
  5680. clearCanvas(this.canvas, this.ctx);
  5681. return this;
  5682. }
  5683. stop() {
  5684. animator.stop(this);
  5685. return this;
  5686. }
  5687. resize(width, height) {
  5688. if (!animator.running(this)) {
  5689. this._resize(width, height);
  5690. } else {
  5691. this._resizeBeforeDraw = {
  5692. width,
  5693. height
  5694. };
  5695. }
  5696. }
  5697. _resize(width, height) {
  5698. const options = this.options;
  5699. const canvas = this.canvas;
  5700. const aspectRatio = options.maintainAspectRatio && this.aspectRatio;
  5701. const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio);
  5702. const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio();
  5703. const mode = this.width ? 'resize' : 'attach';
  5704. this.width = newSize.width;
  5705. this.height = newSize.height;
  5706. this._aspectRatio = this.aspectRatio;
  5707. if (!retinaScale(this, newRatio, true)) {
  5708. return;
  5709. }
  5710. this.notifyPlugins('resize', {
  5711. size: newSize
  5712. });
  5713. callback(options.onResize, [
  5714. this,
  5715. newSize
  5716. ], this);
  5717. if (this.attached) {
  5718. if (this._doResize(mode)) {
  5719. this.render();
  5720. }
  5721. }
  5722. }
  5723. ensureScalesHaveIDs() {
  5724. const options = this.options;
  5725. const scalesOptions = options.scales || {};
  5726. each(scalesOptions, (axisOptions, axisID)=>{
  5727. axisOptions.id = axisID;
  5728. });
  5729. }
  5730. buildOrUpdateScales() {
  5731. const options = this.options;
  5732. const scaleOpts = options.scales;
  5733. const scales = this.scales;
  5734. const updated = Object.keys(scales).reduce((obj, id)=>{
  5735. obj[id] = false;
  5736. return obj;
  5737. }, {});
  5738. let items = [];
  5739. if (scaleOpts) {
  5740. items = items.concat(Object.keys(scaleOpts).map((id)=>{
  5741. const scaleOptions = scaleOpts[id];
  5742. const axis = determineAxis(id, scaleOptions);
  5743. const isRadial = axis === 'r';
  5744. const isHorizontal = axis === 'x';
  5745. return {
  5746. options: scaleOptions,
  5747. dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',
  5748. dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'
  5749. };
  5750. }));
  5751. }
  5752. each(items, (item)=>{
  5753. const scaleOptions = item.options;
  5754. const id = scaleOptions.id;
  5755. const axis = determineAxis(id, scaleOptions);
  5756. const scaleType = valueOrDefault(scaleOptions.type, item.dtype);
  5757. if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {
  5758. scaleOptions.position = item.dposition;
  5759. }
  5760. updated[id] = true;
  5761. let scale = null;
  5762. if (id in scales && scales[id].type === scaleType) {
  5763. scale = scales[id];
  5764. } else {
  5765. const scaleClass = registry.getScale(scaleType);
  5766. scale = new scaleClass({
  5767. id,
  5768. type: scaleType,
  5769. ctx: this.ctx,
  5770. chart: this
  5771. });
  5772. scales[scale.id] = scale;
  5773. }
  5774. scale.init(scaleOptions, options);
  5775. });
  5776. each(updated, (hasUpdated, id)=>{
  5777. if (!hasUpdated) {
  5778. delete scales[id];
  5779. }
  5780. });
  5781. each(scales, (scale)=>{
  5782. layouts.configure(this, scale, scale.options);
  5783. layouts.addBox(this, scale);
  5784. });
  5785. }
  5786. _updateMetasets() {
  5787. const metasets = this._metasets;
  5788. const numData = this.data.datasets.length;
  5789. const numMeta = metasets.length;
  5790. metasets.sort((a, b)=>a.index - b.index);
  5791. if (numMeta > numData) {
  5792. for(let i = numData; i < numMeta; ++i){
  5793. this._destroyDatasetMeta(i);
  5794. }
  5795. metasets.splice(numData, numMeta - numData);
  5796. }
  5797. this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));
  5798. }
  5799. _removeUnreferencedMetasets() {
  5800. const { _metasets: metasets , data: { datasets } } = this;
  5801. if (metasets.length > datasets.length) {
  5802. delete this._stacks;
  5803. }
  5804. metasets.forEach((meta, index)=>{
  5805. if (datasets.filter((x)=>x === meta._dataset).length === 0) {
  5806. this._destroyDatasetMeta(index);
  5807. }
  5808. });
  5809. }
  5810. buildOrUpdateControllers() {
  5811. const newControllers = [];
  5812. const datasets = this.data.datasets;
  5813. let i, ilen;
  5814. this._removeUnreferencedMetasets();
  5815. for(i = 0, ilen = datasets.length; i < ilen; i++){
  5816. const dataset = datasets[i];
  5817. let meta = this.getDatasetMeta(i);
  5818. const type = dataset.type || this.config.type;
  5819. if (meta.type && meta.type !== type) {
  5820. this._destroyDatasetMeta(i);
  5821. meta = this.getDatasetMeta(i);
  5822. }
  5823. meta.type = type;
  5824. meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options);
  5825. meta.order = dataset.order || 0;
  5826. meta.index = i;
  5827. meta.label = '' + dataset.label;
  5828. meta.visible = this.isDatasetVisible(i);
  5829. if (meta.controller) {
  5830. meta.controller.updateIndex(i);
  5831. meta.controller.linkScales();
  5832. } else {
  5833. const ControllerClass = registry.getController(type);
  5834. const { datasetElementType , dataElementType } = defaults.datasets[type];
  5835. Object.assign(ControllerClass, {
  5836. dataElementType: registry.getElement(dataElementType),
  5837. datasetElementType: datasetElementType && registry.getElement(datasetElementType)
  5838. });
  5839. meta.controller = new ControllerClass(this, i);
  5840. newControllers.push(meta.controller);
  5841. }
  5842. }
  5843. this._updateMetasets();
  5844. return newControllers;
  5845. }
  5846. _resetElements() {
  5847. each(this.data.datasets, (dataset, datasetIndex)=>{
  5848. this.getDatasetMeta(datasetIndex).controller.reset();
  5849. }, this);
  5850. }
  5851. reset() {
  5852. this._resetElements();
  5853. this.notifyPlugins('reset');
  5854. }
  5855. update(mode) {
  5856. const config = this.config;
  5857. config.update();
  5858. const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext());
  5859. const animsDisabled = this._animationsDisabled = !options.animation;
  5860. this._updateScales();
  5861. this._checkEventBindings();
  5862. this._updateHiddenIndices();
  5863. this._plugins.invalidate();
  5864. if (this.notifyPlugins('beforeUpdate', {
  5865. mode,
  5866. cancelable: true
  5867. }) === false) {
  5868. return;
  5869. }
  5870. const newControllers = this.buildOrUpdateControllers();
  5871. this.notifyPlugins('beforeElementsUpdate');
  5872. let minPadding = 0;
  5873. for(let i = 0, ilen = this.data.datasets.length; i < ilen; i++){
  5874. const { controller } = this.getDatasetMeta(i);
  5875. const reset = !animsDisabled && newControllers.indexOf(controller) === -1;
  5876. controller.buildOrUpdateElements(reset);
  5877. minPadding = Math.max(+controller.getMaxOverflow(), minPadding);
  5878. }
  5879. minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0;
  5880. this._updateLayout(minPadding);
  5881. if (!animsDisabled) {
  5882. each(newControllers, (controller)=>{
  5883. controller.reset();
  5884. });
  5885. }
  5886. this._updateDatasets(mode);
  5887. this.notifyPlugins('afterUpdate', {
  5888. mode
  5889. });
  5890. this._layers.sort(compare2Level('z', '_idx'));
  5891. const { _active , _lastEvent } = this;
  5892. if (_lastEvent) {
  5893. this._eventHandler(_lastEvent, true);
  5894. } else if (_active.length) {
  5895. this._updateHoverStyles(_active, _active, true);
  5896. }
  5897. this.render();
  5898. }
  5899. _updateScales() {
  5900. each(this.scales, (scale)=>{
  5901. layouts.removeBox(this, scale);
  5902. });
  5903. this.ensureScalesHaveIDs();
  5904. this.buildOrUpdateScales();
  5905. }
  5906. _checkEventBindings() {
  5907. const options = this.options;
  5908. const existingEvents = new Set(Object.keys(this._listeners));
  5909. const newEvents = new Set(options.events);
  5910. if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) {
  5911. this.unbindEvents();
  5912. this.bindEvents();
  5913. }
  5914. }
  5915. _updateHiddenIndices() {
  5916. const { _hiddenIndices } = this;
  5917. const changes = this._getUniformDataChanges() || [];
  5918. for (const { method , start , count } of changes){
  5919. const move = method === '_removeElements' ? -count : count;
  5920. moveNumericKeys(_hiddenIndices, start, move);
  5921. }
  5922. }
  5923. _getUniformDataChanges() {
  5924. const _dataChanges = this._dataChanges;
  5925. if (!_dataChanges || !_dataChanges.length) {
  5926. return;
  5927. }
  5928. this._dataChanges = [];
  5929. const datasetCount = this.data.datasets.length;
  5930. const makeSet = (idx)=>new Set(_dataChanges.filter((c)=>c[0] === idx).map((c, i)=>i + ',' + c.splice(1).join(',')));
  5931. const changeSet = makeSet(0);
  5932. for(let i = 1; i < datasetCount; i++){
  5933. if (!setsEqual(changeSet, makeSet(i))) {
  5934. return;
  5935. }
  5936. }
  5937. return Array.from(changeSet).map((c)=>c.split(',')).map((a)=>({
  5938. method: a[1],
  5939. start: +a[2],
  5940. count: +a[3]
  5941. }));
  5942. }
  5943. _updateLayout(minPadding) {
  5944. if (this.notifyPlugins('beforeLayout', {
  5945. cancelable: true
  5946. }) === false) {
  5947. return;
  5948. }
  5949. layouts.update(this, this.width, this.height, minPadding);
  5950. const area = this.chartArea;
  5951. const noArea = area.width <= 0 || area.height <= 0;
  5952. this._layers = [];
  5953. each(this.boxes, (box)=>{
  5954. if (noArea && box.position === 'chartArea') {
  5955. return;
  5956. }
  5957. if (box.configure) {
  5958. box.configure();
  5959. }
  5960. this._layers.push(...box._layers());
  5961. }, this);
  5962. this._layers.forEach((item, index)=>{
  5963. item._idx = index;
  5964. });
  5965. this.notifyPlugins('afterLayout');
  5966. }
  5967. _updateDatasets(mode) {
  5968. if (this.notifyPlugins('beforeDatasetsUpdate', {
  5969. mode,
  5970. cancelable: true
  5971. }) === false) {
  5972. return;
  5973. }
  5974. for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
  5975. this.getDatasetMeta(i).controller.configure();
  5976. }
  5977. for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
  5978. this._updateDataset(i, isFunction(mode) ? mode({
  5979. datasetIndex: i
  5980. }) : mode);
  5981. }
  5982. this.notifyPlugins('afterDatasetsUpdate', {
  5983. mode
  5984. });
  5985. }
  5986. _updateDataset(index, mode) {
  5987. const meta = this.getDatasetMeta(index);
  5988. const args = {
  5989. meta,
  5990. index,
  5991. mode,
  5992. cancelable: true
  5993. };
  5994. if (this.notifyPlugins('beforeDatasetUpdate', args) === false) {
  5995. return;
  5996. }
  5997. meta.controller._update(mode);
  5998. args.cancelable = false;
  5999. this.notifyPlugins('afterDatasetUpdate', args);
  6000. }
  6001. render() {
  6002. if (this.notifyPlugins('beforeRender', {
  6003. cancelable: true
  6004. }) === false) {
  6005. return;
  6006. }
  6007. if (animator.has(this)) {
  6008. if (this.attached && !animator.running(this)) {
  6009. animator.start(this);
  6010. }
  6011. } else {
  6012. this.draw();
  6013. onAnimationsComplete({
  6014. chart: this
  6015. });
  6016. }
  6017. }
  6018. draw() {
  6019. let i;
  6020. if (this._resizeBeforeDraw) {
  6021. const { width , height } = this._resizeBeforeDraw;
  6022. this._resizeBeforeDraw = null;
  6023. this._resize(width, height);
  6024. }
  6025. this.clear();
  6026. if (this.width <= 0 || this.height <= 0) {
  6027. return;
  6028. }
  6029. if (this.notifyPlugins('beforeDraw', {
  6030. cancelable: true
  6031. }) === false) {
  6032. return;
  6033. }
  6034. const layers = this._layers;
  6035. for(i = 0; i < layers.length && layers[i].z <= 0; ++i){
  6036. layers[i].draw(this.chartArea);
  6037. }
  6038. this._drawDatasets();
  6039. for(; i < layers.length; ++i){
  6040. layers[i].draw(this.chartArea);
  6041. }
  6042. this.notifyPlugins('afterDraw');
  6043. }
  6044. _getSortedDatasetMetas(filterVisible) {
  6045. const metasets = this._sortedMetasets;
  6046. const result = [];
  6047. let i, ilen;
  6048. for(i = 0, ilen = metasets.length; i < ilen; ++i){
  6049. const meta = metasets[i];
  6050. if (!filterVisible || meta.visible) {
  6051. result.push(meta);
  6052. }
  6053. }
  6054. return result;
  6055. }
  6056. getSortedVisibleDatasetMetas() {
  6057. return this._getSortedDatasetMetas(true);
  6058. }
  6059. _drawDatasets() {
  6060. if (this.notifyPlugins('beforeDatasetsDraw', {
  6061. cancelable: true
  6062. }) === false) {
  6063. return;
  6064. }
  6065. const metasets = this.getSortedVisibleDatasetMetas();
  6066. for(let i = metasets.length - 1; i >= 0; --i){
  6067. this._drawDataset(metasets[i]);
  6068. }
  6069. this.notifyPlugins('afterDatasetsDraw');
  6070. }
  6071. _drawDataset(meta) {
  6072. const ctx = this.ctx;
  6073. const clip = meta._clip;
  6074. const useClip = !clip.disabled;
  6075. const area = getDatasetArea(meta, this.chartArea);
  6076. const args = {
  6077. meta,
  6078. index: meta.index,
  6079. cancelable: true
  6080. };
  6081. if (this.notifyPlugins('beforeDatasetDraw', args) === false) {
  6082. return;
  6083. }
  6084. if (useClip) {
  6085. clipArea(ctx, {
  6086. left: clip.left === false ? 0 : area.left - clip.left,
  6087. right: clip.right === false ? this.width : area.right + clip.right,
  6088. top: clip.top === false ? 0 : area.top - clip.top,
  6089. bottom: clip.bottom === false ? this.height : area.bottom + clip.bottom
  6090. });
  6091. }
  6092. meta.controller.draw();
  6093. if (useClip) {
  6094. unclipArea(ctx);
  6095. }
  6096. args.cancelable = false;
  6097. this.notifyPlugins('afterDatasetDraw', args);
  6098. }
  6099. isPointInArea(point) {
  6100. return _isPointInArea(point, this.chartArea, this._minPadding);
  6101. }
  6102. getElementsAtEventForMode(e, mode, options, useFinalPosition) {
  6103. const method = Interaction.modes[mode];
  6104. if (typeof method === 'function') {
  6105. return method(this, e, options, useFinalPosition);
  6106. }
  6107. return [];
  6108. }
  6109. getDatasetMeta(datasetIndex) {
  6110. const dataset = this.data.datasets[datasetIndex];
  6111. const metasets = this._metasets;
  6112. let meta = metasets.filter((x)=>x && x._dataset === dataset).pop();
  6113. if (!meta) {
  6114. meta = {
  6115. type: null,
  6116. data: [],
  6117. dataset: null,
  6118. controller: null,
  6119. hidden: null,
  6120. xAxisID: null,
  6121. yAxisID: null,
  6122. order: dataset && dataset.order || 0,
  6123. index: datasetIndex,
  6124. _dataset: dataset,
  6125. _parsed: [],
  6126. _sorted: false
  6127. };
  6128. metasets.push(meta);
  6129. }
  6130. return meta;
  6131. }
  6132. getContext() {
  6133. return this.$context || (this.$context = createContext(null, {
  6134. chart: this,
  6135. type: 'chart'
  6136. }));
  6137. }
  6138. getVisibleDatasetCount() {
  6139. return this.getSortedVisibleDatasetMetas().length;
  6140. }
  6141. isDatasetVisible(datasetIndex) {
  6142. const dataset = this.data.datasets[datasetIndex];
  6143. if (!dataset) {
  6144. return false;
  6145. }
  6146. const meta = this.getDatasetMeta(datasetIndex);
  6147. return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;
  6148. }
  6149. setDatasetVisibility(datasetIndex, visible) {
  6150. const meta = this.getDatasetMeta(datasetIndex);
  6151. meta.hidden = !visible;
  6152. }
  6153. toggleDataVisibility(index) {
  6154. this._hiddenIndices[index] = !this._hiddenIndices[index];
  6155. }
  6156. getDataVisibility(index) {
  6157. return !this._hiddenIndices[index];
  6158. }
  6159. _updateVisibility(datasetIndex, dataIndex, visible) {
  6160. const mode = visible ? 'show' : 'hide';
  6161. const meta = this.getDatasetMeta(datasetIndex);
  6162. const anims = meta.controller._resolveAnimations(undefined, mode);
  6163. if (defined(dataIndex)) {
  6164. meta.data[dataIndex].hidden = !visible;
  6165. this.update();
  6166. } else {
  6167. this.setDatasetVisibility(datasetIndex, visible);
  6168. anims.update(meta, {
  6169. visible
  6170. });
  6171. this.update((ctx)=>ctx.datasetIndex === datasetIndex ? mode : undefined);
  6172. }
  6173. }
  6174. hide(datasetIndex, dataIndex) {
  6175. this._updateVisibility(datasetIndex, dataIndex, false);
  6176. }
  6177. show(datasetIndex, dataIndex) {
  6178. this._updateVisibility(datasetIndex, dataIndex, true);
  6179. }
  6180. _destroyDatasetMeta(datasetIndex) {
  6181. const meta = this._metasets[datasetIndex];
  6182. if (meta && meta.controller) {
  6183. meta.controller._destroy();
  6184. }
  6185. delete this._metasets[datasetIndex];
  6186. }
  6187. _stop() {
  6188. let i, ilen;
  6189. this.stop();
  6190. animator.remove(this);
  6191. for(i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
  6192. this._destroyDatasetMeta(i);
  6193. }
  6194. }
  6195. destroy() {
  6196. this.notifyPlugins('beforeDestroy');
  6197. const { canvas , ctx } = this;
  6198. this._stop();
  6199. this.config.clearCache();
  6200. if (canvas) {
  6201. this.unbindEvents();
  6202. clearCanvas(canvas, ctx);
  6203. this.platform.releaseContext(ctx);
  6204. this.canvas = null;
  6205. this.ctx = null;
  6206. }
  6207. delete instances[this.id];
  6208. this.notifyPlugins('afterDestroy');
  6209. }
  6210. toBase64Image(...args) {
  6211. return this.canvas.toDataURL(...args);
  6212. }
  6213. bindEvents() {
  6214. this.bindUserEvents();
  6215. if (this.options.responsive) {
  6216. this.bindResponsiveEvents();
  6217. } else {
  6218. this.attached = true;
  6219. }
  6220. }
  6221. bindUserEvents() {
  6222. const listeners = this._listeners;
  6223. const platform = this.platform;
  6224. const _add = (type, listener)=>{
  6225. platform.addEventListener(this, type, listener);
  6226. listeners[type] = listener;
  6227. };
  6228. const listener = (e, x, y)=>{
  6229. e.offsetX = x;
  6230. e.offsetY = y;
  6231. this._eventHandler(e);
  6232. };
  6233. each(this.options.events, (type)=>_add(type, listener));
  6234. }
  6235. bindResponsiveEvents() {
  6236. if (!this._responsiveListeners) {
  6237. this._responsiveListeners = {};
  6238. }
  6239. const listeners = this._responsiveListeners;
  6240. const platform = this.platform;
  6241. const _add = (type, listener)=>{
  6242. platform.addEventListener(this, type, listener);
  6243. listeners[type] = listener;
  6244. };
  6245. const _remove = (type, listener)=>{
  6246. if (listeners[type]) {
  6247. platform.removeEventListener(this, type, listener);
  6248. delete listeners[type];
  6249. }
  6250. };
  6251. const listener = (width, height)=>{
  6252. if (this.canvas) {
  6253. this.resize(width, height);
  6254. }
  6255. };
  6256. let detached;
  6257. const attached = ()=>{
  6258. _remove('attach', attached);
  6259. this.attached = true;
  6260. this.resize();
  6261. _add('resize', listener);
  6262. _add('detach', detached);
  6263. };
  6264. detached = ()=>{
  6265. this.attached = false;
  6266. _remove('resize', listener);
  6267. this._stop();
  6268. this._resize(0, 0);
  6269. _add('attach', attached);
  6270. };
  6271. if (platform.isAttached(this.canvas)) {
  6272. attached();
  6273. } else {
  6274. detached();
  6275. }
  6276. }
  6277. unbindEvents() {
  6278. each(this._listeners, (listener, type)=>{
  6279. this.platform.removeEventListener(this, type, listener);
  6280. });
  6281. this._listeners = {};
  6282. each(this._responsiveListeners, (listener, type)=>{
  6283. this.platform.removeEventListener(this, type, listener);
  6284. });
  6285. this._responsiveListeners = undefined;
  6286. }
  6287. updateHoverStyle(items, mode, enabled) {
  6288. const prefix = enabled ? 'set' : 'remove';
  6289. let meta, item, i, ilen;
  6290. if (mode === 'dataset') {
  6291. meta = this.getDatasetMeta(items[0].datasetIndex);
  6292. meta.controller['_' + prefix + 'DatasetHoverStyle']();
  6293. }
  6294. for(i = 0, ilen = items.length; i < ilen; ++i){
  6295. item = items[i];
  6296. const controller = item && this.getDatasetMeta(item.datasetIndex).controller;
  6297. if (controller) {
  6298. controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
  6299. }
  6300. }
  6301. }
  6302. getActiveElements() {
  6303. return this._active || [];
  6304. }
  6305. setActiveElements(activeElements) {
  6306. const lastActive = this._active || [];
  6307. const active = activeElements.map(({ datasetIndex , index })=>{
  6308. const meta = this.getDatasetMeta(datasetIndex);
  6309. if (!meta) {
  6310. throw new Error('No dataset found at index ' + datasetIndex);
  6311. }
  6312. return {
  6313. datasetIndex,
  6314. element: meta.data[index],
  6315. index
  6316. };
  6317. });
  6318. const changed = !_elementsEqual(active, lastActive);
  6319. if (changed) {
  6320. this._active = active;
  6321. this._lastEvent = null;
  6322. this._updateHoverStyles(active, lastActive);
  6323. }
  6324. }
  6325. notifyPlugins(hook, args, filter) {
  6326. return this._plugins.notify(this, hook, args, filter);
  6327. }
  6328. isPluginEnabled(pluginId) {
  6329. return this._plugins._cache.filter((p)=>p.plugin.id === pluginId).length === 1;
  6330. }
  6331. _updateHoverStyles(active, lastActive, replay) {
  6332. const hoverOptions = this.options.hover;
  6333. const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.datasetIndex === y.datasetIndex && x.index === y.index));
  6334. const deactivated = diff(lastActive, active);
  6335. const activated = replay ? active : diff(active, lastActive);
  6336. if (deactivated.length) {
  6337. this.updateHoverStyle(deactivated, hoverOptions.mode, false);
  6338. }
  6339. if (activated.length && hoverOptions.mode) {
  6340. this.updateHoverStyle(activated, hoverOptions.mode, true);
  6341. }
  6342. }
  6343. _eventHandler(e, replay) {
  6344. const args = {
  6345. event: e,
  6346. replay,
  6347. cancelable: true,
  6348. inChartArea: this.isPointInArea(e)
  6349. };
  6350. const eventFilter = (plugin)=>(plugin.options.events || this.options.events).includes(e.native.type);
  6351. if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) {
  6352. return;
  6353. }
  6354. const changed = this._handleEvent(e, replay, args.inChartArea);
  6355. args.cancelable = false;
  6356. this.notifyPlugins('afterEvent', args, eventFilter);
  6357. if (changed || args.changed) {
  6358. this.render();
  6359. }
  6360. return this;
  6361. }
  6362. _handleEvent(e, replay, inChartArea) {
  6363. const { _active: lastActive = [] , options } = this;
  6364. const useFinalPosition = replay;
  6365. const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition);
  6366. const isClick = _isClickEvent(e);
  6367. const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick);
  6368. if (inChartArea) {
  6369. this._lastEvent = null;
  6370. callback(options.onHover, [
  6371. e,
  6372. active,
  6373. this
  6374. ], this);
  6375. if (isClick) {
  6376. callback(options.onClick, [
  6377. e,
  6378. active,
  6379. this
  6380. ], this);
  6381. }
  6382. }
  6383. const changed = !_elementsEqual(active, lastActive);
  6384. if (changed || replay) {
  6385. this._active = active;
  6386. this._updateHoverStyles(active, lastActive, replay);
  6387. }
  6388. this._lastEvent = lastEvent;
  6389. return changed;
  6390. }
  6391. _getActiveElements(e, lastActive, inChartArea, useFinalPosition) {
  6392. if (e.type === 'mouseout') {
  6393. return [];
  6394. }
  6395. if (!inChartArea) {
  6396. return lastActive;
  6397. }
  6398. const hoverOptions = this.options.hover;
  6399. return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);
  6400. }
  6401. }
  6402. function invalidatePlugins() {
  6403. return each(Chart.instances, (chart)=>chart._plugins.invalidate());
  6404. }
  6405. function clipArc(ctx, element, endAngle) {
  6406. const { startAngle , pixelMargin , x , y , outerRadius , innerRadius } = element;
  6407. let angleMargin = pixelMargin / outerRadius;
  6408. // Draw an inner border by clipping the arc and drawing a double-width border
  6409. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  6410. ctx.beginPath();
  6411. ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  6412. if (innerRadius > pixelMargin) {
  6413. angleMargin = pixelMargin / innerRadius;
  6414. ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);
  6415. } else {
  6416. ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI);
  6417. }
  6418. ctx.closePath();
  6419. ctx.clip();
  6420. }
  6421. function toRadiusCorners(value) {
  6422. return _readValueToProps(value, [
  6423. 'outerStart',
  6424. 'outerEnd',
  6425. 'innerStart',
  6426. 'innerEnd'
  6427. ]);
  6428. }
  6429. /**
  6430. * Parse border radius from the provided options
  6431. */ function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) {
  6432. const o = toRadiusCorners(arc.options.borderRadius);
  6433. const halfThickness = (outerRadius - innerRadius) / 2;
  6434. const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);
  6435. // Outer limits are complicated. We want to compute the available angular distance at
  6436. // a radius of outerRadius - borderRadius because for small angular distances, this term limits.
  6437. // We compute at r = outerRadius - borderRadius because this circle defines the center of the border corners.
  6438. //
  6439. // If the borderRadius is large, that value can become negative.
  6440. // This causes the outer borders to lose their radius entirely, which is rather unexpected. To solve that, if borderRadius > outerRadius
  6441. // we know that the thickness term will dominate and compute the limits at that point
  6442. const computeOuterLimit = (val)=>{
  6443. const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;
  6444. return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit));
  6445. };
  6446. return {
  6447. outerStart: computeOuterLimit(o.outerStart),
  6448. outerEnd: computeOuterLimit(o.outerEnd),
  6449. innerStart: _limitValue(o.innerStart, 0, innerLimit),
  6450. innerEnd: _limitValue(o.innerEnd, 0, innerLimit)
  6451. };
  6452. }
  6453. /**
  6454. * Convert (r, 𝜃) to (x, y)
  6455. */ function rThetaToXY(r, theta, x, y) {
  6456. return {
  6457. x: x + r * Math.cos(theta),
  6458. y: y + r * Math.sin(theta)
  6459. };
  6460. }
  6461. /**
  6462. * Path the arc, respecting border radius by separating into left and right halves.
  6463. *
  6464. * Start End
  6465. *
  6466. * 1--->a--->2 Outer
  6467. * / \
  6468. * 8 3
  6469. * | |
  6470. * | |
  6471. * 7 4
  6472. * \ /
  6473. * 6<---b<---5 Inner
  6474. */ function pathArc(ctx, element, offset, spacing, end, circular) {
  6475. const { x , y , startAngle: start , pixelMargin , innerRadius: innerR } = element;
  6476. const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0);
  6477. const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0;
  6478. let spacingOffset = 0;
  6479. const alpha = end - start;
  6480. if (spacing) {
  6481. // When spacing is present, it is the same for all items
  6482. // So we adjust the start and end angle of the arc such that
  6483. // the distance is the same as it would be without the spacing
  6484. const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;
  6485. const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;
  6486. const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;
  6487. const adjustedAngle = avNogSpacingRadius !== 0 ? alpha * avNogSpacingRadius / (avNogSpacingRadius + spacing) : alpha;
  6488. spacingOffset = (alpha - adjustedAngle) / 2;
  6489. }
  6490. const beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius;
  6491. const angleOffset = (alpha - beta) / 2;
  6492. const startAngle = start + angleOffset + spacingOffset;
  6493. const endAngle = end - angleOffset - spacingOffset;
  6494. const { outerStart , outerEnd , innerStart , innerEnd } = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle);
  6495. const outerStartAdjustedRadius = outerRadius - outerStart;
  6496. const outerEndAdjustedRadius = outerRadius - outerEnd;
  6497. const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;
  6498. const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;
  6499. const innerStartAdjustedRadius = innerRadius + innerStart;
  6500. const innerEndAdjustedRadius = innerRadius + innerEnd;
  6501. const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;
  6502. const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;
  6503. ctx.beginPath();
  6504. if (circular) {
  6505. // The first arc segments from point 1 to point a to point 2
  6506. const outerMidAdjustedAngle = (outerStartAdjustedAngle + outerEndAdjustedAngle) / 2;
  6507. ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerMidAdjustedAngle);
  6508. ctx.arc(x, y, outerRadius, outerMidAdjustedAngle, outerEndAdjustedAngle);
  6509. // The corner segment from point 2 to point 3
  6510. if (outerEnd > 0) {
  6511. const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);
  6512. ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);
  6513. }
  6514. // The line from point 3 to point 4
  6515. const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);
  6516. ctx.lineTo(p4.x, p4.y);
  6517. // The corner segment from point 4 to point 5
  6518. if (innerEnd > 0) {
  6519. const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);
  6520. ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);
  6521. }
  6522. // The inner arc from point 5 to point b to point 6
  6523. const innerMidAdjustedAngle = (endAngle - innerEnd / innerRadius + (startAngle + innerStart / innerRadius)) / 2;
  6524. ctx.arc(x, y, innerRadius, endAngle - innerEnd / innerRadius, innerMidAdjustedAngle, true);
  6525. ctx.arc(x, y, innerRadius, innerMidAdjustedAngle, startAngle + innerStart / innerRadius, true);
  6526. // The corner segment from point 6 to point 7
  6527. if (innerStart > 0) {
  6528. const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);
  6529. ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);
  6530. }
  6531. // The line from point 7 to point 8
  6532. const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);
  6533. ctx.lineTo(p8.x, p8.y);
  6534. // The corner segment from point 8 to point 1
  6535. if (outerStart > 0) {
  6536. const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);
  6537. ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);
  6538. }
  6539. } else {
  6540. ctx.moveTo(x, y);
  6541. const outerStartX = Math.cos(outerStartAdjustedAngle) * outerRadius + x;
  6542. const outerStartY = Math.sin(outerStartAdjustedAngle) * outerRadius + y;
  6543. ctx.lineTo(outerStartX, outerStartY);
  6544. const outerEndX = Math.cos(outerEndAdjustedAngle) * outerRadius + x;
  6545. const outerEndY = Math.sin(outerEndAdjustedAngle) * outerRadius + y;
  6546. ctx.lineTo(outerEndX, outerEndY);
  6547. }
  6548. ctx.closePath();
  6549. }
  6550. function drawArc(ctx, element, offset, spacing, circular) {
  6551. const { fullCircles , startAngle , circumference } = element;
  6552. let endAngle = element.endAngle;
  6553. if (fullCircles) {
  6554. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6555. for(let i = 0; i < fullCircles; ++i){
  6556. ctx.fill();
  6557. }
  6558. if (!isNaN(circumference)) {
  6559. endAngle = startAngle + (circumference % TAU || TAU);
  6560. }
  6561. }
  6562. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6563. ctx.fill();
  6564. return endAngle;
  6565. }
  6566. function drawBorder(ctx, element, offset, spacing, circular) {
  6567. const { fullCircles , startAngle , circumference , options } = element;
  6568. const { borderWidth , borderJoinStyle , borderDash , borderDashOffset } = options;
  6569. const inner = options.borderAlign === 'inner';
  6570. if (!borderWidth) {
  6571. return;
  6572. }
  6573. ctx.setLineDash(borderDash || []);
  6574. ctx.lineDashOffset = borderDashOffset;
  6575. if (inner) {
  6576. ctx.lineWidth = borderWidth * 2;
  6577. ctx.lineJoin = borderJoinStyle || 'round';
  6578. } else {
  6579. ctx.lineWidth = borderWidth;
  6580. ctx.lineJoin = borderJoinStyle || 'bevel';
  6581. }
  6582. let endAngle = element.endAngle;
  6583. if (fullCircles) {
  6584. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6585. for(let i = 0; i < fullCircles; ++i){
  6586. ctx.stroke();
  6587. }
  6588. if (!isNaN(circumference)) {
  6589. endAngle = startAngle + (circumference % TAU || TAU);
  6590. }
  6591. }
  6592. if (inner) {
  6593. clipArc(ctx, element, endAngle);
  6594. }
  6595. if (!fullCircles) {
  6596. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6597. ctx.stroke();
  6598. }
  6599. }
  6600. class ArcElement extends Element {
  6601. static id = 'arc';
  6602. static defaults = {
  6603. borderAlign: 'center',
  6604. borderColor: '#fff',
  6605. borderDash: [],
  6606. borderDashOffset: 0,
  6607. borderJoinStyle: undefined,
  6608. borderRadius: 0,
  6609. borderWidth: 2,
  6610. offset: 0,
  6611. spacing: 0,
  6612. angle: undefined,
  6613. circular: true
  6614. };
  6615. static defaultRoutes = {
  6616. backgroundColor: 'backgroundColor'
  6617. };
  6618. static descriptors = {
  6619. _scriptable: true,
  6620. _indexable: (name)=>name !== 'borderDash'
  6621. };
  6622. circumference;
  6623. endAngle;
  6624. fullCircles;
  6625. innerRadius;
  6626. outerRadius;
  6627. pixelMargin;
  6628. startAngle;
  6629. constructor(cfg){
  6630. super();
  6631. this.options = undefined;
  6632. this.circumference = undefined;
  6633. this.startAngle = undefined;
  6634. this.endAngle = undefined;
  6635. this.innerRadius = undefined;
  6636. this.outerRadius = undefined;
  6637. this.pixelMargin = 0;
  6638. this.fullCircles = 0;
  6639. if (cfg) {
  6640. Object.assign(this, cfg);
  6641. }
  6642. }
  6643. inRange(chartX, chartY, useFinalPosition) {
  6644. const point = this.getProps([
  6645. 'x',
  6646. 'y'
  6647. ], useFinalPosition);
  6648. const { angle , distance } = getAngleFromPoint(point, {
  6649. x: chartX,
  6650. y: chartY
  6651. });
  6652. const { startAngle , endAngle , innerRadius , outerRadius , circumference } = this.getProps([
  6653. 'startAngle',
  6654. 'endAngle',
  6655. 'innerRadius',
  6656. 'outerRadius',
  6657. 'circumference'
  6658. ], useFinalPosition);
  6659. const rAdjust = (this.options.spacing + this.options.borderWidth) / 2;
  6660. const _circumference = valueOrDefault(circumference, endAngle - startAngle);
  6661. const nonZeroBetween = _angleBetween(angle, startAngle, endAngle) && startAngle !== endAngle;
  6662. const betweenAngles = _circumference >= TAU || nonZeroBetween;
  6663. const withinRadius = _isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust);
  6664. return betweenAngles && withinRadius;
  6665. }
  6666. getCenterPoint(useFinalPosition) {
  6667. const { x , y , startAngle , endAngle , innerRadius , outerRadius } = this.getProps([
  6668. 'x',
  6669. 'y',
  6670. 'startAngle',
  6671. 'endAngle',
  6672. 'innerRadius',
  6673. 'outerRadius'
  6674. ], useFinalPosition);
  6675. const { offset , spacing } = this.options;
  6676. const halfAngle = (startAngle + endAngle) / 2;
  6677. const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2;
  6678. return {
  6679. x: x + Math.cos(halfAngle) * halfRadius,
  6680. y: y + Math.sin(halfAngle) * halfRadius
  6681. };
  6682. }
  6683. tooltipPosition(useFinalPosition) {
  6684. return this.getCenterPoint(useFinalPosition);
  6685. }
  6686. draw(ctx) {
  6687. const { options , circumference } = this;
  6688. const offset = (options.offset || 0) / 4;
  6689. const spacing = (options.spacing || 0) / 2;
  6690. const circular = options.circular;
  6691. this.pixelMargin = options.borderAlign === 'inner' ? 0.33 : 0;
  6692. this.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0;
  6693. if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) {
  6694. return;
  6695. }
  6696. ctx.save();
  6697. const halfAngle = (this.startAngle + this.endAngle) / 2;
  6698. ctx.translate(Math.cos(halfAngle) * offset, Math.sin(halfAngle) * offset);
  6699. const fix = 1 - Math.sin(Math.min(PI, circumference || 0));
  6700. const radiusOffset = offset * fix;
  6701. ctx.fillStyle = options.backgroundColor;
  6702. ctx.strokeStyle = options.borderColor;
  6703. drawArc(ctx, this, radiusOffset, spacing, circular);
  6704. drawBorder(ctx, this, radiusOffset, spacing, circular);
  6705. ctx.restore();
  6706. }
  6707. }
  6708. function setStyle(ctx, options, style = options) {
  6709. ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle);
  6710. ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash));
  6711. ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset);
  6712. ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);
  6713. ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth);
  6714. ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor);
  6715. }
  6716. function lineTo(ctx, previous, target) {
  6717. ctx.lineTo(target.x, target.y);
  6718. }
  6719. function getLineMethod(options) {
  6720. if (options.stepped) {
  6721. return _steppedLineTo;
  6722. }
  6723. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  6724. return _bezierCurveTo;
  6725. }
  6726. return lineTo;
  6727. }
  6728. function pathVars(points, segment, params = {}) {
  6729. const count = points.length;
  6730. const { start: paramsStart = 0 , end: paramsEnd = count - 1 } = params;
  6731. const { start: segmentStart , end: segmentEnd } = segment;
  6732. const start = Math.max(paramsStart, segmentStart);
  6733. const end = Math.min(paramsEnd, segmentEnd);
  6734. const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;
  6735. return {
  6736. count,
  6737. start,
  6738. loop: segment.loop,
  6739. ilen: end < start && !outside ? count + end - start : end - start
  6740. };
  6741. }
  6742. function pathSegment(ctx, line, segment, params) {
  6743. const { points , options } = line;
  6744. const { count , start , loop , ilen } = pathVars(points, segment, params);
  6745. const lineMethod = getLineMethod(options);
  6746. let { move =true , reverse } = params || {};
  6747. let i, point, prev;
  6748. for(i = 0; i <= ilen; ++i){
  6749. point = points[(start + (reverse ? ilen - i : i)) % count];
  6750. if (point.skip) {
  6751. continue;
  6752. } else if (move) {
  6753. ctx.moveTo(point.x, point.y);
  6754. move = false;
  6755. } else {
  6756. lineMethod(ctx, prev, point, reverse, options.stepped);
  6757. }
  6758. prev = point;
  6759. }
  6760. if (loop) {
  6761. point = points[(start + (reverse ? ilen : 0)) % count];
  6762. lineMethod(ctx, prev, point, reverse, options.stepped);
  6763. }
  6764. return !!loop;
  6765. }
  6766. function fastPathSegment(ctx, line, segment, params) {
  6767. const points = line.points;
  6768. const { count , start , ilen } = pathVars(points, segment, params);
  6769. const { move =true , reverse } = params || {};
  6770. let avgX = 0;
  6771. let countX = 0;
  6772. let i, point, prevX, minY, maxY, lastY;
  6773. const pointIndex = (index)=>(start + (reverse ? ilen - index : index)) % count;
  6774. const drawX = ()=>{
  6775. if (minY !== maxY) {
  6776. ctx.lineTo(avgX, maxY);
  6777. ctx.lineTo(avgX, minY);
  6778. ctx.lineTo(avgX, lastY);
  6779. }
  6780. };
  6781. if (move) {
  6782. point = points[pointIndex(0)];
  6783. ctx.moveTo(point.x, point.y);
  6784. }
  6785. for(i = 0; i <= ilen; ++i){
  6786. point = points[pointIndex(i)];
  6787. if (point.skip) {
  6788. continue;
  6789. }
  6790. const x = point.x;
  6791. const y = point.y;
  6792. const truncX = x | 0;
  6793. if (truncX === prevX) {
  6794. if (y < minY) {
  6795. minY = y;
  6796. } else if (y > maxY) {
  6797. maxY = y;
  6798. }
  6799. avgX = (countX * avgX + x) / ++countX;
  6800. } else {
  6801. drawX();
  6802. ctx.lineTo(x, y);
  6803. prevX = truncX;
  6804. countX = 0;
  6805. minY = maxY = y;
  6806. }
  6807. lastY = y;
  6808. }
  6809. drawX();
  6810. }
  6811. function _getSegmentMethod(line) {
  6812. const opts = line.options;
  6813. const borderDash = opts.borderDash && opts.borderDash.length;
  6814. const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;
  6815. return useFastPath ? fastPathSegment : pathSegment;
  6816. }
  6817. function _getInterpolationMethod(options) {
  6818. if (options.stepped) {
  6819. return _steppedInterpolation;
  6820. }
  6821. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  6822. return _bezierInterpolation;
  6823. }
  6824. return _pointInLine;
  6825. }
  6826. function strokePathWithCache(ctx, line, start, count) {
  6827. let path = line._path;
  6828. if (!path) {
  6829. path = line._path = new Path2D();
  6830. if (line.path(path, start, count)) {
  6831. path.closePath();
  6832. }
  6833. }
  6834. setStyle(ctx, line.options);
  6835. ctx.stroke(path);
  6836. }
  6837. function strokePathDirect(ctx, line, start, count) {
  6838. const { segments , options } = line;
  6839. const segmentMethod = _getSegmentMethod(line);
  6840. for (const segment of segments){
  6841. setStyle(ctx, options, segment.style);
  6842. ctx.beginPath();
  6843. if (segmentMethod(ctx, line, segment, {
  6844. start,
  6845. end: start + count - 1
  6846. })) {
  6847. ctx.closePath();
  6848. }
  6849. ctx.stroke();
  6850. }
  6851. }
  6852. const usePath2D = typeof Path2D === 'function';
  6853. function draw(ctx, line, start, count) {
  6854. if (usePath2D && !line.options.segment) {
  6855. strokePathWithCache(ctx, line, start, count);
  6856. } else {
  6857. strokePathDirect(ctx, line, start, count);
  6858. }
  6859. }
  6860. class LineElement extends Element {
  6861. static id = 'line';
  6862. static defaults = {
  6863. borderCapStyle: 'butt',
  6864. borderDash: [],
  6865. borderDashOffset: 0,
  6866. borderJoinStyle: 'miter',
  6867. borderWidth: 3,
  6868. capBezierPoints: true,
  6869. cubicInterpolationMode: 'default',
  6870. fill: false,
  6871. spanGaps: false,
  6872. stepped: false,
  6873. tension: 0
  6874. };
  6875. static defaultRoutes = {
  6876. backgroundColor: 'backgroundColor',
  6877. borderColor: 'borderColor'
  6878. };
  6879. static descriptors = {
  6880. _scriptable: true,
  6881. _indexable: (name)=>name !== 'borderDash' && name !== 'fill'
  6882. };
  6883. constructor(cfg){
  6884. super();
  6885. this.animated = true;
  6886. this.options = undefined;
  6887. this._chart = undefined;
  6888. this._loop = undefined;
  6889. this._fullLoop = undefined;
  6890. this._path = undefined;
  6891. this._points = undefined;
  6892. this._segments = undefined;
  6893. this._decimated = false;
  6894. this._pointsUpdated = false;
  6895. this._datasetIndex = undefined;
  6896. if (cfg) {
  6897. Object.assign(this, cfg);
  6898. }
  6899. }
  6900. updateControlPoints(chartArea, indexAxis) {
  6901. const options = this.options;
  6902. if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) {
  6903. const loop = options.spanGaps ? this._loop : this._fullLoop;
  6904. _updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis);
  6905. this._pointsUpdated = true;
  6906. }
  6907. }
  6908. set points(points) {
  6909. this._points = points;
  6910. delete this._segments;
  6911. delete this._path;
  6912. this._pointsUpdated = false;
  6913. }
  6914. get points() {
  6915. return this._points;
  6916. }
  6917. get segments() {
  6918. return this._segments || (this._segments = _computeSegments(this, this.options.segment));
  6919. }
  6920. first() {
  6921. const segments = this.segments;
  6922. const points = this.points;
  6923. return segments.length && points[segments[0].start];
  6924. }
  6925. last() {
  6926. const segments = this.segments;
  6927. const points = this.points;
  6928. const count = segments.length;
  6929. return count && points[segments[count - 1].end];
  6930. }
  6931. interpolate(point, property) {
  6932. const options = this.options;
  6933. const value = point[property];
  6934. const points = this.points;
  6935. const segments = _boundSegments(this, {
  6936. property,
  6937. start: value,
  6938. end: value
  6939. });
  6940. if (!segments.length) {
  6941. return;
  6942. }
  6943. const result = [];
  6944. const _interpolate = _getInterpolationMethod(options);
  6945. let i, ilen;
  6946. for(i = 0, ilen = segments.length; i < ilen; ++i){
  6947. const { start , end } = segments[i];
  6948. const p1 = points[start];
  6949. const p2 = points[end];
  6950. if (p1 === p2) {
  6951. result.push(p1);
  6952. continue;
  6953. }
  6954. const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));
  6955. const interpolated = _interpolate(p1, p2, t, options.stepped);
  6956. interpolated[property] = point[property];
  6957. result.push(interpolated);
  6958. }
  6959. return result.length === 1 ? result[0] : result;
  6960. }
  6961. pathSegment(ctx, segment, params) {
  6962. const segmentMethod = _getSegmentMethod(this);
  6963. return segmentMethod(ctx, this, segment, params);
  6964. }
  6965. path(ctx, start, count) {
  6966. const segments = this.segments;
  6967. const segmentMethod = _getSegmentMethod(this);
  6968. let loop = this._loop;
  6969. start = start || 0;
  6970. count = count || this.points.length - start;
  6971. for (const segment of segments){
  6972. loop &= segmentMethod(ctx, this, segment, {
  6973. start,
  6974. end: start + count - 1
  6975. });
  6976. }
  6977. return !!loop;
  6978. }
  6979. draw(ctx, chartArea, start, count) {
  6980. const options = this.options || {};
  6981. const points = this.points || [];
  6982. if (points.length && options.borderWidth) {
  6983. ctx.save();
  6984. draw(ctx, this, start, count);
  6985. ctx.restore();
  6986. }
  6987. if (this.animated) {
  6988. this._pointsUpdated = false;
  6989. this._path = undefined;
  6990. }
  6991. }
  6992. }
  6993. function inRange$1(el, pos, axis, useFinalPosition) {
  6994. const options = el.options;
  6995. const { [axis]: value } = el.getProps([
  6996. axis
  6997. ], useFinalPosition);
  6998. return Math.abs(pos - value) < options.radius + options.hitRadius;
  6999. }
  7000. class PointElement extends Element {
  7001. static id = 'point';
  7002. parsed;
  7003. skip;
  7004. stop;
  7005. /**
  7006. * @type {any}
  7007. */ static defaults = {
  7008. borderWidth: 1,
  7009. hitRadius: 1,
  7010. hoverBorderWidth: 1,
  7011. hoverRadius: 4,
  7012. pointStyle: 'circle',
  7013. radius: 3,
  7014. rotation: 0
  7015. };
  7016. /**
  7017. * @type {any}
  7018. */ static defaultRoutes = {
  7019. backgroundColor: 'backgroundColor',
  7020. borderColor: 'borderColor'
  7021. };
  7022. constructor(cfg){
  7023. super();
  7024. this.options = undefined;
  7025. this.parsed = undefined;
  7026. this.skip = undefined;
  7027. this.stop = undefined;
  7028. if (cfg) {
  7029. Object.assign(this, cfg);
  7030. }
  7031. }
  7032. inRange(mouseX, mouseY, useFinalPosition) {
  7033. const options = this.options;
  7034. const { x , y } = this.getProps([
  7035. 'x',
  7036. 'y'
  7037. ], useFinalPosition);
  7038. return Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2) < Math.pow(options.hitRadius + options.radius, 2);
  7039. }
  7040. inXRange(mouseX, useFinalPosition) {
  7041. return inRange$1(this, mouseX, 'x', useFinalPosition);
  7042. }
  7043. inYRange(mouseY, useFinalPosition) {
  7044. return inRange$1(this, mouseY, 'y', useFinalPosition);
  7045. }
  7046. getCenterPoint(useFinalPosition) {
  7047. const { x , y } = this.getProps([
  7048. 'x',
  7049. 'y'
  7050. ], useFinalPosition);
  7051. return {
  7052. x,
  7053. y
  7054. };
  7055. }
  7056. size(options) {
  7057. options = options || this.options || {};
  7058. let radius = options.radius || 0;
  7059. radius = Math.max(radius, radius && options.hoverRadius || 0);
  7060. const borderWidth = radius && options.borderWidth || 0;
  7061. return (radius + borderWidth) * 2;
  7062. }
  7063. draw(ctx, area) {
  7064. const options = this.options;
  7065. if (this.skip || options.radius < 0.1 || !_isPointInArea(this, area, this.size(options) / 2)) {
  7066. return;
  7067. }
  7068. ctx.strokeStyle = options.borderColor;
  7069. ctx.lineWidth = options.borderWidth;
  7070. ctx.fillStyle = options.backgroundColor;
  7071. drawPoint(ctx, options, this.x, this.y);
  7072. }
  7073. getRange() {
  7074. const options = this.options || {};
  7075. // @ts-expect-error Fallbacks should never be hit in practice
  7076. return options.radius + options.hitRadius;
  7077. }
  7078. }
  7079. function getBarBounds(bar, useFinalPosition) {
  7080. const { x , y , base , width , height } = bar.getProps([
  7081. 'x',
  7082. 'y',
  7083. 'base',
  7084. 'width',
  7085. 'height'
  7086. ], useFinalPosition);
  7087. let left, right, top, bottom, half;
  7088. if (bar.horizontal) {
  7089. half = height / 2;
  7090. left = Math.min(x, base);
  7091. right = Math.max(x, base);
  7092. top = y - half;
  7093. bottom = y + half;
  7094. } else {
  7095. half = width / 2;
  7096. left = x - half;
  7097. right = x + half;
  7098. top = Math.min(y, base);
  7099. bottom = Math.max(y, base);
  7100. }
  7101. return {
  7102. left,
  7103. top,
  7104. right,
  7105. bottom
  7106. };
  7107. }
  7108. function skipOrLimit(skip, value, min, max) {
  7109. return skip ? 0 : _limitValue(value, min, max);
  7110. }
  7111. function parseBorderWidth(bar, maxW, maxH) {
  7112. const value = bar.options.borderWidth;
  7113. const skip = bar.borderSkipped;
  7114. const o = toTRBL(value);
  7115. return {
  7116. t: skipOrLimit(skip.top, o.top, 0, maxH),
  7117. r: skipOrLimit(skip.right, o.right, 0, maxW),
  7118. b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),
  7119. l: skipOrLimit(skip.left, o.left, 0, maxW)
  7120. };
  7121. }
  7122. function parseBorderRadius(bar, maxW, maxH) {
  7123. const { enableBorderRadius } = bar.getProps([
  7124. 'enableBorderRadius'
  7125. ]);
  7126. const value = bar.options.borderRadius;
  7127. const o = toTRBLCorners(value);
  7128. const maxR = Math.min(maxW, maxH);
  7129. const skip = bar.borderSkipped;
  7130. const enableBorder = enableBorderRadius || isObject(value);
  7131. return {
  7132. topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),
  7133. topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),
  7134. bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),
  7135. bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)
  7136. };
  7137. }
  7138. function boundingRects(bar) {
  7139. const bounds = getBarBounds(bar);
  7140. const width = bounds.right - bounds.left;
  7141. const height = bounds.bottom - bounds.top;
  7142. const border = parseBorderWidth(bar, width / 2, height / 2);
  7143. const radius = parseBorderRadius(bar, width / 2, height / 2);
  7144. return {
  7145. outer: {
  7146. x: bounds.left,
  7147. y: bounds.top,
  7148. w: width,
  7149. h: height,
  7150. radius
  7151. },
  7152. inner: {
  7153. x: bounds.left + border.l,
  7154. y: bounds.top + border.t,
  7155. w: width - border.l - border.r,
  7156. h: height - border.t - border.b,
  7157. radius: {
  7158. topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),
  7159. topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),
  7160. bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),
  7161. bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r))
  7162. }
  7163. }
  7164. };
  7165. }
  7166. function inRange(bar, x, y, useFinalPosition) {
  7167. const skipX = x === null;
  7168. const skipY = y === null;
  7169. const skipBoth = skipX && skipY;
  7170. const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);
  7171. return bounds && (skipX || _isBetween(x, bounds.left, bounds.right)) && (skipY || _isBetween(y, bounds.top, bounds.bottom));
  7172. }
  7173. function hasRadius(radius) {
  7174. return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;
  7175. }
  7176. function addNormalRectPath(ctx, rect) {
  7177. ctx.rect(rect.x, rect.y, rect.w, rect.h);
  7178. }
  7179. function inflateRect(rect, amount, refRect = {}) {
  7180. const x = rect.x !== refRect.x ? -amount : 0;
  7181. const y = rect.y !== refRect.y ? -amount : 0;
  7182. const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x;
  7183. const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y;
  7184. return {
  7185. x: rect.x + x,
  7186. y: rect.y + y,
  7187. w: rect.w + w,
  7188. h: rect.h + h,
  7189. radius: rect.radius
  7190. };
  7191. }
  7192. class BarElement extends Element {
  7193. static id = 'bar';
  7194. static defaults = {
  7195. borderSkipped: 'start',
  7196. borderWidth: 0,
  7197. borderRadius: 0,
  7198. inflateAmount: 'auto',
  7199. pointStyle: undefined
  7200. };
  7201. static defaultRoutes = {
  7202. backgroundColor: 'backgroundColor',
  7203. borderColor: 'borderColor'
  7204. };
  7205. constructor(cfg){
  7206. super();
  7207. this.options = undefined;
  7208. this.horizontal = undefined;
  7209. this.base = undefined;
  7210. this.width = undefined;
  7211. this.height = undefined;
  7212. this.inflateAmount = undefined;
  7213. if (cfg) {
  7214. Object.assign(this, cfg);
  7215. }
  7216. }
  7217. draw(ctx) {
  7218. const { inflateAmount , options: { borderColor , backgroundColor } } = this;
  7219. const { inner , outer } = boundingRects(this);
  7220. const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath;
  7221. ctx.save();
  7222. if (outer.w !== inner.w || outer.h !== inner.h) {
  7223. ctx.beginPath();
  7224. addRectPath(ctx, inflateRect(outer, inflateAmount, inner));
  7225. ctx.clip();
  7226. addRectPath(ctx, inflateRect(inner, -inflateAmount, outer));
  7227. ctx.fillStyle = borderColor;
  7228. ctx.fill('evenodd');
  7229. }
  7230. ctx.beginPath();
  7231. addRectPath(ctx, inflateRect(inner, inflateAmount));
  7232. ctx.fillStyle = backgroundColor;
  7233. ctx.fill();
  7234. ctx.restore();
  7235. }
  7236. inRange(mouseX, mouseY, useFinalPosition) {
  7237. return inRange(this, mouseX, mouseY, useFinalPosition);
  7238. }
  7239. inXRange(mouseX, useFinalPosition) {
  7240. return inRange(this, mouseX, null, useFinalPosition);
  7241. }
  7242. inYRange(mouseY, useFinalPosition) {
  7243. return inRange(this, null, mouseY, useFinalPosition);
  7244. }
  7245. getCenterPoint(useFinalPosition) {
  7246. const { x , y , base , horizontal } = this.getProps([
  7247. 'x',
  7248. 'y',
  7249. 'base',
  7250. 'horizontal'
  7251. ], useFinalPosition);
  7252. return {
  7253. x: horizontal ? (x + base) / 2 : x,
  7254. y: horizontal ? y : (y + base) / 2
  7255. };
  7256. }
  7257. getRange(axis) {
  7258. return axis === 'x' ? this.width / 2 : this.height / 2;
  7259. }
  7260. }
  7261. var elements = /*#__PURE__*/Object.freeze({
  7262. __proto__: null,
  7263. ArcElement: ArcElement,
  7264. BarElement: BarElement,
  7265. LineElement: LineElement,
  7266. PointElement: PointElement
  7267. });
  7268. const BORDER_COLORS = [
  7269. 'rgb(54, 162, 235)',
  7270. 'rgb(255, 99, 132)',
  7271. 'rgb(255, 159, 64)',
  7272. 'rgb(255, 205, 86)',
  7273. 'rgb(75, 192, 192)',
  7274. 'rgb(153, 102, 255)',
  7275. 'rgb(201, 203, 207)' // grey
  7276. ];
  7277. // Border colors with 50% transparency
  7278. const BACKGROUND_COLORS = /* #__PURE__ */ BORDER_COLORS.map((color)=>color.replace('rgb(', 'rgba(').replace(')', ', 0.5)'));
  7279. function getBorderColor(i) {
  7280. return BORDER_COLORS[i % BORDER_COLORS.length];
  7281. }
  7282. function getBackgroundColor(i) {
  7283. return BACKGROUND_COLORS[i % BACKGROUND_COLORS.length];
  7284. }
  7285. function colorizeDefaultDataset(dataset, i) {
  7286. dataset.borderColor = getBorderColor(i);
  7287. dataset.backgroundColor = getBackgroundColor(i);
  7288. return ++i;
  7289. }
  7290. function colorizeDoughnutDataset(dataset, i) {
  7291. dataset.backgroundColor = dataset.data.map(()=>getBorderColor(i++));
  7292. return i;
  7293. }
  7294. function colorizePolarAreaDataset(dataset, i) {
  7295. dataset.backgroundColor = dataset.data.map(()=>getBackgroundColor(i++));
  7296. return i;
  7297. }
  7298. function getColorizer(chart) {
  7299. let i = 0;
  7300. return (dataset, datasetIndex)=>{
  7301. const controller = chart.getDatasetMeta(datasetIndex).controller;
  7302. if (controller instanceof DoughnutController) {
  7303. i = colorizeDoughnutDataset(dataset, i);
  7304. } else if (controller instanceof PolarAreaController) {
  7305. i = colorizePolarAreaDataset(dataset, i);
  7306. } else if (controller) {
  7307. i = colorizeDefaultDataset(dataset, i);
  7308. }
  7309. };
  7310. }
  7311. function containsColorsDefinitions(descriptors) {
  7312. let k;
  7313. for(k in descriptors){
  7314. if (descriptors[k].borderColor || descriptors[k].backgroundColor) {
  7315. return true;
  7316. }
  7317. }
  7318. return false;
  7319. }
  7320. function containsColorsDefinition(descriptor) {
  7321. return descriptor && (descriptor.borderColor || descriptor.backgroundColor);
  7322. }
  7323. var plugin_colors = {
  7324. id: 'colors',
  7325. defaults: {
  7326. enabled: true,
  7327. forceOverride: false
  7328. },
  7329. beforeLayout (chart, _args, options) {
  7330. if (!options.enabled) {
  7331. return;
  7332. }
  7333. const { data: { datasets } , options: chartOptions } = chart.config;
  7334. const { elements } = chartOptions;
  7335. if (!options.forceOverride && (containsColorsDefinitions(datasets) || containsColorsDefinition(chartOptions) || elements && containsColorsDefinitions(elements))) {
  7336. return;
  7337. }
  7338. const colorizer = getColorizer(chart);
  7339. datasets.forEach(colorizer);
  7340. }
  7341. };
  7342. function lttbDecimation(data, start, count, availableWidth, options) {
  7343. const samples = options.samples || availableWidth;
  7344. if (samples >= count) {
  7345. return data.slice(start, start + count);
  7346. }
  7347. const decimated = [];
  7348. const bucketWidth = (count - 2) / (samples - 2);
  7349. let sampledIndex = 0;
  7350. const endIndex = start + count - 1;
  7351. let a = start;
  7352. let i, maxAreaPoint, maxArea, area, nextA;
  7353. decimated[sampledIndex++] = data[a];
  7354. for(i = 0; i < samples - 2; i++){
  7355. let avgX = 0;
  7356. let avgY = 0;
  7357. let j;
  7358. const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;
  7359. const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;
  7360. const avgRangeLength = avgRangeEnd - avgRangeStart;
  7361. for(j = avgRangeStart; j < avgRangeEnd; j++){
  7362. avgX += data[j].x;
  7363. avgY += data[j].y;
  7364. }
  7365. avgX /= avgRangeLength;
  7366. avgY /= avgRangeLength;
  7367. const rangeOffs = Math.floor(i * bucketWidth) + 1 + start;
  7368. const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start;
  7369. const { x: pointAx , y: pointAy } = data[a];
  7370. maxArea = area = -1;
  7371. for(j = rangeOffs; j < rangeTo; j++){
  7372. area = 0.5 * Math.abs((pointAx - avgX) * (data[j].y - pointAy) - (pointAx - data[j].x) * (avgY - pointAy));
  7373. if (area > maxArea) {
  7374. maxArea = area;
  7375. maxAreaPoint = data[j];
  7376. nextA = j;
  7377. }
  7378. }
  7379. decimated[sampledIndex++] = maxAreaPoint;
  7380. a = nextA;
  7381. }
  7382. decimated[sampledIndex++] = data[endIndex];
  7383. return decimated;
  7384. }
  7385. function minMaxDecimation(data, start, count, availableWidth) {
  7386. let avgX = 0;
  7387. let countX = 0;
  7388. let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;
  7389. const decimated = [];
  7390. const endIndex = start + count - 1;
  7391. const xMin = data[start].x;
  7392. const xMax = data[endIndex].x;
  7393. const dx = xMax - xMin;
  7394. for(i = start; i < start + count; ++i){
  7395. point = data[i];
  7396. x = (point.x - xMin) / dx * availableWidth;
  7397. y = point.y;
  7398. const truncX = x | 0;
  7399. if (truncX === prevX) {
  7400. if (y < minY) {
  7401. minY = y;
  7402. minIndex = i;
  7403. } else if (y > maxY) {
  7404. maxY = y;
  7405. maxIndex = i;
  7406. }
  7407. avgX = (countX * avgX + point.x) / ++countX;
  7408. } else {
  7409. const lastIndex = i - 1;
  7410. if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) {
  7411. const intermediateIndex1 = Math.min(minIndex, maxIndex);
  7412. const intermediateIndex2 = Math.max(minIndex, maxIndex);
  7413. if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {
  7414. decimated.push({
  7415. ...data[intermediateIndex1],
  7416. x: avgX
  7417. });
  7418. }
  7419. if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {
  7420. decimated.push({
  7421. ...data[intermediateIndex2],
  7422. x: avgX
  7423. });
  7424. }
  7425. }
  7426. if (i > 0 && lastIndex !== startIndex) {
  7427. decimated.push(data[lastIndex]);
  7428. }
  7429. decimated.push(point);
  7430. prevX = truncX;
  7431. countX = 0;
  7432. minY = maxY = y;
  7433. minIndex = maxIndex = startIndex = i;
  7434. }
  7435. }
  7436. return decimated;
  7437. }
  7438. function cleanDecimatedDataset(dataset) {
  7439. if (dataset._decimated) {
  7440. const data = dataset._data;
  7441. delete dataset._decimated;
  7442. delete dataset._data;
  7443. Object.defineProperty(dataset, 'data', {
  7444. configurable: true,
  7445. enumerable: true,
  7446. writable: true,
  7447. value: data
  7448. });
  7449. }
  7450. }
  7451. function cleanDecimatedData(chart) {
  7452. chart.data.datasets.forEach((dataset)=>{
  7453. cleanDecimatedDataset(dataset);
  7454. });
  7455. }
  7456. function getStartAndCountOfVisiblePointsSimplified(meta, points) {
  7457. const pointCount = points.length;
  7458. let start = 0;
  7459. let count;
  7460. const { iScale } = meta;
  7461. const { min , max , minDefined , maxDefined } = iScale.getUserBounds();
  7462. if (minDefined) {
  7463. start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);
  7464. }
  7465. if (maxDefined) {
  7466. count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;
  7467. } else {
  7468. count = pointCount - start;
  7469. }
  7470. return {
  7471. start,
  7472. count
  7473. };
  7474. }
  7475. var plugin_decimation = {
  7476. id: 'decimation',
  7477. defaults: {
  7478. algorithm: 'min-max',
  7479. enabled: false
  7480. },
  7481. beforeElementsUpdate: (chart, args, options)=>{
  7482. if (!options.enabled) {
  7483. cleanDecimatedData(chart);
  7484. return;
  7485. }
  7486. const availableWidth = chart.width;
  7487. chart.data.datasets.forEach((dataset, datasetIndex)=>{
  7488. const { _data , indexAxis } = dataset;
  7489. const meta = chart.getDatasetMeta(datasetIndex);
  7490. const data = _data || dataset.data;
  7491. if (resolve([
  7492. indexAxis,
  7493. chart.options.indexAxis
  7494. ]) === 'y') {
  7495. return;
  7496. }
  7497. if (!meta.controller.supportsDecimation) {
  7498. return;
  7499. }
  7500. const xAxis = chart.scales[meta.xAxisID];
  7501. if (xAxis.type !== 'linear' && xAxis.type !== 'time') {
  7502. return;
  7503. }
  7504. if (chart.options.parsing) {
  7505. return;
  7506. }
  7507. let { start , count } = getStartAndCountOfVisiblePointsSimplified(meta, data);
  7508. const threshold = options.threshold || 4 * availableWidth;
  7509. if (count <= threshold) {
  7510. cleanDecimatedDataset(dataset);
  7511. return;
  7512. }
  7513. if (isNullOrUndef(_data)) {
  7514. dataset._data = data;
  7515. delete dataset.data;
  7516. Object.defineProperty(dataset, 'data', {
  7517. configurable: true,
  7518. enumerable: true,
  7519. get: function() {
  7520. return this._decimated;
  7521. },
  7522. set: function(d) {
  7523. this._data = d;
  7524. }
  7525. });
  7526. }
  7527. let decimated;
  7528. switch(options.algorithm){
  7529. case 'lttb':
  7530. decimated = lttbDecimation(data, start, count, availableWidth, options);
  7531. break;
  7532. case 'min-max':
  7533. decimated = minMaxDecimation(data, start, count, availableWidth);
  7534. break;
  7535. default:
  7536. throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);
  7537. }
  7538. dataset._decimated = decimated;
  7539. });
  7540. },
  7541. destroy (chart) {
  7542. cleanDecimatedData(chart);
  7543. }
  7544. };
  7545. function _segments(line, target, property) {
  7546. const segments = line.segments;
  7547. const points = line.points;
  7548. const tpoints = target.points;
  7549. const parts = [];
  7550. for (const segment of segments){
  7551. let { start , end } = segment;
  7552. end = _findSegmentEnd(start, end, points);
  7553. const bounds = _getBounds(property, points[start], points[end], segment.loop);
  7554. if (!target.segments) {
  7555. parts.push({
  7556. source: segment,
  7557. target: bounds,
  7558. start: points[start],
  7559. end: points[end]
  7560. });
  7561. continue;
  7562. }
  7563. const targetSegments = _boundSegments(target, bounds);
  7564. for (const tgt of targetSegments){
  7565. const subBounds = _getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);
  7566. const fillSources = _boundSegment(segment, points, subBounds);
  7567. for (const fillSource of fillSources){
  7568. parts.push({
  7569. source: fillSource,
  7570. target: tgt,
  7571. start: {
  7572. [property]: _getEdge(bounds, subBounds, 'start', Math.max)
  7573. },
  7574. end: {
  7575. [property]: _getEdge(bounds, subBounds, 'end', Math.min)
  7576. }
  7577. });
  7578. }
  7579. }
  7580. }
  7581. return parts;
  7582. }
  7583. function _getBounds(property, first, last, loop) {
  7584. if (loop) {
  7585. return;
  7586. }
  7587. let start = first[property];
  7588. let end = last[property];
  7589. if (property === 'angle') {
  7590. start = _normalizeAngle(start);
  7591. end = _normalizeAngle(end);
  7592. }
  7593. return {
  7594. property,
  7595. start,
  7596. end
  7597. };
  7598. }
  7599. function _pointsFromSegments(boundary, line) {
  7600. const { x =null , y =null } = boundary || {};
  7601. const linePoints = line.points;
  7602. const points = [];
  7603. line.segments.forEach(({ start , end })=>{
  7604. end = _findSegmentEnd(start, end, linePoints);
  7605. const first = linePoints[start];
  7606. const last = linePoints[end];
  7607. if (y !== null) {
  7608. points.push({
  7609. x: first.x,
  7610. y
  7611. });
  7612. points.push({
  7613. x: last.x,
  7614. y
  7615. });
  7616. } else if (x !== null) {
  7617. points.push({
  7618. x,
  7619. y: first.y
  7620. });
  7621. points.push({
  7622. x,
  7623. y: last.y
  7624. });
  7625. }
  7626. });
  7627. return points;
  7628. }
  7629. function _findSegmentEnd(start, end, points) {
  7630. for(; end > start; end--){
  7631. const point = points[end];
  7632. if (!isNaN(point.x) && !isNaN(point.y)) {
  7633. break;
  7634. }
  7635. }
  7636. return end;
  7637. }
  7638. function _getEdge(a, b, prop, fn) {
  7639. if (a && b) {
  7640. return fn(a[prop], b[prop]);
  7641. }
  7642. return a ? a[prop] : b ? b[prop] : 0;
  7643. }
  7644. function _createBoundaryLine(boundary, line) {
  7645. let points = [];
  7646. let _loop = false;
  7647. if (isArray(boundary)) {
  7648. _loop = true;
  7649. points = boundary;
  7650. } else {
  7651. points = _pointsFromSegments(boundary, line);
  7652. }
  7653. return points.length ? new LineElement({
  7654. points,
  7655. options: {
  7656. tension: 0
  7657. },
  7658. _loop,
  7659. _fullLoop: _loop
  7660. }) : null;
  7661. }
  7662. function _shouldApplyFill(source) {
  7663. return source && source.fill !== false;
  7664. }
  7665. function _resolveTarget(sources, index, propagate) {
  7666. const source = sources[index];
  7667. let fill = source.fill;
  7668. const visited = [
  7669. index
  7670. ];
  7671. let target;
  7672. if (!propagate) {
  7673. return fill;
  7674. }
  7675. while(fill !== false && visited.indexOf(fill) === -1){
  7676. if (!isNumberFinite(fill)) {
  7677. return fill;
  7678. }
  7679. target = sources[fill];
  7680. if (!target) {
  7681. return false;
  7682. }
  7683. if (target.visible) {
  7684. return fill;
  7685. }
  7686. visited.push(fill);
  7687. fill = target.fill;
  7688. }
  7689. return false;
  7690. }
  7691. function _decodeFill(line, index, count) {
  7692. const fill = parseFillOption(line);
  7693. if (isObject(fill)) {
  7694. return isNaN(fill.value) ? false : fill;
  7695. }
  7696. let target = parseFloat(fill);
  7697. if (isNumberFinite(target) && Math.floor(target) === target) {
  7698. return decodeTargetIndex(fill[0], index, target, count);
  7699. }
  7700. return [
  7701. 'origin',
  7702. 'start',
  7703. 'end',
  7704. 'stack',
  7705. 'shape'
  7706. ].indexOf(fill) >= 0 && fill;
  7707. }
  7708. function decodeTargetIndex(firstCh, index, target, count) {
  7709. if (firstCh === '-' || firstCh === '+') {
  7710. target = index + target;
  7711. }
  7712. if (target === index || target < 0 || target >= count) {
  7713. return false;
  7714. }
  7715. return target;
  7716. }
  7717. function _getTargetPixel(fill, scale) {
  7718. let pixel = null;
  7719. if (fill === 'start') {
  7720. pixel = scale.bottom;
  7721. } else if (fill === 'end') {
  7722. pixel = scale.top;
  7723. } else if (isObject(fill)) {
  7724. pixel = scale.getPixelForValue(fill.value);
  7725. } else if (scale.getBasePixel) {
  7726. pixel = scale.getBasePixel();
  7727. }
  7728. return pixel;
  7729. }
  7730. function _getTargetValue(fill, scale, startValue) {
  7731. let value;
  7732. if (fill === 'start') {
  7733. value = startValue;
  7734. } else if (fill === 'end') {
  7735. value = scale.options.reverse ? scale.min : scale.max;
  7736. } else if (isObject(fill)) {
  7737. value = fill.value;
  7738. } else {
  7739. value = scale.getBaseValue();
  7740. }
  7741. return value;
  7742. }
  7743. function parseFillOption(line) {
  7744. const options = line.options;
  7745. const fillOption = options.fill;
  7746. let fill = valueOrDefault(fillOption && fillOption.target, fillOption);
  7747. if (fill === undefined) {
  7748. fill = !!options.backgroundColor;
  7749. }
  7750. if (fill === false || fill === null) {
  7751. return false;
  7752. }
  7753. if (fill === true) {
  7754. return 'origin';
  7755. }
  7756. return fill;
  7757. }
  7758. function _buildStackLine(source) {
  7759. const { scale , index , line } = source;
  7760. const points = [];
  7761. const segments = line.segments;
  7762. const sourcePoints = line.points;
  7763. const linesBelow = getLinesBelow(scale, index);
  7764. linesBelow.push(_createBoundaryLine({
  7765. x: null,
  7766. y: scale.bottom
  7767. }, line));
  7768. for(let i = 0; i < segments.length; i++){
  7769. const segment = segments[i];
  7770. for(let j = segment.start; j <= segment.end; j++){
  7771. addPointsBelow(points, sourcePoints[j], linesBelow);
  7772. }
  7773. }
  7774. return new LineElement({
  7775. points,
  7776. options: {}
  7777. });
  7778. }
  7779. function getLinesBelow(scale, index) {
  7780. const below = [];
  7781. const metas = scale.getMatchingVisibleMetas('line');
  7782. for(let i = 0; i < metas.length; i++){
  7783. const meta = metas[i];
  7784. if (meta.index === index) {
  7785. break;
  7786. }
  7787. if (!meta.hidden) {
  7788. below.unshift(meta.dataset);
  7789. }
  7790. }
  7791. return below;
  7792. }
  7793. function addPointsBelow(points, sourcePoint, linesBelow) {
  7794. const postponed = [];
  7795. for(let j = 0; j < linesBelow.length; j++){
  7796. const line = linesBelow[j];
  7797. const { first , last , point } = findPoint(line, sourcePoint, 'x');
  7798. if (!point || first && last) {
  7799. continue;
  7800. }
  7801. if (first) {
  7802. postponed.unshift(point);
  7803. } else {
  7804. points.push(point);
  7805. if (!last) {
  7806. break;
  7807. }
  7808. }
  7809. }
  7810. points.push(...postponed);
  7811. }
  7812. function findPoint(line, sourcePoint, property) {
  7813. const point = line.interpolate(sourcePoint, property);
  7814. if (!point) {
  7815. return {};
  7816. }
  7817. const pointValue = point[property];
  7818. const segments = line.segments;
  7819. const linePoints = line.points;
  7820. let first = false;
  7821. let last = false;
  7822. for(let i = 0; i < segments.length; i++){
  7823. const segment = segments[i];
  7824. const firstValue = linePoints[segment.start][property];
  7825. const lastValue = linePoints[segment.end][property];
  7826. if (_isBetween(pointValue, firstValue, lastValue)) {
  7827. first = pointValue === firstValue;
  7828. last = pointValue === lastValue;
  7829. break;
  7830. }
  7831. }
  7832. return {
  7833. first,
  7834. last,
  7835. point
  7836. };
  7837. }
  7838. class simpleArc {
  7839. constructor(opts){
  7840. this.x = opts.x;
  7841. this.y = opts.y;
  7842. this.radius = opts.radius;
  7843. }
  7844. pathSegment(ctx, bounds, opts) {
  7845. const { x , y , radius } = this;
  7846. bounds = bounds || {
  7847. start: 0,
  7848. end: TAU
  7849. };
  7850. ctx.arc(x, y, radius, bounds.end, bounds.start, true);
  7851. return !opts.bounds;
  7852. }
  7853. interpolate(point) {
  7854. const { x , y , radius } = this;
  7855. const angle = point.angle;
  7856. return {
  7857. x: x + Math.cos(angle) * radius,
  7858. y: y + Math.sin(angle) * radius,
  7859. angle
  7860. };
  7861. }
  7862. }
  7863. function _getTarget(source) {
  7864. const { chart , fill , line } = source;
  7865. if (isNumberFinite(fill)) {
  7866. return getLineByIndex(chart, fill);
  7867. }
  7868. if (fill === 'stack') {
  7869. return _buildStackLine(source);
  7870. }
  7871. if (fill === 'shape') {
  7872. return true;
  7873. }
  7874. const boundary = computeBoundary(source);
  7875. if (boundary instanceof simpleArc) {
  7876. return boundary;
  7877. }
  7878. return _createBoundaryLine(boundary, line);
  7879. }
  7880. function getLineByIndex(chart, index) {
  7881. const meta = chart.getDatasetMeta(index);
  7882. const visible = meta && chart.isDatasetVisible(index);
  7883. return visible ? meta.dataset : null;
  7884. }
  7885. function computeBoundary(source) {
  7886. const scale = source.scale || {};
  7887. if (scale.getPointPositionForValue) {
  7888. return computeCircularBoundary(source);
  7889. }
  7890. return computeLinearBoundary(source);
  7891. }
  7892. function computeLinearBoundary(source) {
  7893. const { scale ={} , fill } = source;
  7894. const pixel = _getTargetPixel(fill, scale);
  7895. if (isNumberFinite(pixel)) {
  7896. const horizontal = scale.isHorizontal();
  7897. return {
  7898. x: horizontal ? pixel : null,
  7899. y: horizontal ? null : pixel
  7900. };
  7901. }
  7902. return null;
  7903. }
  7904. function computeCircularBoundary(source) {
  7905. const { scale , fill } = source;
  7906. const options = scale.options;
  7907. const length = scale.getLabels().length;
  7908. const start = options.reverse ? scale.max : scale.min;
  7909. const value = _getTargetValue(fill, scale, start);
  7910. const target = [];
  7911. if (options.grid.circular) {
  7912. const center = scale.getPointPositionForValue(0, start);
  7913. return new simpleArc({
  7914. x: center.x,
  7915. y: center.y,
  7916. radius: scale.getDistanceFromCenterForValue(value)
  7917. });
  7918. }
  7919. for(let i = 0; i < length; ++i){
  7920. target.push(scale.getPointPositionForValue(i, value));
  7921. }
  7922. return target;
  7923. }
  7924. function _drawfill(ctx, source, area) {
  7925. const target = _getTarget(source);
  7926. const { line , scale , axis } = source;
  7927. const lineOpts = line.options;
  7928. const fillOption = lineOpts.fill;
  7929. const color = lineOpts.backgroundColor;
  7930. const { above =color , below =color } = fillOption || {};
  7931. if (target && line.points.length) {
  7932. clipArea(ctx, area);
  7933. doFill(ctx, {
  7934. line,
  7935. target,
  7936. above,
  7937. below,
  7938. area,
  7939. scale,
  7940. axis
  7941. });
  7942. unclipArea(ctx);
  7943. }
  7944. }
  7945. function doFill(ctx, cfg) {
  7946. const { line , target , above , below , area , scale } = cfg;
  7947. const property = line._loop ? 'angle' : cfg.axis;
  7948. ctx.save();
  7949. if (property === 'x' && below !== above) {
  7950. clipVertical(ctx, target, area.top);
  7951. fill(ctx, {
  7952. line,
  7953. target,
  7954. color: above,
  7955. scale,
  7956. property
  7957. });
  7958. ctx.restore();
  7959. ctx.save();
  7960. clipVertical(ctx, target, area.bottom);
  7961. }
  7962. fill(ctx, {
  7963. line,
  7964. target,
  7965. color: below,
  7966. scale,
  7967. property
  7968. });
  7969. ctx.restore();
  7970. }
  7971. function clipVertical(ctx, target, clipY) {
  7972. const { segments , points } = target;
  7973. let first = true;
  7974. let lineLoop = false;
  7975. ctx.beginPath();
  7976. for (const segment of segments){
  7977. const { start , end } = segment;
  7978. const firstPoint = points[start];
  7979. const lastPoint = points[_findSegmentEnd(start, end, points)];
  7980. if (first) {
  7981. ctx.moveTo(firstPoint.x, firstPoint.y);
  7982. first = false;
  7983. } else {
  7984. ctx.lineTo(firstPoint.x, clipY);
  7985. ctx.lineTo(firstPoint.x, firstPoint.y);
  7986. }
  7987. lineLoop = !!target.pathSegment(ctx, segment, {
  7988. move: lineLoop
  7989. });
  7990. if (lineLoop) {
  7991. ctx.closePath();
  7992. } else {
  7993. ctx.lineTo(lastPoint.x, clipY);
  7994. }
  7995. }
  7996. ctx.lineTo(target.first().x, clipY);
  7997. ctx.closePath();
  7998. ctx.clip();
  7999. }
  8000. function fill(ctx, cfg) {
  8001. const { line , target , property , color , scale } = cfg;
  8002. const segments = _segments(line, target, property);
  8003. for (const { source: src , target: tgt , start , end } of segments){
  8004. const { style: { backgroundColor =color } = {} } = src;
  8005. const notShape = target !== true;
  8006. ctx.save();
  8007. ctx.fillStyle = backgroundColor;
  8008. clipBounds(ctx, scale, notShape && _getBounds(property, start, end));
  8009. ctx.beginPath();
  8010. const lineLoop = !!line.pathSegment(ctx, src);
  8011. let loop;
  8012. if (notShape) {
  8013. if (lineLoop) {
  8014. ctx.closePath();
  8015. } else {
  8016. interpolatedLineTo(ctx, target, end, property);
  8017. }
  8018. const targetLoop = !!target.pathSegment(ctx, tgt, {
  8019. move: lineLoop,
  8020. reverse: true
  8021. });
  8022. loop = lineLoop && targetLoop;
  8023. if (!loop) {
  8024. interpolatedLineTo(ctx, target, start, property);
  8025. }
  8026. }
  8027. ctx.closePath();
  8028. ctx.fill(loop ? 'evenodd' : 'nonzero');
  8029. ctx.restore();
  8030. }
  8031. }
  8032. function clipBounds(ctx, scale, bounds) {
  8033. const { top , bottom } = scale.chart.chartArea;
  8034. const { property , start , end } = bounds || {};
  8035. if (property === 'x') {
  8036. ctx.beginPath();
  8037. ctx.rect(start, top, end - start, bottom - top);
  8038. ctx.clip();
  8039. }
  8040. }
  8041. function interpolatedLineTo(ctx, target, point, property) {
  8042. const interpolatedPoint = target.interpolate(point, property);
  8043. if (interpolatedPoint) {
  8044. ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);
  8045. }
  8046. }
  8047. var index = {
  8048. id: 'filler',
  8049. afterDatasetsUpdate (chart, _args, options) {
  8050. const count = (chart.data.datasets || []).length;
  8051. const sources = [];
  8052. let meta, i, line, source;
  8053. for(i = 0; i < count; ++i){
  8054. meta = chart.getDatasetMeta(i);
  8055. line = meta.dataset;
  8056. source = null;
  8057. if (line && line.options && line instanceof LineElement) {
  8058. source = {
  8059. visible: chart.isDatasetVisible(i),
  8060. index: i,
  8061. fill: _decodeFill(line, i, count),
  8062. chart,
  8063. axis: meta.controller.options.indexAxis,
  8064. scale: meta.vScale,
  8065. line
  8066. };
  8067. }
  8068. meta.$filler = source;
  8069. sources.push(source);
  8070. }
  8071. for(i = 0; i < count; ++i){
  8072. source = sources[i];
  8073. if (!source || source.fill === false) {
  8074. continue;
  8075. }
  8076. source.fill = _resolveTarget(sources, i, options.propagate);
  8077. }
  8078. },
  8079. beforeDraw (chart, _args, options) {
  8080. const draw = options.drawTime === 'beforeDraw';
  8081. const metasets = chart.getSortedVisibleDatasetMetas();
  8082. const area = chart.chartArea;
  8083. for(let i = metasets.length - 1; i >= 0; --i){
  8084. const source = metasets[i].$filler;
  8085. if (!source) {
  8086. continue;
  8087. }
  8088. source.line.updateControlPoints(area, source.axis);
  8089. if (draw && source.fill) {
  8090. _drawfill(chart.ctx, source, area);
  8091. }
  8092. }
  8093. },
  8094. beforeDatasetsDraw (chart, _args, options) {
  8095. if (options.drawTime !== 'beforeDatasetsDraw') {
  8096. return;
  8097. }
  8098. const metasets = chart.getSortedVisibleDatasetMetas();
  8099. for(let i = metasets.length - 1; i >= 0; --i){
  8100. const source = metasets[i].$filler;
  8101. if (_shouldApplyFill(source)) {
  8102. _drawfill(chart.ctx, source, chart.chartArea);
  8103. }
  8104. }
  8105. },
  8106. beforeDatasetDraw (chart, args, options) {
  8107. const source = args.meta.$filler;
  8108. if (!_shouldApplyFill(source) || options.drawTime !== 'beforeDatasetDraw') {
  8109. return;
  8110. }
  8111. _drawfill(chart.ctx, source, chart.chartArea);
  8112. },
  8113. defaults: {
  8114. propagate: true,
  8115. drawTime: 'beforeDatasetDraw'
  8116. }
  8117. };
  8118. const getBoxSize = (labelOpts, fontSize)=>{
  8119. let { boxHeight =fontSize , boxWidth =fontSize } = labelOpts;
  8120. if (labelOpts.usePointStyle) {
  8121. boxHeight = Math.min(boxHeight, fontSize);
  8122. boxWidth = labelOpts.pointStyleWidth || Math.min(boxWidth, fontSize);
  8123. }
  8124. return {
  8125. boxWidth,
  8126. boxHeight,
  8127. itemHeight: Math.max(fontSize, boxHeight)
  8128. };
  8129. };
  8130. const itemsEqual = (a, b)=>a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;
  8131. class Legend extends Element {
  8132. constructor(config){
  8133. super();
  8134. this._added = false;
  8135. this.legendHitBoxes = [];
  8136. this._hoveredItem = null;
  8137. this.doughnutMode = false;
  8138. this.chart = config.chart;
  8139. this.options = config.options;
  8140. this.ctx = config.ctx;
  8141. this.legendItems = undefined;
  8142. this.columnSizes = undefined;
  8143. this.lineWidths = undefined;
  8144. this.maxHeight = undefined;
  8145. this.maxWidth = undefined;
  8146. this.top = undefined;
  8147. this.bottom = undefined;
  8148. this.left = undefined;
  8149. this.right = undefined;
  8150. this.height = undefined;
  8151. this.width = undefined;
  8152. this._margins = undefined;
  8153. this.position = undefined;
  8154. this.weight = undefined;
  8155. this.fullSize = undefined;
  8156. }
  8157. update(maxWidth, maxHeight, margins) {
  8158. this.maxWidth = maxWidth;
  8159. this.maxHeight = maxHeight;
  8160. this._margins = margins;
  8161. this.setDimensions();
  8162. this.buildLabels();
  8163. this.fit();
  8164. }
  8165. setDimensions() {
  8166. if (this.isHorizontal()) {
  8167. this.width = this.maxWidth;
  8168. this.left = this._margins.left;
  8169. this.right = this.width;
  8170. } else {
  8171. this.height = this.maxHeight;
  8172. this.top = this._margins.top;
  8173. this.bottom = this.height;
  8174. }
  8175. }
  8176. buildLabels() {
  8177. const labelOpts = this.options.labels || {};
  8178. let legendItems = callback(labelOpts.generateLabels, [
  8179. this.chart
  8180. ], this) || [];
  8181. if (labelOpts.filter) {
  8182. legendItems = legendItems.filter((item)=>labelOpts.filter(item, this.chart.data));
  8183. }
  8184. if (labelOpts.sort) {
  8185. legendItems = legendItems.sort((a, b)=>labelOpts.sort(a, b, this.chart.data));
  8186. }
  8187. if (this.options.reverse) {
  8188. legendItems.reverse();
  8189. }
  8190. this.legendItems = legendItems;
  8191. }
  8192. fit() {
  8193. const { options , ctx } = this;
  8194. if (!options.display) {
  8195. this.width = this.height = 0;
  8196. return;
  8197. }
  8198. const labelOpts = options.labels;
  8199. const labelFont = toFont(labelOpts.font);
  8200. const fontSize = labelFont.size;
  8201. const titleHeight = this._computeTitleHeight();
  8202. const { boxWidth , itemHeight } = getBoxSize(labelOpts, fontSize);
  8203. let width, height;
  8204. ctx.font = labelFont.string;
  8205. if (this.isHorizontal()) {
  8206. width = this.maxWidth;
  8207. height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;
  8208. } else {
  8209. height = this.maxHeight;
  8210. width = this._fitCols(titleHeight, labelFont, boxWidth, itemHeight) + 10;
  8211. }
  8212. this.width = Math.min(width, options.maxWidth || this.maxWidth);
  8213. this.height = Math.min(height, options.maxHeight || this.maxHeight);
  8214. }
  8215. _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {
  8216. const { ctx , maxWidth , options: { labels: { padding } } } = this;
  8217. const hitboxes = this.legendHitBoxes = [];
  8218. const lineWidths = this.lineWidths = [
  8219. 0
  8220. ];
  8221. const lineHeight = itemHeight + padding;
  8222. let totalHeight = titleHeight;
  8223. ctx.textAlign = 'left';
  8224. ctx.textBaseline = 'middle';
  8225. let row = -1;
  8226. let top = -lineHeight;
  8227. this.legendItems.forEach((legendItem, i)=>{
  8228. const itemWidth = boxWidth + fontSize / 2 + ctx.measureText(legendItem.text).width;
  8229. if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {
  8230. totalHeight += lineHeight;
  8231. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  8232. top += lineHeight;
  8233. row++;
  8234. }
  8235. hitboxes[i] = {
  8236. left: 0,
  8237. top,
  8238. row,
  8239. width: itemWidth,
  8240. height: itemHeight
  8241. };
  8242. lineWidths[lineWidths.length - 1] += itemWidth + padding;
  8243. });
  8244. return totalHeight;
  8245. }
  8246. _fitCols(titleHeight, labelFont, boxWidth, _itemHeight) {
  8247. const { ctx , maxHeight , options: { labels: { padding } } } = this;
  8248. const hitboxes = this.legendHitBoxes = [];
  8249. const columnSizes = this.columnSizes = [];
  8250. const heightLimit = maxHeight - titleHeight;
  8251. let totalWidth = padding;
  8252. let currentColWidth = 0;
  8253. let currentColHeight = 0;
  8254. let left = 0;
  8255. let col = 0;
  8256. this.legendItems.forEach((legendItem, i)=>{
  8257. const { itemWidth , itemHeight } = calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight);
  8258. if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) {
  8259. totalWidth += currentColWidth + padding;
  8260. columnSizes.push({
  8261. width: currentColWidth,
  8262. height: currentColHeight
  8263. });
  8264. left += currentColWidth + padding;
  8265. col++;
  8266. currentColWidth = currentColHeight = 0;
  8267. }
  8268. hitboxes[i] = {
  8269. left,
  8270. top: currentColHeight,
  8271. col,
  8272. width: itemWidth,
  8273. height: itemHeight
  8274. };
  8275. currentColWidth = Math.max(currentColWidth, itemWidth);
  8276. currentColHeight += itemHeight + padding;
  8277. });
  8278. totalWidth += currentColWidth;
  8279. columnSizes.push({
  8280. width: currentColWidth,
  8281. height: currentColHeight
  8282. });
  8283. return totalWidth;
  8284. }
  8285. adjustHitBoxes() {
  8286. if (!this.options.display) {
  8287. return;
  8288. }
  8289. const titleHeight = this._computeTitleHeight();
  8290. const { legendHitBoxes: hitboxes , options: { align , labels: { padding } , rtl } } = this;
  8291. const rtlHelper = getRtlAdapter(rtl, this.left, this.width);
  8292. if (this.isHorizontal()) {
  8293. let row = 0;
  8294. let left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);
  8295. for (const hitbox of hitboxes){
  8296. if (row !== hitbox.row) {
  8297. row = hitbox.row;
  8298. left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);
  8299. }
  8300. hitbox.top += this.top + titleHeight + padding;
  8301. hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width);
  8302. left += hitbox.width + padding;
  8303. }
  8304. } else {
  8305. let col = 0;
  8306. let top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);
  8307. for (const hitbox of hitboxes){
  8308. if (hitbox.col !== col) {
  8309. col = hitbox.col;
  8310. top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);
  8311. }
  8312. hitbox.top = top;
  8313. hitbox.left += this.left + padding;
  8314. hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width);
  8315. top += hitbox.height + padding;
  8316. }
  8317. }
  8318. }
  8319. isHorizontal() {
  8320. return this.options.position === 'top' || this.options.position === 'bottom';
  8321. }
  8322. draw() {
  8323. if (this.options.display) {
  8324. const ctx = this.ctx;
  8325. clipArea(ctx, this);
  8326. this._draw();
  8327. unclipArea(ctx);
  8328. }
  8329. }
  8330. _draw() {
  8331. const { options: opts , columnSizes , lineWidths , ctx } = this;
  8332. const { align , labels: labelOpts } = opts;
  8333. const defaultColor = defaults.color;
  8334. const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);
  8335. const labelFont = toFont(labelOpts.font);
  8336. const { padding } = labelOpts;
  8337. const fontSize = labelFont.size;
  8338. const halfFontSize = fontSize / 2;
  8339. let cursor;
  8340. this.drawTitle();
  8341. ctx.textAlign = rtlHelper.textAlign('left');
  8342. ctx.textBaseline = 'middle';
  8343. ctx.lineWidth = 0.5;
  8344. ctx.font = labelFont.string;
  8345. const { boxWidth , boxHeight , itemHeight } = getBoxSize(labelOpts, fontSize);
  8346. const drawLegendBox = function(x, y, legendItem) {
  8347. if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {
  8348. return;
  8349. }
  8350. ctx.save();
  8351. const lineWidth = valueOrDefault(legendItem.lineWidth, 1);
  8352. ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);
  8353. ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt');
  8354. ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0);
  8355. ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter');
  8356. ctx.lineWidth = lineWidth;
  8357. ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor);
  8358. ctx.setLineDash(valueOrDefault(legendItem.lineDash, []));
  8359. if (labelOpts.usePointStyle) {
  8360. const drawOptions = {
  8361. radius: boxHeight * Math.SQRT2 / 2,
  8362. pointStyle: legendItem.pointStyle,
  8363. rotation: legendItem.rotation,
  8364. borderWidth: lineWidth
  8365. };
  8366. const centerX = rtlHelper.xPlus(x, boxWidth / 2);
  8367. const centerY = y + halfFontSize;
  8368. drawPointLegend(ctx, drawOptions, centerX, centerY, labelOpts.pointStyleWidth && boxWidth);
  8369. } else {
  8370. const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);
  8371. const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);
  8372. const borderRadius = toTRBLCorners(legendItem.borderRadius);
  8373. ctx.beginPath();
  8374. if (Object.values(borderRadius).some((v)=>v !== 0)) {
  8375. addRoundedRectPath(ctx, {
  8376. x: xBoxLeft,
  8377. y: yBoxTop,
  8378. w: boxWidth,
  8379. h: boxHeight,
  8380. radius: borderRadius
  8381. });
  8382. } else {
  8383. ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);
  8384. }
  8385. ctx.fill();
  8386. if (lineWidth !== 0) {
  8387. ctx.stroke();
  8388. }
  8389. }
  8390. ctx.restore();
  8391. };
  8392. const fillText = function(x, y, legendItem) {
  8393. renderText(ctx, legendItem.text, x, y + itemHeight / 2, labelFont, {
  8394. strikethrough: legendItem.hidden,
  8395. textAlign: rtlHelper.textAlign(legendItem.textAlign)
  8396. });
  8397. };
  8398. const isHorizontal = this.isHorizontal();
  8399. const titleHeight = this._computeTitleHeight();
  8400. if (isHorizontal) {
  8401. cursor = {
  8402. x: _alignStartEnd(align, this.left + padding, this.right - lineWidths[0]),
  8403. y: this.top + padding + titleHeight,
  8404. line: 0
  8405. };
  8406. } else {
  8407. cursor = {
  8408. x: this.left + padding,
  8409. y: _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height),
  8410. line: 0
  8411. };
  8412. }
  8413. overrideTextDirection(this.ctx, opts.textDirection);
  8414. const lineHeight = itemHeight + padding;
  8415. this.legendItems.forEach((legendItem, i)=>{
  8416. ctx.strokeStyle = legendItem.fontColor;
  8417. ctx.fillStyle = legendItem.fontColor;
  8418. const textWidth = ctx.measureText(legendItem.text).width;
  8419. const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));
  8420. const width = boxWidth + halfFontSize + textWidth;
  8421. let x = cursor.x;
  8422. let y = cursor.y;
  8423. rtlHelper.setWidth(this.width);
  8424. if (isHorizontal) {
  8425. if (i > 0 && x + width + padding > this.right) {
  8426. y = cursor.y += lineHeight;
  8427. cursor.line++;
  8428. x = cursor.x = _alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]);
  8429. }
  8430. } else if (i > 0 && y + lineHeight > this.bottom) {
  8431. x = cursor.x = x + columnSizes[cursor.line].width + padding;
  8432. cursor.line++;
  8433. y = cursor.y = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height);
  8434. }
  8435. const realX = rtlHelper.x(x);
  8436. drawLegendBox(realX, y, legendItem);
  8437. x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl);
  8438. fillText(rtlHelper.x(x), y, legendItem);
  8439. if (isHorizontal) {
  8440. cursor.x += width + padding;
  8441. } else if (typeof legendItem.text !== 'string') {
  8442. const fontLineHeight = labelFont.lineHeight;
  8443. cursor.y += calculateLegendItemHeight(legendItem, fontLineHeight) + padding;
  8444. } else {
  8445. cursor.y += lineHeight;
  8446. }
  8447. });
  8448. restoreTextDirection(this.ctx, opts.textDirection);
  8449. }
  8450. drawTitle() {
  8451. const opts = this.options;
  8452. const titleOpts = opts.title;
  8453. const titleFont = toFont(titleOpts.font);
  8454. const titlePadding = toPadding(titleOpts.padding);
  8455. if (!titleOpts.display) {
  8456. return;
  8457. }
  8458. const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);
  8459. const ctx = this.ctx;
  8460. const position = titleOpts.position;
  8461. const halfFontSize = titleFont.size / 2;
  8462. const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;
  8463. let y;
  8464. let left = this.left;
  8465. let maxWidth = this.width;
  8466. if (this.isHorizontal()) {
  8467. maxWidth = Math.max(...this.lineWidths);
  8468. y = this.top + topPaddingPlusHalfFontSize;
  8469. left = _alignStartEnd(opts.align, left, this.right - maxWidth);
  8470. } else {
  8471. const maxHeight = this.columnSizes.reduce((acc, size)=>Math.max(acc, size.height), 0);
  8472. y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight());
  8473. }
  8474. const x = _alignStartEnd(position, left, left + maxWidth);
  8475. ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position));
  8476. ctx.textBaseline = 'middle';
  8477. ctx.strokeStyle = titleOpts.color;
  8478. ctx.fillStyle = titleOpts.color;
  8479. ctx.font = titleFont.string;
  8480. renderText(ctx, titleOpts.text, x, y, titleFont);
  8481. }
  8482. _computeTitleHeight() {
  8483. const titleOpts = this.options.title;
  8484. const titleFont = toFont(titleOpts.font);
  8485. const titlePadding = toPadding(titleOpts.padding);
  8486. return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
  8487. }
  8488. _getLegendItemAt(x, y) {
  8489. let i, hitBox, lh;
  8490. if (_isBetween(x, this.left, this.right) && _isBetween(y, this.top, this.bottom)) {
  8491. lh = this.legendHitBoxes;
  8492. for(i = 0; i < lh.length; ++i){
  8493. hitBox = lh[i];
  8494. if (_isBetween(x, hitBox.left, hitBox.left + hitBox.width) && _isBetween(y, hitBox.top, hitBox.top + hitBox.height)) {
  8495. return this.legendItems[i];
  8496. }
  8497. }
  8498. }
  8499. return null;
  8500. }
  8501. handleEvent(e) {
  8502. const opts = this.options;
  8503. if (!isListened(e.type, opts)) {
  8504. return;
  8505. }
  8506. const hoveredItem = this._getLegendItemAt(e.x, e.y);
  8507. if (e.type === 'mousemove' || e.type === 'mouseout') {
  8508. const previous = this._hoveredItem;
  8509. const sameItem = itemsEqual(previous, hoveredItem);
  8510. if (previous && !sameItem) {
  8511. callback(opts.onLeave, [
  8512. e,
  8513. previous,
  8514. this
  8515. ], this);
  8516. }
  8517. this._hoveredItem = hoveredItem;
  8518. if (hoveredItem && !sameItem) {
  8519. callback(opts.onHover, [
  8520. e,
  8521. hoveredItem,
  8522. this
  8523. ], this);
  8524. }
  8525. } else if (hoveredItem) {
  8526. callback(opts.onClick, [
  8527. e,
  8528. hoveredItem,
  8529. this
  8530. ], this);
  8531. }
  8532. }
  8533. }
  8534. function calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight) {
  8535. const itemWidth = calculateItemWidth(legendItem, boxWidth, labelFont, ctx);
  8536. const itemHeight = calculateItemHeight(_itemHeight, legendItem, labelFont.lineHeight);
  8537. return {
  8538. itemWidth,
  8539. itemHeight
  8540. };
  8541. }
  8542. function calculateItemWidth(legendItem, boxWidth, labelFont, ctx) {
  8543. let legendItemText = legendItem.text;
  8544. if (legendItemText && typeof legendItemText !== 'string') {
  8545. legendItemText = legendItemText.reduce((a, b)=>a.length > b.length ? a : b);
  8546. }
  8547. return boxWidth + labelFont.size / 2 + ctx.measureText(legendItemText).width;
  8548. }
  8549. function calculateItemHeight(_itemHeight, legendItem, fontLineHeight) {
  8550. let itemHeight = _itemHeight;
  8551. if (typeof legendItem.text !== 'string') {
  8552. itemHeight = calculateLegendItemHeight(legendItem, fontLineHeight);
  8553. }
  8554. return itemHeight;
  8555. }
  8556. function calculateLegendItemHeight(legendItem, fontLineHeight) {
  8557. const labelHeight = legendItem.text ? legendItem.text.length : 0;
  8558. return fontLineHeight * labelHeight;
  8559. }
  8560. function isListened(type, opts) {
  8561. if ((type === 'mousemove' || type === 'mouseout') && (opts.onHover || opts.onLeave)) {
  8562. return true;
  8563. }
  8564. if (opts.onClick && (type === 'click' || type === 'mouseup')) {
  8565. return true;
  8566. }
  8567. return false;
  8568. }
  8569. var plugin_legend = {
  8570. id: 'legend',
  8571. _element: Legend,
  8572. start (chart, _args, options) {
  8573. const legend = chart.legend = new Legend({
  8574. ctx: chart.ctx,
  8575. options,
  8576. chart
  8577. });
  8578. layouts.configure(chart, legend, options);
  8579. layouts.addBox(chart, legend);
  8580. },
  8581. stop (chart) {
  8582. layouts.removeBox(chart, chart.legend);
  8583. delete chart.legend;
  8584. },
  8585. beforeUpdate (chart, _args, options) {
  8586. const legend = chart.legend;
  8587. layouts.configure(chart, legend, options);
  8588. legend.options = options;
  8589. },
  8590. afterUpdate (chart) {
  8591. const legend = chart.legend;
  8592. legend.buildLabels();
  8593. legend.adjustHitBoxes();
  8594. },
  8595. afterEvent (chart, args) {
  8596. if (!args.replay) {
  8597. chart.legend.handleEvent(args.event);
  8598. }
  8599. },
  8600. defaults: {
  8601. display: true,
  8602. position: 'top',
  8603. align: 'center',
  8604. fullSize: true,
  8605. reverse: false,
  8606. weight: 1000,
  8607. onClick (e, legendItem, legend) {
  8608. const index = legendItem.datasetIndex;
  8609. const ci = legend.chart;
  8610. if (ci.isDatasetVisible(index)) {
  8611. ci.hide(index);
  8612. legendItem.hidden = true;
  8613. } else {
  8614. ci.show(index);
  8615. legendItem.hidden = false;
  8616. }
  8617. },
  8618. onHover: null,
  8619. onLeave: null,
  8620. labels: {
  8621. color: (ctx)=>ctx.chart.options.color,
  8622. boxWidth: 40,
  8623. padding: 10,
  8624. generateLabels (chart) {
  8625. const datasets = chart.data.datasets;
  8626. const { labels: { usePointStyle , pointStyle , textAlign , color , useBorderRadius , borderRadius } } = chart.legend.options;
  8627. return chart._getSortedDatasetMetas().map((meta)=>{
  8628. const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  8629. const borderWidth = toPadding(style.borderWidth);
  8630. return {
  8631. text: datasets[meta.index].label,
  8632. fillStyle: style.backgroundColor,
  8633. fontColor: color,
  8634. hidden: !meta.visible,
  8635. lineCap: style.borderCapStyle,
  8636. lineDash: style.borderDash,
  8637. lineDashOffset: style.borderDashOffset,
  8638. lineJoin: style.borderJoinStyle,
  8639. lineWidth: (borderWidth.width + borderWidth.height) / 4,
  8640. strokeStyle: style.borderColor,
  8641. pointStyle: pointStyle || style.pointStyle,
  8642. rotation: style.rotation,
  8643. textAlign: textAlign || style.textAlign,
  8644. borderRadius: useBorderRadius && (borderRadius || style.borderRadius),
  8645. datasetIndex: meta.index
  8646. };
  8647. }, this);
  8648. }
  8649. },
  8650. title: {
  8651. color: (ctx)=>ctx.chart.options.color,
  8652. display: false,
  8653. position: 'center',
  8654. text: ''
  8655. }
  8656. },
  8657. descriptors: {
  8658. _scriptable: (name)=>!name.startsWith('on'),
  8659. labels: {
  8660. _scriptable: (name)=>![
  8661. 'generateLabels',
  8662. 'filter',
  8663. 'sort'
  8664. ].includes(name)
  8665. }
  8666. }
  8667. };
  8668. class Title extends Element {
  8669. constructor(config){
  8670. super();
  8671. this.chart = config.chart;
  8672. this.options = config.options;
  8673. this.ctx = config.ctx;
  8674. this._padding = undefined;
  8675. this.top = undefined;
  8676. this.bottom = undefined;
  8677. this.left = undefined;
  8678. this.right = undefined;
  8679. this.width = undefined;
  8680. this.height = undefined;
  8681. this.position = undefined;
  8682. this.weight = undefined;
  8683. this.fullSize = undefined;
  8684. }
  8685. update(maxWidth, maxHeight) {
  8686. const opts = this.options;
  8687. this.left = 0;
  8688. this.top = 0;
  8689. if (!opts.display) {
  8690. this.width = this.height = this.right = this.bottom = 0;
  8691. return;
  8692. }
  8693. this.width = this.right = maxWidth;
  8694. this.height = this.bottom = maxHeight;
  8695. const lineCount = isArray(opts.text) ? opts.text.length : 1;
  8696. this._padding = toPadding(opts.padding);
  8697. const textSize = lineCount * toFont(opts.font).lineHeight + this._padding.height;
  8698. if (this.isHorizontal()) {
  8699. this.height = textSize;
  8700. } else {
  8701. this.width = textSize;
  8702. }
  8703. }
  8704. isHorizontal() {
  8705. const pos = this.options.position;
  8706. return pos === 'top' || pos === 'bottom';
  8707. }
  8708. _drawArgs(offset) {
  8709. const { top , left , bottom , right , options } = this;
  8710. const align = options.align;
  8711. let rotation = 0;
  8712. let maxWidth, titleX, titleY;
  8713. if (this.isHorizontal()) {
  8714. titleX = _alignStartEnd(align, left, right);
  8715. titleY = top + offset;
  8716. maxWidth = right - left;
  8717. } else {
  8718. if (options.position === 'left') {
  8719. titleX = left + offset;
  8720. titleY = _alignStartEnd(align, bottom, top);
  8721. rotation = PI * -0.5;
  8722. } else {
  8723. titleX = right - offset;
  8724. titleY = _alignStartEnd(align, top, bottom);
  8725. rotation = PI * 0.5;
  8726. }
  8727. maxWidth = bottom - top;
  8728. }
  8729. return {
  8730. titleX,
  8731. titleY,
  8732. maxWidth,
  8733. rotation
  8734. };
  8735. }
  8736. draw() {
  8737. const ctx = this.ctx;
  8738. const opts = this.options;
  8739. if (!opts.display) {
  8740. return;
  8741. }
  8742. const fontOpts = toFont(opts.font);
  8743. const lineHeight = fontOpts.lineHeight;
  8744. const offset = lineHeight / 2 + this._padding.top;
  8745. const { titleX , titleY , maxWidth , rotation } = this._drawArgs(offset);
  8746. renderText(ctx, opts.text, 0, 0, fontOpts, {
  8747. color: opts.color,
  8748. maxWidth,
  8749. rotation,
  8750. textAlign: _toLeftRightCenter(opts.align),
  8751. textBaseline: 'middle',
  8752. translation: [
  8753. titleX,
  8754. titleY
  8755. ]
  8756. });
  8757. }
  8758. }
  8759. function createTitle(chart, titleOpts) {
  8760. const title = new Title({
  8761. ctx: chart.ctx,
  8762. options: titleOpts,
  8763. chart
  8764. });
  8765. layouts.configure(chart, title, titleOpts);
  8766. layouts.addBox(chart, title);
  8767. chart.titleBlock = title;
  8768. }
  8769. var plugin_title = {
  8770. id: 'title',
  8771. _element: Title,
  8772. start (chart, _args, options) {
  8773. createTitle(chart, options);
  8774. },
  8775. stop (chart) {
  8776. const titleBlock = chart.titleBlock;
  8777. layouts.removeBox(chart, titleBlock);
  8778. delete chart.titleBlock;
  8779. },
  8780. beforeUpdate (chart, _args, options) {
  8781. const title = chart.titleBlock;
  8782. layouts.configure(chart, title, options);
  8783. title.options = options;
  8784. },
  8785. defaults: {
  8786. align: 'center',
  8787. display: false,
  8788. font: {
  8789. weight: 'bold'
  8790. },
  8791. fullSize: true,
  8792. padding: 10,
  8793. position: 'top',
  8794. text: '',
  8795. weight: 2000
  8796. },
  8797. defaultRoutes: {
  8798. color: 'color'
  8799. },
  8800. descriptors: {
  8801. _scriptable: true,
  8802. _indexable: false
  8803. }
  8804. };
  8805. const map = new WeakMap();
  8806. var plugin_subtitle = {
  8807. id: 'subtitle',
  8808. start (chart, _args, options) {
  8809. const title = new Title({
  8810. ctx: chart.ctx,
  8811. options,
  8812. chart
  8813. });
  8814. layouts.configure(chart, title, options);
  8815. layouts.addBox(chart, title);
  8816. map.set(chart, title);
  8817. },
  8818. stop (chart) {
  8819. layouts.removeBox(chart, map.get(chart));
  8820. map.delete(chart);
  8821. },
  8822. beforeUpdate (chart, _args, options) {
  8823. const title = map.get(chart);
  8824. layouts.configure(chart, title, options);
  8825. title.options = options;
  8826. },
  8827. defaults: {
  8828. align: 'center',
  8829. display: false,
  8830. font: {
  8831. weight: 'normal'
  8832. },
  8833. fullSize: true,
  8834. padding: 0,
  8835. position: 'top',
  8836. text: '',
  8837. weight: 1500
  8838. },
  8839. defaultRoutes: {
  8840. color: 'color'
  8841. },
  8842. descriptors: {
  8843. _scriptable: true,
  8844. _indexable: false
  8845. }
  8846. };
  8847. const positioners = {
  8848. average (items) {
  8849. if (!items.length) {
  8850. return false;
  8851. }
  8852. let i, len;
  8853. let xSet = new Set();
  8854. let y = 0;
  8855. let count = 0;
  8856. for(i = 0, len = items.length; i < len; ++i){
  8857. const el = items[i].element;
  8858. if (el && el.hasValue()) {
  8859. const pos = el.tooltipPosition();
  8860. xSet.add(pos.x);
  8861. y += pos.y;
  8862. ++count;
  8863. }
  8864. }
  8865. if (count === 0 || xSet.size === 0) {
  8866. return false;
  8867. }
  8868. const xAverage = [
  8869. ...xSet
  8870. ].reduce((a, b)=>a + b) / xSet.size;
  8871. return {
  8872. x: xAverage,
  8873. y: y / count
  8874. };
  8875. },
  8876. nearest (items, eventPosition) {
  8877. if (!items.length) {
  8878. return false;
  8879. }
  8880. let x = eventPosition.x;
  8881. let y = eventPosition.y;
  8882. let minDistance = Number.POSITIVE_INFINITY;
  8883. let i, len, nearestElement;
  8884. for(i = 0, len = items.length; i < len; ++i){
  8885. const el = items[i].element;
  8886. if (el && el.hasValue()) {
  8887. const center = el.getCenterPoint();
  8888. const d = distanceBetweenPoints(eventPosition, center);
  8889. if (d < minDistance) {
  8890. minDistance = d;
  8891. nearestElement = el;
  8892. }
  8893. }
  8894. }
  8895. if (nearestElement) {
  8896. const tp = nearestElement.tooltipPosition();
  8897. x = tp.x;
  8898. y = tp.y;
  8899. }
  8900. return {
  8901. x,
  8902. y
  8903. };
  8904. }
  8905. };
  8906. function pushOrConcat(base, toPush) {
  8907. if (toPush) {
  8908. if (isArray(toPush)) {
  8909. Array.prototype.push.apply(base, toPush);
  8910. } else {
  8911. base.push(toPush);
  8912. }
  8913. }
  8914. return base;
  8915. }
  8916. function splitNewlines(str) {
  8917. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  8918. return str.split('\n');
  8919. }
  8920. return str;
  8921. }
  8922. function createTooltipItem(chart, item) {
  8923. const { element , datasetIndex , index } = item;
  8924. const controller = chart.getDatasetMeta(datasetIndex).controller;
  8925. const { label , value } = controller.getLabelAndValue(index);
  8926. return {
  8927. chart,
  8928. label,
  8929. parsed: controller.getParsed(index),
  8930. raw: chart.data.datasets[datasetIndex].data[index],
  8931. formattedValue: value,
  8932. dataset: controller.getDataset(),
  8933. dataIndex: index,
  8934. datasetIndex,
  8935. element
  8936. };
  8937. }
  8938. function getTooltipSize(tooltip, options) {
  8939. const ctx = tooltip.chart.ctx;
  8940. const { body , footer , title } = tooltip;
  8941. const { boxWidth , boxHeight } = options;
  8942. const bodyFont = toFont(options.bodyFont);
  8943. const titleFont = toFont(options.titleFont);
  8944. const footerFont = toFont(options.footerFont);
  8945. const titleLineCount = title.length;
  8946. const footerLineCount = footer.length;
  8947. const bodyLineItemCount = body.length;
  8948. const padding = toPadding(options.padding);
  8949. let height = padding.height;
  8950. let width = 0;
  8951. let combinedBodyLength = body.reduce((count, bodyItem)=>count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);
  8952. combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;
  8953. if (titleLineCount) {
  8954. height += titleLineCount * titleFont.lineHeight + (titleLineCount - 1) * options.titleSpacing + options.titleMarginBottom;
  8955. }
  8956. if (combinedBodyLength) {
  8957. const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;
  8958. height += bodyLineItemCount * bodyLineHeight + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight + (combinedBodyLength - 1) * options.bodySpacing;
  8959. }
  8960. if (footerLineCount) {
  8961. height += options.footerMarginTop + footerLineCount * footerFont.lineHeight + (footerLineCount - 1) * options.footerSpacing;
  8962. }
  8963. let widthPadding = 0;
  8964. const maxLineWidth = function(line) {
  8965. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  8966. };
  8967. ctx.save();
  8968. ctx.font = titleFont.string;
  8969. each(tooltip.title, maxLineWidth);
  8970. ctx.font = bodyFont.string;
  8971. each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);
  8972. widthPadding = options.displayColors ? boxWidth + 2 + options.boxPadding : 0;
  8973. each(body, (bodyItem)=>{
  8974. each(bodyItem.before, maxLineWidth);
  8975. each(bodyItem.lines, maxLineWidth);
  8976. each(bodyItem.after, maxLineWidth);
  8977. });
  8978. widthPadding = 0;
  8979. ctx.font = footerFont.string;
  8980. each(tooltip.footer, maxLineWidth);
  8981. ctx.restore();
  8982. width += padding.width;
  8983. return {
  8984. width,
  8985. height
  8986. };
  8987. }
  8988. function determineYAlign(chart, size) {
  8989. const { y , height } = size;
  8990. if (y < height / 2) {
  8991. return 'top';
  8992. } else if (y > chart.height - height / 2) {
  8993. return 'bottom';
  8994. }
  8995. return 'center';
  8996. }
  8997. function doesNotFitWithAlign(xAlign, chart, options, size) {
  8998. const { x , width } = size;
  8999. const caret = options.caretSize + options.caretPadding;
  9000. if (xAlign === 'left' && x + width + caret > chart.width) {
  9001. return true;
  9002. }
  9003. if (xAlign === 'right' && x - width - caret < 0) {
  9004. return true;
  9005. }
  9006. }
  9007. function determineXAlign(chart, options, size, yAlign) {
  9008. const { x , width } = size;
  9009. const { width: chartWidth , chartArea: { left , right } } = chart;
  9010. let xAlign = 'center';
  9011. if (yAlign === 'center') {
  9012. xAlign = x <= (left + right) / 2 ? 'left' : 'right';
  9013. } else if (x <= width / 2) {
  9014. xAlign = 'left';
  9015. } else if (x >= chartWidth - width / 2) {
  9016. xAlign = 'right';
  9017. }
  9018. if (doesNotFitWithAlign(xAlign, chart, options, size)) {
  9019. xAlign = 'center';
  9020. }
  9021. return xAlign;
  9022. }
  9023. function determineAlignment(chart, options, size) {
  9024. const yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size);
  9025. return {
  9026. xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign),
  9027. yAlign
  9028. };
  9029. }
  9030. function alignX(size, xAlign) {
  9031. let { x , width } = size;
  9032. if (xAlign === 'right') {
  9033. x -= width;
  9034. } else if (xAlign === 'center') {
  9035. x -= width / 2;
  9036. }
  9037. return x;
  9038. }
  9039. function alignY(size, yAlign, paddingAndSize) {
  9040. let { y , height } = size;
  9041. if (yAlign === 'top') {
  9042. y += paddingAndSize;
  9043. } else if (yAlign === 'bottom') {
  9044. y -= height + paddingAndSize;
  9045. } else {
  9046. y -= height / 2;
  9047. }
  9048. return y;
  9049. }
  9050. function getBackgroundPoint(options, size, alignment, chart) {
  9051. const { caretSize , caretPadding , cornerRadius } = options;
  9052. const { xAlign , yAlign } = alignment;
  9053. const paddingAndSize = caretSize + caretPadding;
  9054. const { topLeft , topRight , bottomLeft , bottomRight } = toTRBLCorners(cornerRadius);
  9055. let x = alignX(size, xAlign);
  9056. const y = alignY(size, yAlign, paddingAndSize);
  9057. if (yAlign === 'center') {
  9058. if (xAlign === 'left') {
  9059. x += paddingAndSize;
  9060. } else if (xAlign === 'right') {
  9061. x -= paddingAndSize;
  9062. }
  9063. } else if (xAlign === 'left') {
  9064. x -= Math.max(topLeft, bottomLeft) + caretSize;
  9065. } else if (xAlign === 'right') {
  9066. x += Math.max(topRight, bottomRight) + caretSize;
  9067. }
  9068. return {
  9069. x: _limitValue(x, 0, chart.width - size.width),
  9070. y: _limitValue(y, 0, chart.height - size.height)
  9071. };
  9072. }
  9073. function getAlignedX(tooltip, align, options) {
  9074. const padding = toPadding(options.padding);
  9075. return align === 'center' ? tooltip.x + tooltip.width / 2 : align === 'right' ? tooltip.x + tooltip.width - padding.right : tooltip.x + padding.left;
  9076. }
  9077. function getBeforeAfterBodyLines(callback) {
  9078. return pushOrConcat([], splitNewlines(callback));
  9079. }
  9080. function createTooltipContext(parent, tooltip, tooltipItems) {
  9081. return createContext(parent, {
  9082. tooltip,
  9083. tooltipItems,
  9084. type: 'tooltip'
  9085. });
  9086. }
  9087. function overrideCallbacks(callbacks, context) {
  9088. const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;
  9089. return override ? callbacks.override(override) : callbacks;
  9090. }
  9091. const defaultCallbacks = {
  9092. beforeTitle: noop,
  9093. title (tooltipItems) {
  9094. if (tooltipItems.length > 0) {
  9095. const item = tooltipItems[0];
  9096. const labels = item.chart.data.labels;
  9097. const labelCount = labels ? labels.length : 0;
  9098. if (this && this.options && this.options.mode === 'dataset') {
  9099. return item.dataset.label || '';
  9100. } else if (item.label) {
  9101. return item.label;
  9102. } else if (labelCount > 0 && item.dataIndex < labelCount) {
  9103. return labels[item.dataIndex];
  9104. }
  9105. }
  9106. return '';
  9107. },
  9108. afterTitle: noop,
  9109. beforeBody: noop,
  9110. beforeLabel: noop,
  9111. label (tooltipItem) {
  9112. if (this && this.options && this.options.mode === 'dataset') {
  9113. return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;
  9114. }
  9115. let label = tooltipItem.dataset.label || '';
  9116. if (label) {
  9117. label += ': ';
  9118. }
  9119. const value = tooltipItem.formattedValue;
  9120. if (!isNullOrUndef(value)) {
  9121. label += value;
  9122. }
  9123. return label;
  9124. },
  9125. labelColor (tooltipItem) {
  9126. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  9127. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  9128. return {
  9129. borderColor: options.borderColor,
  9130. backgroundColor: options.backgroundColor,
  9131. borderWidth: options.borderWidth,
  9132. borderDash: options.borderDash,
  9133. borderDashOffset: options.borderDashOffset,
  9134. borderRadius: 0
  9135. };
  9136. },
  9137. labelTextColor () {
  9138. return this.options.bodyColor;
  9139. },
  9140. labelPointStyle (tooltipItem) {
  9141. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  9142. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  9143. return {
  9144. pointStyle: options.pointStyle,
  9145. rotation: options.rotation
  9146. };
  9147. },
  9148. afterLabel: noop,
  9149. afterBody: noop,
  9150. beforeFooter: noop,
  9151. footer: noop,
  9152. afterFooter: noop
  9153. };
  9154. function invokeCallbackWithFallback(callbacks, name, ctx, arg) {
  9155. const result = callbacks[name].call(ctx, arg);
  9156. if (typeof result === 'undefined') {
  9157. return defaultCallbacks[name].call(ctx, arg);
  9158. }
  9159. return result;
  9160. }
  9161. class Tooltip extends Element {
  9162. static positioners = positioners;
  9163. constructor(config){
  9164. super();
  9165. this.opacity = 0;
  9166. this._active = [];
  9167. this._eventPosition = undefined;
  9168. this._size = undefined;
  9169. this._cachedAnimations = undefined;
  9170. this._tooltipItems = [];
  9171. this.$animations = undefined;
  9172. this.$context = undefined;
  9173. this.chart = config.chart;
  9174. this.options = config.options;
  9175. this.dataPoints = undefined;
  9176. this.title = undefined;
  9177. this.beforeBody = undefined;
  9178. this.body = undefined;
  9179. this.afterBody = undefined;
  9180. this.footer = undefined;
  9181. this.xAlign = undefined;
  9182. this.yAlign = undefined;
  9183. this.x = undefined;
  9184. this.y = undefined;
  9185. this.height = undefined;
  9186. this.width = undefined;
  9187. this.caretX = undefined;
  9188. this.caretY = undefined;
  9189. this.labelColors = undefined;
  9190. this.labelPointStyles = undefined;
  9191. this.labelTextColors = undefined;
  9192. }
  9193. initialize(options) {
  9194. this.options = options;
  9195. this._cachedAnimations = undefined;
  9196. this.$context = undefined;
  9197. }
  9198. _resolveAnimations() {
  9199. const cached = this._cachedAnimations;
  9200. if (cached) {
  9201. return cached;
  9202. }
  9203. const chart = this.chart;
  9204. const options = this.options.setContext(this.getContext());
  9205. const opts = options.enabled && chart.options.animation && options.animations;
  9206. const animations = new Animations(this.chart, opts);
  9207. if (opts._cacheable) {
  9208. this._cachedAnimations = Object.freeze(animations);
  9209. }
  9210. return animations;
  9211. }
  9212. getContext() {
  9213. return this.$context || (this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems));
  9214. }
  9215. getTitle(context, options) {
  9216. const { callbacks } = options;
  9217. const beforeTitle = invokeCallbackWithFallback(callbacks, 'beforeTitle', this, context);
  9218. const title = invokeCallbackWithFallback(callbacks, 'title', this, context);
  9219. const afterTitle = invokeCallbackWithFallback(callbacks, 'afterTitle', this, context);
  9220. let lines = [];
  9221. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  9222. lines = pushOrConcat(lines, splitNewlines(title));
  9223. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  9224. return lines;
  9225. }
  9226. getBeforeBody(tooltipItems, options) {
  9227. return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'beforeBody', this, tooltipItems));
  9228. }
  9229. getBody(tooltipItems, options) {
  9230. const { callbacks } = options;
  9231. const bodyItems = [];
  9232. each(tooltipItems, (context)=>{
  9233. const bodyItem = {
  9234. before: [],
  9235. lines: [],
  9236. after: []
  9237. };
  9238. const scoped = overrideCallbacks(callbacks, context);
  9239. pushOrConcat(bodyItem.before, splitNewlines(invokeCallbackWithFallback(scoped, 'beforeLabel', this, context)));
  9240. pushOrConcat(bodyItem.lines, invokeCallbackWithFallback(scoped, 'label', this, context));
  9241. pushOrConcat(bodyItem.after, splitNewlines(invokeCallbackWithFallback(scoped, 'afterLabel', this, context)));
  9242. bodyItems.push(bodyItem);
  9243. });
  9244. return bodyItems;
  9245. }
  9246. getAfterBody(tooltipItems, options) {
  9247. return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'afterBody', this, tooltipItems));
  9248. }
  9249. getFooter(tooltipItems, options) {
  9250. const { callbacks } = options;
  9251. const beforeFooter = invokeCallbackWithFallback(callbacks, 'beforeFooter', this, tooltipItems);
  9252. const footer = invokeCallbackWithFallback(callbacks, 'footer', this, tooltipItems);
  9253. const afterFooter = invokeCallbackWithFallback(callbacks, 'afterFooter', this, tooltipItems);
  9254. let lines = [];
  9255. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  9256. lines = pushOrConcat(lines, splitNewlines(footer));
  9257. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  9258. return lines;
  9259. }
  9260. _createItems(options) {
  9261. const active = this._active;
  9262. const data = this.chart.data;
  9263. const labelColors = [];
  9264. const labelPointStyles = [];
  9265. const labelTextColors = [];
  9266. let tooltipItems = [];
  9267. let i, len;
  9268. for(i = 0, len = active.length; i < len; ++i){
  9269. tooltipItems.push(createTooltipItem(this.chart, active[i]));
  9270. }
  9271. if (options.filter) {
  9272. tooltipItems = tooltipItems.filter((element, index, array)=>options.filter(element, index, array, data));
  9273. }
  9274. if (options.itemSort) {
  9275. tooltipItems = tooltipItems.sort((a, b)=>options.itemSort(a, b, data));
  9276. }
  9277. each(tooltipItems, (context)=>{
  9278. const scoped = overrideCallbacks(options.callbacks, context);
  9279. labelColors.push(invokeCallbackWithFallback(scoped, 'labelColor', this, context));
  9280. labelPointStyles.push(invokeCallbackWithFallback(scoped, 'labelPointStyle', this, context));
  9281. labelTextColors.push(invokeCallbackWithFallback(scoped, 'labelTextColor', this, context));
  9282. });
  9283. this.labelColors = labelColors;
  9284. this.labelPointStyles = labelPointStyles;
  9285. this.labelTextColors = labelTextColors;
  9286. this.dataPoints = tooltipItems;
  9287. return tooltipItems;
  9288. }
  9289. update(changed, replay) {
  9290. const options = this.options.setContext(this.getContext());
  9291. const active = this._active;
  9292. let properties;
  9293. let tooltipItems = [];
  9294. if (!active.length) {
  9295. if (this.opacity !== 0) {
  9296. properties = {
  9297. opacity: 0
  9298. };
  9299. }
  9300. } else {
  9301. const position = positioners[options.position].call(this, active, this._eventPosition);
  9302. tooltipItems = this._createItems(options);
  9303. this.title = this.getTitle(tooltipItems, options);
  9304. this.beforeBody = this.getBeforeBody(tooltipItems, options);
  9305. this.body = this.getBody(tooltipItems, options);
  9306. this.afterBody = this.getAfterBody(tooltipItems, options);
  9307. this.footer = this.getFooter(tooltipItems, options);
  9308. const size = this._size = getTooltipSize(this, options);
  9309. const positionAndSize = Object.assign({}, position, size);
  9310. const alignment = determineAlignment(this.chart, options, positionAndSize);
  9311. const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart);
  9312. this.xAlign = alignment.xAlign;
  9313. this.yAlign = alignment.yAlign;
  9314. properties = {
  9315. opacity: 1,
  9316. x: backgroundPoint.x,
  9317. y: backgroundPoint.y,
  9318. width: size.width,
  9319. height: size.height,
  9320. caretX: position.x,
  9321. caretY: position.y
  9322. };
  9323. }
  9324. this._tooltipItems = tooltipItems;
  9325. this.$context = undefined;
  9326. if (properties) {
  9327. this._resolveAnimations().update(this, properties);
  9328. }
  9329. if (changed && options.external) {
  9330. options.external.call(this, {
  9331. chart: this.chart,
  9332. tooltip: this,
  9333. replay
  9334. });
  9335. }
  9336. }
  9337. drawCaret(tooltipPoint, ctx, size, options) {
  9338. const caretPosition = this.getCaretPosition(tooltipPoint, size, options);
  9339. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  9340. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  9341. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  9342. }
  9343. getCaretPosition(tooltipPoint, size, options) {
  9344. const { xAlign , yAlign } = this;
  9345. const { caretSize , cornerRadius } = options;
  9346. const { topLeft , topRight , bottomLeft , bottomRight } = toTRBLCorners(cornerRadius);
  9347. const { x: ptX , y: ptY } = tooltipPoint;
  9348. const { width , height } = size;
  9349. let x1, x2, x3, y1, y2, y3;
  9350. if (yAlign === 'center') {
  9351. y2 = ptY + height / 2;
  9352. if (xAlign === 'left') {
  9353. x1 = ptX;
  9354. x2 = x1 - caretSize;
  9355. y1 = y2 + caretSize;
  9356. y3 = y2 - caretSize;
  9357. } else {
  9358. x1 = ptX + width;
  9359. x2 = x1 + caretSize;
  9360. y1 = y2 - caretSize;
  9361. y3 = y2 + caretSize;
  9362. }
  9363. x3 = x1;
  9364. } else {
  9365. if (xAlign === 'left') {
  9366. x2 = ptX + Math.max(topLeft, bottomLeft) + caretSize;
  9367. } else if (xAlign === 'right') {
  9368. x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize;
  9369. } else {
  9370. x2 = this.caretX;
  9371. }
  9372. if (yAlign === 'top') {
  9373. y1 = ptY;
  9374. y2 = y1 - caretSize;
  9375. x1 = x2 - caretSize;
  9376. x3 = x2 + caretSize;
  9377. } else {
  9378. y1 = ptY + height;
  9379. y2 = y1 + caretSize;
  9380. x1 = x2 + caretSize;
  9381. x3 = x2 - caretSize;
  9382. }
  9383. y3 = y1;
  9384. }
  9385. return {
  9386. x1,
  9387. x2,
  9388. x3,
  9389. y1,
  9390. y2,
  9391. y3
  9392. };
  9393. }
  9394. drawTitle(pt, ctx, options) {
  9395. const title = this.title;
  9396. const length = title.length;
  9397. let titleFont, titleSpacing, i;
  9398. if (length) {
  9399. const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);
  9400. pt.x = getAlignedX(this, options.titleAlign, options);
  9401. ctx.textAlign = rtlHelper.textAlign(options.titleAlign);
  9402. ctx.textBaseline = 'middle';
  9403. titleFont = toFont(options.titleFont);
  9404. titleSpacing = options.titleSpacing;
  9405. ctx.fillStyle = options.titleColor;
  9406. ctx.font = titleFont.string;
  9407. for(i = 0; i < length; ++i){
  9408. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);
  9409. pt.y += titleFont.lineHeight + titleSpacing;
  9410. if (i + 1 === length) {
  9411. pt.y += options.titleMarginBottom - titleSpacing;
  9412. }
  9413. }
  9414. }
  9415. }
  9416. _drawColorBox(ctx, pt, i, rtlHelper, options) {
  9417. const labelColor = this.labelColors[i];
  9418. const labelPointStyle = this.labelPointStyles[i];
  9419. const { boxHeight , boxWidth } = options;
  9420. const bodyFont = toFont(options.bodyFont);
  9421. const colorX = getAlignedX(this, 'left', options);
  9422. const rtlColorX = rtlHelper.x(colorX);
  9423. const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;
  9424. const colorY = pt.y + yOffSet;
  9425. if (options.usePointStyle) {
  9426. const drawOptions = {
  9427. radius: Math.min(boxWidth, boxHeight) / 2,
  9428. pointStyle: labelPointStyle.pointStyle,
  9429. rotation: labelPointStyle.rotation,
  9430. borderWidth: 1
  9431. };
  9432. const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;
  9433. const centerY = colorY + boxHeight / 2;
  9434. ctx.strokeStyle = options.multiKeyBackground;
  9435. ctx.fillStyle = options.multiKeyBackground;
  9436. drawPoint(ctx, drawOptions, centerX, centerY);
  9437. ctx.strokeStyle = labelColor.borderColor;
  9438. ctx.fillStyle = labelColor.backgroundColor;
  9439. drawPoint(ctx, drawOptions, centerX, centerY);
  9440. } else {
  9441. ctx.lineWidth = isObject(labelColor.borderWidth) ? Math.max(...Object.values(labelColor.borderWidth)) : labelColor.borderWidth || 1;
  9442. ctx.strokeStyle = labelColor.borderColor;
  9443. ctx.setLineDash(labelColor.borderDash || []);
  9444. ctx.lineDashOffset = labelColor.borderDashOffset || 0;
  9445. const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth);
  9446. const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2);
  9447. const borderRadius = toTRBLCorners(labelColor.borderRadius);
  9448. if (Object.values(borderRadius).some((v)=>v !== 0)) {
  9449. ctx.beginPath();
  9450. ctx.fillStyle = options.multiKeyBackground;
  9451. addRoundedRectPath(ctx, {
  9452. x: outerX,
  9453. y: colorY,
  9454. w: boxWidth,
  9455. h: boxHeight,
  9456. radius: borderRadius
  9457. });
  9458. ctx.fill();
  9459. ctx.stroke();
  9460. ctx.fillStyle = labelColor.backgroundColor;
  9461. ctx.beginPath();
  9462. addRoundedRectPath(ctx, {
  9463. x: innerX,
  9464. y: colorY + 1,
  9465. w: boxWidth - 2,
  9466. h: boxHeight - 2,
  9467. radius: borderRadius
  9468. });
  9469. ctx.fill();
  9470. } else {
  9471. ctx.fillStyle = options.multiKeyBackground;
  9472. ctx.fillRect(outerX, colorY, boxWidth, boxHeight);
  9473. ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);
  9474. ctx.fillStyle = labelColor.backgroundColor;
  9475. ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);
  9476. }
  9477. }
  9478. ctx.fillStyle = this.labelTextColors[i];
  9479. }
  9480. drawBody(pt, ctx, options) {
  9481. const { body } = this;
  9482. const { bodySpacing , bodyAlign , displayColors , boxHeight , boxWidth , boxPadding } = options;
  9483. const bodyFont = toFont(options.bodyFont);
  9484. let bodyLineHeight = bodyFont.lineHeight;
  9485. let xLinePadding = 0;
  9486. const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);
  9487. const fillLineOfText = function(line) {
  9488. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);
  9489. pt.y += bodyLineHeight + bodySpacing;
  9490. };
  9491. const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  9492. let bodyItem, textColor, lines, i, j, ilen, jlen;
  9493. ctx.textAlign = bodyAlign;
  9494. ctx.textBaseline = 'middle';
  9495. ctx.font = bodyFont.string;
  9496. pt.x = getAlignedX(this, bodyAlignForCalculation, options);
  9497. ctx.fillStyle = options.bodyColor;
  9498. each(this.beforeBody, fillLineOfText);
  9499. xLinePadding = displayColors && bodyAlignForCalculation !== 'right' ? bodyAlign === 'center' ? boxWidth / 2 + boxPadding : boxWidth + 2 + boxPadding : 0;
  9500. for(i = 0, ilen = body.length; i < ilen; ++i){
  9501. bodyItem = body[i];
  9502. textColor = this.labelTextColors[i];
  9503. ctx.fillStyle = textColor;
  9504. each(bodyItem.before, fillLineOfText);
  9505. lines = bodyItem.lines;
  9506. if (displayColors && lines.length) {
  9507. this._drawColorBox(ctx, pt, i, rtlHelper, options);
  9508. bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);
  9509. }
  9510. for(j = 0, jlen = lines.length; j < jlen; ++j){
  9511. fillLineOfText(lines[j]);
  9512. bodyLineHeight = bodyFont.lineHeight;
  9513. }
  9514. each(bodyItem.after, fillLineOfText);
  9515. }
  9516. xLinePadding = 0;
  9517. bodyLineHeight = bodyFont.lineHeight;
  9518. each(this.afterBody, fillLineOfText);
  9519. pt.y -= bodySpacing;
  9520. }
  9521. drawFooter(pt, ctx, options) {
  9522. const footer = this.footer;
  9523. const length = footer.length;
  9524. let footerFont, i;
  9525. if (length) {
  9526. const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);
  9527. pt.x = getAlignedX(this, options.footerAlign, options);
  9528. pt.y += options.footerMarginTop;
  9529. ctx.textAlign = rtlHelper.textAlign(options.footerAlign);
  9530. ctx.textBaseline = 'middle';
  9531. footerFont = toFont(options.footerFont);
  9532. ctx.fillStyle = options.footerColor;
  9533. ctx.font = footerFont.string;
  9534. for(i = 0; i < length; ++i){
  9535. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);
  9536. pt.y += footerFont.lineHeight + options.footerSpacing;
  9537. }
  9538. }
  9539. }
  9540. drawBackground(pt, ctx, tooltipSize, options) {
  9541. const { xAlign , yAlign } = this;
  9542. const { x , y } = pt;
  9543. const { width , height } = tooltipSize;
  9544. const { topLeft , topRight , bottomLeft , bottomRight } = toTRBLCorners(options.cornerRadius);
  9545. ctx.fillStyle = options.backgroundColor;
  9546. ctx.strokeStyle = options.borderColor;
  9547. ctx.lineWidth = options.borderWidth;
  9548. ctx.beginPath();
  9549. ctx.moveTo(x + topLeft, y);
  9550. if (yAlign === 'top') {
  9551. this.drawCaret(pt, ctx, tooltipSize, options);
  9552. }
  9553. ctx.lineTo(x + width - topRight, y);
  9554. ctx.quadraticCurveTo(x + width, y, x + width, y + topRight);
  9555. if (yAlign === 'center' && xAlign === 'right') {
  9556. this.drawCaret(pt, ctx, tooltipSize, options);
  9557. }
  9558. ctx.lineTo(x + width, y + height - bottomRight);
  9559. ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height);
  9560. if (yAlign === 'bottom') {
  9561. this.drawCaret(pt, ctx, tooltipSize, options);
  9562. }
  9563. ctx.lineTo(x + bottomLeft, y + height);
  9564. ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft);
  9565. if (yAlign === 'center' && xAlign === 'left') {
  9566. this.drawCaret(pt, ctx, tooltipSize, options);
  9567. }
  9568. ctx.lineTo(x, y + topLeft);
  9569. ctx.quadraticCurveTo(x, y, x + topLeft, y);
  9570. ctx.closePath();
  9571. ctx.fill();
  9572. if (options.borderWidth > 0) {
  9573. ctx.stroke();
  9574. }
  9575. }
  9576. _updateAnimationTarget(options) {
  9577. const chart = this.chart;
  9578. const anims = this.$animations;
  9579. const animX = anims && anims.x;
  9580. const animY = anims && anims.y;
  9581. if (animX || animY) {
  9582. const position = positioners[options.position].call(this, this._active, this._eventPosition);
  9583. if (!position) {
  9584. return;
  9585. }
  9586. const size = this._size = getTooltipSize(this, options);
  9587. const positionAndSize = Object.assign({}, position, this._size);
  9588. const alignment = determineAlignment(chart, options, positionAndSize);
  9589. const point = getBackgroundPoint(options, positionAndSize, alignment, chart);
  9590. if (animX._to !== point.x || animY._to !== point.y) {
  9591. this.xAlign = alignment.xAlign;
  9592. this.yAlign = alignment.yAlign;
  9593. this.width = size.width;
  9594. this.height = size.height;
  9595. this.caretX = position.x;
  9596. this.caretY = position.y;
  9597. this._resolveAnimations().update(this, point);
  9598. }
  9599. }
  9600. }
  9601. _willRender() {
  9602. return !!this.opacity;
  9603. }
  9604. draw(ctx) {
  9605. const options = this.options.setContext(this.getContext());
  9606. let opacity = this.opacity;
  9607. if (!opacity) {
  9608. return;
  9609. }
  9610. this._updateAnimationTarget(options);
  9611. const tooltipSize = {
  9612. width: this.width,
  9613. height: this.height
  9614. };
  9615. const pt = {
  9616. x: this.x,
  9617. y: this.y
  9618. };
  9619. opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
  9620. const padding = toPadding(options.padding);
  9621. const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length;
  9622. if (options.enabled && hasTooltipContent) {
  9623. ctx.save();
  9624. ctx.globalAlpha = opacity;
  9625. this.drawBackground(pt, ctx, tooltipSize, options);
  9626. overrideTextDirection(ctx, options.textDirection);
  9627. pt.y += padding.top;
  9628. this.drawTitle(pt, ctx, options);
  9629. this.drawBody(pt, ctx, options);
  9630. this.drawFooter(pt, ctx, options);
  9631. restoreTextDirection(ctx, options.textDirection);
  9632. ctx.restore();
  9633. }
  9634. }
  9635. getActiveElements() {
  9636. return this._active || [];
  9637. }
  9638. setActiveElements(activeElements, eventPosition) {
  9639. const lastActive = this._active;
  9640. const active = activeElements.map(({ datasetIndex , index })=>{
  9641. const meta = this.chart.getDatasetMeta(datasetIndex);
  9642. if (!meta) {
  9643. throw new Error('Cannot find a dataset at index ' + datasetIndex);
  9644. }
  9645. return {
  9646. datasetIndex,
  9647. element: meta.data[index],
  9648. index
  9649. };
  9650. });
  9651. const changed = !_elementsEqual(lastActive, active);
  9652. const positionChanged = this._positionChanged(active, eventPosition);
  9653. if (changed || positionChanged) {
  9654. this._active = active;
  9655. this._eventPosition = eventPosition;
  9656. this._ignoreReplayEvents = true;
  9657. this.update(true);
  9658. }
  9659. }
  9660. handleEvent(e, replay, inChartArea = true) {
  9661. if (replay && this._ignoreReplayEvents) {
  9662. return false;
  9663. }
  9664. this._ignoreReplayEvents = false;
  9665. const options = this.options;
  9666. const lastActive = this._active || [];
  9667. const active = this._getActiveElements(e, lastActive, replay, inChartArea);
  9668. const positionChanged = this._positionChanged(active, e);
  9669. const changed = replay || !_elementsEqual(active, lastActive) || positionChanged;
  9670. if (changed) {
  9671. this._active = active;
  9672. if (options.enabled || options.external) {
  9673. this._eventPosition = {
  9674. x: e.x,
  9675. y: e.y
  9676. };
  9677. this.update(true, replay);
  9678. }
  9679. }
  9680. return changed;
  9681. }
  9682. _getActiveElements(e, lastActive, replay, inChartArea) {
  9683. const options = this.options;
  9684. if (e.type === 'mouseout') {
  9685. return [];
  9686. }
  9687. if (!inChartArea) {
  9688. return lastActive.filter((i)=>this.chart.data.datasets[i.datasetIndex] && this.chart.getDatasetMeta(i.datasetIndex).controller.getParsed(i.index) !== undefined);
  9689. }
  9690. const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay);
  9691. if (options.reverse) {
  9692. active.reverse();
  9693. }
  9694. return active;
  9695. }
  9696. _positionChanged(active, e) {
  9697. const { caretX , caretY , options } = this;
  9698. const position = positioners[options.position].call(this, active, e);
  9699. return position !== false && (caretX !== position.x || caretY !== position.y);
  9700. }
  9701. }
  9702. var plugin_tooltip = {
  9703. id: 'tooltip',
  9704. _element: Tooltip,
  9705. positioners,
  9706. afterInit (chart, _args, options) {
  9707. if (options) {
  9708. chart.tooltip = new Tooltip({
  9709. chart,
  9710. options
  9711. });
  9712. }
  9713. },
  9714. beforeUpdate (chart, _args, options) {
  9715. if (chart.tooltip) {
  9716. chart.tooltip.initialize(options);
  9717. }
  9718. },
  9719. reset (chart, _args, options) {
  9720. if (chart.tooltip) {
  9721. chart.tooltip.initialize(options);
  9722. }
  9723. },
  9724. afterDraw (chart) {
  9725. const tooltip = chart.tooltip;
  9726. if (tooltip && tooltip._willRender()) {
  9727. const args = {
  9728. tooltip
  9729. };
  9730. if (chart.notifyPlugins('beforeTooltipDraw', {
  9731. ...args,
  9732. cancelable: true
  9733. }) === false) {
  9734. return;
  9735. }
  9736. tooltip.draw(chart.ctx);
  9737. chart.notifyPlugins('afterTooltipDraw', args);
  9738. }
  9739. },
  9740. afterEvent (chart, args) {
  9741. if (chart.tooltip) {
  9742. const useFinalPosition = args.replay;
  9743. if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) {
  9744. args.changed = true;
  9745. }
  9746. }
  9747. },
  9748. defaults: {
  9749. enabled: true,
  9750. external: null,
  9751. position: 'average',
  9752. backgroundColor: 'rgba(0,0,0,0.8)',
  9753. titleColor: '#fff',
  9754. titleFont: {
  9755. weight: 'bold'
  9756. },
  9757. titleSpacing: 2,
  9758. titleMarginBottom: 6,
  9759. titleAlign: 'left',
  9760. bodyColor: '#fff',
  9761. bodySpacing: 2,
  9762. bodyFont: {},
  9763. bodyAlign: 'left',
  9764. footerColor: '#fff',
  9765. footerSpacing: 2,
  9766. footerMarginTop: 6,
  9767. footerFont: {
  9768. weight: 'bold'
  9769. },
  9770. footerAlign: 'left',
  9771. padding: 6,
  9772. caretPadding: 2,
  9773. caretSize: 5,
  9774. cornerRadius: 6,
  9775. boxHeight: (ctx, opts)=>opts.bodyFont.size,
  9776. boxWidth: (ctx, opts)=>opts.bodyFont.size,
  9777. multiKeyBackground: '#fff',
  9778. displayColors: true,
  9779. boxPadding: 0,
  9780. borderColor: 'rgba(0,0,0,0)',
  9781. borderWidth: 0,
  9782. animation: {
  9783. duration: 400,
  9784. easing: 'easeOutQuart'
  9785. },
  9786. animations: {
  9787. numbers: {
  9788. type: 'number',
  9789. properties: [
  9790. 'x',
  9791. 'y',
  9792. 'width',
  9793. 'height',
  9794. 'caretX',
  9795. 'caretY'
  9796. ]
  9797. },
  9798. opacity: {
  9799. easing: 'linear',
  9800. duration: 200
  9801. }
  9802. },
  9803. callbacks: defaultCallbacks
  9804. },
  9805. defaultRoutes: {
  9806. bodyFont: 'font',
  9807. footerFont: 'font',
  9808. titleFont: 'font'
  9809. },
  9810. descriptors: {
  9811. _scriptable: (name)=>name !== 'filter' && name !== 'itemSort' && name !== 'external',
  9812. _indexable: false,
  9813. callbacks: {
  9814. _scriptable: false,
  9815. _indexable: false
  9816. },
  9817. animation: {
  9818. _fallback: false
  9819. },
  9820. animations: {
  9821. _fallback: 'animation'
  9822. }
  9823. },
  9824. additionalOptionScopes: [
  9825. 'interaction'
  9826. ]
  9827. };
  9828. var plugins = /*#__PURE__*/Object.freeze({
  9829. __proto__: null,
  9830. Colors: plugin_colors,
  9831. Decimation: plugin_decimation,
  9832. Filler: index,
  9833. Legend: plugin_legend,
  9834. SubTitle: plugin_subtitle,
  9835. Title: plugin_title,
  9836. Tooltip: plugin_tooltip
  9837. });
  9838. const addIfString = (labels, raw, index, addedLabels)=>{
  9839. if (typeof raw === 'string') {
  9840. index = labels.push(raw) - 1;
  9841. addedLabels.unshift({
  9842. index,
  9843. label: raw
  9844. });
  9845. } else if (isNaN(raw)) {
  9846. index = null;
  9847. }
  9848. return index;
  9849. };
  9850. function findOrAddLabel(labels, raw, index, addedLabels) {
  9851. const first = labels.indexOf(raw);
  9852. if (first === -1) {
  9853. return addIfString(labels, raw, index, addedLabels);
  9854. }
  9855. const last = labels.lastIndexOf(raw);
  9856. return first !== last ? index : first;
  9857. }
  9858. const validIndex = (index, max)=>index === null ? null : _limitValue(Math.round(index), 0, max);
  9859. function _getLabelForValue(value) {
  9860. const labels = this.getLabels();
  9861. if (value >= 0 && value < labels.length) {
  9862. return labels[value];
  9863. }
  9864. return value;
  9865. }
  9866. class CategoryScale extends Scale {
  9867. static id = 'category';
  9868. static defaults = {
  9869. ticks: {
  9870. callback: _getLabelForValue
  9871. }
  9872. };
  9873. constructor(cfg){
  9874. super(cfg);
  9875. this._startValue = undefined;
  9876. this._valueRange = 0;
  9877. this._addedLabels = [];
  9878. }
  9879. init(scaleOptions) {
  9880. const added = this._addedLabels;
  9881. if (added.length) {
  9882. const labels = this.getLabels();
  9883. for (const { index , label } of added){
  9884. if (labels[index] === label) {
  9885. labels.splice(index, 1);
  9886. }
  9887. }
  9888. this._addedLabels = [];
  9889. }
  9890. super.init(scaleOptions);
  9891. }
  9892. parse(raw, index) {
  9893. if (isNullOrUndef(raw)) {
  9894. return null;
  9895. }
  9896. const labels = this.getLabels();
  9897. index = isFinite(index) && labels[index] === raw ? index : findOrAddLabel(labels, raw, valueOrDefault(index, raw), this._addedLabels);
  9898. return validIndex(index, labels.length - 1);
  9899. }
  9900. determineDataLimits() {
  9901. const { minDefined , maxDefined } = this.getUserBounds();
  9902. let { min , max } = this.getMinMax(true);
  9903. if (this.options.bounds === 'ticks') {
  9904. if (!minDefined) {
  9905. min = 0;
  9906. }
  9907. if (!maxDefined) {
  9908. max = this.getLabels().length - 1;
  9909. }
  9910. }
  9911. this.min = min;
  9912. this.max = max;
  9913. }
  9914. buildTicks() {
  9915. const min = this.min;
  9916. const max = this.max;
  9917. const offset = this.options.offset;
  9918. const ticks = [];
  9919. let labels = this.getLabels();
  9920. labels = min === 0 && max === labels.length - 1 ? labels : labels.slice(min, max + 1);
  9921. this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);
  9922. this._startValue = this.min - (offset ? 0.5 : 0);
  9923. for(let value = min; value <= max; value++){
  9924. ticks.push({
  9925. value
  9926. });
  9927. }
  9928. return ticks;
  9929. }
  9930. getLabelForValue(value) {
  9931. return _getLabelForValue.call(this, value);
  9932. }
  9933. configure() {
  9934. super.configure();
  9935. if (!this.isHorizontal()) {
  9936. this._reversePixels = !this._reversePixels;
  9937. }
  9938. }
  9939. getPixelForValue(value) {
  9940. if (typeof value !== 'number') {
  9941. value = this.parse(value);
  9942. }
  9943. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  9944. }
  9945. getPixelForTick(index) {
  9946. const ticks = this.ticks;
  9947. if (index < 0 || index > ticks.length - 1) {
  9948. return null;
  9949. }
  9950. return this.getPixelForValue(ticks[index].value);
  9951. }
  9952. getValueForPixel(pixel) {
  9953. return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange);
  9954. }
  9955. getBasePixel() {
  9956. return this.bottom;
  9957. }
  9958. }
  9959. function generateTicks$1(generationOptions, dataRange) {
  9960. const ticks = [];
  9961. const MIN_SPACING = 1e-14;
  9962. const { bounds , step , min , max , precision , count , maxTicks , maxDigits , includeBounds } = generationOptions;
  9963. const unit = step || 1;
  9964. const maxSpaces = maxTicks - 1;
  9965. const { min: rmin , max: rmax } = dataRange;
  9966. const minDefined = !isNullOrUndef(min);
  9967. const maxDefined = !isNullOrUndef(max);
  9968. const countDefined = !isNullOrUndef(count);
  9969. const minSpacing = (rmax - rmin) / (maxDigits + 1);
  9970. let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit;
  9971. let factor, niceMin, niceMax, numSpaces;
  9972. if (spacing < MIN_SPACING && !minDefined && !maxDefined) {
  9973. return [
  9974. {
  9975. value: rmin
  9976. },
  9977. {
  9978. value: rmax
  9979. }
  9980. ];
  9981. }
  9982. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  9983. if (numSpaces > maxSpaces) {
  9984. spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit;
  9985. }
  9986. if (!isNullOrUndef(precision)) {
  9987. factor = Math.pow(10, precision);
  9988. spacing = Math.ceil(spacing * factor) / factor;
  9989. }
  9990. if (bounds === 'ticks') {
  9991. niceMin = Math.floor(rmin / spacing) * spacing;
  9992. niceMax = Math.ceil(rmax / spacing) * spacing;
  9993. } else {
  9994. niceMin = rmin;
  9995. niceMax = rmax;
  9996. }
  9997. if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) {
  9998. numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks));
  9999. spacing = (max - min) / numSpaces;
  10000. niceMin = min;
  10001. niceMax = max;
  10002. } else if (countDefined) {
  10003. niceMin = minDefined ? min : niceMin;
  10004. niceMax = maxDefined ? max : niceMax;
  10005. numSpaces = count - 1;
  10006. spacing = (niceMax - niceMin) / numSpaces;
  10007. } else {
  10008. numSpaces = (niceMax - niceMin) / spacing;
  10009. if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  10010. numSpaces = Math.round(numSpaces);
  10011. } else {
  10012. numSpaces = Math.ceil(numSpaces);
  10013. }
  10014. }
  10015. const decimalPlaces = Math.max(_decimalPlaces(spacing), _decimalPlaces(niceMin));
  10016. factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision);
  10017. niceMin = Math.round(niceMin * factor) / factor;
  10018. niceMax = Math.round(niceMax * factor) / factor;
  10019. let j = 0;
  10020. if (minDefined) {
  10021. if (includeBounds && niceMin !== min) {
  10022. ticks.push({
  10023. value: min
  10024. });
  10025. if (niceMin < min) {
  10026. j++;
  10027. }
  10028. if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) {
  10029. j++;
  10030. }
  10031. } else if (niceMin < min) {
  10032. j++;
  10033. }
  10034. }
  10035. for(; j < numSpaces; ++j){
  10036. const tickValue = Math.round((niceMin + j * spacing) * factor) / factor;
  10037. if (maxDefined && tickValue > max) {
  10038. break;
  10039. }
  10040. ticks.push({
  10041. value: tickValue
  10042. });
  10043. }
  10044. if (maxDefined && includeBounds && niceMax !== max) {
  10045. if (ticks.length && almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) {
  10046. ticks[ticks.length - 1].value = max;
  10047. } else {
  10048. ticks.push({
  10049. value: max
  10050. });
  10051. }
  10052. } else if (!maxDefined || niceMax === max) {
  10053. ticks.push({
  10054. value: niceMax
  10055. });
  10056. }
  10057. return ticks;
  10058. }
  10059. function relativeLabelSize(value, minSpacing, { horizontal , minRotation }) {
  10060. const rad = toRadians(minRotation);
  10061. const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001;
  10062. const length = 0.75 * minSpacing * ('' + value).length;
  10063. return Math.min(minSpacing / ratio, length);
  10064. }
  10065. class LinearScaleBase extends Scale {
  10066. constructor(cfg){
  10067. super(cfg);
  10068. this.start = undefined;
  10069. this.end = undefined;
  10070. this._startValue = undefined;
  10071. this._endValue = undefined;
  10072. this._valueRange = 0;
  10073. }
  10074. parse(raw, index) {
  10075. if (isNullOrUndef(raw)) {
  10076. return null;
  10077. }
  10078. if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {
  10079. return null;
  10080. }
  10081. return +raw;
  10082. }
  10083. handleTickRangeOptions() {
  10084. const { beginAtZero } = this.options;
  10085. const { minDefined , maxDefined } = this.getUserBounds();
  10086. let { min , max } = this;
  10087. const setMin = (v)=>min = minDefined ? min : v;
  10088. const setMax = (v)=>max = maxDefined ? max : v;
  10089. if (beginAtZero) {
  10090. const minSign = sign(min);
  10091. const maxSign = sign(max);
  10092. if (minSign < 0 && maxSign < 0) {
  10093. setMax(0);
  10094. } else if (minSign > 0 && maxSign > 0) {
  10095. setMin(0);
  10096. }
  10097. }
  10098. if (min === max) {
  10099. let offset = max === 0 ? 1 : Math.abs(max * 0.05);
  10100. setMax(max + offset);
  10101. if (!beginAtZero) {
  10102. setMin(min - offset);
  10103. }
  10104. }
  10105. this.min = min;
  10106. this.max = max;
  10107. }
  10108. getTickLimit() {
  10109. const tickOpts = this.options.ticks;
  10110. let { maxTicksLimit , stepSize } = tickOpts;
  10111. let maxTicks;
  10112. if (stepSize) {
  10113. maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1;
  10114. if (maxTicks > 1000) {
  10115. console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`);
  10116. maxTicks = 1000;
  10117. }
  10118. } else {
  10119. maxTicks = this.computeTickLimit();
  10120. maxTicksLimit = maxTicksLimit || 11;
  10121. }
  10122. if (maxTicksLimit) {
  10123. maxTicks = Math.min(maxTicksLimit, maxTicks);
  10124. }
  10125. return maxTicks;
  10126. }
  10127. computeTickLimit() {
  10128. return Number.POSITIVE_INFINITY;
  10129. }
  10130. buildTicks() {
  10131. const opts = this.options;
  10132. const tickOpts = opts.ticks;
  10133. let maxTicks = this.getTickLimit();
  10134. maxTicks = Math.max(2, maxTicks);
  10135. const numericGeneratorOptions = {
  10136. maxTicks,
  10137. bounds: opts.bounds,
  10138. min: opts.min,
  10139. max: opts.max,
  10140. precision: tickOpts.precision,
  10141. step: tickOpts.stepSize,
  10142. count: tickOpts.count,
  10143. maxDigits: this._maxDigits(),
  10144. horizontal: this.isHorizontal(),
  10145. minRotation: tickOpts.minRotation || 0,
  10146. includeBounds: tickOpts.includeBounds !== false
  10147. };
  10148. const dataRange = this._range || this;
  10149. const ticks = generateTicks$1(numericGeneratorOptions, dataRange);
  10150. if (opts.bounds === 'ticks') {
  10151. _setMinAndMaxByKey(ticks, this, 'value');
  10152. }
  10153. if (opts.reverse) {
  10154. ticks.reverse();
  10155. this.start = this.max;
  10156. this.end = this.min;
  10157. } else {
  10158. this.start = this.min;
  10159. this.end = this.max;
  10160. }
  10161. return ticks;
  10162. }
  10163. configure() {
  10164. const ticks = this.ticks;
  10165. let start = this.min;
  10166. let end = this.max;
  10167. super.configure();
  10168. if (this.options.offset && ticks.length) {
  10169. const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  10170. start -= offset;
  10171. end += offset;
  10172. }
  10173. this._startValue = start;
  10174. this._endValue = end;
  10175. this._valueRange = end - start;
  10176. }
  10177. getLabelForValue(value) {
  10178. return formatNumber(value, this.chart.options.locale, this.options.ticks.format);
  10179. }
  10180. }
  10181. class LinearScale extends LinearScaleBase {
  10182. static id = 'linear';
  10183. static defaults = {
  10184. ticks: {
  10185. callback: Ticks.formatters.numeric
  10186. }
  10187. };
  10188. determineDataLimits() {
  10189. const { min , max } = this.getMinMax(true);
  10190. this.min = isNumberFinite(min) ? min : 0;
  10191. this.max = isNumberFinite(max) ? max : 1;
  10192. this.handleTickRangeOptions();
  10193. }
  10194. computeTickLimit() {
  10195. const horizontal = this.isHorizontal();
  10196. const length = horizontal ? this.width : this.height;
  10197. const minRotation = toRadians(this.options.ticks.minRotation);
  10198. const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001;
  10199. const tickFont = this._resolveTickFontOptions(0);
  10200. return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio));
  10201. }
  10202. getPixelForValue(value) {
  10203. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  10204. }
  10205. getValueForPixel(pixel) {
  10206. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  10207. }
  10208. }
  10209. const log10Floor = (v)=>Math.floor(log10(v));
  10210. const changeExponent = (v, m)=>Math.pow(10, log10Floor(v) + m);
  10211. function isMajor(tickVal) {
  10212. const remain = tickVal / Math.pow(10, log10Floor(tickVal));
  10213. return remain === 1;
  10214. }
  10215. function steps(min, max, rangeExp) {
  10216. const rangeStep = Math.pow(10, rangeExp);
  10217. const start = Math.floor(min / rangeStep);
  10218. const end = Math.ceil(max / rangeStep);
  10219. return end - start;
  10220. }
  10221. function startExp(min, max) {
  10222. const range = max - min;
  10223. let rangeExp = log10Floor(range);
  10224. while(steps(min, max, rangeExp) > 10){
  10225. rangeExp++;
  10226. }
  10227. while(steps(min, max, rangeExp) < 10){
  10228. rangeExp--;
  10229. }
  10230. return Math.min(rangeExp, log10Floor(min));
  10231. }
  10232. function generateTicks(generationOptions, { min , max }) {
  10233. min = finiteOrDefault(generationOptions.min, min);
  10234. const ticks = [];
  10235. const minExp = log10Floor(min);
  10236. let exp = startExp(min, max);
  10237. let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  10238. const stepSize = Math.pow(10, exp);
  10239. const base = minExp > exp ? Math.pow(10, minExp) : 0;
  10240. const start = Math.round((min - base) * precision) / precision;
  10241. const offset = Math.floor((min - base) / stepSize / 10) * stepSize * 10;
  10242. let significand = Math.floor((start - offset) / Math.pow(10, exp));
  10243. let value = finiteOrDefault(generationOptions.min, Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision);
  10244. while(value < max){
  10245. ticks.push({
  10246. value,
  10247. major: isMajor(value),
  10248. significand
  10249. });
  10250. if (significand >= 10) {
  10251. significand = significand < 15 ? 15 : 20;
  10252. } else {
  10253. significand++;
  10254. }
  10255. if (significand >= 20) {
  10256. exp++;
  10257. significand = 2;
  10258. precision = exp >= 0 ? 1 : precision;
  10259. }
  10260. value = Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision;
  10261. }
  10262. const lastTick = finiteOrDefault(generationOptions.max, value);
  10263. ticks.push({
  10264. value: lastTick,
  10265. major: isMajor(lastTick),
  10266. significand
  10267. });
  10268. return ticks;
  10269. }
  10270. class LogarithmicScale extends Scale {
  10271. static id = 'logarithmic';
  10272. static defaults = {
  10273. ticks: {
  10274. callback: Ticks.formatters.logarithmic,
  10275. major: {
  10276. enabled: true
  10277. }
  10278. }
  10279. };
  10280. constructor(cfg){
  10281. super(cfg);
  10282. this.start = undefined;
  10283. this.end = undefined;
  10284. this._startValue = undefined;
  10285. this._valueRange = 0;
  10286. }
  10287. parse(raw, index) {
  10288. const value = LinearScaleBase.prototype.parse.apply(this, [
  10289. raw,
  10290. index
  10291. ]);
  10292. if (value === 0) {
  10293. this._zero = true;
  10294. return undefined;
  10295. }
  10296. return isNumberFinite(value) && value > 0 ? value : null;
  10297. }
  10298. determineDataLimits() {
  10299. const { min , max } = this.getMinMax(true);
  10300. this.min = isNumberFinite(min) ? Math.max(0, min) : null;
  10301. this.max = isNumberFinite(max) ? Math.max(0, max) : null;
  10302. if (this.options.beginAtZero) {
  10303. this._zero = true;
  10304. }
  10305. if (this._zero && this.min !== this._suggestedMin && !isNumberFinite(this._userMin)) {
  10306. this.min = min === changeExponent(this.min, 0) ? changeExponent(this.min, -1) : changeExponent(this.min, 0);
  10307. }
  10308. this.handleTickRangeOptions();
  10309. }
  10310. handleTickRangeOptions() {
  10311. const { minDefined , maxDefined } = this.getUserBounds();
  10312. let min = this.min;
  10313. let max = this.max;
  10314. const setMin = (v)=>min = minDefined ? min : v;
  10315. const setMax = (v)=>max = maxDefined ? max : v;
  10316. if (min === max) {
  10317. if (min <= 0) {
  10318. setMin(1);
  10319. setMax(10);
  10320. } else {
  10321. setMin(changeExponent(min, -1));
  10322. setMax(changeExponent(max, +1));
  10323. }
  10324. }
  10325. if (min <= 0) {
  10326. setMin(changeExponent(max, -1));
  10327. }
  10328. if (max <= 0) {
  10329. setMax(changeExponent(min, +1));
  10330. }
  10331. this.min = min;
  10332. this.max = max;
  10333. }
  10334. buildTicks() {
  10335. const opts = this.options;
  10336. const generationOptions = {
  10337. min: this._userMin,
  10338. max: this._userMax
  10339. };
  10340. const ticks = generateTicks(generationOptions, this);
  10341. if (opts.bounds === 'ticks') {
  10342. _setMinAndMaxByKey(ticks, this, 'value');
  10343. }
  10344. if (opts.reverse) {
  10345. ticks.reverse();
  10346. this.start = this.max;
  10347. this.end = this.min;
  10348. } else {
  10349. this.start = this.min;
  10350. this.end = this.max;
  10351. }
  10352. return ticks;
  10353. }
  10354. getLabelForValue(value) {
  10355. return value === undefined ? '0' : formatNumber(value, this.chart.options.locale, this.options.ticks.format);
  10356. }
  10357. configure() {
  10358. const start = this.min;
  10359. super.configure();
  10360. this._startValue = log10(start);
  10361. this._valueRange = log10(this.max) - log10(start);
  10362. }
  10363. getPixelForValue(value) {
  10364. if (value === undefined || value === 0) {
  10365. value = this.min;
  10366. }
  10367. if (value === null || isNaN(value)) {
  10368. return NaN;
  10369. }
  10370. return this.getPixelForDecimal(value === this.min ? 0 : (log10(value) - this._startValue) / this._valueRange);
  10371. }
  10372. getValueForPixel(pixel) {
  10373. const decimal = this.getDecimalForPixel(pixel);
  10374. return Math.pow(10, this._startValue + decimal * this._valueRange);
  10375. }
  10376. }
  10377. function getTickBackdropHeight(opts) {
  10378. const tickOpts = opts.ticks;
  10379. if (tickOpts.display && opts.display) {
  10380. const padding = toPadding(tickOpts.backdropPadding);
  10381. return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height;
  10382. }
  10383. return 0;
  10384. }
  10385. function measureLabelSize(ctx, font, label) {
  10386. label = isArray(label) ? label : [
  10387. label
  10388. ];
  10389. return {
  10390. w: _longestText(ctx, font.string, label),
  10391. h: label.length * font.lineHeight
  10392. };
  10393. }
  10394. function determineLimits(angle, pos, size, min, max) {
  10395. if (angle === min || angle === max) {
  10396. return {
  10397. start: pos - size / 2,
  10398. end: pos + size / 2
  10399. };
  10400. } else if (angle < min || angle > max) {
  10401. return {
  10402. start: pos - size,
  10403. end: pos
  10404. };
  10405. }
  10406. return {
  10407. start: pos,
  10408. end: pos + size
  10409. };
  10410. }
  10411. function fitWithPointLabels(scale) {
  10412. const orig = {
  10413. l: scale.left + scale._padding.left,
  10414. r: scale.right - scale._padding.right,
  10415. t: scale.top + scale._padding.top,
  10416. b: scale.bottom - scale._padding.bottom
  10417. };
  10418. const limits = Object.assign({}, orig);
  10419. const labelSizes = [];
  10420. const padding = [];
  10421. const valueCount = scale._pointLabels.length;
  10422. const pointLabelOpts = scale.options.pointLabels;
  10423. const additionalAngle = pointLabelOpts.centerPointLabels ? PI / valueCount : 0;
  10424. for(let i = 0; i < valueCount; i++){
  10425. const opts = pointLabelOpts.setContext(scale.getPointLabelContext(i));
  10426. padding[i] = opts.padding;
  10427. const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle);
  10428. const plFont = toFont(opts.font);
  10429. const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]);
  10430. labelSizes[i] = textSize;
  10431. const angleRadians = _normalizeAngle(scale.getIndexAngle(i) + additionalAngle);
  10432. const angle = Math.round(toDegrees(angleRadians));
  10433. const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  10434. const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  10435. updateLimits(limits, orig, angleRadians, hLimits, vLimits);
  10436. }
  10437. scale.setCenterPoint(orig.l - limits.l, limits.r - orig.r, orig.t - limits.t, limits.b - orig.b);
  10438. scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding);
  10439. }
  10440. function updateLimits(limits, orig, angle, hLimits, vLimits) {
  10441. const sin = Math.abs(Math.sin(angle));
  10442. const cos = Math.abs(Math.cos(angle));
  10443. let x = 0;
  10444. let y = 0;
  10445. if (hLimits.start < orig.l) {
  10446. x = (orig.l - hLimits.start) / sin;
  10447. limits.l = Math.min(limits.l, orig.l - x);
  10448. } else if (hLimits.end > orig.r) {
  10449. x = (hLimits.end - orig.r) / sin;
  10450. limits.r = Math.max(limits.r, orig.r + x);
  10451. }
  10452. if (vLimits.start < orig.t) {
  10453. y = (orig.t - vLimits.start) / cos;
  10454. limits.t = Math.min(limits.t, orig.t - y);
  10455. } else if (vLimits.end > orig.b) {
  10456. y = (vLimits.end - orig.b) / cos;
  10457. limits.b = Math.max(limits.b, orig.b + y);
  10458. }
  10459. }
  10460. function createPointLabelItem(scale, index, itemOpts) {
  10461. const outerDistance = scale.drawingArea;
  10462. const { extra , additionalAngle , padding , size } = itemOpts;
  10463. const pointLabelPosition = scale.getPointPosition(index, outerDistance + extra + padding, additionalAngle);
  10464. const angle = Math.round(toDegrees(_normalizeAngle(pointLabelPosition.angle + HALF_PI)));
  10465. const y = yForAngle(pointLabelPosition.y, size.h, angle);
  10466. const textAlign = getTextAlignForAngle(angle);
  10467. const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign);
  10468. return {
  10469. visible: true,
  10470. x: pointLabelPosition.x,
  10471. y,
  10472. textAlign,
  10473. left,
  10474. top: y,
  10475. right: left + size.w,
  10476. bottom: y + size.h
  10477. };
  10478. }
  10479. function isNotOverlapped(item, area) {
  10480. if (!area) {
  10481. return true;
  10482. }
  10483. const { left , top , right , bottom } = item;
  10484. const apexesInArea = _isPointInArea({
  10485. x: left,
  10486. y: top
  10487. }, area) || _isPointInArea({
  10488. x: left,
  10489. y: bottom
  10490. }, area) || _isPointInArea({
  10491. x: right,
  10492. y: top
  10493. }, area) || _isPointInArea({
  10494. x: right,
  10495. y: bottom
  10496. }, area);
  10497. return !apexesInArea;
  10498. }
  10499. function buildPointLabelItems(scale, labelSizes, padding) {
  10500. const items = [];
  10501. const valueCount = scale._pointLabels.length;
  10502. const opts = scale.options;
  10503. const { centerPointLabels , display } = opts.pointLabels;
  10504. const itemOpts = {
  10505. extra: getTickBackdropHeight(opts) / 2,
  10506. additionalAngle: centerPointLabels ? PI / valueCount : 0
  10507. };
  10508. let area;
  10509. for(let i = 0; i < valueCount; i++){
  10510. itemOpts.padding = padding[i];
  10511. itemOpts.size = labelSizes[i];
  10512. const item = createPointLabelItem(scale, i, itemOpts);
  10513. items.push(item);
  10514. if (display === 'auto') {
  10515. item.visible = isNotOverlapped(item, area);
  10516. if (item.visible) {
  10517. area = item;
  10518. }
  10519. }
  10520. }
  10521. return items;
  10522. }
  10523. function getTextAlignForAngle(angle) {
  10524. if (angle === 0 || angle === 180) {
  10525. return 'center';
  10526. } else if (angle < 180) {
  10527. return 'left';
  10528. }
  10529. return 'right';
  10530. }
  10531. function leftForTextAlign(x, w, align) {
  10532. if (align === 'right') {
  10533. x -= w;
  10534. } else if (align === 'center') {
  10535. x -= w / 2;
  10536. }
  10537. return x;
  10538. }
  10539. function yForAngle(y, h, angle) {
  10540. if (angle === 90 || angle === 270) {
  10541. y -= h / 2;
  10542. } else if (angle > 270 || angle < 90) {
  10543. y -= h;
  10544. }
  10545. return y;
  10546. }
  10547. function drawPointLabelBox(ctx, opts, item) {
  10548. const { left , top , right , bottom } = item;
  10549. const { backdropColor } = opts;
  10550. if (!isNullOrUndef(backdropColor)) {
  10551. const borderRadius = toTRBLCorners(opts.borderRadius);
  10552. const padding = toPadding(opts.backdropPadding);
  10553. ctx.fillStyle = backdropColor;
  10554. const backdropLeft = left - padding.left;
  10555. const backdropTop = top - padding.top;
  10556. const backdropWidth = right - left + padding.width;
  10557. const backdropHeight = bottom - top + padding.height;
  10558. if (Object.values(borderRadius).some((v)=>v !== 0)) {
  10559. ctx.beginPath();
  10560. addRoundedRectPath(ctx, {
  10561. x: backdropLeft,
  10562. y: backdropTop,
  10563. w: backdropWidth,
  10564. h: backdropHeight,
  10565. radius: borderRadius
  10566. });
  10567. ctx.fill();
  10568. } else {
  10569. ctx.fillRect(backdropLeft, backdropTop, backdropWidth, backdropHeight);
  10570. }
  10571. }
  10572. }
  10573. function drawPointLabels(scale, labelCount) {
  10574. const { ctx , options: { pointLabels } } = scale;
  10575. for(let i = labelCount - 1; i >= 0; i--){
  10576. const item = scale._pointLabelItems[i];
  10577. if (!item.visible) {
  10578. continue;
  10579. }
  10580. const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i));
  10581. drawPointLabelBox(ctx, optsAtIndex, item);
  10582. const plFont = toFont(optsAtIndex.font);
  10583. const { x , y , textAlign } = item;
  10584. renderText(ctx, scale._pointLabels[i], x, y + plFont.lineHeight / 2, plFont, {
  10585. color: optsAtIndex.color,
  10586. textAlign: textAlign,
  10587. textBaseline: 'middle'
  10588. });
  10589. }
  10590. }
  10591. function pathRadiusLine(scale, radius, circular, labelCount) {
  10592. const { ctx } = scale;
  10593. if (circular) {
  10594. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU);
  10595. } else {
  10596. let pointPosition = scale.getPointPosition(0, radius);
  10597. ctx.moveTo(pointPosition.x, pointPosition.y);
  10598. for(let i = 1; i < labelCount; i++){
  10599. pointPosition = scale.getPointPosition(i, radius);
  10600. ctx.lineTo(pointPosition.x, pointPosition.y);
  10601. }
  10602. }
  10603. }
  10604. function drawRadiusLine(scale, gridLineOpts, radius, labelCount, borderOpts) {
  10605. const ctx = scale.ctx;
  10606. const circular = gridLineOpts.circular;
  10607. const { color , lineWidth } = gridLineOpts;
  10608. if (!circular && !labelCount || !color || !lineWidth || radius < 0) {
  10609. return;
  10610. }
  10611. ctx.save();
  10612. ctx.strokeStyle = color;
  10613. ctx.lineWidth = lineWidth;
  10614. ctx.setLineDash(borderOpts.dash);
  10615. ctx.lineDashOffset = borderOpts.dashOffset;
  10616. ctx.beginPath();
  10617. pathRadiusLine(scale, radius, circular, labelCount);
  10618. ctx.closePath();
  10619. ctx.stroke();
  10620. ctx.restore();
  10621. }
  10622. function createPointLabelContext(parent, index, label) {
  10623. return createContext(parent, {
  10624. label,
  10625. index,
  10626. type: 'pointLabel'
  10627. });
  10628. }
  10629. class RadialLinearScale extends LinearScaleBase {
  10630. static id = 'radialLinear';
  10631. static defaults = {
  10632. display: true,
  10633. animate: true,
  10634. position: 'chartArea',
  10635. angleLines: {
  10636. display: true,
  10637. lineWidth: 1,
  10638. borderDash: [],
  10639. borderDashOffset: 0.0
  10640. },
  10641. grid: {
  10642. circular: false
  10643. },
  10644. startAngle: 0,
  10645. ticks: {
  10646. showLabelBackdrop: true,
  10647. callback: Ticks.formatters.numeric
  10648. },
  10649. pointLabels: {
  10650. backdropColor: undefined,
  10651. backdropPadding: 2,
  10652. display: true,
  10653. font: {
  10654. size: 10
  10655. },
  10656. callback (label) {
  10657. return label;
  10658. },
  10659. padding: 5,
  10660. centerPointLabels: false
  10661. }
  10662. };
  10663. static defaultRoutes = {
  10664. 'angleLines.color': 'borderColor',
  10665. 'pointLabels.color': 'color',
  10666. 'ticks.color': 'color'
  10667. };
  10668. static descriptors = {
  10669. angleLines: {
  10670. _fallback: 'grid'
  10671. }
  10672. };
  10673. constructor(cfg){
  10674. super(cfg);
  10675. this.xCenter = undefined;
  10676. this.yCenter = undefined;
  10677. this.drawingArea = undefined;
  10678. this._pointLabels = [];
  10679. this._pointLabelItems = [];
  10680. }
  10681. setDimensions() {
  10682. const padding = this._padding = toPadding(getTickBackdropHeight(this.options) / 2);
  10683. const w = this.width = this.maxWidth - padding.width;
  10684. const h = this.height = this.maxHeight - padding.height;
  10685. this.xCenter = Math.floor(this.left + w / 2 + padding.left);
  10686. this.yCenter = Math.floor(this.top + h / 2 + padding.top);
  10687. this.drawingArea = Math.floor(Math.min(w, h) / 2);
  10688. }
  10689. determineDataLimits() {
  10690. const { min , max } = this.getMinMax(false);
  10691. this.min = isNumberFinite(min) && !isNaN(min) ? min : 0;
  10692. this.max = isNumberFinite(max) && !isNaN(max) ? max : 0;
  10693. this.handleTickRangeOptions();
  10694. }
  10695. computeTickLimit() {
  10696. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  10697. }
  10698. generateTickLabels(ticks) {
  10699. LinearScaleBase.prototype.generateTickLabels.call(this, ticks);
  10700. this._pointLabels = this.getLabels().map((value, index)=>{
  10701. const label = callback(this.options.pointLabels.callback, [
  10702. value,
  10703. index
  10704. ], this);
  10705. return label || label === 0 ? label : '';
  10706. }).filter((v, i)=>this.chart.getDataVisibility(i));
  10707. }
  10708. fit() {
  10709. const opts = this.options;
  10710. if (opts.display && opts.pointLabels.display) {
  10711. fitWithPointLabels(this);
  10712. } else {
  10713. this.setCenterPoint(0, 0, 0, 0);
  10714. }
  10715. }
  10716. setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {
  10717. this.xCenter += Math.floor((leftMovement - rightMovement) / 2);
  10718. this.yCenter += Math.floor((topMovement - bottomMovement) / 2);
  10719. this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement));
  10720. }
  10721. getIndexAngle(index) {
  10722. const angleMultiplier = TAU / (this._pointLabels.length || 1);
  10723. const startAngle = this.options.startAngle || 0;
  10724. return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));
  10725. }
  10726. getDistanceFromCenterForValue(value) {
  10727. if (isNullOrUndef(value)) {
  10728. return NaN;
  10729. }
  10730. const scalingFactor = this.drawingArea / (this.max - this.min);
  10731. if (this.options.reverse) {
  10732. return (this.max - value) * scalingFactor;
  10733. }
  10734. return (value - this.min) * scalingFactor;
  10735. }
  10736. getValueForDistanceFromCenter(distance) {
  10737. if (isNullOrUndef(distance)) {
  10738. return NaN;
  10739. }
  10740. const scaledDistance = distance / (this.drawingArea / (this.max - this.min));
  10741. return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance;
  10742. }
  10743. getPointLabelContext(index) {
  10744. const pointLabels = this._pointLabels || [];
  10745. if (index >= 0 && index < pointLabels.length) {
  10746. const pointLabel = pointLabels[index];
  10747. return createPointLabelContext(this.getContext(), index, pointLabel);
  10748. }
  10749. }
  10750. getPointPosition(index, distanceFromCenter, additionalAngle = 0) {
  10751. const angle = this.getIndexAngle(index) - HALF_PI + additionalAngle;
  10752. return {
  10753. x: Math.cos(angle) * distanceFromCenter + this.xCenter,
  10754. y: Math.sin(angle) * distanceFromCenter + this.yCenter,
  10755. angle
  10756. };
  10757. }
  10758. getPointPositionForValue(index, value) {
  10759. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  10760. }
  10761. getBasePosition(index) {
  10762. return this.getPointPositionForValue(index || 0, this.getBaseValue());
  10763. }
  10764. getPointLabelPosition(index) {
  10765. const { left , top , right , bottom } = this._pointLabelItems[index];
  10766. return {
  10767. left,
  10768. top,
  10769. right,
  10770. bottom
  10771. };
  10772. }
  10773. drawBackground() {
  10774. const { backgroundColor , grid: { circular } } = this.options;
  10775. if (backgroundColor) {
  10776. const ctx = this.ctx;
  10777. ctx.save();
  10778. ctx.beginPath();
  10779. pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length);
  10780. ctx.closePath();
  10781. ctx.fillStyle = backgroundColor;
  10782. ctx.fill();
  10783. ctx.restore();
  10784. }
  10785. }
  10786. drawGrid() {
  10787. const ctx = this.ctx;
  10788. const opts = this.options;
  10789. const { angleLines , grid , border } = opts;
  10790. const labelCount = this._pointLabels.length;
  10791. let i, offset, position;
  10792. if (opts.pointLabels.display) {
  10793. drawPointLabels(this, labelCount);
  10794. }
  10795. if (grid.display) {
  10796. this.ticks.forEach((tick, index)=>{
  10797. if (index !== 0 || index === 0 && this.min < 0) {
  10798. offset = this.getDistanceFromCenterForValue(tick.value);
  10799. const context = this.getContext(index);
  10800. const optsAtIndex = grid.setContext(context);
  10801. const optsAtIndexBorder = border.setContext(context);
  10802. drawRadiusLine(this, optsAtIndex, offset, labelCount, optsAtIndexBorder);
  10803. }
  10804. });
  10805. }
  10806. if (angleLines.display) {
  10807. ctx.save();
  10808. for(i = labelCount - 1; i >= 0; i--){
  10809. const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i));
  10810. const { color , lineWidth } = optsAtIndex;
  10811. if (!lineWidth || !color) {
  10812. continue;
  10813. }
  10814. ctx.lineWidth = lineWidth;
  10815. ctx.strokeStyle = color;
  10816. ctx.setLineDash(optsAtIndex.borderDash);
  10817. ctx.lineDashOffset = optsAtIndex.borderDashOffset;
  10818. offset = this.getDistanceFromCenterForValue(opts.reverse ? this.min : this.max);
  10819. position = this.getPointPosition(i, offset);
  10820. ctx.beginPath();
  10821. ctx.moveTo(this.xCenter, this.yCenter);
  10822. ctx.lineTo(position.x, position.y);
  10823. ctx.stroke();
  10824. }
  10825. ctx.restore();
  10826. }
  10827. }
  10828. drawBorder() {}
  10829. drawLabels() {
  10830. const ctx = this.ctx;
  10831. const opts = this.options;
  10832. const tickOpts = opts.ticks;
  10833. if (!tickOpts.display) {
  10834. return;
  10835. }
  10836. const startAngle = this.getIndexAngle(0);
  10837. let offset, width;
  10838. ctx.save();
  10839. ctx.translate(this.xCenter, this.yCenter);
  10840. ctx.rotate(startAngle);
  10841. ctx.textAlign = 'center';
  10842. ctx.textBaseline = 'middle';
  10843. this.ticks.forEach((tick, index)=>{
  10844. if (index === 0 && this.min >= 0 && !opts.reverse) {
  10845. return;
  10846. }
  10847. const optsAtIndex = tickOpts.setContext(this.getContext(index));
  10848. const tickFont = toFont(optsAtIndex.font);
  10849. offset = this.getDistanceFromCenterForValue(this.ticks[index].value);
  10850. if (optsAtIndex.showLabelBackdrop) {
  10851. ctx.font = tickFont.string;
  10852. width = ctx.measureText(tick.label).width;
  10853. ctx.fillStyle = optsAtIndex.backdropColor;
  10854. const padding = toPadding(optsAtIndex.backdropPadding);
  10855. ctx.fillRect(-width / 2 - padding.left, -offset - tickFont.size / 2 - padding.top, width + padding.width, tickFont.size + padding.height);
  10856. }
  10857. renderText(ctx, tick.label, 0, -offset, tickFont, {
  10858. color: optsAtIndex.color,
  10859. strokeColor: optsAtIndex.textStrokeColor,
  10860. strokeWidth: optsAtIndex.textStrokeWidth
  10861. });
  10862. });
  10863. ctx.restore();
  10864. }
  10865. drawTitle() {}
  10866. }
  10867. const INTERVALS = {
  10868. millisecond: {
  10869. common: true,
  10870. size: 1,
  10871. steps: 1000
  10872. },
  10873. second: {
  10874. common: true,
  10875. size: 1000,
  10876. steps: 60
  10877. },
  10878. minute: {
  10879. common: true,
  10880. size: 60000,
  10881. steps: 60
  10882. },
  10883. hour: {
  10884. common: true,
  10885. size: 3600000,
  10886. steps: 24
  10887. },
  10888. day: {
  10889. common: true,
  10890. size: 86400000,
  10891. steps: 30
  10892. },
  10893. week: {
  10894. common: false,
  10895. size: 604800000,
  10896. steps: 4
  10897. },
  10898. month: {
  10899. common: true,
  10900. size: 2.628e9,
  10901. steps: 12
  10902. },
  10903. quarter: {
  10904. common: false,
  10905. size: 7.884e9,
  10906. steps: 4
  10907. },
  10908. year: {
  10909. common: true,
  10910. size: 3.154e10
  10911. }
  10912. };
  10913. const UNITS = /* #__PURE__ */ Object.keys(INTERVALS);
  10914. function sorter(a, b) {
  10915. return a - b;
  10916. }
  10917. function parse(scale, input) {
  10918. if (isNullOrUndef(input)) {
  10919. return null;
  10920. }
  10921. const adapter = scale._adapter;
  10922. const { parser , round , isoWeekday } = scale._parseOpts;
  10923. let value = input;
  10924. if (typeof parser === 'function') {
  10925. value = parser(value);
  10926. }
  10927. if (!isNumberFinite(value)) {
  10928. value = typeof parser === 'string' ? adapter.parse(value, parser) : adapter.parse(value);
  10929. }
  10930. if (value === null) {
  10931. return null;
  10932. }
  10933. if (round) {
  10934. value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true) ? adapter.startOf(value, 'isoWeek', isoWeekday) : adapter.startOf(value, round);
  10935. }
  10936. return +value;
  10937. }
  10938. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  10939. const ilen = UNITS.length;
  10940. for(let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i){
  10941. const interval = INTERVALS[UNITS[i]];
  10942. const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;
  10943. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  10944. return UNITS[i];
  10945. }
  10946. }
  10947. return UNITS[ilen - 1];
  10948. }
  10949. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  10950. for(let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--){
  10951. const unit = UNITS[i];
  10952. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  10953. return unit;
  10954. }
  10955. }
  10956. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  10957. }
  10958. function determineMajorUnit(unit) {
  10959. for(let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i){
  10960. if (INTERVALS[UNITS[i]].common) {
  10961. return UNITS[i];
  10962. }
  10963. }
  10964. }
  10965. function addTick(ticks, time, timestamps) {
  10966. if (!timestamps) {
  10967. ticks[time] = true;
  10968. } else if (timestamps.length) {
  10969. const { lo , hi } = _lookup(timestamps, time);
  10970. const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];
  10971. ticks[timestamp] = true;
  10972. }
  10973. }
  10974. function setMajorTicks(scale, ticks, map, majorUnit) {
  10975. const adapter = scale._adapter;
  10976. const first = +adapter.startOf(ticks[0].value, majorUnit);
  10977. const last = ticks[ticks.length - 1].value;
  10978. let major, index;
  10979. for(major = first; major <= last; major = +adapter.add(major, 1, majorUnit)){
  10980. index = map[major];
  10981. if (index >= 0) {
  10982. ticks[index].major = true;
  10983. }
  10984. }
  10985. return ticks;
  10986. }
  10987. function ticksFromTimestamps(scale, values, majorUnit) {
  10988. const ticks = [];
  10989. const map = {};
  10990. const ilen = values.length;
  10991. let i, value;
  10992. for(i = 0; i < ilen; ++i){
  10993. value = values[i];
  10994. map[value] = i;
  10995. ticks.push({
  10996. value,
  10997. major: false
  10998. });
  10999. }
  11000. return ilen === 0 || !majorUnit ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  11001. }
  11002. class TimeScale extends Scale {
  11003. static id = 'time';
  11004. static defaults = {
  11005. bounds: 'data',
  11006. adapters: {},
  11007. time: {
  11008. parser: false,
  11009. unit: false,
  11010. round: false,
  11011. isoWeekday: false,
  11012. minUnit: 'millisecond',
  11013. displayFormats: {}
  11014. },
  11015. ticks: {
  11016. source: 'auto',
  11017. callback: false,
  11018. major: {
  11019. enabled: false
  11020. }
  11021. }
  11022. };
  11023. constructor(props){
  11024. super(props);
  11025. this._cache = {
  11026. data: [],
  11027. labels: [],
  11028. all: []
  11029. };
  11030. this._unit = 'day';
  11031. this._majorUnit = undefined;
  11032. this._offsets = {};
  11033. this._normalized = false;
  11034. this._parseOpts = undefined;
  11035. }
  11036. init(scaleOpts, opts = {}) {
  11037. const time = scaleOpts.time || (scaleOpts.time = {});
  11038. const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);
  11039. adapter.init(opts);
  11040. mergeIf(time.displayFormats, adapter.formats());
  11041. this._parseOpts = {
  11042. parser: time.parser,
  11043. round: time.round,
  11044. isoWeekday: time.isoWeekday
  11045. };
  11046. super.init(scaleOpts);
  11047. this._normalized = opts.normalized;
  11048. }
  11049. parse(raw, index) {
  11050. if (raw === undefined) {
  11051. return null;
  11052. }
  11053. return parse(this, raw);
  11054. }
  11055. beforeLayout() {
  11056. super.beforeLayout();
  11057. this._cache = {
  11058. data: [],
  11059. labels: [],
  11060. all: []
  11061. };
  11062. }
  11063. determineDataLimits() {
  11064. const options = this.options;
  11065. const adapter = this._adapter;
  11066. const unit = options.time.unit || 'day';
  11067. let { min , max , minDefined , maxDefined } = this.getUserBounds();
  11068. function _applyBounds(bounds) {
  11069. if (!minDefined && !isNaN(bounds.min)) {
  11070. min = Math.min(min, bounds.min);
  11071. }
  11072. if (!maxDefined && !isNaN(bounds.max)) {
  11073. max = Math.max(max, bounds.max);
  11074. }
  11075. }
  11076. if (!minDefined || !maxDefined) {
  11077. _applyBounds(this._getLabelBounds());
  11078. if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {
  11079. _applyBounds(this.getMinMax(false));
  11080. }
  11081. }
  11082. min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);
  11083. max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;
  11084. this.min = Math.min(min, max - 1);
  11085. this.max = Math.max(min + 1, max);
  11086. }
  11087. _getLabelBounds() {
  11088. const arr = this.getLabelTimestamps();
  11089. let min = Number.POSITIVE_INFINITY;
  11090. let max = Number.NEGATIVE_INFINITY;
  11091. if (arr.length) {
  11092. min = arr[0];
  11093. max = arr[arr.length - 1];
  11094. }
  11095. return {
  11096. min,
  11097. max
  11098. };
  11099. }
  11100. buildTicks() {
  11101. const options = this.options;
  11102. const timeOpts = options.time;
  11103. const tickOpts = options.ticks;
  11104. const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate();
  11105. if (options.bounds === 'ticks' && timestamps.length) {
  11106. this.min = this._userMin || timestamps[0];
  11107. this.max = this._userMax || timestamps[timestamps.length - 1];
  11108. }
  11109. const min = this.min;
  11110. const max = this.max;
  11111. const ticks = _filterBetween(timestamps, min, max);
  11112. this._unit = timeOpts.unit || (tickOpts.autoSkip ? determineUnitForAutoTicks(timeOpts.minUnit, this.min, this.max, this._getLabelCapacity(min)) : determineUnitForFormatting(this, ticks.length, timeOpts.minUnit, this.min, this.max));
  11113. this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined : determineMajorUnit(this._unit);
  11114. this.initOffsets(timestamps);
  11115. if (options.reverse) {
  11116. ticks.reverse();
  11117. }
  11118. return ticksFromTimestamps(this, ticks, this._majorUnit);
  11119. }
  11120. afterAutoSkip() {
  11121. if (this.options.offsetAfterAutoskip) {
  11122. this.initOffsets(this.ticks.map((tick)=>+tick.value));
  11123. }
  11124. }
  11125. initOffsets(timestamps = []) {
  11126. let start = 0;
  11127. let end = 0;
  11128. let first, last;
  11129. if (this.options.offset && timestamps.length) {
  11130. first = this.getDecimalForValue(timestamps[0]);
  11131. if (timestamps.length === 1) {
  11132. start = 1 - first;
  11133. } else {
  11134. start = (this.getDecimalForValue(timestamps[1]) - first) / 2;
  11135. }
  11136. last = this.getDecimalForValue(timestamps[timestamps.length - 1]);
  11137. if (timestamps.length === 1) {
  11138. end = last;
  11139. } else {
  11140. end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;
  11141. }
  11142. }
  11143. const limit = timestamps.length < 3 ? 0.5 : 0.25;
  11144. start = _limitValue(start, 0, limit);
  11145. end = _limitValue(end, 0, limit);
  11146. this._offsets = {
  11147. start,
  11148. end,
  11149. factor: 1 / (start + 1 + end)
  11150. };
  11151. }
  11152. _generate() {
  11153. const adapter = this._adapter;
  11154. const min = this.min;
  11155. const max = this.max;
  11156. const options = this.options;
  11157. const timeOpts = options.time;
  11158. const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min));
  11159. const stepSize = valueOrDefault(options.ticks.stepSize, 1);
  11160. const weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  11161. const hasWeekday = isNumber(weekday) || weekday === true;
  11162. const ticks = {};
  11163. let first = min;
  11164. let time, count;
  11165. if (hasWeekday) {
  11166. first = +adapter.startOf(first, 'isoWeek', weekday);
  11167. }
  11168. first = +adapter.startOf(first, hasWeekday ? 'day' : minor);
  11169. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  11170. throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);
  11171. }
  11172. const timestamps = options.ticks.source === 'data' && this.getDataTimestamps();
  11173. for(time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++){
  11174. addTick(ticks, time, timestamps);
  11175. }
  11176. if (time === max || options.bounds === 'ticks' || count === 1) {
  11177. addTick(ticks, time, timestamps);
  11178. }
  11179. return Object.keys(ticks).sort(sorter).map((x)=>+x);
  11180. }
  11181. getLabelForValue(value) {
  11182. const adapter = this._adapter;
  11183. const timeOpts = this.options.time;
  11184. if (timeOpts.tooltipFormat) {
  11185. return adapter.format(value, timeOpts.tooltipFormat);
  11186. }
  11187. return adapter.format(value, timeOpts.displayFormats.datetime);
  11188. }
  11189. format(value, format) {
  11190. const options = this.options;
  11191. const formats = options.time.displayFormats;
  11192. const unit = this._unit;
  11193. const fmt = format || formats[unit];
  11194. return this._adapter.format(value, fmt);
  11195. }
  11196. _tickFormatFunction(time, index, ticks, format) {
  11197. const options = this.options;
  11198. const formatter = options.ticks.callback;
  11199. if (formatter) {
  11200. return callback(formatter, [
  11201. time,
  11202. index,
  11203. ticks
  11204. ], this);
  11205. }
  11206. const formats = options.time.displayFormats;
  11207. const unit = this._unit;
  11208. const majorUnit = this._majorUnit;
  11209. const minorFormat = unit && formats[unit];
  11210. const majorFormat = majorUnit && formats[majorUnit];
  11211. const tick = ticks[index];
  11212. const major = majorUnit && majorFormat && tick && tick.major;
  11213. return this._adapter.format(time, format || (major ? majorFormat : minorFormat));
  11214. }
  11215. generateTickLabels(ticks) {
  11216. let i, ilen, tick;
  11217. for(i = 0, ilen = ticks.length; i < ilen; ++i){
  11218. tick = ticks[i];
  11219. tick.label = this._tickFormatFunction(tick.value, i, ticks);
  11220. }
  11221. }
  11222. getDecimalForValue(value) {
  11223. return value === null ? NaN : (value - this.min) / (this.max - this.min);
  11224. }
  11225. getPixelForValue(value) {
  11226. const offsets = this._offsets;
  11227. const pos = this.getDecimalForValue(value);
  11228. return this.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  11229. }
  11230. getValueForPixel(pixel) {
  11231. const offsets = this._offsets;
  11232. const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  11233. return this.min + pos * (this.max - this.min);
  11234. }
  11235. _getLabelSize(label) {
  11236. const ticksOpts = this.options.ticks;
  11237. const tickLabelWidth = this.ctx.measureText(label).width;
  11238. const angle = toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  11239. const cosRotation = Math.cos(angle);
  11240. const sinRotation = Math.sin(angle);
  11241. const tickFontSize = this._resolveTickFontOptions(0).size;
  11242. return {
  11243. w: tickLabelWidth * cosRotation + tickFontSize * sinRotation,
  11244. h: tickLabelWidth * sinRotation + tickFontSize * cosRotation
  11245. };
  11246. }
  11247. _getLabelCapacity(exampleTime) {
  11248. const timeOpts = this.options.time;
  11249. const displayFormats = timeOpts.displayFormats;
  11250. const format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  11251. const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [
  11252. exampleTime
  11253. ], this._majorUnit), format);
  11254. const size = this._getLabelSize(exampleLabel);
  11255. const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1;
  11256. return capacity > 0 ? capacity : 1;
  11257. }
  11258. getDataTimestamps() {
  11259. let timestamps = this._cache.data || [];
  11260. let i, ilen;
  11261. if (timestamps.length) {
  11262. return timestamps;
  11263. }
  11264. const metas = this.getMatchingVisibleMetas();
  11265. if (this._normalized && metas.length) {
  11266. return this._cache.data = metas[0].controller.getAllParsedValues(this);
  11267. }
  11268. for(i = 0, ilen = metas.length; i < ilen; ++i){
  11269. timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this));
  11270. }
  11271. return this._cache.data = this.normalize(timestamps);
  11272. }
  11273. getLabelTimestamps() {
  11274. const timestamps = this._cache.labels || [];
  11275. let i, ilen;
  11276. if (timestamps.length) {
  11277. return timestamps;
  11278. }
  11279. const labels = this.getLabels();
  11280. for(i = 0, ilen = labels.length; i < ilen; ++i){
  11281. timestamps.push(parse(this, labels[i]));
  11282. }
  11283. return this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps);
  11284. }
  11285. normalize(values) {
  11286. return _arrayUnique(values.sort(sorter));
  11287. }
  11288. }
  11289. function interpolate(table, val, reverse) {
  11290. let lo = 0;
  11291. let hi = table.length - 1;
  11292. let prevSource, nextSource, prevTarget, nextTarget;
  11293. if (reverse) {
  11294. if (val >= table[lo].pos && val <= table[hi].pos) {
  11295. ({ lo , hi } = _lookupByKey(table, 'pos', val));
  11296. }
  11297. ({ pos: prevSource , time: prevTarget } = table[lo]);
  11298. ({ pos: nextSource , time: nextTarget } = table[hi]);
  11299. } else {
  11300. if (val >= table[lo].time && val <= table[hi].time) {
  11301. ({ lo , hi } = _lookupByKey(table, 'time', val));
  11302. }
  11303. ({ time: prevSource , pos: prevTarget } = table[lo]);
  11304. ({ time: nextSource , pos: nextTarget } = table[hi]);
  11305. }
  11306. const span = nextSource - prevSource;
  11307. return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;
  11308. }
  11309. class TimeSeriesScale extends TimeScale {
  11310. static id = 'timeseries';
  11311. static defaults = TimeScale.defaults;
  11312. constructor(props){
  11313. super(props);
  11314. this._table = [];
  11315. this._minPos = undefined;
  11316. this._tableRange = undefined;
  11317. }
  11318. initOffsets() {
  11319. const timestamps = this._getTimestampsForTable();
  11320. const table = this._table = this.buildLookupTable(timestamps);
  11321. this._minPos = interpolate(table, this.min);
  11322. this._tableRange = interpolate(table, this.max) - this._minPos;
  11323. super.initOffsets(timestamps);
  11324. }
  11325. buildLookupTable(timestamps) {
  11326. const { min , max } = this;
  11327. const items = [];
  11328. const table = [];
  11329. let i, ilen, prev, curr, next;
  11330. for(i = 0, ilen = timestamps.length; i < ilen; ++i){
  11331. curr = timestamps[i];
  11332. if (curr >= min && curr <= max) {
  11333. items.push(curr);
  11334. }
  11335. }
  11336. if (items.length < 2) {
  11337. return [
  11338. {
  11339. time: min,
  11340. pos: 0
  11341. },
  11342. {
  11343. time: max,
  11344. pos: 1
  11345. }
  11346. ];
  11347. }
  11348. for(i = 0, ilen = items.length; i < ilen; ++i){
  11349. next = items[i + 1];
  11350. prev = items[i - 1];
  11351. curr = items[i];
  11352. if (Math.round((next + prev) / 2) !== curr) {
  11353. table.push({
  11354. time: curr,
  11355. pos: i / (ilen - 1)
  11356. });
  11357. }
  11358. }
  11359. return table;
  11360. }
  11361. _generate() {
  11362. const min = this.min;
  11363. const max = this.max;
  11364. let timestamps = super.getDataTimestamps();
  11365. if (!timestamps.includes(min) || !timestamps.length) {
  11366. timestamps.splice(0, 0, min);
  11367. }
  11368. if (!timestamps.includes(max) || timestamps.length === 1) {
  11369. timestamps.push(max);
  11370. }
  11371. return timestamps.sort((a, b)=>a - b);
  11372. }
  11373. _getTimestampsForTable() {
  11374. let timestamps = this._cache.all || [];
  11375. if (timestamps.length) {
  11376. return timestamps;
  11377. }
  11378. const data = this.getDataTimestamps();
  11379. const label = this.getLabelTimestamps();
  11380. if (data.length && label.length) {
  11381. timestamps = this.normalize(data.concat(label));
  11382. } else {
  11383. timestamps = data.length ? data : label;
  11384. }
  11385. timestamps = this._cache.all = timestamps;
  11386. return timestamps;
  11387. }
  11388. getDecimalForValue(value) {
  11389. return (interpolate(this._table, value) - this._minPos) / this._tableRange;
  11390. }
  11391. getValueForPixel(pixel) {
  11392. const offsets = this._offsets;
  11393. const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  11394. return interpolate(this._table, decimal * this._tableRange + this._minPos, true);
  11395. }
  11396. }
  11397. var scales = /*#__PURE__*/Object.freeze({
  11398. __proto__: null,
  11399. CategoryScale: CategoryScale,
  11400. LinearScale: LinearScale,
  11401. LogarithmicScale: LogarithmicScale,
  11402. RadialLinearScale: RadialLinearScale,
  11403. TimeScale: TimeScale,
  11404. TimeSeriesScale: TimeSeriesScale
  11405. });
  11406. const registerables = [
  11407. controllers,
  11408. elements,
  11409. plugins,
  11410. scales
  11411. ];
  11412. export { Animation, Animations, ArcElement, BarController, BarElement, BasePlatform, BasicPlatform, BubbleController, CategoryScale, Chart, plugin_colors as Colors, DatasetController, plugin_decimation as Decimation, DomPlatform, DoughnutController, Element, index as Filler, Interaction, plugin_legend as Legend, LineController, LineElement, LinearScale, LogarithmicScale, PieController, PointElement, PolarAreaController, RadarController, RadialLinearScale, Scale, ScatterController, plugin_subtitle as SubTitle, Ticks, TimeScale, TimeSeriesScale, plugin_title as Title, plugin_tooltip as Tooltip, adapters as _adapters, _detectPlatform, animator, controllers, defaults, elements, layouts, plugins, registerables, registry, scales };
  11413. //# sourceMappingURL=chart.js.map