Node-Red configuration
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

chart.cjs 401KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520
  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. 'use strict';
  8. var helpers_segment = require('./chunks/helpers.segment.cjs');
  9. require('@kurkle/color');
  10. class Animator {
  11. constructor(){
  12. this._request = null;
  13. this._charts = new Map();
  14. this._running = false;
  15. this._lastDate = undefined;
  16. }
  17. _notify(chart, anims, date, type) {
  18. const callbacks = anims.listeners[type];
  19. const numSteps = anims.duration;
  20. callbacks.forEach((fn)=>fn({
  21. chart,
  22. initial: anims.initial,
  23. numSteps,
  24. currentStep: Math.min(date - anims.start, numSteps)
  25. }));
  26. }
  27. _refresh() {
  28. if (this._request) {
  29. return;
  30. }
  31. this._running = true;
  32. this._request = helpers_segment.requestAnimFrame.call(window, ()=>{
  33. this._update();
  34. this._request = null;
  35. if (this._running) {
  36. this._refresh();
  37. }
  38. });
  39. }
  40. _update(date = Date.now()) {
  41. let remaining = 0;
  42. this._charts.forEach((anims, chart)=>{
  43. if (!anims.running || !anims.items.length) {
  44. return;
  45. }
  46. const items = anims.items;
  47. let i = items.length - 1;
  48. let draw = false;
  49. let item;
  50. for(; i >= 0; --i){
  51. item = items[i];
  52. if (item._active) {
  53. if (item._total > anims.duration) {
  54. anims.duration = item._total;
  55. }
  56. item.tick(date);
  57. draw = true;
  58. } else {
  59. items[i] = items[items.length - 1];
  60. items.pop();
  61. }
  62. }
  63. if (draw) {
  64. chart.draw();
  65. this._notify(chart, anims, date, 'progress');
  66. }
  67. if (!items.length) {
  68. anims.running = false;
  69. this._notify(chart, anims, date, 'complete');
  70. anims.initial = false;
  71. }
  72. remaining += items.length;
  73. });
  74. this._lastDate = date;
  75. if (remaining === 0) {
  76. this._running = false;
  77. }
  78. }
  79. _getAnims(chart) {
  80. const charts = this._charts;
  81. let anims = charts.get(chart);
  82. if (!anims) {
  83. anims = {
  84. running: false,
  85. initial: true,
  86. items: [],
  87. listeners: {
  88. complete: [],
  89. progress: []
  90. }
  91. };
  92. charts.set(chart, anims);
  93. }
  94. return anims;
  95. }
  96. listen(chart, event, cb) {
  97. this._getAnims(chart).listeners[event].push(cb);
  98. }
  99. add(chart, items) {
  100. if (!items || !items.length) {
  101. return;
  102. }
  103. this._getAnims(chart).items.push(...items);
  104. }
  105. has(chart) {
  106. return this._getAnims(chart).items.length > 0;
  107. }
  108. start(chart) {
  109. const anims = this._charts.get(chart);
  110. if (!anims) {
  111. return;
  112. }
  113. anims.running = true;
  114. anims.start = Date.now();
  115. anims.duration = anims.items.reduce((acc, cur)=>Math.max(acc, cur._duration), 0);
  116. this._refresh();
  117. }
  118. running(chart) {
  119. if (!this._running) {
  120. return false;
  121. }
  122. const anims = this._charts.get(chart);
  123. if (!anims || !anims.running || !anims.items.length) {
  124. return false;
  125. }
  126. return true;
  127. }
  128. stop(chart) {
  129. const anims = this._charts.get(chart);
  130. if (!anims || !anims.items.length) {
  131. return;
  132. }
  133. const items = anims.items;
  134. let i = items.length - 1;
  135. for(; i >= 0; --i){
  136. items[i].cancel();
  137. }
  138. anims.items = [];
  139. this._notify(chart, anims, Date.now(), 'complete');
  140. }
  141. remove(chart) {
  142. return this._charts.delete(chart);
  143. }
  144. }
  145. var animator = /* #__PURE__ */ new Animator();
  146. const transparent = 'transparent';
  147. const interpolators = {
  148. boolean (from, to, factor) {
  149. return factor > 0.5 ? to : from;
  150. },
  151. color (from, to, factor) {
  152. const c0 = helpers_segment.color(from || transparent);
  153. const c1 = c0.valid && helpers_segment.color(to || transparent);
  154. return c1 && c1.valid ? c1.mix(c0, factor).hexString() : to;
  155. },
  156. number (from, to, factor) {
  157. return from + (to - from) * factor;
  158. }
  159. };
  160. class Animation {
  161. constructor(cfg, target, prop, to){
  162. const currentValue = target[prop];
  163. to = helpers_segment.resolve([
  164. cfg.to,
  165. to,
  166. currentValue,
  167. cfg.from
  168. ]);
  169. const from = helpers_segment.resolve([
  170. cfg.from,
  171. currentValue,
  172. to
  173. ]);
  174. this._active = true;
  175. this._fn = cfg.fn || interpolators[cfg.type || typeof from];
  176. this._easing = helpers_segment.effects[cfg.easing] || helpers_segment.effects.linear;
  177. this._start = Math.floor(Date.now() + (cfg.delay || 0));
  178. this._duration = this._total = Math.floor(cfg.duration);
  179. this._loop = !!cfg.loop;
  180. this._target = target;
  181. this._prop = prop;
  182. this._from = from;
  183. this._to = to;
  184. this._promises = undefined;
  185. }
  186. active() {
  187. return this._active;
  188. }
  189. update(cfg, to, date) {
  190. if (this._active) {
  191. this._notify(false);
  192. const currentValue = this._target[this._prop];
  193. const elapsed = date - this._start;
  194. const remain = this._duration - elapsed;
  195. this._start = date;
  196. this._duration = Math.floor(Math.max(remain, cfg.duration));
  197. this._total += elapsed;
  198. this._loop = !!cfg.loop;
  199. this._to = helpers_segment.resolve([
  200. cfg.to,
  201. to,
  202. currentValue,
  203. cfg.from
  204. ]);
  205. this._from = helpers_segment.resolve([
  206. cfg.from,
  207. currentValue,
  208. to
  209. ]);
  210. }
  211. }
  212. cancel() {
  213. if (this._active) {
  214. this.tick(Date.now());
  215. this._active = false;
  216. this._notify(false);
  217. }
  218. }
  219. tick(date) {
  220. const elapsed = date - this._start;
  221. const duration = this._duration;
  222. const prop = this._prop;
  223. const from = this._from;
  224. const loop = this._loop;
  225. const to = this._to;
  226. let factor;
  227. this._active = from !== to && (loop || elapsed < duration);
  228. if (!this._active) {
  229. this._target[prop] = to;
  230. this._notify(true);
  231. return;
  232. }
  233. if (elapsed < 0) {
  234. this._target[prop] = from;
  235. return;
  236. }
  237. factor = elapsed / duration % 2;
  238. factor = loop && factor > 1 ? 2 - factor : factor;
  239. factor = this._easing(Math.min(1, Math.max(0, factor)));
  240. this._target[prop] = this._fn(from, to, factor);
  241. }
  242. wait() {
  243. const promises = this._promises || (this._promises = []);
  244. return new Promise((res, rej)=>{
  245. promises.push({
  246. res,
  247. rej
  248. });
  249. });
  250. }
  251. _notify(resolved) {
  252. const method = resolved ? 'res' : 'rej';
  253. const promises = this._promises || [];
  254. for(let i = 0; i < promises.length; i++){
  255. promises[i][method]();
  256. }
  257. }
  258. }
  259. class Animations {
  260. constructor(chart, config){
  261. this._chart = chart;
  262. this._properties = new Map();
  263. this.configure(config);
  264. }
  265. configure(config) {
  266. if (!helpers_segment.isObject(config)) {
  267. return;
  268. }
  269. const animationOptions = Object.keys(helpers_segment.defaults.animation);
  270. const animatedProps = this._properties;
  271. Object.getOwnPropertyNames(config).forEach((key)=>{
  272. const cfg = config[key];
  273. if (!helpers_segment.isObject(cfg)) {
  274. return;
  275. }
  276. const resolved = {};
  277. for (const option of animationOptions){
  278. resolved[option] = cfg[option];
  279. }
  280. (helpers_segment.isArray(cfg.properties) && cfg.properties || [
  281. key
  282. ]).forEach((prop)=>{
  283. if (prop === key || !animatedProps.has(prop)) {
  284. animatedProps.set(prop, resolved);
  285. }
  286. });
  287. });
  288. }
  289. _animateOptions(target, values) {
  290. const newOptions = values.options;
  291. const options = resolveTargetOptions(target, newOptions);
  292. if (!options) {
  293. return [];
  294. }
  295. const animations = this._createAnimations(options, newOptions);
  296. if (newOptions.$shared) {
  297. awaitAll(target.options.$animations, newOptions).then(()=>{
  298. target.options = newOptions;
  299. }, ()=>{
  300. });
  301. }
  302. return animations;
  303. }
  304. _createAnimations(target, values) {
  305. const animatedProps = this._properties;
  306. const animations = [];
  307. const running = target.$animations || (target.$animations = {});
  308. const props = Object.keys(values);
  309. const date = Date.now();
  310. let i;
  311. for(i = props.length - 1; i >= 0; --i){
  312. const prop = props[i];
  313. if (prop.charAt(0) === '$') {
  314. continue;
  315. }
  316. if (prop === 'options') {
  317. animations.push(...this._animateOptions(target, values));
  318. continue;
  319. }
  320. const value = values[prop];
  321. let animation = running[prop];
  322. const cfg = animatedProps.get(prop);
  323. if (animation) {
  324. if (cfg && animation.active()) {
  325. animation.update(cfg, value, date);
  326. continue;
  327. } else {
  328. animation.cancel();
  329. }
  330. }
  331. if (!cfg || !cfg.duration) {
  332. target[prop] = value;
  333. continue;
  334. }
  335. running[prop] = animation = new Animation(cfg, target, prop, value);
  336. animations.push(animation);
  337. }
  338. return animations;
  339. }
  340. update(target, values) {
  341. if (this._properties.size === 0) {
  342. Object.assign(target, values);
  343. return;
  344. }
  345. const animations = this._createAnimations(target, values);
  346. if (animations.length) {
  347. animator.add(this._chart, animations);
  348. return true;
  349. }
  350. }
  351. }
  352. function awaitAll(animations, properties) {
  353. const running = [];
  354. const keys = Object.keys(properties);
  355. for(let i = 0; i < keys.length; i++){
  356. const anim = animations[keys[i]];
  357. if (anim && anim.active()) {
  358. running.push(anim.wait());
  359. }
  360. }
  361. return Promise.all(running);
  362. }
  363. function resolveTargetOptions(target, newOptions) {
  364. if (!newOptions) {
  365. return;
  366. }
  367. let options = target.options;
  368. if (!options) {
  369. target.options = newOptions;
  370. return;
  371. }
  372. if (options.$shared) {
  373. target.options = options = Object.assign({}, options, {
  374. $shared: false,
  375. $animations: {}
  376. });
  377. }
  378. return options;
  379. }
  380. function scaleClip(scale, allowedOverflow) {
  381. const opts = scale && scale.options || {};
  382. const reverse = opts.reverse;
  383. const min = opts.min === undefined ? allowedOverflow : 0;
  384. const max = opts.max === undefined ? allowedOverflow : 0;
  385. return {
  386. start: reverse ? max : min,
  387. end: reverse ? min : max
  388. };
  389. }
  390. function defaultClip(xScale, yScale, allowedOverflow) {
  391. if (allowedOverflow === false) {
  392. return false;
  393. }
  394. const x = scaleClip(xScale, allowedOverflow);
  395. const y = scaleClip(yScale, allowedOverflow);
  396. return {
  397. top: y.end,
  398. right: x.end,
  399. bottom: y.start,
  400. left: x.start
  401. };
  402. }
  403. function toClip(value) {
  404. let t, r, b, l;
  405. if (helpers_segment.isObject(value)) {
  406. t = value.top;
  407. r = value.right;
  408. b = value.bottom;
  409. l = value.left;
  410. } else {
  411. t = r = b = l = value;
  412. }
  413. return {
  414. top: t,
  415. right: r,
  416. bottom: b,
  417. left: l,
  418. disabled: value === false
  419. };
  420. }
  421. function getSortedDatasetIndices(chart, filterVisible) {
  422. const keys = [];
  423. const metasets = chart._getSortedDatasetMetas(filterVisible);
  424. let i, ilen;
  425. for(i = 0, ilen = metasets.length; i < ilen; ++i){
  426. keys.push(metasets[i].index);
  427. }
  428. return keys;
  429. }
  430. function applyStack(stack, value, dsIndex, options = {}) {
  431. const keys = stack.keys;
  432. const singleMode = options.mode === 'single';
  433. let i, ilen, datasetIndex, otherValue;
  434. if (value === null) {
  435. return;
  436. }
  437. for(i = 0, ilen = keys.length; i < ilen; ++i){
  438. datasetIndex = +keys[i];
  439. if (datasetIndex === dsIndex) {
  440. if (options.all) {
  441. continue;
  442. }
  443. break;
  444. }
  445. otherValue = stack.values[datasetIndex];
  446. if (helpers_segment.isNumberFinite(otherValue) && (singleMode || value === 0 || helpers_segment.sign(value) === helpers_segment.sign(otherValue))) {
  447. value += otherValue;
  448. }
  449. }
  450. return value;
  451. }
  452. function convertObjectDataToArray(data, meta) {
  453. const { iScale , vScale } = meta;
  454. const iAxisKey = iScale.axis === 'x' ? 'x' : 'y';
  455. const vAxisKey = vScale.axis === 'x' ? 'x' : 'y';
  456. const keys = Object.keys(data);
  457. const adata = new Array(keys.length);
  458. let i, ilen, key;
  459. for(i = 0, ilen = keys.length; i < ilen; ++i){
  460. key = keys[i];
  461. adata[i] = {
  462. [iAxisKey]: key,
  463. [vAxisKey]: data[key]
  464. };
  465. }
  466. return adata;
  467. }
  468. function isStacked(scale, meta) {
  469. const stacked = scale && scale.options.stacked;
  470. return stacked || stacked === undefined && meta.stack !== undefined;
  471. }
  472. function getStackKey(indexScale, valueScale, meta) {
  473. return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;
  474. }
  475. function getUserBounds(scale) {
  476. const { min , max , minDefined , maxDefined } = scale.getUserBounds();
  477. return {
  478. min: minDefined ? min : Number.NEGATIVE_INFINITY,
  479. max: maxDefined ? max : Number.POSITIVE_INFINITY
  480. };
  481. }
  482. function getOrCreateStack(stacks, stackKey, indexValue) {
  483. const subStack = stacks[stackKey] || (stacks[stackKey] = {});
  484. return subStack[indexValue] || (subStack[indexValue] = {});
  485. }
  486. function getLastIndexInStack(stack, vScale, positive, type) {
  487. for (const meta of vScale.getMatchingVisibleMetas(type).reverse()){
  488. const value = stack[meta.index];
  489. if (positive && value > 0 || !positive && value < 0) {
  490. return meta.index;
  491. }
  492. }
  493. return null;
  494. }
  495. function updateStacks(controller, parsed) {
  496. const { chart , _cachedMeta: meta } = controller;
  497. const stacks = chart._stacks || (chart._stacks = {});
  498. const { iScale , vScale , index: datasetIndex } = meta;
  499. const iAxis = iScale.axis;
  500. const vAxis = vScale.axis;
  501. const key = getStackKey(iScale, vScale, meta);
  502. const ilen = parsed.length;
  503. let stack;
  504. for(let i = 0; i < ilen; ++i){
  505. const item = parsed[i];
  506. const { [iAxis]: index , [vAxis]: value } = item;
  507. const itemStacks = item._stacks || (item._stacks = {});
  508. stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);
  509. stack[datasetIndex] = value;
  510. stack._top = getLastIndexInStack(stack, vScale, true, meta.type);
  511. stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type);
  512. const visualValues = stack._visualValues || (stack._visualValues = {});
  513. visualValues[datasetIndex] = value;
  514. }
  515. }
  516. function getFirstScaleId(chart, axis) {
  517. const scales = chart.scales;
  518. return Object.keys(scales).filter((key)=>scales[key].axis === axis).shift();
  519. }
  520. function createDatasetContext(parent, index) {
  521. return helpers_segment.createContext(parent, {
  522. active: false,
  523. dataset: undefined,
  524. datasetIndex: index,
  525. index,
  526. mode: 'default',
  527. type: 'dataset'
  528. });
  529. }
  530. function createDataContext(parent, index, element) {
  531. return helpers_segment.createContext(parent, {
  532. active: false,
  533. dataIndex: index,
  534. parsed: undefined,
  535. raw: undefined,
  536. element,
  537. index,
  538. mode: 'default',
  539. type: 'data'
  540. });
  541. }
  542. function clearStacks(meta, items) {
  543. const datasetIndex = meta.controller.index;
  544. const axis = meta.vScale && meta.vScale.axis;
  545. if (!axis) {
  546. return;
  547. }
  548. items = items || meta._parsed;
  549. for (const parsed of items){
  550. const stacks = parsed._stacks;
  551. if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {
  552. return;
  553. }
  554. delete stacks[axis][datasetIndex];
  555. if (stacks[axis]._visualValues !== undefined && stacks[axis]._visualValues[datasetIndex] !== undefined) {
  556. delete stacks[axis]._visualValues[datasetIndex];
  557. }
  558. }
  559. }
  560. const isDirectUpdateMode = (mode)=>mode === 'reset' || mode === 'none';
  561. const cloneIfNotShared = (cached, shared)=>shared ? cached : Object.assign({}, cached);
  562. const createStack = (canStack, meta, chart)=>canStack && !meta.hidden && meta._stacked && {
  563. keys: getSortedDatasetIndices(chart, true),
  564. values: null
  565. };
  566. class DatasetController {
  567. static defaults = {};
  568. static datasetElementType = null;
  569. static dataElementType = null;
  570. constructor(chart, datasetIndex){
  571. this.chart = chart;
  572. this._ctx = chart.ctx;
  573. this.index = datasetIndex;
  574. this._cachedDataOpts = {};
  575. this._cachedMeta = this.getMeta();
  576. this._type = this._cachedMeta.type;
  577. this.options = undefined;
  578. this._parsing = false;
  579. this._data = undefined;
  580. this._objectData = undefined;
  581. this._sharedOptions = undefined;
  582. this._drawStart = undefined;
  583. this._drawCount = undefined;
  584. this.enableOptionSharing = false;
  585. this.supportsDecimation = false;
  586. this.$context = undefined;
  587. this._syncList = [];
  588. this.datasetElementType = new.target.datasetElementType;
  589. this.dataElementType = new.target.dataElementType;
  590. this.initialize();
  591. }
  592. initialize() {
  593. const meta = this._cachedMeta;
  594. this.configure();
  595. this.linkScales();
  596. meta._stacked = isStacked(meta.vScale, meta);
  597. this.addElements();
  598. if (this.options.fill && !this.chart.isPluginEnabled('filler')) {
  599. 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");
  600. }
  601. }
  602. updateIndex(datasetIndex) {
  603. if (this.index !== datasetIndex) {
  604. clearStacks(this._cachedMeta);
  605. }
  606. this.index = datasetIndex;
  607. }
  608. linkScales() {
  609. const chart = this.chart;
  610. const meta = this._cachedMeta;
  611. const dataset = this.getDataset();
  612. const chooseId = (axis, x, y, r)=>axis === 'x' ? x : axis === 'r' ? r : y;
  613. const xid = meta.xAxisID = helpers_segment.valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));
  614. const yid = meta.yAxisID = helpers_segment.valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));
  615. const rid = meta.rAxisID = helpers_segment.valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));
  616. const indexAxis = meta.indexAxis;
  617. const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);
  618. const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);
  619. meta.xScale = this.getScaleForId(xid);
  620. meta.yScale = this.getScaleForId(yid);
  621. meta.rScale = this.getScaleForId(rid);
  622. meta.iScale = this.getScaleForId(iid);
  623. meta.vScale = this.getScaleForId(vid);
  624. }
  625. getDataset() {
  626. return this.chart.data.datasets[this.index];
  627. }
  628. getMeta() {
  629. return this.chart.getDatasetMeta(this.index);
  630. }
  631. getScaleForId(scaleID) {
  632. return this.chart.scales[scaleID];
  633. }
  634. _getOtherScale(scale) {
  635. const meta = this._cachedMeta;
  636. return scale === meta.iScale ? meta.vScale : meta.iScale;
  637. }
  638. reset() {
  639. this._update('reset');
  640. }
  641. _destroy() {
  642. const meta = this._cachedMeta;
  643. if (this._data) {
  644. helpers_segment.unlistenArrayEvents(this._data, this);
  645. }
  646. if (meta._stacked) {
  647. clearStacks(meta);
  648. }
  649. }
  650. _dataCheck() {
  651. const dataset = this.getDataset();
  652. const data = dataset.data || (dataset.data = []);
  653. const _data = this._data;
  654. if (helpers_segment.isObject(data)) {
  655. const meta = this._cachedMeta;
  656. this._data = convertObjectDataToArray(data, meta);
  657. } else if (_data !== data) {
  658. if (_data) {
  659. helpers_segment.unlistenArrayEvents(_data, this);
  660. const meta = this._cachedMeta;
  661. clearStacks(meta);
  662. meta._parsed = [];
  663. }
  664. if (data && Object.isExtensible(data)) {
  665. helpers_segment.listenArrayEvents(data, this);
  666. }
  667. this._syncList = [];
  668. this._data = data;
  669. }
  670. }
  671. addElements() {
  672. const meta = this._cachedMeta;
  673. this._dataCheck();
  674. if (this.datasetElementType) {
  675. meta.dataset = new this.datasetElementType();
  676. }
  677. }
  678. buildOrUpdateElements(resetNewElements) {
  679. const meta = this._cachedMeta;
  680. const dataset = this.getDataset();
  681. let stackChanged = false;
  682. this._dataCheck();
  683. const oldStacked = meta._stacked;
  684. meta._stacked = isStacked(meta.vScale, meta);
  685. if (meta.stack !== dataset.stack) {
  686. stackChanged = true;
  687. clearStacks(meta);
  688. meta.stack = dataset.stack;
  689. }
  690. this._resyncElements(resetNewElements);
  691. if (stackChanged || oldStacked !== meta._stacked) {
  692. updateStacks(this, meta._parsed);
  693. }
  694. }
  695. configure() {
  696. const config = this.chart.config;
  697. const scopeKeys = config.datasetScopeKeys(this._type);
  698. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true);
  699. this.options = config.createResolver(scopes, this.getContext());
  700. this._parsing = this.options.parsing;
  701. this._cachedDataOpts = {};
  702. }
  703. parse(start, count) {
  704. const { _cachedMeta: meta , _data: data } = this;
  705. const { iScale , _stacked } = meta;
  706. const iAxis = iScale.axis;
  707. let sorted = start === 0 && count === data.length ? true : meta._sorted;
  708. let prev = start > 0 && meta._parsed[start - 1];
  709. let i, cur, parsed;
  710. if (this._parsing === false) {
  711. meta._parsed = data;
  712. meta._sorted = true;
  713. parsed = data;
  714. } else {
  715. if (helpers_segment.isArray(data[start])) {
  716. parsed = this.parseArrayData(meta, data, start, count);
  717. } else if (helpers_segment.isObject(data[start])) {
  718. parsed = this.parseObjectData(meta, data, start, count);
  719. } else {
  720. parsed = this.parsePrimitiveData(meta, data, start, count);
  721. }
  722. const isNotInOrderComparedToPrev = ()=>cur[iAxis] === null || prev && cur[iAxis] < prev[iAxis];
  723. for(i = 0; i < count; ++i){
  724. meta._parsed[i + start] = cur = parsed[i];
  725. if (sorted) {
  726. if (isNotInOrderComparedToPrev()) {
  727. sorted = false;
  728. }
  729. prev = cur;
  730. }
  731. }
  732. meta._sorted = sorted;
  733. }
  734. if (_stacked) {
  735. updateStacks(this, parsed);
  736. }
  737. }
  738. parsePrimitiveData(meta, data, start, count) {
  739. const { iScale , vScale } = meta;
  740. const iAxis = iScale.axis;
  741. const vAxis = vScale.axis;
  742. const labels = iScale.getLabels();
  743. const singleScale = iScale === vScale;
  744. const parsed = new Array(count);
  745. let i, ilen, index;
  746. for(i = 0, ilen = count; i < ilen; ++i){
  747. index = i + start;
  748. parsed[i] = {
  749. [iAxis]: singleScale || iScale.parse(labels[index], index),
  750. [vAxis]: vScale.parse(data[index], index)
  751. };
  752. }
  753. return parsed;
  754. }
  755. parseArrayData(meta, data, start, count) {
  756. const { xScale , yScale } = meta;
  757. const parsed = new Array(count);
  758. let i, ilen, index, item;
  759. for(i = 0, ilen = count; i < ilen; ++i){
  760. index = i + start;
  761. item = data[index];
  762. parsed[i] = {
  763. x: xScale.parse(item[0], index),
  764. y: yScale.parse(item[1], index)
  765. };
  766. }
  767. return parsed;
  768. }
  769. parseObjectData(meta, data, start, count) {
  770. const { xScale , yScale } = meta;
  771. const { xAxisKey ='x' , yAxisKey ='y' } = this._parsing;
  772. const parsed = new Array(count);
  773. let i, ilen, index, item;
  774. for(i = 0, ilen = count; i < ilen; ++i){
  775. index = i + start;
  776. item = data[index];
  777. parsed[i] = {
  778. x: xScale.parse(helpers_segment.resolveObjectKey(item, xAxisKey), index),
  779. y: yScale.parse(helpers_segment.resolveObjectKey(item, yAxisKey), index)
  780. };
  781. }
  782. return parsed;
  783. }
  784. getParsed(index) {
  785. return this._cachedMeta._parsed[index];
  786. }
  787. getDataElement(index) {
  788. return this._cachedMeta.data[index];
  789. }
  790. applyStack(scale, parsed, mode) {
  791. const chart = this.chart;
  792. const meta = this._cachedMeta;
  793. const value = parsed[scale.axis];
  794. const stack = {
  795. keys: getSortedDatasetIndices(chart, true),
  796. values: parsed._stacks[scale.axis]._visualValues
  797. };
  798. return applyStack(stack, value, meta.index, {
  799. mode
  800. });
  801. }
  802. updateRangeFromParsed(range, scale, parsed, stack) {
  803. const parsedValue = parsed[scale.axis];
  804. let value = parsedValue === null ? NaN : parsedValue;
  805. const values = stack && parsed._stacks[scale.axis];
  806. if (stack && values) {
  807. stack.values = values;
  808. value = applyStack(stack, parsedValue, this._cachedMeta.index);
  809. }
  810. range.min = Math.min(range.min, value);
  811. range.max = Math.max(range.max, value);
  812. }
  813. getMinMax(scale, canStack) {
  814. const meta = this._cachedMeta;
  815. const _parsed = meta._parsed;
  816. const sorted = meta._sorted && scale === meta.iScale;
  817. const ilen = _parsed.length;
  818. const otherScale = this._getOtherScale(scale);
  819. const stack = createStack(canStack, meta, this.chart);
  820. const range = {
  821. min: Number.POSITIVE_INFINITY,
  822. max: Number.NEGATIVE_INFINITY
  823. };
  824. const { min: otherMin , max: otherMax } = getUserBounds(otherScale);
  825. let i, parsed;
  826. function _skip() {
  827. parsed = _parsed[i];
  828. const otherValue = parsed[otherScale.axis];
  829. return !helpers_segment.isNumberFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue;
  830. }
  831. for(i = 0; i < ilen; ++i){
  832. if (_skip()) {
  833. continue;
  834. }
  835. this.updateRangeFromParsed(range, scale, parsed, stack);
  836. if (sorted) {
  837. break;
  838. }
  839. }
  840. if (sorted) {
  841. for(i = ilen - 1; i >= 0; --i){
  842. if (_skip()) {
  843. continue;
  844. }
  845. this.updateRangeFromParsed(range, scale, parsed, stack);
  846. break;
  847. }
  848. }
  849. return range;
  850. }
  851. getAllParsedValues(scale) {
  852. const parsed = this._cachedMeta._parsed;
  853. const values = [];
  854. let i, ilen, value;
  855. for(i = 0, ilen = parsed.length; i < ilen; ++i){
  856. value = parsed[i][scale.axis];
  857. if (helpers_segment.isNumberFinite(value)) {
  858. values.push(value);
  859. }
  860. }
  861. return values;
  862. }
  863. getMaxOverflow() {
  864. return false;
  865. }
  866. getLabelAndValue(index) {
  867. const meta = this._cachedMeta;
  868. const iScale = meta.iScale;
  869. const vScale = meta.vScale;
  870. const parsed = this.getParsed(index);
  871. return {
  872. label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',
  873. value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''
  874. };
  875. }
  876. _update(mode) {
  877. const meta = this._cachedMeta;
  878. this.update(mode || 'default');
  879. meta._clip = toClip(helpers_segment.valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow())));
  880. }
  881. update(mode) {}
  882. draw() {
  883. const ctx = this._ctx;
  884. const chart = this.chart;
  885. const meta = this._cachedMeta;
  886. const elements = meta.data || [];
  887. const area = chart.chartArea;
  888. const active = [];
  889. const start = this._drawStart || 0;
  890. const count = this._drawCount || elements.length - start;
  891. const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop;
  892. let i;
  893. if (meta.dataset) {
  894. meta.dataset.draw(ctx, area, start, count);
  895. }
  896. for(i = start; i < start + count; ++i){
  897. const element = elements[i];
  898. if (element.hidden) {
  899. continue;
  900. }
  901. if (element.active && drawActiveElementsOnTop) {
  902. active.push(element);
  903. } else {
  904. element.draw(ctx, area);
  905. }
  906. }
  907. for(i = 0; i < active.length; ++i){
  908. active[i].draw(ctx, area);
  909. }
  910. }
  911. getStyle(index, active) {
  912. const mode = active ? 'active' : 'default';
  913. return index === undefined && this._cachedMeta.dataset ? this.resolveDatasetElementOptions(mode) : this.resolveDataElementOptions(index || 0, mode);
  914. }
  915. getContext(index, active, mode) {
  916. const dataset = this.getDataset();
  917. let context;
  918. if (index >= 0 && index < this._cachedMeta.data.length) {
  919. const element = this._cachedMeta.data[index];
  920. context = element.$context || (element.$context = createDataContext(this.getContext(), index, element));
  921. context.parsed = this.getParsed(index);
  922. context.raw = dataset.data[index];
  923. context.index = context.dataIndex = index;
  924. } else {
  925. context = this.$context || (this.$context = createDatasetContext(this.chart.getContext(), this.index));
  926. context.dataset = dataset;
  927. context.index = context.datasetIndex = this.index;
  928. }
  929. context.active = !!active;
  930. context.mode = mode;
  931. return context;
  932. }
  933. resolveDatasetElementOptions(mode) {
  934. return this._resolveElementOptions(this.datasetElementType.id, mode);
  935. }
  936. resolveDataElementOptions(index, mode) {
  937. return this._resolveElementOptions(this.dataElementType.id, mode, index);
  938. }
  939. _resolveElementOptions(elementType, mode = 'default', index) {
  940. const active = mode === 'active';
  941. const cache = this._cachedDataOpts;
  942. const cacheKey = elementType + '-' + mode;
  943. const cached = cache[cacheKey];
  944. const sharing = this.enableOptionSharing && helpers_segment.defined(index);
  945. if (cached) {
  946. return cloneIfNotShared(cached, sharing);
  947. }
  948. const config = this.chart.config;
  949. const scopeKeys = config.datasetElementScopeKeys(this._type, elementType);
  950. const prefixes = active ? [
  951. `${elementType}Hover`,
  952. 'hover',
  953. elementType,
  954. ''
  955. ] : [
  956. elementType,
  957. ''
  958. ];
  959. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);
  960. const names = Object.keys(helpers_segment.defaults.elements[elementType]);
  961. const context = ()=>this.getContext(index, active, mode);
  962. const values = config.resolveNamedOptions(scopes, names, context, prefixes);
  963. if (values.$shared) {
  964. values.$shared = sharing;
  965. cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));
  966. }
  967. return values;
  968. }
  969. _resolveAnimations(index, transition, active) {
  970. const chart = this.chart;
  971. const cache = this._cachedDataOpts;
  972. const cacheKey = `animation-${transition}`;
  973. const cached = cache[cacheKey];
  974. if (cached) {
  975. return cached;
  976. }
  977. let options;
  978. if (chart.options.animation !== false) {
  979. const config = this.chart.config;
  980. const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition);
  981. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);
  982. options = config.createResolver(scopes, this.getContext(index, active, transition));
  983. }
  984. const animations = new Animations(chart, options && options.animations);
  985. if (options && options._cacheable) {
  986. cache[cacheKey] = Object.freeze(animations);
  987. }
  988. return animations;
  989. }
  990. getSharedOptions(options) {
  991. if (!options.$shared) {
  992. return;
  993. }
  994. return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));
  995. }
  996. includeOptions(mode, sharedOptions) {
  997. return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;
  998. }
  999. _getSharedOptions(start, mode) {
  1000. const firstOpts = this.resolveDataElementOptions(start, mode);
  1001. const previouslySharedOptions = this._sharedOptions;
  1002. const sharedOptions = this.getSharedOptions(firstOpts);
  1003. const includeOptions = this.includeOptions(mode, sharedOptions) || sharedOptions !== previouslySharedOptions;
  1004. this.updateSharedOptions(sharedOptions, mode, firstOpts);
  1005. return {
  1006. sharedOptions,
  1007. includeOptions
  1008. };
  1009. }
  1010. updateElement(element, index, properties, mode) {
  1011. if (isDirectUpdateMode(mode)) {
  1012. Object.assign(element, properties);
  1013. } else {
  1014. this._resolveAnimations(index, mode).update(element, properties);
  1015. }
  1016. }
  1017. updateSharedOptions(sharedOptions, mode, newOptions) {
  1018. if (sharedOptions && !isDirectUpdateMode(mode)) {
  1019. this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);
  1020. }
  1021. }
  1022. _setStyle(element, index, mode, active) {
  1023. element.active = active;
  1024. const options = this.getStyle(index, active);
  1025. this._resolveAnimations(index, mode, active).update(element, {
  1026. options: !active && this.getSharedOptions(options) || options
  1027. });
  1028. }
  1029. removeHoverStyle(element, datasetIndex, index) {
  1030. this._setStyle(element, index, 'active', false);
  1031. }
  1032. setHoverStyle(element, datasetIndex, index) {
  1033. this._setStyle(element, index, 'active', true);
  1034. }
  1035. _removeDatasetHoverStyle() {
  1036. const element = this._cachedMeta.dataset;
  1037. if (element) {
  1038. this._setStyle(element, undefined, 'active', false);
  1039. }
  1040. }
  1041. _setDatasetHoverStyle() {
  1042. const element = this._cachedMeta.dataset;
  1043. if (element) {
  1044. this._setStyle(element, undefined, 'active', true);
  1045. }
  1046. }
  1047. _resyncElements(resetNewElements) {
  1048. const data = this._data;
  1049. const elements = this._cachedMeta.data;
  1050. for (const [method, arg1, arg2] of this._syncList){
  1051. this[method](arg1, arg2);
  1052. }
  1053. this._syncList = [];
  1054. const numMeta = elements.length;
  1055. const numData = data.length;
  1056. const count = Math.min(numData, numMeta);
  1057. if (count) {
  1058. this.parse(0, count);
  1059. }
  1060. if (numData > numMeta) {
  1061. this._insertElements(numMeta, numData - numMeta, resetNewElements);
  1062. } else if (numData < numMeta) {
  1063. this._removeElements(numData, numMeta - numData);
  1064. }
  1065. }
  1066. _insertElements(start, count, resetNewElements = true) {
  1067. const meta = this._cachedMeta;
  1068. const data = meta.data;
  1069. const end = start + count;
  1070. let i;
  1071. const move = (arr)=>{
  1072. arr.length += count;
  1073. for(i = arr.length - 1; i >= end; i--){
  1074. arr[i] = arr[i - count];
  1075. }
  1076. };
  1077. move(data);
  1078. for(i = start; i < end; ++i){
  1079. data[i] = new this.dataElementType();
  1080. }
  1081. if (this._parsing) {
  1082. move(meta._parsed);
  1083. }
  1084. this.parse(start, count);
  1085. if (resetNewElements) {
  1086. this.updateElements(data, start, count, 'reset');
  1087. }
  1088. }
  1089. updateElements(element, start, count, mode) {}
  1090. _removeElements(start, count) {
  1091. const meta = this._cachedMeta;
  1092. if (this._parsing) {
  1093. const removed = meta._parsed.splice(start, count);
  1094. if (meta._stacked) {
  1095. clearStacks(meta, removed);
  1096. }
  1097. }
  1098. meta.data.splice(start, count);
  1099. }
  1100. _sync(args) {
  1101. if (this._parsing) {
  1102. this._syncList.push(args);
  1103. } else {
  1104. const [method, arg1, arg2] = args;
  1105. this[method](arg1, arg2);
  1106. }
  1107. this.chart._dataChanges.push([
  1108. this.index,
  1109. ...args
  1110. ]);
  1111. }
  1112. _onDataPush() {
  1113. const count = arguments.length;
  1114. this._sync([
  1115. '_insertElements',
  1116. this.getDataset().data.length - count,
  1117. count
  1118. ]);
  1119. }
  1120. _onDataPop() {
  1121. this._sync([
  1122. '_removeElements',
  1123. this._cachedMeta.data.length - 1,
  1124. 1
  1125. ]);
  1126. }
  1127. _onDataShift() {
  1128. this._sync([
  1129. '_removeElements',
  1130. 0,
  1131. 1
  1132. ]);
  1133. }
  1134. _onDataSplice(start, count) {
  1135. if (count) {
  1136. this._sync([
  1137. '_removeElements',
  1138. start,
  1139. count
  1140. ]);
  1141. }
  1142. const newCount = arguments.length - 2;
  1143. if (newCount) {
  1144. this._sync([
  1145. '_insertElements',
  1146. start,
  1147. newCount
  1148. ]);
  1149. }
  1150. }
  1151. _onDataUnshift() {
  1152. this._sync([
  1153. '_insertElements',
  1154. 0,
  1155. arguments.length
  1156. ]);
  1157. }
  1158. }
  1159. function getAllScaleValues(scale, type) {
  1160. if (!scale._cache.$bar) {
  1161. const visibleMetas = scale.getMatchingVisibleMetas(type);
  1162. let values = [];
  1163. for(let i = 0, ilen = visibleMetas.length; i < ilen; i++){
  1164. values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale));
  1165. }
  1166. scale._cache.$bar = helpers_segment._arrayUnique(values.sort((a, b)=>a - b));
  1167. }
  1168. return scale._cache.$bar;
  1169. }
  1170. function computeMinSampleSize(meta) {
  1171. const scale = meta.iScale;
  1172. const values = getAllScaleValues(scale, meta.type);
  1173. let min = scale._length;
  1174. let i, ilen, curr, prev;
  1175. const updateMinAndPrev = ()=>{
  1176. if (curr === 32767 || curr === -32768) {
  1177. return;
  1178. }
  1179. if (helpers_segment.defined(prev)) {
  1180. min = Math.min(min, Math.abs(curr - prev) || min);
  1181. }
  1182. prev = curr;
  1183. };
  1184. for(i = 0, ilen = values.length; i < ilen; ++i){
  1185. curr = scale.getPixelForValue(values[i]);
  1186. updateMinAndPrev();
  1187. }
  1188. prev = undefined;
  1189. for(i = 0, ilen = scale.ticks.length; i < ilen; ++i){
  1190. curr = scale.getPixelForTick(i);
  1191. updateMinAndPrev();
  1192. }
  1193. return min;
  1194. }
  1195. function computeFitCategoryTraits(index, ruler, options, stackCount) {
  1196. const thickness = options.barThickness;
  1197. let size, ratio;
  1198. if (helpers_segment.isNullOrUndef(thickness)) {
  1199. size = ruler.min * options.categoryPercentage;
  1200. ratio = options.barPercentage;
  1201. } else {
  1202. size = thickness * stackCount;
  1203. ratio = 1;
  1204. }
  1205. return {
  1206. chunk: size / stackCount,
  1207. ratio,
  1208. start: ruler.pixels[index] - size / 2
  1209. };
  1210. }
  1211. function computeFlexCategoryTraits(index, ruler, options, stackCount) {
  1212. const pixels = ruler.pixels;
  1213. const curr = pixels[index];
  1214. let prev = index > 0 ? pixels[index - 1] : null;
  1215. let next = index < pixels.length - 1 ? pixels[index + 1] : null;
  1216. const percent = options.categoryPercentage;
  1217. if (prev === null) {
  1218. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  1219. }
  1220. if (next === null) {
  1221. next = curr + curr - prev;
  1222. }
  1223. const start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  1224. const size = Math.abs(next - prev) / 2 * percent;
  1225. return {
  1226. chunk: size / stackCount,
  1227. ratio: options.barPercentage,
  1228. start
  1229. };
  1230. }
  1231. function parseFloatBar(entry, item, vScale, i) {
  1232. const startValue = vScale.parse(entry[0], i);
  1233. const endValue = vScale.parse(entry[1], i);
  1234. const min = Math.min(startValue, endValue);
  1235. const max = Math.max(startValue, endValue);
  1236. let barStart = min;
  1237. let barEnd = max;
  1238. if (Math.abs(min) > Math.abs(max)) {
  1239. barStart = max;
  1240. barEnd = min;
  1241. }
  1242. item[vScale.axis] = barEnd;
  1243. item._custom = {
  1244. barStart,
  1245. barEnd,
  1246. start: startValue,
  1247. end: endValue,
  1248. min,
  1249. max
  1250. };
  1251. }
  1252. function parseValue(entry, item, vScale, i) {
  1253. if (helpers_segment.isArray(entry)) {
  1254. parseFloatBar(entry, item, vScale, i);
  1255. } else {
  1256. item[vScale.axis] = vScale.parse(entry, i);
  1257. }
  1258. return item;
  1259. }
  1260. function parseArrayOrPrimitive(meta, data, start, count) {
  1261. const iScale = meta.iScale;
  1262. const vScale = meta.vScale;
  1263. const labels = iScale.getLabels();
  1264. const singleScale = iScale === vScale;
  1265. const parsed = [];
  1266. let i, ilen, item, entry;
  1267. for(i = start, ilen = start + count; i < ilen; ++i){
  1268. entry = data[i];
  1269. item = {};
  1270. item[iScale.axis] = singleScale || iScale.parse(labels[i], i);
  1271. parsed.push(parseValue(entry, item, vScale, i));
  1272. }
  1273. return parsed;
  1274. }
  1275. function isFloatBar(custom) {
  1276. return custom && custom.barStart !== undefined && custom.barEnd !== undefined;
  1277. }
  1278. function barSign(size, vScale, actualBase) {
  1279. if (size !== 0) {
  1280. return helpers_segment.sign(size);
  1281. }
  1282. return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);
  1283. }
  1284. function borderProps(properties) {
  1285. let reverse, start, end, top, bottom;
  1286. if (properties.horizontal) {
  1287. reverse = properties.base > properties.x;
  1288. start = 'left';
  1289. end = 'right';
  1290. } else {
  1291. reverse = properties.base < properties.y;
  1292. start = 'bottom';
  1293. end = 'top';
  1294. }
  1295. if (reverse) {
  1296. top = 'end';
  1297. bottom = 'start';
  1298. } else {
  1299. top = 'start';
  1300. bottom = 'end';
  1301. }
  1302. return {
  1303. start,
  1304. end,
  1305. reverse,
  1306. top,
  1307. bottom
  1308. };
  1309. }
  1310. function setBorderSkipped(properties, options, stack, index) {
  1311. let edge = options.borderSkipped;
  1312. const res = {};
  1313. if (!edge) {
  1314. properties.borderSkipped = res;
  1315. return;
  1316. }
  1317. if (edge === true) {
  1318. properties.borderSkipped = {
  1319. top: true,
  1320. right: true,
  1321. bottom: true,
  1322. left: true
  1323. };
  1324. return;
  1325. }
  1326. const { start , end , reverse , top , bottom } = borderProps(properties);
  1327. if (edge === 'middle' && stack) {
  1328. properties.enableBorderRadius = true;
  1329. if ((stack._top || 0) === index) {
  1330. edge = top;
  1331. } else if ((stack._bottom || 0) === index) {
  1332. edge = bottom;
  1333. } else {
  1334. res[parseEdge(bottom, start, end, reverse)] = true;
  1335. edge = top;
  1336. }
  1337. }
  1338. res[parseEdge(edge, start, end, reverse)] = true;
  1339. properties.borderSkipped = res;
  1340. }
  1341. function parseEdge(edge, a, b, reverse) {
  1342. if (reverse) {
  1343. edge = swap(edge, a, b);
  1344. edge = startEnd(edge, b, a);
  1345. } else {
  1346. edge = startEnd(edge, a, b);
  1347. }
  1348. return edge;
  1349. }
  1350. function swap(orig, v1, v2) {
  1351. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  1352. }
  1353. function startEnd(v, start, end) {
  1354. return v === 'start' ? start : v === 'end' ? end : v;
  1355. }
  1356. function setInflateAmount(properties, { inflateAmount }, ratio) {
  1357. properties.inflateAmount = inflateAmount === 'auto' ? ratio === 1 ? 0.33 : 0 : inflateAmount;
  1358. }
  1359. class BarController extends DatasetController {
  1360. static id = 'bar';
  1361. static defaults = {
  1362. datasetElementType: false,
  1363. dataElementType: 'bar',
  1364. categoryPercentage: 0.8,
  1365. barPercentage: 0.9,
  1366. grouped: true,
  1367. animations: {
  1368. numbers: {
  1369. type: 'number',
  1370. properties: [
  1371. 'x',
  1372. 'y',
  1373. 'base',
  1374. 'width',
  1375. 'height'
  1376. ]
  1377. }
  1378. }
  1379. };
  1380. static overrides = {
  1381. scales: {
  1382. _index_: {
  1383. type: 'category',
  1384. offset: true,
  1385. grid: {
  1386. offset: true
  1387. }
  1388. },
  1389. _value_: {
  1390. type: 'linear',
  1391. beginAtZero: true
  1392. }
  1393. }
  1394. };
  1395. parsePrimitiveData(meta, data, start, count) {
  1396. return parseArrayOrPrimitive(meta, data, start, count);
  1397. }
  1398. parseArrayData(meta, data, start, count) {
  1399. return parseArrayOrPrimitive(meta, data, start, count);
  1400. }
  1401. parseObjectData(meta, data, start, count) {
  1402. const { iScale , vScale } = meta;
  1403. const { xAxisKey ='x' , yAxisKey ='y' } = this._parsing;
  1404. const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;
  1405. const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;
  1406. const parsed = [];
  1407. let i, ilen, item, obj;
  1408. for(i = start, ilen = start + count; i < ilen; ++i){
  1409. obj = data[i];
  1410. item = {};
  1411. item[iScale.axis] = iScale.parse(helpers_segment.resolveObjectKey(obj, iAxisKey), i);
  1412. parsed.push(parseValue(helpers_segment.resolveObjectKey(obj, vAxisKey), item, vScale, i));
  1413. }
  1414. return parsed;
  1415. }
  1416. updateRangeFromParsed(range, scale, parsed, stack) {
  1417. super.updateRangeFromParsed(range, scale, parsed, stack);
  1418. const custom = parsed._custom;
  1419. if (custom && scale === this._cachedMeta.vScale) {
  1420. range.min = Math.min(range.min, custom.min);
  1421. range.max = Math.max(range.max, custom.max);
  1422. }
  1423. }
  1424. getMaxOverflow() {
  1425. return 0;
  1426. }
  1427. getLabelAndValue(index) {
  1428. const meta = this._cachedMeta;
  1429. const { iScale , vScale } = meta;
  1430. const parsed = this.getParsed(index);
  1431. const custom = parsed._custom;
  1432. const value = isFloatBar(custom) ? '[' + custom.start + ', ' + custom.end + ']' : '' + vScale.getLabelForValue(parsed[vScale.axis]);
  1433. return {
  1434. label: '' + iScale.getLabelForValue(parsed[iScale.axis]),
  1435. value
  1436. };
  1437. }
  1438. initialize() {
  1439. this.enableOptionSharing = true;
  1440. super.initialize();
  1441. const meta = this._cachedMeta;
  1442. meta.stack = this.getDataset().stack;
  1443. }
  1444. update(mode) {
  1445. const meta = this._cachedMeta;
  1446. this.updateElements(meta.data, 0, meta.data.length, mode);
  1447. }
  1448. updateElements(bars, start, count, mode) {
  1449. const reset = mode === 'reset';
  1450. const { index , _cachedMeta: { vScale } } = this;
  1451. const base = vScale.getBasePixel();
  1452. const horizontal = vScale.isHorizontal();
  1453. const ruler = this._getRuler();
  1454. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  1455. for(let i = start; i < start + count; i++){
  1456. const parsed = this.getParsed(i);
  1457. const vpixels = reset || helpers_segment.isNullOrUndef(parsed[vScale.axis]) ? {
  1458. base,
  1459. head: base
  1460. } : this._calculateBarValuePixels(i);
  1461. const ipixels = this._calculateBarIndexPixels(i, ruler);
  1462. const stack = (parsed._stacks || {})[vScale.axis];
  1463. const properties = {
  1464. horizontal,
  1465. base: vpixels.base,
  1466. enableBorderRadius: !stack || isFloatBar(parsed._custom) || index === stack._top || index === stack._bottom,
  1467. x: horizontal ? vpixels.head : ipixels.center,
  1468. y: horizontal ? ipixels.center : vpixels.head,
  1469. height: horizontal ? ipixels.size : Math.abs(vpixels.size),
  1470. width: horizontal ? Math.abs(vpixels.size) : ipixels.size
  1471. };
  1472. if (includeOptions) {
  1473. properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);
  1474. }
  1475. const options = properties.options || bars[i].options;
  1476. setBorderSkipped(properties, options, stack, index);
  1477. setInflateAmount(properties, options, ruler.ratio);
  1478. this.updateElement(bars[i], i, properties, mode);
  1479. }
  1480. }
  1481. _getStacks(last, dataIndex) {
  1482. const { iScale } = this._cachedMeta;
  1483. const metasets = iScale.getMatchingVisibleMetas(this._type).filter((meta)=>meta.controller.options.grouped);
  1484. const stacked = iScale.options.stacked;
  1485. const stacks = [];
  1486. const currentParsed = this._cachedMeta.controller.getParsed(dataIndex);
  1487. const iScaleValue = currentParsed && currentParsed[iScale.axis];
  1488. const skipNull = (meta)=>{
  1489. const parsed = meta._parsed.find((item)=>item[iScale.axis] === iScaleValue);
  1490. const val = parsed && parsed[meta.vScale.axis];
  1491. if (helpers_segment.isNullOrUndef(val) || isNaN(val)) {
  1492. return true;
  1493. }
  1494. };
  1495. for (const meta of metasets){
  1496. if (dataIndex !== undefined && skipNull(meta)) {
  1497. continue;
  1498. }
  1499. if (stacked === false || stacks.indexOf(meta.stack) === -1 || stacked === undefined && meta.stack === undefined) {
  1500. stacks.push(meta.stack);
  1501. }
  1502. if (meta.index === last) {
  1503. break;
  1504. }
  1505. }
  1506. if (!stacks.length) {
  1507. stacks.push(undefined);
  1508. }
  1509. return stacks;
  1510. }
  1511. _getStackCount(index) {
  1512. return this._getStacks(undefined, index).length;
  1513. }
  1514. _getStackIndex(datasetIndex, name, dataIndex) {
  1515. const stacks = this._getStacks(datasetIndex, dataIndex);
  1516. const index = name !== undefined ? stacks.indexOf(name) : -1;
  1517. return index === -1 ? stacks.length - 1 : index;
  1518. }
  1519. _getRuler() {
  1520. const opts = this.options;
  1521. const meta = this._cachedMeta;
  1522. const iScale = meta.iScale;
  1523. const pixels = [];
  1524. let i, ilen;
  1525. for(i = 0, ilen = meta.data.length; i < ilen; ++i){
  1526. pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i));
  1527. }
  1528. const barThickness = opts.barThickness;
  1529. const min = barThickness || computeMinSampleSize(meta);
  1530. return {
  1531. min,
  1532. pixels,
  1533. start: iScale._startPixel,
  1534. end: iScale._endPixel,
  1535. stackCount: this._getStackCount(),
  1536. scale: iScale,
  1537. grouped: opts.grouped,
  1538. ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage
  1539. };
  1540. }
  1541. _calculateBarValuePixels(index) {
  1542. const { _cachedMeta: { vScale , _stacked , index: datasetIndex } , options: { base: baseValue , minBarLength } } = this;
  1543. const actualBase = baseValue || 0;
  1544. const parsed = this.getParsed(index);
  1545. const custom = parsed._custom;
  1546. const floating = isFloatBar(custom);
  1547. let value = parsed[vScale.axis];
  1548. let start = 0;
  1549. let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value;
  1550. let head, size;
  1551. if (length !== value) {
  1552. start = length - value;
  1553. length = value;
  1554. }
  1555. if (floating) {
  1556. value = custom.barStart;
  1557. length = custom.barEnd - custom.barStart;
  1558. if (value !== 0 && helpers_segment.sign(value) !== helpers_segment.sign(custom.barEnd)) {
  1559. start = 0;
  1560. }
  1561. start += value;
  1562. }
  1563. const startValue = !helpers_segment.isNullOrUndef(baseValue) && !floating ? baseValue : start;
  1564. let base = vScale.getPixelForValue(startValue);
  1565. if (this.chart.getDataVisibility(index)) {
  1566. head = vScale.getPixelForValue(start + length);
  1567. } else {
  1568. head = base;
  1569. }
  1570. size = head - base;
  1571. if (Math.abs(size) < minBarLength) {
  1572. size = barSign(size, vScale, actualBase) * minBarLength;
  1573. if (value === actualBase) {
  1574. base -= size / 2;
  1575. }
  1576. const startPixel = vScale.getPixelForDecimal(0);
  1577. const endPixel = vScale.getPixelForDecimal(1);
  1578. const min = Math.min(startPixel, endPixel);
  1579. const max = Math.max(startPixel, endPixel);
  1580. base = Math.max(Math.min(base, max), min);
  1581. head = base + size;
  1582. if (_stacked && !floating) {
  1583. parsed._stacks[vScale.axis]._visualValues[datasetIndex] = vScale.getValueForPixel(head) - vScale.getValueForPixel(base);
  1584. }
  1585. }
  1586. if (base === vScale.getPixelForValue(actualBase)) {
  1587. const halfGrid = helpers_segment.sign(size) * vScale.getLineWidthForValue(actualBase) / 2;
  1588. base += halfGrid;
  1589. size -= halfGrid;
  1590. }
  1591. return {
  1592. size,
  1593. base,
  1594. head,
  1595. center: head + size / 2
  1596. };
  1597. }
  1598. _calculateBarIndexPixels(index, ruler) {
  1599. const scale = ruler.scale;
  1600. const options = this.options;
  1601. const skipNull = options.skipNull;
  1602. const maxBarThickness = helpers_segment.valueOrDefault(options.maxBarThickness, Infinity);
  1603. let center, size;
  1604. if (ruler.grouped) {
  1605. const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount;
  1606. const range = options.barThickness === 'flex' ? computeFlexCategoryTraits(index, ruler, options, stackCount) : computeFitCategoryTraits(index, ruler, options, stackCount);
  1607. const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined);
  1608. center = range.start + range.chunk * stackIndex + range.chunk / 2;
  1609. size = Math.min(maxBarThickness, range.chunk * range.ratio);
  1610. } else {
  1611. center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index);
  1612. size = Math.min(maxBarThickness, ruler.min * ruler.ratio);
  1613. }
  1614. return {
  1615. base: center - size / 2,
  1616. head: center + size / 2,
  1617. center,
  1618. size
  1619. };
  1620. }
  1621. draw() {
  1622. const meta = this._cachedMeta;
  1623. const vScale = meta.vScale;
  1624. const rects = meta.data;
  1625. const ilen = rects.length;
  1626. let i = 0;
  1627. for(; i < ilen; ++i){
  1628. if (this.getParsed(i)[vScale.axis] !== null && !rects[i].hidden) {
  1629. rects[i].draw(this._ctx);
  1630. }
  1631. }
  1632. }
  1633. }
  1634. class BubbleController extends DatasetController {
  1635. static id = 'bubble';
  1636. static defaults = {
  1637. datasetElementType: false,
  1638. dataElementType: 'point',
  1639. animations: {
  1640. numbers: {
  1641. type: 'number',
  1642. properties: [
  1643. 'x',
  1644. 'y',
  1645. 'borderWidth',
  1646. 'radius'
  1647. ]
  1648. }
  1649. }
  1650. };
  1651. static overrides = {
  1652. scales: {
  1653. x: {
  1654. type: 'linear'
  1655. },
  1656. y: {
  1657. type: 'linear'
  1658. }
  1659. }
  1660. };
  1661. initialize() {
  1662. this.enableOptionSharing = true;
  1663. super.initialize();
  1664. }
  1665. parsePrimitiveData(meta, data, start, count) {
  1666. const parsed = super.parsePrimitiveData(meta, data, start, count);
  1667. for(let i = 0; i < parsed.length; i++){
  1668. parsed[i]._custom = this.resolveDataElementOptions(i + start).radius;
  1669. }
  1670. return parsed;
  1671. }
  1672. parseArrayData(meta, data, start, count) {
  1673. const parsed = super.parseArrayData(meta, data, start, count);
  1674. for(let i = 0; i < parsed.length; i++){
  1675. const item = data[start + i];
  1676. parsed[i]._custom = helpers_segment.valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius);
  1677. }
  1678. return parsed;
  1679. }
  1680. parseObjectData(meta, data, start, count) {
  1681. const parsed = super.parseObjectData(meta, data, start, count);
  1682. for(let i = 0; i < parsed.length; i++){
  1683. const item = data[start + i];
  1684. parsed[i]._custom = helpers_segment.valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius);
  1685. }
  1686. return parsed;
  1687. }
  1688. getMaxOverflow() {
  1689. const data = this._cachedMeta.data;
  1690. let max = 0;
  1691. for(let i = data.length - 1; i >= 0; --i){
  1692. max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);
  1693. }
  1694. return max > 0 && max;
  1695. }
  1696. getLabelAndValue(index) {
  1697. const meta = this._cachedMeta;
  1698. const labels = this.chart.data.labels || [];
  1699. const { xScale , yScale } = meta;
  1700. const parsed = this.getParsed(index);
  1701. const x = xScale.getLabelForValue(parsed.x);
  1702. const y = yScale.getLabelForValue(parsed.y);
  1703. const r = parsed._custom;
  1704. return {
  1705. label: labels[index] || '',
  1706. value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'
  1707. };
  1708. }
  1709. update(mode) {
  1710. const points = this._cachedMeta.data;
  1711. this.updateElements(points, 0, points.length, mode);
  1712. }
  1713. updateElements(points, start, count, mode) {
  1714. const reset = mode === 'reset';
  1715. const { iScale , vScale } = this._cachedMeta;
  1716. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  1717. const iAxis = iScale.axis;
  1718. const vAxis = vScale.axis;
  1719. for(let i = start; i < start + count; i++){
  1720. const point = points[i];
  1721. const parsed = !reset && this.getParsed(i);
  1722. const properties = {};
  1723. const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);
  1724. const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);
  1725. properties.skip = isNaN(iPixel) || isNaN(vPixel);
  1726. if (includeOptions) {
  1727. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  1728. if (reset) {
  1729. properties.options.radius = 0;
  1730. }
  1731. }
  1732. this.updateElement(point, i, properties, mode);
  1733. }
  1734. }
  1735. resolveDataElementOptions(index, mode) {
  1736. const parsed = this.getParsed(index);
  1737. let values = super.resolveDataElementOptions(index, mode);
  1738. if (values.$shared) {
  1739. values = Object.assign({}, values, {
  1740. $shared: false
  1741. });
  1742. }
  1743. const radius = values.radius;
  1744. if (mode !== 'active') {
  1745. values.radius = 0;
  1746. }
  1747. values.radius += helpers_segment.valueOrDefault(parsed && parsed._custom, radius);
  1748. return values;
  1749. }
  1750. }
  1751. function getRatioAndOffset(rotation, circumference, cutout) {
  1752. let ratioX = 1;
  1753. let ratioY = 1;
  1754. let offsetX = 0;
  1755. let offsetY = 0;
  1756. if (circumference < helpers_segment.TAU) {
  1757. const startAngle = rotation;
  1758. const endAngle = startAngle + circumference;
  1759. const startX = Math.cos(startAngle);
  1760. const startY = Math.sin(startAngle);
  1761. const endX = Math.cos(endAngle);
  1762. const endY = Math.sin(endAngle);
  1763. const calcMax = (angle, a, b)=>helpers_segment._angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);
  1764. const calcMin = (angle, a, b)=>helpers_segment._angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);
  1765. const maxX = calcMax(0, startX, endX);
  1766. const maxY = calcMax(helpers_segment.HALF_PI, startY, endY);
  1767. const minX = calcMin(helpers_segment.PI, startX, endX);
  1768. const minY = calcMin(helpers_segment.PI + helpers_segment.HALF_PI, startY, endY);
  1769. ratioX = (maxX - minX) / 2;
  1770. ratioY = (maxY - minY) / 2;
  1771. offsetX = -(maxX + minX) / 2;
  1772. offsetY = -(maxY + minY) / 2;
  1773. }
  1774. return {
  1775. ratioX,
  1776. ratioY,
  1777. offsetX,
  1778. offsetY
  1779. };
  1780. }
  1781. class DoughnutController extends DatasetController {
  1782. static id = 'doughnut';
  1783. static defaults = {
  1784. datasetElementType: false,
  1785. dataElementType: 'arc',
  1786. animation: {
  1787. animateRotate: true,
  1788. animateScale: false
  1789. },
  1790. animations: {
  1791. numbers: {
  1792. type: 'number',
  1793. properties: [
  1794. 'circumference',
  1795. 'endAngle',
  1796. 'innerRadius',
  1797. 'outerRadius',
  1798. 'startAngle',
  1799. 'x',
  1800. 'y',
  1801. 'offset',
  1802. 'borderWidth',
  1803. 'spacing'
  1804. ]
  1805. }
  1806. },
  1807. cutout: '50%',
  1808. rotation: 0,
  1809. circumference: 360,
  1810. radius: '100%',
  1811. spacing: 0,
  1812. indexAxis: 'r'
  1813. };
  1814. static descriptors = {
  1815. _scriptable: (name)=>name !== 'spacing',
  1816. _indexable: (name)=>name !== 'spacing' && !name.startsWith('borderDash') && !name.startsWith('hoverBorderDash')
  1817. };
  1818. static overrides = {
  1819. aspectRatio: 1,
  1820. plugins: {
  1821. legend: {
  1822. labels: {
  1823. generateLabels (chart) {
  1824. const data = chart.data;
  1825. if (data.labels.length && data.datasets.length) {
  1826. const { labels: { pointStyle , color } } = chart.legend.options;
  1827. return data.labels.map((label, i)=>{
  1828. const meta = chart.getDatasetMeta(0);
  1829. const style = meta.controller.getStyle(i);
  1830. return {
  1831. text: label,
  1832. fillStyle: style.backgroundColor,
  1833. strokeStyle: style.borderColor,
  1834. fontColor: color,
  1835. lineWidth: style.borderWidth,
  1836. pointStyle: pointStyle,
  1837. hidden: !chart.getDataVisibility(i),
  1838. index: i
  1839. };
  1840. });
  1841. }
  1842. return [];
  1843. }
  1844. },
  1845. onClick (e, legendItem, legend) {
  1846. legend.chart.toggleDataVisibility(legendItem.index);
  1847. legend.chart.update();
  1848. }
  1849. }
  1850. }
  1851. };
  1852. constructor(chart, datasetIndex){
  1853. super(chart, datasetIndex);
  1854. this.enableOptionSharing = true;
  1855. this.innerRadius = undefined;
  1856. this.outerRadius = undefined;
  1857. this.offsetX = undefined;
  1858. this.offsetY = undefined;
  1859. }
  1860. linkScales() {}
  1861. parse(start, count) {
  1862. const data = this.getDataset().data;
  1863. const meta = this._cachedMeta;
  1864. if (this._parsing === false) {
  1865. meta._parsed = data;
  1866. } else {
  1867. let getter = (i)=>+data[i];
  1868. if (helpers_segment.isObject(data[start])) {
  1869. const { key ='value' } = this._parsing;
  1870. getter = (i)=>+helpers_segment.resolveObjectKey(data[i], key);
  1871. }
  1872. let i, ilen;
  1873. for(i = start, ilen = start + count; i < ilen; ++i){
  1874. meta._parsed[i] = getter(i);
  1875. }
  1876. }
  1877. }
  1878. _getRotation() {
  1879. return helpers_segment.toRadians(this.options.rotation - 90);
  1880. }
  1881. _getCircumference() {
  1882. return helpers_segment.toRadians(this.options.circumference);
  1883. }
  1884. _getRotationExtents() {
  1885. let min = helpers_segment.TAU;
  1886. let max = -helpers_segment.TAU;
  1887. for(let i = 0; i < this.chart.data.datasets.length; ++i){
  1888. if (this.chart.isDatasetVisible(i) && this.chart.getDatasetMeta(i).type === this._type) {
  1889. const controller = this.chart.getDatasetMeta(i).controller;
  1890. const rotation = controller._getRotation();
  1891. const circumference = controller._getCircumference();
  1892. min = Math.min(min, rotation);
  1893. max = Math.max(max, rotation + circumference);
  1894. }
  1895. }
  1896. return {
  1897. rotation: min,
  1898. circumference: max - min
  1899. };
  1900. }
  1901. update(mode) {
  1902. const chart = this.chart;
  1903. const { chartArea } = chart;
  1904. const meta = this._cachedMeta;
  1905. const arcs = meta.data;
  1906. const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;
  1907. const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);
  1908. const cutout = Math.min(helpers_segment.toPercentage(this.options.cutout, maxSize), 1);
  1909. const chartWeight = this._getRingWeight(this.index);
  1910. const { circumference , rotation } = this._getRotationExtents();
  1911. const { ratioX , ratioY , offsetX , offsetY } = getRatioAndOffset(rotation, circumference, cutout);
  1912. const maxWidth = (chartArea.width - spacing) / ratioX;
  1913. const maxHeight = (chartArea.height - spacing) / ratioY;
  1914. const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  1915. const outerRadius = helpers_segment.toDimension(this.options.radius, maxRadius);
  1916. const innerRadius = Math.max(outerRadius * cutout, 0);
  1917. const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();
  1918. this.offsetX = offsetX * outerRadius;
  1919. this.offsetY = offsetY * outerRadius;
  1920. meta.total = this.calculateTotal();
  1921. this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);
  1922. this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);
  1923. this.updateElements(arcs, 0, arcs.length, mode);
  1924. }
  1925. _circumference(i, reset) {
  1926. const opts = this.options;
  1927. const meta = this._cachedMeta;
  1928. const circumference = this._getCircumference();
  1929. if (reset && opts.animation.animateRotate || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {
  1930. return 0;
  1931. }
  1932. return this.calculateCircumference(meta._parsed[i] * circumference / helpers_segment.TAU);
  1933. }
  1934. updateElements(arcs, start, count, mode) {
  1935. const reset = mode === 'reset';
  1936. const chart = this.chart;
  1937. const chartArea = chart.chartArea;
  1938. const opts = chart.options;
  1939. const animationOpts = opts.animation;
  1940. const centerX = (chartArea.left + chartArea.right) / 2;
  1941. const centerY = (chartArea.top + chartArea.bottom) / 2;
  1942. const animateScale = reset && animationOpts.animateScale;
  1943. const innerRadius = animateScale ? 0 : this.innerRadius;
  1944. const outerRadius = animateScale ? 0 : this.outerRadius;
  1945. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  1946. let startAngle = this._getRotation();
  1947. let i;
  1948. for(i = 0; i < start; ++i){
  1949. startAngle += this._circumference(i, reset);
  1950. }
  1951. for(i = start; i < start + count; ++i){
  1952. const circumference = this._circumference(i, reset);
  1953. const arc = arcs[i];
  1954. const properties = {
  1955. x: centerX + this.offsetX,
  1956. y: centerY + this.offsetY,
  1957. startAngle,
  1958. endAngle: startAngle + circumference,
  1959. circumference,
  1960. outerRadius,
  1961. innerRadius
  1962. };
  1963. if (includeOptions) {
  1964. properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);
  1965. }
  1966. startAngle += circumference;
  1967. this.updateElement(arc, i, properties, mode);
  1968. }
  1969. }
  1970. calculateTotal() {
  1971. const meta = this._cachedMeta;
  1972. const metaData = meta.data;
  1973. let total = 0;
  1974. let i;
  1975. for(i = 0; i < metaData.length; i++){
  1976. const value = meta._parsed[i];
  1977. if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {
  1978. total += Math.abs(value);
  1979. }
  1980. }
  1981. return total;
  1982. }
  1983. calculateCircumference(value) {
  1984. const total = this._cachedMeta.total;
  1985. if (total > 0 && !isNaN(value)) {
  1986. return helpers_segment.TAU * (Math.abs(value) / total);
  1987. }
  1988. return 0;
  1989. }
  1990. getLabelAndValue(index) {
  1991. const meta = this._cachedMeta;
  1992. const chart = this.chart;
  1993. const labels = chart.data.labels || [];
  1994. const value = helpers_segment.formatNumber(meta._parsed[index], chart.options.locale);
  1995. return {
  1996. label: labels[index] || '',
  1997. value
  1998. };
  1999. }
  2000. getMaxBorderWidth(arcs) {
  2001. let max = 0;
  2002. const chart = this.chart;
  2003. let i, ilen, meta, controller, options;
  2004. if (!arcs) {
  2005. for(i = 0, ilen = chart.data.datasets.length; i < ilen; ++i){
  2006. if (chart.isDatasetVisible(i)) {
  2007. meta = chart.getDatasetMeta(i);
  2008. arcs = meta.data;
  2009. controller = meta.controller;
  2010. break;
  2011. }
  2012. }
  2013. }
  2014. if (!arcs) {
  2015. return 0;
  2016. }
  2017. for(i = 0, ilen = arcs.length; i < ilen; ++i){
  2018. options = controller.resolveDataElementOptions(i);
  2019. if (options.borderAlign !== 'inner') {
  2020. max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);
  2021. }
  2022. }
  2023. return max;
  2024. }
  2025. getMaxOffset(arcs) {
  2026. let max = 0;
  2027. for(let i = 0, ilen = arcs.length; i < ilen; ++i){
  2028. const options = this.resolveDataElementOptions(i);
  2029. max = Math.max(max, options.offset || 0, options.hoverOffset || 0);
  2030. }
  2031. return max;
  2032. }
  2033. _getRingWeightOffset(datasetIndex) {
  2034. let ringWeightOffset = 0;
  2035. for(let i = 0; i < datasetIndex; ++i){
  2036. if (this.chart.isDatasetVisible(i)) {
  2037. ringWeightOffset += this._getRingWeight(i);
  2038. }
  2039. }
  2040. return ringWeightOffset;
  2041. }
  2042. _getRingWeight(datasetIndex) {
  2043. return Math.max(helpers_segment.valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);
  2044. }
  2045. _getVisibleDatasetWeightTotal() {
  2046. return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;
  2047. }
  2048. }
  2049. class LineController extends DatasetController {
  2050. static id = 'line';
  2051. static defaults = {
  2052. datasetElementType: 'line',
  2053. dataElementType: 'point',
  2054. showLine: true,
  2055. spanGaps: false
  2056. };
  2057. static overrides = {
  2058. scales: {
  2059. _index_: {
  2060. type: 'category'
  2061. },
  2062. _value_: {
  2063. type: 'linear'
  2064. }
  2065. }
  2066. };
  2067. initialize() {
  2068. this.enableOptionSharing = true;
  2069. this.supportsDecimation = true;
  2070. super.initialize();
  2071. }
  2072. update(mode) {
  2073. const meta = this._cachedMeta;
  2074. const { dataset: line , data: points = [] , _dataset } = meta;
  2075. const animationsDisabled = this.chart._animationsDisabled;
  2076. let { start , count } = helpers_segment._getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
  2077. this._drawStart = start;
  2078. this._drawCount = count;
  2079. if (helpers_segment._scaleRangesChanged(meta)) {
  2080. start = 0;
  2081. count = points.length;
  2082. }
  2083. line._chart = this.chart;
  2084. line._datasetIndex = this.index;
  2085. line._decimated = !!_dataset._decimated;
  2086. line.points = points;
  2087. const options = this.resolveDatasetElementOptions(mode);
  2088. if (!this.options.showLine) {
  2089. options.borderWidth = 0;
  2090. }
  2091. options.segment = this.options.segment;
  2092. this.updateElement(line, undefined, {
  2093. animated: !animationsDisabled,
  2094. options
  2095. }, mode);
  2096. this.updateElements(points, start, count, mode);
  2097. }
  2098. updateElements(points, start, count, mode) {
  2099. const reset = mode === 'reset';
  2100. const { iScale , vScale , _stacked , _dataset } = this._cachedMeta;
  2101. const { sharedOptions , includeOptions } = this._getSharedOptions(start, mode);
  2102. const iAxis = iScale.axis;
  2103. const vAxis = vScale.axis;
  2104. const { spanGaps , segment } = this.options;
  2105. const maxGapLength = helpers_segment.isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
  2106. const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';
  2107. const end = start + count;
  2108. const pointsCount = points.length;
  2109. let prevParsed = start > 0 && this.getParsed(start - 1);
  2110. for(let i = 0; i < pointsCount; ++i){
  2111. const point = points[i];
  2112. const properties = directUpdate ? point : {};
  2113. if (i < start || i >= end) {
  2114. properties.skip = true;
  2115. continue;
  2116. }
  2117. const parsed = this.getParsed(i);
  2118. const nullData = helpers_segment.isNullOrUndef(parsed[vAxis]);
  2119. const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
  2120. const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
  2121. properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
  2122. properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;
  2123. if (segment) {
  2124. properties.parsed = parsed;
  2125. properties.raw = _dataset.data[i];
  2126. }
  2127. if (includeOptions) {
  2128. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2129. }
  2130. if (!directUpdate) {
  2131. this.updateElement(point, i, properties, mode);
  2132. }
  2133. prevParsed = parsed;
  2134. }
  2135. }
  2136. getMaxOverflow() {
  2137. const meta = this._cachedMeta;
  2138. const dataset = meta.dataset;
  2139. const border = dataset.options && dataset.options.borderWidth || 0;
  2140. const data = meta.data || [];
  2141. if (!data.length) {
  2142. return border;
  2143. }
  2144. const firstPoint = data[0].size(this.resolveDataElementOptions(0));
  2145. const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));
  2146. return Math.max(border, firstPoint, lastPoint) / 2;
  2147. }
  2148. draw() {
  2149. const meta = this._cachedMeta;
  2150. meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);
  2151. super.draw();
  2152. }
  2153. }
  2154. class PolarAreaController extends DatasetController {
  2155. static id = 'polarArea';
  2156. static defaults = {
  2157. dataElementType: 'arc',
  2158. animation: {
  2159. animateRotate: true,
  2160. animateScale: true
  2161. },
  2162. animations: {
  2163. numbers: {
  2164. type: 'number',
  2165. properties: [
  2166. 'x',
  2167. 'y',
  2168. 'startAngle',
  2169. 'endAngle',
  2170. 'innerRadius',
  2171. 'outerRadius'
  2172. ]
  2173. }
  2174. },
  2175. indexAxis: 'r',
  2176. startAngle: 0
  2177. };
  2178. static overrides = {
  2179. aspectRatio: 1,
  2180. plugins: {
  2181. legend: {
  2182. labels: {
  2183. generateLabels (chart) {
  2184. const data = chart.data;
  2185. if (data.labels.length && data.datasets.length) {
  2186. const { labels: { pointStyle , color } } = chart.legend.options;
  2187. return data.labels.map((label, i)=>{
  2188. const meta = chart.getDatasetMeta(0);
  2189. const style = meta.controller.getStyle(i);
  2190. return {
  2191. text: label,
  2192. fillStyle: style.backgroundColor,
  2193. strokeStyle: style.borderColor,
  2194. fontColor: color,
  2195. lineWidth: style.borderWidth,
  2196. pointStyle: pointStyle,
  2197. hidden: !chart.getDataVisibility(i),
  2198. index: i
  2199. };
  2200. });
  2201. }
  2202. return [];
  2203. }
  2204. },
  2205. onClick (e, legendItem, legend) {
  2206. legend.chart.toggleDataVisibility(legendItem.index);
  2207. legend.chart.update();
  2208. }
  2209. }
  2210. },
  2211. scales: {
  2212. r: {
  2213. type: 'radialLinear',
  2214. angleLines: {
  2215. display: false
  2216. },
  2217. beginAtZero: true,
  2218. grid: {
  2219. circular: true
  2220. },
  2221. pointLabels: {
  2222. display: false
  2223. },
  2224. startAngle: 0
  2225. }
  2226. }
  2227. };
  2228. constructor(chart, datasetIndex){
  2229. super(chart, datasetIndex);
  2230. this.innerRadius = undefined;
  2231. this.outerRadius = undefined;
  2232. }
  2233. getLabelAndValue(index) {
  2234. const meta = this._cachedMeta;
  2235. const chart = this.chart;
  2236. const labels = chart.data.labels || [];
  2237. const value = helpers_segment.formatNumber(meta._parsed[index].r, chart.options.locale);
  2238. return {
  2239. label: labels[index] || '',
  2240. value
  2241. };
  2242. }
  2243. parseObjectData(meta, data, start, count) {
  2244. return helpers_segment._parseObjectDataRadialScale.bind(this)(meta, data, start, count);
  2245. }
  2246. update(mode) {
  2247. const arcs = this._cachedMeta.data;
  2248. this._updateRadius();
  2249. this.updateElements(arcs, 0, arcs.length, mode);
  2250. }
  2251. getMinMax() {
  2252. const meta = this._cachedMeta;
  2253. const range = {
  2254. min: Number.POSITIVE_INFINITY,
  2255. max: Number.NEGATIVE_INFINITY
  2256. };
  2257. meta.data.forEach((element, index)=>{
  2258. const parsed = this.getParsed(index).r;
  2259. if (!isNaN(parsed) && this.chart.getDataVisibility(index)) {
  2260. if (parsed < range.min) {
  2261. range.min = parsed;
  2262. }
  2263. if (parsed > range.max) {
  2264. range.max = parsed;
  2265. }
  2266. }
  2267. });
  2268. return range;
  2269. }
  2270. _updateRadius() {
  2271. const chart = this.chart;
  2272. const chartArea = chart.chartArea;
  2273. const opts = chart.options;
  2274. const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  2275. const outerRadius = Math.max(minSize / 2, 0);
  2276. const innerRadius = Math.max(opts.cutoutPercentage ? outerRadius / 100 * opts.cutoutPercentage : 1, 0);
  2277. const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();
  2278. this.outerRadius = outerRadius - radiusLength * this.index;
  2279. this.innerRadius = this.outerRadius - radiusLength;
  2280. }
  2281. updateElements(arcs, start, count, mode) {
  2282. const reset = mode === 'reset';
  2283. const chart = this.chart;
  2284. const opts = chart.options;
  2285. const animationOpts = opts.animation;
  2286. const scale = this._cachedMeta.rScale;
  2287. const centerX = scale.xCenter;
  2288. const centerY = scale.yCenter;
  2289. const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * helpers_segment.PI;
  2290. let angle = datasetStartAngle;
  2291. let i;
  2292. const defaultAngle = 360 / this.countVisibleElements();
  2293. for(i = 0; i < start; ++i){
  2294. angle += this._computeAngle(i, mode, defaultAngle);
  2295. }
  2296. for(i = start; i < start + count; i++){
  2297. const arc = arcs[i];
  2298. let startAngle = angle;
  2299. let endAngle = angle + this._computeAngle(i, mode, defaultAngle);
  2300. let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0;
  2301. angle = endAngle;
  2302. if (reset) {
  2303. if (animationOpts.animateScale) {
  2304. outerRadius = 0;
  2305. }
  2306. if (animationOpts.animateRotate) {
  2307. startAngle = endAngle = datasetStartAngle;
  2308. }
  2309. }
  2310. const properties = {
  2311. x: centerX,
  2312. y: centerY,
  2313. innerRadius: 0,
  2314. outerRadius,
  2315. startAngle,
  2316. endAngle,
  2317. options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode)
  2318. };
  2319. this.updateElement(arc, i, properties, mode);
  2320. }
  2321. }
  2322. countVisibleElements() {
  2323. const meta = this._cachedMeta;
  2324. let count = 0;
  2325. meta.data.forEach((element, index)=>{
  2326. if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) {
  2327. count++;
  2328. }
  2329. });
  2330. return count;
  2331. }
  2332. _computeAngle(index, mode, defaultAngle) {
  2333. return this.chart.getDataVisibility(index) ? helpers_segment.toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle) : 0;
  2334. }
  2335. }
  2336. class PieController extends DoughnutController {
  2337. static id = 'pie';
  2338. static defaults = {
  2339. cutout: 0,
  2340. rotation: 0,
  2341. circumference: 360,
  2342. radius: '100%'
  2343. };
  2344. }
  2345. class RadarController extends DatasetController {
  2346. static id = 'radar';
  2347. static defaults = {
  2348. datasetElementType: 'line',
  2349. dataElementType: 'point',
  2350. indexAxis: 'r',
  2351. showLine: true,
  2352. elements: {
  2353. line: {
  2354. fill: 'start'
  2355. }
  2356. }
  2357. };
  2358. static overrides = {
  2359. aspectRatio: 1,
  2360. scales: {
  2361. r: {
  2362. type: 'radialLinear'
  2363. }
  2364. }
  2365. };
  2366. getLabelAndValue(index) {
  2367. const vScale = this._cachedMeta.vScale;
  2368. const parsed = this.getParsed(index);
  2369. return {
  2370. label: vScale.getLabels()[index],
  2371. value: '' + vScale.getLabelForValue(parsed[vScale.axis])
  2372. };
  2373. }
  2374. parseObjectData(meta, data, start, count) {
  2375. return helpers_segment._parseObjectDataRadialScale.bind(this)(meta, data, start, count);
  2376. }
  2377. update(mode) {
  2378. const meta = this._cachedMeta;
  2379. const line = meta.dataset;
  2380. const points = meta.data || [];
  2381. const labels = meta.iScale.getLabels();
  2382. line.points = points;
  2383. if (mode !== 'resize') {
  2384. const options = this.resolveDatasetElementOptions(mode);
  2385. if (!this.options.showLine) {
  2386. options.borderWidth = 0;
  2387. }
  2388. const properties = {
  2389. _loop: true,
  2390. _fullLoop: labels.length === points.length,
  2391. options
  2392. };
  2393. this.updateElement(line, undefined, properties, mode);
  2394. }
  2395. this.updateElements(points, 0, points.length, mode);
  2396. }
  2397. updateElements(points, start, count, mode) {
  2398. const scale = this._cachedMeta.rScale;
  2399. const reset = mode === 'reset';
  2400. for(let i = start; i < start + count; i++){
  2401. const point = points[i];
  2402. const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2403. const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r);
  2404. const x = reset ? scale.xCenter : pointPosition.x;
  2405. const y = reset ? scale.yCenter : pointPosition.y;
  2406. const properties = {
  2407. x,
  2408. y,
  2409. angle: pointPosition.angle,
  2410. skip: isNaN(x) || isNaN(y),
  2411. options
  2412. };
  2413. this.updateElement(point, i, properties, mode);
  2414. }
  2415. }
  2416. }
  2417. class ScatterController extends DatasetController {
  2418. static id = 'scatter';
  2419. static defaults = {
  2420. datasetElementType: false,
  2421. dataElementType: 'point',
  2422. showLine: false,
  2423. fill: false
  2424. };
  2425. static overrides = {
  2426. interaction: {
  2427. mode: 'point'
  2428. },
  2429. scales: {
  2430. x: {
  2431. type: 'linear'
  2432. },
  2433. y: {
  2434. type: 'linear'
  2435. }
  2436. }
  2437. };
  2438. getLabelAndValue(index) {
  2439. const meta = this._cachedMeta;
  2440. const labels = this.chart.data.labels || [];
  2441. const { xScale , yScale } = meta;
  2442. const parsed = this.getParsed(index);
  2443. const x = xScale.getLabelForValue(parsed.x);
  2444. const y = yScale.getLabelForValue(parsed.y);
  2445. return {
  2446. label: labels[index] || '',
  2447. value: '(' + x + ', ' + y + ')'
  2448. };
  2449. }
  2450. update(mode) {
  2451. const meta = this._cachedMeta;
  2452. const { data: points = [] } = meta;
  2453. const animationsDisabled = this.chart._animationsDisabled;
  2454. let { start , count } = helpers_segment._getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
  2455. this._drawStart = start;
  2456. this._drawCount = count;
  2457. if (helpers_segment._scaleRangesChanged(meta)) {
  2458. start = 0;
  2459. count = points.length;
  2460. }
  2461. if (this.options.showLine) {
  2462. if (!this.datasetElementType) {
  2463. this.addElements();
  2464. }
  2465. const { dataset: line , _dataset } = meta;
  2466. line._chart = this.chart;
  2467. line._datasetIndex = this.index;
  2468. line._decimated = !!_dataset._decimated;
  2469. line.points = points;
  2470. const options = this.resolveDatasetElementOptions(mode);
  2471. options.segment = this.options.segment;
  2472. this.updateElement(line, undefined, {
  2473. animated: !animationsDisabled,
  2474. options
  2475. }, mode);
  2476. } else if (this.datasetElementType) {
  2477. delete meta.dataset;
  2478. this.datasetElementType = false;
  2479. }
  2480. this.updateElements(points, start, count, mode);
  2481. }
  2482. addElements() {
  2483. const { showLine } = this.options;
  2484. if (!this.datasetElementType && showLine) {
  2485. this.datasetElementType = this.chart.registry.getElement('line');
  2486. }
  2487. super.addElements();
  2488. }
  2489. updateElements(points, start, count, mode) {
  2490. const reset = mode === 'reset';
  2491. const { iScale , vScale , _stacked , _dataset } = this._cachedMeta;
  2492. const firstOpts = this.resolveDataElementOptions(start, mode);
  2493. const sharedOptions = this.getSharedOptions(firstOpts);
  2494. const includeOptions = this.includeOptions(mode, sharedOptions);
  2495. const iAxis = iScale.axis;
  2496. const vAxis = vScale.axis;
  2497. const { spanGaps , segment } = this.options;
  2498. const maxGapLength = helpers_segment.isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
  2499. const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';
  2500. let prevParsed = start > 0 && this.getParsed(start - 1);
  2501. for(let i = start; i < start + count; ++i){
  2502. const point = points[i];
  2503. const parsed = this.getParsed(i);
  2504. const properties = directUpdate ? point : {};
  2505. const nullData = helpers_segment.isNullOrUndef(parsed[vAxis]);
  2506. const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
  2507. const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
  2508. properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
  2509. properties.stop = i > 0 && Math.abs(parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;
  2510. if (segment) {
  2511. properties.parsed = parsed;
  2512. properties.raw = _dataset.data[i];
  2513. }
  2514. if (includeOptions) {
  2515. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2516. }
  2517. if (!directUpdate) {
  2518. this.updateElement(point, i, properties, mode);
  2519. }
  2520. prevParsed = parsed;
  2521. }
  2522. this.updateSharedOptions(sharedOptions, mode, firstOpts);
  2523. }
  2524. getMaxOverflow() {
  2525. const meta = this._cachedMeta;
  2526. const data = meta.data || [];
  2527. if (!this.options.showLine) {
  2528. let max = 0;
  2529. for(let i = data.length - 1; i >= 0; --i){
  2530. max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);
  2531. }
  2532. return max > 0 && max;
  2533. }
  2534. const dataset = meta.dataset;
  2535. const border = dataset.options && dataset.options.borderWidth || 0;
  2536. if (!data.length) {
  2537. return border;
  2538. }
  2539. const firstPoint = data[0].size(this.resolveDataElementOptions(0));
  2540. const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));
  2541. return Math.max(border, firstPoint, lastPoint) / 2;
  2542. }
  2543. }
  2544. var controllers = /*#__PURE__*/Object.freeze({
  2545. __proto__: null,
  2546. BarController: BarController,
  2547. BubbleController: BubbleController,
  2548. DoughnutController: DoughnutController,
  2549. LineController: LineController,
  2550. PieController: PieController,
  2551. PolarAreaController: PolarAreaController,
  2552. RadarController: RadarController,
  2553. ScatterController: ScatterController
  2554. });
  2555. /**
  2556. * @namespace Chart._adapters
  2557. * @since 2.8.0
  2558. * @private
  2559. */ function abstract() {
  2560. throw new Error('This method is not implemented: Check that a complete date adapter is provided.');
  2561. }
  2562. /**
  2563. * Date adapter (current used by the time scale)
  2564. * @namespace Chart._adapters._date
  2565. * @memberof Chart._adapters
  2566. * @private
  2567. */ class DateAdapterBase {
  2568. /**
  2569. * Override default date adapter methods.
  2570. * Accepts type parameter to define options type.
  2571. * @example
  2572. * Chart._adapters._date.override<{myAdapterOption: string}>({
  2573. * init() {
  2574. * console.log(this.options.myAdapterOption);
  2575. * }
  2576. * })
  2577. */ static override(members) {
  2578. Object.assign(DateAdapterBase.prototype, members);
  2579. }
  2580. options;
  2581. constructor(options){
  2582. this.options = options || {};
  2583. }
  2584. // eslint-disable-next-line @typescript-eslint/no-empty-function
  2585. init() {}
  2586. formats() {
  2587. return abstract();
  2588. }
  2589. parse() {
  2590. return abstract();
  2591. }
  2592. format() {
  2593. return abstract();
  2594. }
  2595. add() {
  2596. return abstract();
  2597. }
  2598. diff() {
  2599. return abstract();
  2600. }
  2601. startOf() {
  2602. return abstract();
  2603. }
  2604. endOf() {
  2605. return abstract();
  2606. }
  2607. }
  2608. var adapters = {
  2609. _date: DateAdapterBase
  2610. };
  2611. function binarySearch(metaset, axis, value, intersect) {
  2612. const { controller , data , _sorted } = metaset;
  2613. const iScale = controller._cachedMeta.iScale;
  2614. if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) {
  2615. const lookupMethod = iScale._reversePixels ? helpers_segment._rlookupByKey : helpers_segment._lookupByKey;
  2616. if (!intersect) {
  2617. return lookupMethod(data, axis, value);
  2618. } else if (controller._sharedOptions) {
  2619. const el = data[0];
  2620. const range = typeof el.getRange === 'function' && el.getRange(axis);
  2621. if (range) {
  2622. const start = lookupMethod(data, axis, value - range);
  2623. const end = lookupMethod(data, axis, value + range);
  2624. return {
  2625. lo: start.lo,
  2626. hi: end.hi
  2627. };
  2628. }
  2629. }
  2630. }
  2631. return {
  2632. lo: 0,
  2633. hi: data.length - 1
  2634. };
  2635. }
  2636. function evaluateInteractionItems(chart, axis, position, handler, intersect) {
  2637. const metasets = chart.getSortedVisibleDatasetMetas();
  2638. const value = position[axis];
  2639. for(let i = 0, ilen = metasets.length; i < ilen; ++i){
  2640. const { index , data } = metasets[i];
  2641. const { lo , hi } = binarySearch(metasets[i], axis, value, intersect);
  2642. for(let j = lo; j <= hi; ++j){
  2643. const element = data[j];
  2644. if (!element.skip) {
  2645. handler(element, index, j);
  2646. }
  2647. }
  2648. }
  2649. }
  2650. function getDistanceMetricForAxis(axis) {
  2651. const useX = axis.indexOf('x') !== -1;
  2652. const useY = axis.indexOf('y') !== -1;
  2653. return function(pt1, pt2) {
  2654. const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  2655. const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  2656. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  2657. };
  2658. }
  2659. function getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) {
  2660. const items = [];
  2661. if (!includeInvisible && !chart.isPointInArea(position)) {
  2662. return items;
  2663. }
  2664. const evaluationFunc = function(element, datasetIndex, index) {
  2665. if (!includeInvisible && !helpers_segment._isPointInArea(element, chart.chartArea, 0)) {
  2666. return;
  2667. }
  2668. if (element.inRange(position.x, position.y, useFinalPosition)) {
  2669. items.push({
  2670. element,
  2671. datasetIndex,
  2672. index
  2673. });
  2674. }
  2675. };
  2676. evaluateInteractionItems(chart, axis, position, evaluationFunc, true);
  2677. return items;
  2678. }
  2679. function getNearestRadialItems(chart, position, axis, useFinalPosition) {
  2680. let items = [];
  2681. function evaluationFunc(element, datasetIndex, index) {
  2682. const { startAngle , endAngle } = element.getProps([
  2683. 'startAngle',
  2684. 'endAngle'
  2685. ], useFinalPosition);
  2686. const { angle } = helpers_segment.getAngleFromPoint(element, {
  2687. x: position.x,
  2688. y: position.y
  2689. });
  2690. if (helpers_segment._angleBetween(angle, startAngle, endAngle)) {
  2691. items.push({
  2692. element,
  2693. datasetIndex,
  2694. index
  2695. });
  2696. }
  2697. }
  2698. evaluateInteractionItems(chart, axis, position, evaluationFunc);
  2699. return items;
  2700. }
  2701. function getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {
  2702. let items = [];
  2703. const distanceMetric = getDistanceMetricForAxis(axis);
  2704. let minDistance = Number.POSITIVE_INFINITY;
  2705. function evaluationFunc(element, datasetIndex, index) {
  2706. const inRange = element.inRange(position.x, position.y, useFinalPosition);
  2707. if (intersect && !inRange) {
  2708. return;
  2709. }
  2710. const center = element.getCenterPoint(useFinalPosition);
  2711. const pointInArea = !!includeInvisible || chart.isPointInArea(center);
  2712. if (!pointInArea && !inRange) {
  2713. return;
  2714. }
  2715. const distance = distanceMetric(position, center);
  2716. if (distance < minDistance) {
  2717. items = [
  2718. {
  2719. element,
  2720. datasetIndex,
  2721. index
  2722. }
  2723. ];
  2724. minDistance = distance;
  2725. } else if (distance === minDistance) {
  2726. items.push({
  2727. element,
  2728. datasetIndex,
  2729. index
  2730. });
  2731. }
  2732. }
  2733. evaluateInteractionItems(chart, axis, position, evaluationFunc);
  2734. return items;
  2735. }
  2736. function getNearestItems(chart, position, axis, intersect, useFinalPosition, includeInvisible) {
  2737. if (!includeInvisible && !chart.isPointInArea(position)) {
  2738. return [];
  2739. }
  2740. return axis === 'r' && !intersect ? getNearestRadialItems(chart, position, axis, useFinalPosition) : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition, includeInvisible);
  2741. }
  2742. function getAxisItems(chart, position, axis, intersect, useFinalPosition) {
  2743. const items = [];
  2744. const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';
  2745. let intersectsItem = false;
  2746. evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index)=>{
  2747. if (element[rangeMethod] && element[rangeMethod](position[axis], useFinalPosition)) {
  2748. items.push({
  2749. element,
  2750. datasetIndex,
  2751. index
  2752. });
  2753. intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition);
  2754. }
  2755. });
  2756. if (intersect && !intersectsItem) {
  2757. return [];
  2758. }
  2759. return items;
  2760. }
  2761. var Interaction = {
  2762. evaluateInteractionItems,
  2763. modes: {
  2764. index (chart, e, options, useFinalPosition) {
  2765. const position = helpers_segment.getRelativePosition(e, chart);
  2766. const axis = options.axis || 'x';
  2767. const includeInvisible = options.includeInvisible || false;
  2768. const items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);
  2769. const elements = [];
  2770. if (!items.length) {
  2771. return [];
  2772. }
  2773. chart.getSortedVisibleDatasetMetas().forEach((meta)=>{
  2774. const index = items[0].index;
  2775. const element = meta.data[index];
  2776. if (element && !element.skip) {
  2777. elements.push({
  2778. element,
  2779. datasetIndex: meta.index,
  2780. index
  2781. });
  2782. }
  2783. });
  2784. return elements;
  2785. },
  2786. dataset (chart, e, options, useFinalPosition) {
  2787. const position = helpers_segment.getRelativePosition(e, chart);
  2788. const axis = options.axis || 'xy';
  2789. const includeInvisible = options.includeInvisible || false;
  2790. let items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible) : getNearestItems(chart, position, axis, false, useFinalPosition, includeInvisible);
  2791. if (items.length > 0) {
  2792. const datasetIndex = items[0].datasetIndex;
  2793. const data = chart.getDatasetMeta(datasetIndex).data;
  2794. items = [];
  2795. for(let i = 0; i < data.length; ++i){
  2796. items.push({
  2797. element: data[i],
  2798. datasetIndex,
  2799. index: i
  2800. });
  2801. }
  2802. }
  2803. return items;
  2804. },
  2805. point (chart, e, options, useFinalPosition) {
  2806. const position = helpers_segment.getRelativePosition(e, chart);
  2807. const axis = options.axis || 'xy';
  2808. const includeInvisible = options.includeInvisible || false;
  2809. return getIntersectItems(chart, position, axis, useFinalPosition, includeInvisible);
  2810. },
  2811. nearest (chart, e, options, useFinalPosition) {
  2812. const position = helpers_segment.getRelativePosition(e, chart);
  2813. const axis = options.axis || 'xy';
  2814. const includeInvisible = options.includeInvisible || false;
  2815. return getNearestItems(chart, position, axis, options.intersect, useFinalPosition, includeInvisible);
  2816. },
  2817. x (chart, e, options, useFinalPosition) {
  2818. const position = helpers_segment.getRelativePosition(e, chart);
  2819. return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition);
  2820. },
  2821. y (chart, e, options, useFinalPosition) {
  2822. const position = helpers_segment.getRelativePosition(e, chart);
  2823. return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition);
  2824. }
  2825. }
  2826. };
  2827. const STATIC_POSITIONS = [
  2828. 'left',
  2829. 'top',
  2830. 'right',
  2831. 'bottom'
  2832. ];
  2833. function filterByPosition(array, position) {
  2834. return array.filter((v)=>v.pos === position);
  2835. }
  2836. function filterDynamicPositionByAxis(array, axis) {
  2837. return array.filter((v)=>STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);
  2838. }
  2839. function sortByWeight(array, reverse) {
  2840. return array.sort((a, b)=>{
  2841. const v0 = reverse ? b : a;
  2842. const v1 = reverse ? a : b;
  2843. return v0.weight === v1.weight ? v0.index - v1.index : v0.weight - v1.weight;
  2844. });
  2845. }
  2846. function wrapBoxes(boxes) {
  2847. const layoutBoxes = [];
  2848. let i, ilen, box, pos, stack, stackWeight;
  2849. for(i = 0, ilen = (boxes || []).length; i < ilen; ++i){
  2850. box = boxes[i];
  2851. ({ position: pos , options: { stack , stackWeight =1 } } = box);
  2852. layoutBoxes.push({
  2853. index: i,
  2854. box,
  2855. pos,
  2856. horizontal: box.isHorizontal(),
  2857. weight: box.weight,
  2858. stack: stack && pos + stack,
  2859. stackWeight
  2860. });
  2861. }
  2862. return layoutBoxes;
  2863. }
  2864. function buildStacks(layouts) {
  2865. const stacks = {};
  2866. for (const wrap of layouts){
  2867. const { stack , pos , stackWeight } = wrap;
  2868. if (!stack || !STATIC_POSITIONS.includes(pos)) {
  2869. continue;
  2870. }
  2871. const _stack = stacks[stack] || (stacks[stack] = {
  2872. count: 0,
  2873. placed: 0,
  2874. weight: 0,
  2875. size: 0
  2876. });
  2877. _stack.count++;
  2878. _stack.weight += stackWeight;
  2879. }
  2880. return stacks;
  2881. }
  2882. function setLayoutDims(layouts, params) {
  2883. const stacks = buildStacks(layouts);
  2884. const { vBoxMaxWidth , hBoxMaxHeight } = params;
  2885. let i, ilen, layout;
  2886. for(i = 0, ilen = layouts.length; i < ilen; ++i){
  2887. layout = layouts[i];
  2888. const { fullSize } = layout.box;
  2889. const stack = stacks[layout.stack];
  2890. const factor = stack && layout.stackWeight / stack.weight;
  2891. if (layout.horizontal) {
  2892. layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;
  2893. layout.height = hBoxMaxHeight;
  2894. } else {
  2895. layout.width = vBoxMaxWidth;
  2896. layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;
  2897. }
  2898. }
  2899. return stacks;
  2900. }
  2901. function buildLayoutBoxes(boxes) {
  2902. const layoutBoxes = wrapBoxes(boxes);
  2903. const fullSize = sortByWeight(layoutBoxes.filter((wrap)=>wrap.box.fullSize), true);
  2904. const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  2905. const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  2906. const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  2907. const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  2908. const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');
  2909. const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');
  2910. return {
  2911. fullSize,
  2912. leftAndTop: left.concat(top),
  2913. rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),
  2914. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  2915. vertical: left.concat(right).concat(centerVertical),
  2916. horizontal: top.concat(bottom).concat(centerHorizontal)
  2917. };
  2918. }
  2919. function getCombinedMax(maxPadding, chartArea, a, b) {
  2920. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  2921. }
  2922. function updateMaxPadding(maxPadding, boxPadding) {
  2923. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  2924. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  2925. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  2926. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  2927. }
  2928. function updateDims(chartArea, params, layout, stacks) {
  2929. const { pos , box } = layout;
  2930. const maxPadding = chartArea.maxPadding;
  2931. if (!helpers_segment.isObject(pos)) {
  2932. if (layout.size) {
  2933. chartArea[pos] -= layout.size;
  2934. }
  2935. const stack = stacks[layout.stack] || {
  2936. size: 0,
  2937. count: 1
  2938. };
  2939. stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);
  2940. layout.size = stack.size / stack.count;
  2941. chartArea[pos] += layout.size;
  2942. }
  2943. if (box.getPadding) {
  2944. updateMaxPadding(maxPadding, box.getPadding());
  2945. }
  2946. const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));
  2947. const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));
  2948. const widthChanged = newWidth !== chartArea.w;
  2949. const heightChanged = newHeight !== chartArea.h;
  2950. chartArea.w = newWidth;
  2951. chartArea.h = newHeight;
  2952. return layout.horizontal ? {
  2953. same: widthChanged,
  2954. other: heightChanged
  2955. } : {
  2956. same: heightChanged,
  2957. other: widthChanged
  2958. };
  2959. }
  2960. function handleMaxPadding(chartArea) {
  2961. const maxPadding = chartArea.maxPadding;
  2962. function updatePos(pos) {
  2963. const change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  2964. chartArea[pos] += change;
  2965. return change;
  2966. }
  2967. chartArea.y += updatePos('top');
  2968. chartArea.x += updatePos('left');
  2969. updatePos('right');
  2970. updatePos('bottom');
  2971. }
  2972. function getMargins(horizontal, chartArea) {
  2973. const maxPadding = chartArea.maxPadding;
  2974. function marginForPositions(positions) {
  2975. const margin = {
  2976. left: 0,
  2977. top: 0,
  2978. right: 0,
  2979. bottom: 0
  2980. };
  2981. positions.forEach((pos)=>{
  2982. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  2983. });
  2984. return margin;
  2985. }
  2986. return horizontal ? marginForPositions([
  2987. 'left',
  2988. 'right'
  2989. ]) : marginForPositions([
  2990. 'top',
  2991. 'bottom'
  2992. ]);
  2993. }
  2994. function fitBoxes(boxes, chartArea, params, stacks) {
  2995. const refitBoxes = [];
  2996. let i, ilen, layout, box, refit, changed;
  2997. for(i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i){
  2998. layout = boxes[i];
  2999. box = layout.box;
  3000. box.update(layout.width || chartArea.w, layout.height || chartArea.h, getMargins(layout.horizontal, chartArea));
  3001. const { same , other } = updateDims(chartArea, params, layout, stacks);
  3002. refit |= same && refitBoxes.length;
  3003. changed = changed || other;
  3004. if (!box.fullSize) {
  3005. refitBoxes.push(layout);
  3006. }
  3007. }
  3008. return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;
  3009. }
  3010. function setBoxDims(box, left, top, width, height) {
  3011. box.top = top;
  3012. box.left = left;
  3013. box.right = left + width;
  3014. box.bottom = top + height;
  3015. box.width = width;
  3016. box.height = height;
  3017. }
  3018. function placeBoxes(boxes, chartArea, params, stacks) {
  3019. const userPadding = params.padding;
  3020. let { x , y } = chartArea;
  3021. for (const layout of boxes){
  3022. const box = layout.box;
  3023. const stack = stacks[layout.stack] || {
  3024. count: 1,
  3025. placed: 0,
  3026. weight: 1
  3027. };
  3028. const weight = layout.stackWeight / stack.weight || 1;
  3029. if (layout.horizontal) {
  3030. const width = chartArea.w * weight;
  3031. const height = stack.size || box.height;
  3032. if (helpers_segment.defined(stack.start)) {
  3033. y = stack.start;
  3034. }
  3035. if (box.fullSize) {
  3036. setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);
  3037. } else {
  3038. setBoxDims(box, chartArea.left + stack.placed, y, width, height);
  3039. }
  3040. stack.start = y;
  3041. stack.placed += width;
  3042. y = box.bottom;
  3043. } else {
  3044. const height = chartArea.h * weight;
  3045. const width = stack.size || box.width;
  3046. if (helpers_segment.defined(stack.start)) {
  3047. x = stack.start;
  3048. }
  3049. if (box.fullSize) {
  3050. setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);
  3051. } else {
  3052. setBoxDims(box, x, chartArea.top + stack.placed, width, height);
  3053. }
  3054. stack.start = x;
  3055. stack.placed += height;
  3056. x = box.right;
  3057. }
  3058. }
  3059. chartArea.x = x;
  3060. chartArea.y = y;
  3061. }
  3062. var layouts = {
  3063. addBox (chart, item) {
  3064. if (!chart.boxes) {
  3065. chart.boxes = [];
  3066. }
  3067. item.fullSize = item.fullSize || false;
  3068. item.position = item.position || 'top';
  3069. item.weight = item.weight || 0;
  3070. item._layers = item._layers || function() {
  3071. return [
  3072. {
  3073. z: 0,
  3074. draw (chartArea) {
  3075. item.draw(chartArea);
  3076. }
  3077. }
  3078. ];
  3079. };
  3080. chart.boxes.push(item);
  3081. },
  3082. removeBox (chart, layoutItem) {
  3083. const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  3084. if (index !== -1) {
  3085. chart.boxes.splice(index, 1);
  3086. }
  3087. },
  3088. configure (chart, item, options) {
  3089. item.fullSize = options.fullSize;
  3090. item.position = options.position;
  3091. item.weight = options.weight;
  3092. },
  3093. update (chart, width, height, minPadding) {
  3094. if (!chart) {
  3095. return;
  3096. }
  3097. const padding = helpers_segment.toPadding(chart.options.layout.padding);
  3098. const availableWidth = Math.max(width - padding.width, 0);
  3099. const availableHeight = Math.max(height - padding.height, 0);
  3100. const boxes = buildLayoutBoxes(chart.boxes);
  3101. const verticalBoxes = boxes.vertical;
  3102. const horizontalBoxes = boxes.horizontal;
  3103. helpers_segment.each(chart.boxes, (box)=>{
  3104. if (typeof box.beforeLayout === 'function') {
  3105. box.beforeLayout();
  3106. }
  3107. });
  3108. const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap)=>wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;
  3109. const params = Object.freeze({
  3110. outerWidth: width,
  3111. outerHeight: height,
  3112. padding,
  3113. availableWidth,
  3114. availableHeight,
  3115. vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,
  3116. hBoxMaxHeight: availableHeight / 2
  3117. });
  3118. const maxPadding = Object.assign({}, padding);
  3119. updateMaxPadding(maxPadding, helpers_segment.toPadding(minPadding));
  3120. const chartArea = Object.assign({
  3121. maxPadding,
  3122. w: availableWidth,
  3123. h: availableHeight,
  3124. x: padding.left,
  3125. y: padding.top
  3126. }, padding);
  3127. const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  3128. fitBoxes(boxes.fullSize, chartArea, params, stacks);
  3129. fitBoxes(verticalBoxes, chartArea, params, stacks);
  3130. if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {
  3131. fitBoxes(verticalBoxes, chartArea, params, stacks);
  3132. }
  3133. handleMaxPadding(chartArea);
  3134. placeBoxes(boxes.leftAndTop, chartArea, params, stacks);
  3135. chartArea.x += chartArea.w;
  3136. chartArea.y += chartArea.h;
  3137. placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);
  3138. chart.chartArea = {
  3139. left: chartArea.left,
  3140. top: chartArea.top,
  3141. right: chartArea.left + chartArea.w,
  3142. bottom: chartArea.top + chartArea.h,
  3143. height: chartArea.h,
  3144. width: chartArea.w
  3145. };
  3146. helpers_segment.each(boxes.chartArea, (layout)=>{
  3147. const box = layout.box;
  3148. Object.assign(box, chart.chartArea);
  3149. box.update(chartArea.w, chartArea.h, {
  3150. left: 0,
  3151. top: 0,
  3152. right: 0,
  3153. bottom: 0
  3154. });
  3155. });
  3156. }
  3157. };
  3158. class BasePlatform {
  3159. acquireContext(canvas, aspectRatio) {}
  3160. releaseContext(context) {
  3161. return false;
  3162. }
  3163. addEventListener(chart, type, listener) {}
  3164. removeEventListener(chart, type, listener) {}
  3165. getDevicePixelRatio() {
  3166. return 1;
  3167. }
  3168. getMaximumSize(element, width, height, aspectRatio) {
  3169. width = Math.max(0, width || element.width);
  3170. height = height || element.height;
  3171. return {
  3172. width,
  3173. height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)
  3174. };
  3175. }
  3176. isAttached(canvas) {
  3177. return true;
  3178. }
  3179. updateConfig(config) {
  3180. }
  3181. }
  3182. class BasicPlatform extends BasePlatform {
  3183. acquireContext(item) {
  3184. return item && item.getContext && item.getContext('2d') || null;
  3185. }
  3186. updateConfig(config) {
  3187. config.options.animation = false;
  3188. }
  3189. }
  3190. const EXPANDO_KEY = '$chartjs';
  3191. const EVENT_TYPES = {
  3192. touchstart: 'mousedown',
  3193. touchmove: 'mousemove',
  3194. touchend: 'mouseup',
  3195. pointerenter: 'mouseenter',
  3196. pointerdown: 'mousedown',
  3197. pointermove: 'mousemove',
  3198. pointerup: 'mouseup',
  3199. pointerleave: 'mouseout',
  3200. pointerout: 'mouseout'
  3201. };
  3202. const isNullOrEmpty = (value)=>value === null || value === '';
  3203. function initCanvas(canvas, aspectRatio) {
  3204. const style = canvas.style;
  3205. const renderHeight = canvas.getAttribute('height');
  3206. const renderWidth = canvas.getAttribute('width');
  3207. canvas[EXPANDO_KEY] = {
  3208. initial: {
  3209. height: renderHeight,
  3210. width: renderWidth,
  3211. style: {
  3212. display: style.display,
  3213. height: style.height,
  3214. width: style.width
  3215. }
  3216. }
  3217. };
  3218. style.display = style.display || 'block';
  3219. style.boxSizing = style.boxSizing || 'border-box';
  3220. if (isNullOrEmpty(renderWidth)) {
  3221. const displayWidth = helpers_segment.readUsedSize(canvas, 'width');
  3222. if (displayWidth !== undefined) {
  3223. canvas.width = displayWidth;
  3224. }
  3225. }
  3226. if (isNullOrEmpty(renderHeight)) {
  3227. if (canvas.style.height === '') {
  3228. canvas.height = canvas.width / (aspectRatio || 2);
  3229. } else {
  3230. const displayHeight = helpers_segment.readUsedSize(canvas, 'height');
  3231. if (displayHeight !== undefined) {
  3232. canvas.height = displayHeight;
  3233. }
  3234. }
  3235. }
  3236. return canvas;
  3237. }
  3238. const eventListenerOptions = helpers_segment.supportsEventListenerOptions ? {
  3239. passive: true
  3240. } : false;
  3241. function addListener(node, type, listener) {
  3242. if (node) {
  3243. node.addEventListener(type, listener, eventListenerOptions);
  3244. }
  3245. }
  3246. function removeListener(chart, type, listener) {
  3247. if (chart && chart.canvas) {
  3248. chart.canvas.removeEventListener(type, listener, eventListenerOptions);
  3249. }
  3250. }
  3251. function fromNativeEvent(event, chart) {
  3252. const type = EVENT_TYPES[event.type] || event.type;
  3253. const { x , y } = helpers_segment.getRelativePosition(event, chart);
  3254. return {
  3255. type,
  3256. chart,
  3257. native: event,
  3258. x: x !== undefined ? x : null,
  3259. y: y !== undefined ? y : null
  3260. };
  3261. }
  3262. function nodeListContains(nodeList, canvas) {
  3263. for (const node of nodeList){
  3264. if (node === canvas || node.contains(canvas)) {
  3265. return true;
  3266. }
  3267. }
  3268. }
  3269. function createAttachObserver(chart, type, listener) {
  3270. const canvas = chart.canvas;
  3271. const observer = new MutationObserver((entries)=>{
  3272. let trigger = false;
  3273. for (const entry of entries){
  3274. trigger = trigger || nodeListContains(entry.addedNodes, canvas);
  3275. trigger = trigger && !nodeListContains(entry.removedNodes, canvas);
  3276. }
  3277. if (trigger) {
  3278. listener();
  3279. }
  3280. });
  3281. observer.observe(document, {
  3282. childList: true,
  3283. subtree: true
  3284. });
  3285. return observer;
  3286. }
  3287. function createDetachObserver(chart, type, listener) {
  3288. const canvas = chart.canvas;
  3289. const observer = new MutationObserver((entries)=>{
  3290. let trigger = false;
  3291. for (const entry of entries){
  3292. trigger = trigger || nodeListContains(entry.removedNodes, canvas);
  3293. trigger = trigger && !nodeListContains(entry.addedNodes, canvas);
  3294. }
  3295. if (trigger) {
  3296. listener();
  3297. }
  3298. });
  3299. observer.observe(document, {
  3300. childList: true,
  3301. subtree: true
  3302. });
  3303. return observer;
  3304. }
  3305. const drpListeningCharts = new Map();
  3306. let oldDevicePixelRatio = 0;
  3307. function onWindowResize() {
  3308. const dpr = window.devicePixelRatio;
  3309. if (dpr === oldDevicePixelRatio) {
  3310. return;
  3311. }
  3312. oldDevicePixelRatio = dpr;
  3313. drpListeningCharts.forEach((resize, chart)=>{
  3314. if (chart.currentDevicePixelRatio !== dpr) {
  3315. resize();
  3316. }
  3317. });
  3318. }
  3319. function listenDevicePixelRatioChanges(chart, resize) {
  3320. if (!drpListeningCharts.size) {
  3321. window.addEventListener('resize', onWindowResize);
  3322. }
  3323. drpListeningCharts.set(chart, resize);
  3324. }
  3325. function unlistenDevicePixelRatioChanges(chart) {
  3326. drpListeningCharts.delete(chart);
  3327. if (!drpListeningCharts.size) {
  3328. window.removeEventListener('resize', onWindowResize);
  3329. }
  3330. }
  3331. function createResizeObserver(chart, type, listener) {
  3332. const canvas = chart.canvas;
  3333. const container = canvas && helpers_segment._getParentNode(canvas);
  3334. if (!container) {
  3335. return;
  3336. }
  3337. const resize = helpers_segment.throttled((width, height)=>{
  3338. const w = container.clientWidth;
  3339. listener(width, height);
  3340. if (w < container.clientWidth) {
  3341. listener();
  3342. }
  3343. }, window);
  3344. const observer = new ResizeObserver((entries)=>{
  3345. const entry = entries[0];
  3346. const width = entry.contentRect.width;
  3347. const height = entry.contentRect.height;
  3348. if (width === 0 && height === 0) {
  3349. return;
  3350. }
  3351. resize(width, height);
  3352. });
  3353. observer.observe(container);
  3354. listenDevicePixelRatioChanges(chart, resize);
  3355. return observer;
  3356. }
  3357. function releaseObserver(chart, type, observer) {
  3358. if (observer) {
  3359. observer.disconnect();
  3360. }
  3361. if (type === 'resize') {
  3362. unlistenDevicePixelRatioChanges(chart);
  3363. }
  3364. }
  3365. function createProxyAndListen(chart, type, listener) {
  3366. const canvas = chart.canvas;
  3367. const proxy = helpers_segment.throttled((event)=>{
  3368. if (chart.ctx !== null) {
  3369. listener(fromNativeEvent(event, chart));
  3370. }
  3371. }, chart);
  3372. addListener(canvas, type, proxy);
  3373. return proxy;
  3374. }
  3375. class DomPlatform extends BasePlatform {
  3376. acquireContext(canvas, aspectRatio) {
  3377. const context = canvas && canvas.getContext && canvas.getContext('2d');
  3378. if (context && context.canvas === canvas) {
  3379. initCanvas(canvas, aspectRatio);
  3380. return context;
  3381. }
  3382. return null;
  3383. }
  3384. releaseContext(context) {
  3385. const canvas = context.canvas;
  3386. if (!canvas[EXPANDO_KEY]) {
  3387. return false;
  3388. }
  3389. const initial = canvas[EXPANDO_KEY].initial;
  3390. [
  3391. 'height',
  3392. 'width'
  3393. ].forEach((prop)=>{
  3394. const value = initial[prop];
  3395. if (helpers_segment.isNullOrUndef(value)) {
  3396. canvas.removeAttribute(prop);
  3397. } else {
  3398. canvas.setAttribute(prop, value);
  3399. }
  3400. });
  3401. const style = initial.style || {};
  3402. Object.keys(style).forEach((key)=>{
  3403. canvas.style[key] = style[key];
  3404. });
  3405. canvas.width = canvas.width;
  3406. delete canvas[EXPANDO_KEY];
  3407. return true;
  3408. }
  3409. addEventListener(chart, type, listener) {
  3410. this.removeEventListener(chart, type);
  3411. const proxies = chart.$proxies || (chart.$proxies = {});
  3412. const handlers = {
  3413. attach: createAttachObserver,
  3414. detach: createDetachObserver,
  3415. resize: createResizeObserver
  3416. };
  3417. const handler = handlers[type] || createProxyAndListen;
  3418. proxies[type] = handler(chart, type, listener);
  3419. }
  3420. removeEventListener(chart, type) {
  3421. const proxies = chart.$proxies || (chart.$proxies = {});
  3422. const proxy = proxies[type];
  3423. if (!proxy) {
  3424. return;
  3425. }
  3426. const handlers = {
  3427. attach: releaseObserver,
  3428. detach: releaseObserver,
  3429. resize: releaseObserver
  3430. };
  3431. const handler = handlers[type] || removeListener;
  3432. handler(chart, type, proxy);
  3433. proxies[type] = undefined;
  3434. }
  3435. getDevicePixelRatio() {
  3436. return window.devicePixelRatio;
  3437. }
  3438. getMaximumSize(canvas, width, height, aspectRatio) {
  3439. return helpers_segment.getMaximumSize(canvas, width, height, aspectRatio);
  3440. }
  3441. isAttached(canvas) {
  3442. const container = canvas && helpers_segment._getParentNode(canvas);
  3443. return !!(container && container.isConnected);
  3444. }
  3445. }
  3446. function _detectPlatform(canvas) {
  3447. if (!helpers_segment._isDomSupported() || typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) {
  3448. return BasicPlatform;
  3449. }
  3450. return DomPlatform;
  3451. }
  3452. class Element {
  3453. static defaults = {};
  3454. static defaultRoutes = undefined;
  3455. x;
  3456. y;
  3457. active = false;
  3458. options;
  3459. $animations;
  3460. tooltipPosition(useFinalPosition) {
  3461. const { x , y } = this.getProps([
  3462. 'x',
  3463. 'y'
  3464. ], useFinalPosition);
  3465. return {
  3466. x,
  3467. y
  3468. };
  3469. }
  3470. hasValue() {
  3471. return helpers_segment.isNumber(this.x) && helpers_segment.isNumber(this.y);
  3472. }
  3473. getProps(props, final) {
  3474. const anims = this.$animations;
  3475. if (!final || !anims) {
  3476. // let's not create an object, if not needed
  3477. return this;
  3478. }
  3479. const ret = {};
  3480. props.forEach((prop)=>{
  3481. ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop];
  3482. });
  3483. return ret;
  3484. }
  3485. }
  3486. function autoSkip(scale, ticks) {
  3487. const tickOpts = scale.options.ticks;
  3488. const determinedMaxTicks = determineMaxTicks(scale);
  3489. const ticksLimit = Math.min(tickOpts.maxTicksLimit || determinedMaxTicks, determinedMaxTicks);
  3490. const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  3491. const numMajorIndices = majorIndices.length;
  3492. const first = majorIndices[0];
  3493. const last = majorIndices[numMajorIndices - 1];
  3494. const newTicks = [];
  3495. if (numMajorIndices > ticksLimit) {
  3496. skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);
  3497. return newTicks;
  3498. }
  3499. const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);
  3500. if (numMajorIndices > 0) {
  3501. let i, ilen;
  3502. const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
  3503. skip(ticks, newTicks, spacing, helpers_segment.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  3504. for(i = 0, ilen = numMajorIndices - 1; i < ilen; i++){
  3505. skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
  3506. }
  3507. skip(ticks, newTicks, spacing, last, helpers_segment.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  3508. return newTicks;
  3509. }
  3510. skip(ticks, newTicks, spacing);
  3511. return newTicks;
  3512. }
  3513. function determineMaxTicks(scale) {
  3514. const offset = scale.options.offset;
  3515. const tickLength = scale._tickSize();
  3516. const maxScale = scale._length / tickLength + (offset ? 0 : 1);
  3517. const maxChart = scale._maxLength / tickLength;
  3518. return Math.floor(Math.min(maxScale, maxChart));
  3519. }
  3520. function calculateSpacing(majorIndices, ticks, ticksLimit) {
  3521. const evenMajorSpacing = getEvenSpacing(majorIndices);
  3522. const spacing = ticks.length / ticksLimit;
  3523. if (!evenMajorSpacing) {
  3524. return Math.max(spacing, 1);
  3525. }
  3526. const factors = helpers_segment._factorize(evenMajorSpacing);
  3527. for(let i = 0, ilen = factors.length - 1; i < ilen; i++){
  3528. const factor = factors[i];
  3529. if (factor > spacing) {
  3530. return factor;
  3531. }
  3532. }
  3533. return Math.max(spacing, 1);
  3534. }
  3535. function getMajorIndices(ticks) {
  3536. const result = [];
  3537. let i, ilen;
  3538. for(i = 0, ilen = ticks.length; i < ilen; i++){
  3539. if (ticks[i].major) {
  3540. result.push(i);
  3541. }
  3542. }
  3543. return result;
  3544. }
  3545. function skipMajors(ticks, newTicks, majorIndices, spacing) {
  3546. let count = 0;
  3547. let next = majorIndices[0];
  3548. let i;
  3549. spacing = Math.ceil(spacing);
  3550. for(i = 0; i < ticks.length; i++){
  3551. if (i === next) {
  3552. newTicks.push(ticks[i]);
  3553. count++;
  3554. next = majorIndices[count * spacing];
  3555. }
  3556. }
  3557. }
  3558. function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
  3559. const start = helpers_segment.valueOrDefault(majorStart, 0);
  3560. const end = Math.min(helpers_segment.valueOrDefault(majorEnd, ticks.length), ticks.length);
  3561. let count = 0;
  3562. let length, i, next;
  3563. spacing = Math.ceil(spacing);
  3564. if (majorEnd) {
  3565. length = majorEnd - majorStart;
  3566. spacing = length / Math.floor(length / spacing);
  3567. }
  3568. next = start;
  3569. while(next < 0){
  3570. count++;
  3571. next = Math.round(start + count * spacing);
  3572. }
  3573. for(i = Math.max(start, 0); i < end; i++){
  3574. if (i === next) {
  3575. newTicks.push(ticks[i]);
  3576. count++;
  3577. next = Math.round(start + count * spacing);
  3578. }
  3579. }
  3580. }
  3581. function getEvenSpacing(arr) {
  3582. const len = arr.length;
  3583. let i, diff;
  3584. if (len < 2) {
  3585. return false;
  3586. }
  3587. for(diff = arr[0], i = 1; i < len; ++i){
  3588. if (arr[i] - arr[i - 1] !== diff) {
  3589. return false;
  3590. }
  3591. }
  3592. return diff;
  3593. }
  3594. const reverseAlign = (align)=>align === 'left' ? 'right' : align === 'right' ? 'left' : align;
  3595. const offsetFromEdge = (scale, edge, offset)=>edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;
  3596. const getTicksLimit = (ticksLength, maxTicksLimit)=>Math.min(maxTicksLimit || ticksLength, ticksLength);
  3597. function sample(arr, numItems) {
  3598. const result = [];
  3599. const increment = arr.length / numItems;
  3600. const len = arr.length;
  3601. let i = 0;
  3602. for(; i < len; i += increment){
  3603. result.push(arr[Math.floor(i)]);
  3604. }
  3605. return result;
  3606. }
  3607. function getPixelForGridLine(scale, index, offsetGridLines) {
  3608. const length = scale.ticks.length;
  3609. const validIndex = Math.min(index, length - 1);
  3610. const start = scale._startPixel;
  3611. const end = scale._endPixel;
  3612. const epsilon = 1e-6;
  3613. let lineValue = scale.getPixelForTick(validIndex);
  3614. let offset;
  3615. if (offsetGridLines) {
  3616. if (length === 1) {
  3617. offset = Math.max(lineValue - start, end - lineValue);
  3618. } else if (index === 0) {
  3619. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  3620. } else {
  3621. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  3622. }
  3623. lineValue += validIndex < index ? offset : -offset;
  3624. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  3625. return;
  3626. }
  3627. }
  3628. return lineValue;
  3629. }
  3630. function garbageCollect(caches, length) {
  3631. helpers_segment.each(caches, (cache)=>{
  3632. const gc = cache.gc;
  3633. const gcLen = gc.length / 2;
  3634. let i;
  3635. if (gcLen > length) {
  3636. for(i = 0; i < gcLen; ++i){
  3637. delete cache.data[gc[i]];
  3638. }
  3639. gc.splice(0, gcLen);
  3640. }
  3641. });
  3642. }
  3643. function getTickMarkLength(options) {
  3644. return options.drawTicks ? options.tickLength : 0;
  3645. }
  3646. function getTitleHeight(options, fallback) {
  3647. if (!options.display) {
  3648. return 0;
  3649. }
  3650. const font = helpers_segment.toFont(options.font, fallback);
  3651. const padding = helpers_segment.toPadding(options.padding);
  3652. const lines = helpers_segment.isArray(options.text) ? options.text.length : 1;
  3653. return lines * font.lineHeight + padding.height;
  3654. }
  3655. function createScaleContext(parent, scale) {
  3656. return helpers_segment.createContext(parent, {
  3657. scale,
  3658. type: 'scale'
  3659. });
  3660. }
  3661. function createTickContext(parent, index, tick) {
  3662. return helpers_segment.createContext(parent, {
  3663. tick,
  3664. index,
  3665. type: 'tick'
  3666. });
  3667. }
  3668. function titleAlign(align, position, reverse) {
  3669. let ret = helpers_segment._toLeftRightCenter(align);
  3670. if (reverse && position !== 'right' || !reverse && position === 'right') {
  3671. ret = reverseAlign(ret);
  3672. }
  3673. return ret;
  3674. }
  3675. function titleArgs(scale, offset, position, align) {
  3676. const { top , left , bottom , right , chart } = scale;
  3677. const { chartArea , scales } = chart;
  3678. let rotation = 0;
  3679. let maxWidth, titleX, titleY;
  3680. const height = bottom - top;
  3681. const width = right - left;
  3682. if (scale.isHorizontal()) {
  3683. titleX = helpers_segment._alignStartEnd(align, left, right);
  3684. if (helpers_segment.isObject(position)) {
  3685. const positionAxisID = Object.keys(position)[0];
  3686. const value = position[positionAxisID];
  3687. titleY = scales[positionAxisID].getPixelForValue(value) + height - offset;
  3688. } else if (position === 'center') {
  3689. titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset;
  3690. } else {
  3691. titleY = offsetFromEdge(scale, position, offset);
  3692. }
  3693. maxWidth = right - left;
  3694. } else {
  3695. if (helpers_segment.isObject(position)) {
  3696. const positionAxisID = Object.keys(position)[0];
  3697. const value = position[positionAxisID];
  3698. titleX = scales[positionAxisID].getPixelForValue(value) - width + offset;
  3699. } else if (position === 'center') {
  3700. titleX = (chartArea.left + chartArea.right) / 2 - width + offset;
  3701. } else {
  3702. titleX = offsetFromEdge(scale, position, offset);
  3703. }
  3704. titleY = helpers_segment._alignStartEnd(align, bottom, top);
  3705. rotation = position === 'left' ? -helpers_segment.HALF_PI : helpers_segment.HALF_PI;
  3706. }
  3707. return {
  3708. titleX,
  3709. titleY,
  3710. maxWidth,
  3711. rotation
  3712. };
  3713. }
  3714. class Scale extends Element {
  3715. constructor(cfg){
  3716. super();
  3717. this.id = cfg.id;
  3718. this.type = cfg.type;
  3719. this.options = undefined;
  3720. this.ctx = cfg.ctx;
  3721. this.chart = cfg.chart;
  3722. this.top = undefined;
  3723. this.bottom = undefined;
  3724. this.left = undefined;
  3725. this.right = undefined;
  3726. this.width = undefined;
  3727. this.height = undefined;
  3728. this._margins = {
  3729. left: 0,
  3730. right: 0,
  3731. top: 0,
  3732. bottom: 0
  3733. };
  3734. this.maxWidth = undefined;
  3735. this.maxHeight = undefined;
  3736. this.paddingTop = undefined;
  3737. this.paddingBottom = undefined;
  3738. this.paddingLeft = undefined;
  3739. this.paddingRight = undefined;
  3740. this.axis = undefined;
  3741. this.labelRotation = undefined;
  3742. this.min = undefined;
  3743. this.max = undefined;
  3744. this._range = undefined;
  3745. this.ticks = [];
  3746. this._gridLineItems = null;
  3747. this._labelItems = null;
  3748. this._labelSizes = null;
  3749. this._length = 0;
  3750. this._maxLength = 0;
  3751. this._longestTextCache = {};
  3752. this._startPixel = undefined;
  3753. this._endPixel = undefined;
  3754. this._reversePixels = false;
  3755. this._userMax = undefined;
  3756. this._userMin = undefined;
  3757. this._suggestedMax = undefined;
  3758. this._suggestedMin = undefined;
  3759. this._ticksLength = 0;
  3760. this._borderValue = 0;
  3761. this._cache = {};
  3762. this._dataLimitsCached = false;
  3763. this.$context = undefined;
  3764. }
  3765. init(options) {
  3766. this.options = options.setContext(this.getContext());
  3767. this.axis = options.axis;
  3768. this._userMin = this.parse(options.min);
  3769. this._userMax = this.parse(options.max);
  3770. this._suggestedMin = this.parse(options.suggestedMin);
  3771. this._suggestedMax = this.parse(options.suggestedMax);
  3772. }
  3773. parse(raw, index) {
  3774. return raw;
  3775. }
  3776. getUserBounds() {
  3777. let { _userMin , _userMax , _suggestedMin , _suggestedMax } = this;
  3778. _userMin = helpers_segment.finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);
  3779. _userMax = helpers_segment.finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);
  3780. _suggestedMin = helpers_segment.finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);
  3781. _suggestedMax = helpers_segment.finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);
  3782. return {
  3783. min: helpers_segment.finiteOrDefault(_userMin, _suggestedMin),
  3784. max: helpers_segment.finiteOrDefault(_userMax, _suggestedMax),
  3785. minDefined: helpers_segment.isNumberFinite(_userMin),
  3786. maxDefined: helpers_segment.isNumberFinite(_userMax)
  3787. };
  3788. }
  3789. getMinMax(canStack) {
  3790. let { min , max , minDefined , maxDefined } = this.getUserBounds();
  3791. let range;
  3792. if (minDefined && maxDefined) {
  3793. return {
  3794. min,
  3795. max
  3796. };
  3797. }
  3798. const metas = this.getMatchingVisibleMetas();
  3799. for(let i = 0, ilen = metas.length; i < ilen; ++i){
  3800. range = metas[i].controller.getMinMax(this, canStack);
  3801. if (!minDefined) {
  3802. min = Math.min(min, range.min);
  3803. }
  3804. if (!maxDefined) {
  3805. max = Math.max(max, range.max);
  3806. }
  3807. }
  3808. min = maxDefined && min > max ? max : min;
  3809. max = minDefined && min > max ? min : max;
  3810. return {
  3811. min: helpers_segment.finiteOrDefault(min, helpers_segment.finiteOrDefault(max, min)),
  3812. max: helpers_segment.finiteOrDefault(max, helpers_segment.finiteOrDefault(min, max))
  3813. };
  3814. }
  3815. getPadding() {
  3816. return {
  3817. left: this.paddingLeft || 0,
  3818. top: this.paddingTop || 0,
  3819. right: this.paddingRight || 0,
  3820. bottom: this.paddingBottom || 0
  3821. };
  3822. }
  3823. getTicks() {
  3824. return this.ticks;
  3825. }
  3826. getLabels() {
  3827. const data = this.chart.data;
  3828. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  3829. }
  3830. getLabelItems(chartArea = this.chart.chartArea) {
  3831. const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea));
  3832. return items;
  3833. }
  3834. beforeLayout() {
  3835. this._cache = {};
  3836. this._dataLimitsCached = false;
  3837. }
  3838. beforeUpdate() {
  3839. helpers_segment.callback(this.options.beforeUpdate, [
  3840. this
  3841. ]);
  3842. }
  3843. update(maxWidth, maxHeight, margins) {
  3844. const { beginAtZero , grace , ticks: tickOpts } = this.options;
  3845. const sampleSize = tickOpts.sampleSize;
  3846. this.beforeUpdate();
  3847. this.maxWidth = maxWidth;
  3848. this.maxHeight = maxHeight;
  3849. this._margins = margins = Object.assign({
  3850. left: 0,
  3851. right: 0,
  3852. top: 0,
  3853. bottom: 0
  3854. }, margins);
  3855. this.ticks = null;
  3856. this._labelSizes = null;
  3857. this._gridLineItems = null;
  3858. this._labelItems = null;
  3859. this.beforeSetDimensions();
  3860. this.setDimensions();
  3861. this.afterSetDimensions();
  3862. this._maxLength = this.isHorizontal() ? this.width + margins.left + margins.right : this.height + margins.top + margins.bottom;
  3863. if (!this._dataLimitsCached) {
  3864. this.beforeDataLimits();
  3865. this.determineDataLimits();
  3866. this.afterDataLimits();
  3867. this._range = helpers_segment._addGrace(this, grace, beginAtZero);
  3868. this._dataLimitsCached = true;
  3869. }
  3870. this.beforeBuildTicks();
  3871. this.ticks = this.buildTicks() || [];
  3872. this.afterBuildTicks();
  3873. const samplingEnabled = sampleSize < this.ticks.length;
  3874. this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks);
  3875. this.configure();
  3876. this.beforeCalculateLabelRotation();
  3877. this.calculateLabelRotation();
  3878. this.afterCalculateLabelRotation();
  3879. if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {
  3880. this.ticks = autoSkip(this, this.ticks);
  3881. this._labelSizes = null;
  3882. this.afterAutoSkip();
  3883. }
  3884. if (samplingEnabled) {
  3885. this._convertTicksToLabels(this.ticks);
  3886. }
  3887. this.beforeFit();
  3888. this.fit();
  3889. this.afterFit();
  3890. this.afterUpdate();
  3891. }
  3892. configure() {
  3893. let reversePixels = this.options.reverse;
  3894. let startPixel, endPixel;
  3895. if (this.isHorizontal()) {
  3896. startPixel = this.left;
  3897. endPixel = this.right;
  3898. } else {
  3899. startPixel = this.top;
  3900. endPixel = this.bottom;
  3901. reversePixels = !reversePixels;
  3902. }
  3903. this._startPixel = startPixel;
  3904. this._endPixel = endPixel;
  3905. this._reversePixels = reversePixels;
  3906. this._length = endPixel - startPixel;
  3907. this._alignToPixels = this.options.alignToPixels;
  3908. }
  3909. afterUpdate() {
  3910. helpers_segment.callback(this.options.afterUpdate, [
  3911. this
  3912. ]);
  3913. }
  3914. beforeSetDimensions() {
  3915. helpers_segment.callback(this.options.beforeSetDimensions, [
  3916. this
  3917. ]);
  3918. }
  3919. setDimensions() {
  3920. if (this.isHorizontal()) {
  3921. this.width = this.maxWidth;
  3922. this.left = 0;
  3923. this.right = this.width;
  3924. } else {
  3925. this.height = this.maxHeight;
  3926. this.top = 0;
  3927. this.bottom = this.height;
  3928. }
  3929. this.paddingLeft = 0;
  3930. this.paddingTop = 0;
  3931. this.paddingRight = 0;
  3932. this.paddingBottom = 0;
  3933. }
  3934. afterSetDimensions() {
  3935. helpers_segment.callback(this.options.afterSetDimensions, [
  3936. this
  3937. ]);
  3938. }
  3939. _callHooks(name) {
  3940. this.chart.notifyPlugins(name, this.getContext());
  3941. helpers_segment.callback(this.options[name], [
  3942. this
  3943. ]);
  3944. }
  3945. beforeDataLimits() {
  3946. this._callHooks('beforeDataLimits');
  3947. }
  3948. determineDataLimits() {}
  3949. afterDataLimits() {
  3950. this._callHooks('afterDataLimits');
  3951. }
  3952. beforeBuildTicks() {
  3953. this._callHooks('beforeBuildTicks');
  3954. }
  3955. buildTicks() {
  3956. return [];
  3957. }
  3958. afterBuildTicks() {
  3959. this._callHooks('afterBuildTicks');
  3960. }
  3961. beforeTickToLabelConversion() {
  3962. helpers_segment.callback(this.options.beforeTickToLabelConversion, [
  3963. this
  3964. ]);
  3965. }
  3966. generateTickLabels(ticks) {
  3967. const tickOpts = this.options.ticks;
  3968. let i, ilen, tick;
  3969. for(i = 0, ilen = ticks.length; i < ilen; i++){
  3970. tick = ticks[i];
  3971. tick.label = helpers_segment.callback(tickOpts.callback, [
  3972. tick.value,
  3973. i,
  3974. ticks
  3975. ], this);
  3976. }
  3977. }
  3978. afterTickToLabelConversion() {
  3979. helpers_segment.callback(this.options.afterTickToLabelConversion, [
  3980. this
  3981. ]);
  3982. }
  3983. beforeCalculateLabelRotation() {
  3984. helpers_segment.callback(this.options.beforeCalculateLabelRotation, [
  3985. this
  3986. ]);
  3987. }
  3988. calculateLabelRotation() {
  3989. const options = this.options;
  3990. const tickOpts = options.ticks;
  3991. const numTicks = getTicksLimit(this.ticks.length, options.ticks.maxTicksLimit);
  3992. const minRotation = tickOpts.minRotation || 0;
  3993. const maxRotation = tickOpts.maxRotation;
  3994. let labelRotation = minRotation;
  3995. let tickWidth, maxHeight, maxLabelDiagonal;
  3996. if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) {
  3997. this.labelRotation = minRotation;
  3998. return;
  3999. }
  4000. const labelSizes = this._getLabelSizes();
  4001. const maxLabelWidth = labelSizes.widest.width;
  4002. const maxLabelHeight = labelSizes.highest.height;
  4003. const maxWidth = helpers_segment._limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth);
  4004. tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1);
  4005. if (maxLabelWidth + 6 > tickWidth) {
  4006. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  4007. maxHeight = this.maxHeight - getTickMarkLength(options.grid) - tickOpts.padding - getTitleHeight(options.title, this.chart.options.font);
  4008. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  4009. labelRotation = helpers_segment.toDegrees(Math.min(Math.asin(helpers_segment._limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)), Math.asin(helpers_segment._limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(helpers_segment._limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))));
  4010. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  4011. }
  4012. this.labelRotation = labelRotation;
  4013. }
  4014. afterCalculateLabelRotation() {
  4015. helpers_segment.callback(this.options.afterCalculateLabelRotation, [
  4016. this
  4017. ]);
  4018. }
  4019. afterAutoSkip() {}
  4020. beforeFit() {
  4021. helpers_segment.callback(this.options.beforeFit, [
  4022. this
  4023. ]);
  4024. }
  4025. fit() {
  4026. const minSize = {
  4027. width: 0,
  4028. height: 0
  4029. };
  4030. const { chart , options: { ticks: tickOpts , title: titleOpts , grid: gridOpts } } = this;
  4031. const display = this._isVisible();
  4032. const isHorizontal = this.isHorizontal();
  4033. if (display) {
  4034. const titleHeight = getTitleHeight(titleOpts, chart.options.font);
  4035. if (isHorizontal) {
  4036. minSize.width = this.maxWidth;
  4037. minSize.height = getTickMarkLength(gridOpts) + titleHeight;
  4038. } else {
  4039. minSize.height = this.maxHeight;
  4040. minSize.width = getTickMarkLength(gridOpts) + titleHeight;
  4041. }
  4042. if (tickOpts.display && this.ticks.length) {
  4043. const { first , last , widest , highest } = this._getLabelSizes();
  4044. const tickPadding = tickOpts.padding * 2;
  4045. const angleRadians = helpers_segment.toRadians(this.labelRotation);
  4046. const cos = Math.cos(angleRadians);
  4047. const sin = Math.sin(angleRadians);
  4048. if (isHorizontal) {
  4049. const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;
  4050. minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding);
  4051. } else {
  4052. const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;
  4053. minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding);
  4054. }
  4055. this._calculatePadding(first, last, sin, cos);
  4056. }
  4057. }
  4058. this._handleMargins();
  4059. if (isHorizontal) {
  4060. this.width = this._length = chart.width - this._margins.left - this._margins.right;
  4061. this.height = minSize.height;
  4062. } else {
  4063. this.width = minSize.width;
  4064. this.height = this._length = chart.height - this._margins.top - this._margins.bottom;
  4065. }
  4066. }
  4067. _calculatePadding(first, last, sin, cos) {
  4068. const { ticks: { align , padding } , position } = this.options;
  4069. const isRotated = this.labelRotation !== 0;
  4070. const labelsBelowTicks = position !== 'top' && this.axis === 'x';
  4071. if (this.isHorizontal()) {
  4072. const offsetLeft = this.getPixelForTick(0) - this.left;
  4073. const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1);
  4074. let paddingLeft = 0;
  4075. let paddingRight = 0;
  4076. if (isRotated) {
  4077. if (labelsBelowTicks) {
  4078. paddingLeft = cos * first.width;
  4079. paddingRight = sin * last.height;
  4080. } else {
  4081. paddingLeft = sin * first.height;
  4082. paddingRight = cos * last.width;
  4083. }
  4084. } else if (align === 'start') {
  4085. paddingRight = last.width;
  4086. } else if (align === 'end') {
  4087. paddingLeft = first.width;
  4088. } else if (align !== 'inner') {
  4089. paddingLeft = first.width / 2;
  4090. paddingRight = last.width / 2;
  4091. }
  4092. this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0);
  4093. this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0);
  4094. } else {
  4095. let paddingTop = last.height / 2;
  4096. let paddingBottom = first.height / 2;
  4097. if (align === 'start') {
  4098. paddingTop = 0;
  4099. paddingBottom = first.height;
  4100. } else if (align === 'end') {
  4101. paddingTop = last.height;
  4102. paddingBottom = 0;
  4103. }
  4104. this.paddingTop = paddingTop + padding;
  4105. this.paddingBottom = paddingBottom + padding;
  4106. }
  4107. }
  4108. _handleMargins() {
  4109. if (this._margins) {
  4110. this._margins.left = Math.max(this.paddingLeft, this._margins.left);
  4111. this._margins.top = Math.max(this.paddingTop, this._margins.top);
  4112. this._margins.right = Math.max(this.paddingRight, this._margins.right);
  4113. this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom);
  4114. }
  4115. }
  4116. afterFit() {
  4117. helpers_segment.callback(this.options.afterFit, [
  4118. this
  4119. ]);
  4120. }
  4121. isHorizontal() {
  4122. const { axis , position } = this.options;
  4123. return position === 'top' || position === 'bottom' || axis === 'x';
  4124. }
  4125. isFullSize() {
  4126. return this.options.fullSize;
  4127. }
  4128. _convertTicksToLabels(ticks) {
  4129. this.beforeTickToLabelConversion();
  4130. this.generateTickLabels(ticks);
  4131. let i, ilen;
  4132. for(i = 0, ilen = ticks.length; i < ilen; i++){
  4133. if (helpers_segment.isNullOrUndef(ticks[i].label)) {
  4134. ticks.splice(i, 1);
  4135. ilen--;
  4136. i--;
  4137. }
  4138. }
  4139. this.afterTickToLabelConversion();
  4140. }
  4141. _getLabelSizes() {
  4142. let labelSizes = this._labelSizes;
  4143. if (!labelSizes) {
  4144. const sampleSize = this.options.ticks.sampleSize;
  4145. let ticks = this.ticks;
  4146. if (sampleSize < ticks.length) {
  4147. ticks = sample(ticks, sampleSize);
  4148. }
  4149. this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length, this.options.ticks.maxTicksLimit);
  4150. }
  4151. return labelSizes;
  4152. }
  4153. _computeLabelSizes(ticks, length, maxTicksLimit) {
  4154. const { ctx , _longestTextCache: caches } = this;
  4155. const widths = [];
  4156. const heights = [];
  4157. const increment = Math.floor(length / getTicksLimit(length, maxTicksLimit));
  4158. let widestLabelSize = 0;
  4159. let highestLabelSize = 0;
  4160. let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;
  4161. for(i = 0; i < length; i += increment){
  4162. label = ticks[i].label;
  4163. tickFont = this._resolveTickFontOptions(i);
  4164. ctx.font = fontString = tickFont.string;
  4165. cache = caches[fontString] = caches[fontString] || {
  4166. data: {},
  4167. gc: []
  4168. };
  4169. lineHeight = tickFont.lineHeight;
  4170. width = height = 0;
  4171. if (!helpers_segment.isNullOrUndef(label) && !helpers_segment.isArray(label)) {
  4172. width = helpers_segment._measureText(ctx, cache.data, cache.gc, width, label);
  4173. height = lineHeight;
  4174. } else if (helpers_segment.isArray(label)) {
  4175. for(j = 0, jlen = label.length; j < jlen; ++j){
  4176. nestedLabel = label[j];
  4177. if (!helpers_segment.isNullOrUndef(nestedLabel) && !helpers_segment.isArray(nestedLabel)) {
  4178. width = helpers_segment._measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  4179. height += lineHeight;
  4180. }
  4181. }
  4182. }
  4183. widths.push(width);
  4184. heights.push(height);
  4185. widestLabelSize = Math.max(width, widestLabelSize);
  4186. highestLabelSize = Math.max(height, highestLabelSize);
  4187. }
  4188. garbageCollect(caches, length);
  4189. const widest = widths.indexOf(widestLabelSize);
  4190. const highest = heights.indexOf(highestLabelSize);
  4191. const valueAt = (idx)=>({
  4192. width: widths[idx] || 0,
  4193. height: heights[idx] || 0
  4194. });
  4195. return {
  4196. first: valueAt(0),
  4197. last: valueAt(length - 1),
  4198. widest: valueAt(widest),
  4199. highest: valueAt(highest),
  4200. widths,
  4201. heights
  4202. };
  4203. }
  4204. getLabelForValue(value) {
  4205. return value;
  4206. }
  4207. getPixelForValue(value, index) {
  4208. return NaN;
  4209. }
  4210. getValueForPixel(pixel) {}
  4211. getPixelForTick(index) {
  4212. const ticks = this.ticks;
  4213. if (index < 0 || index > ticks.length - 1) {
  4214. return null;
  4215. }
  4216. return this.getPixelForValue(ticks[index].value);
  4217. }
  4218. getPixelForDecimal(decimal) {
  4219. if (this._reversePixels) {
  4220. decimal = 1 - decimal;
  4221. }
  4222. const pixel = this._startPixel + decimal * this._length;
  4223. return helpers_segment._int16Range(this._alignToPixels ? helpers_segment._alignPixel(this.chart, pixel, 0) : pixel);
  4224. }
  4225. getDecimalForPixel(pixel) {
  4226. const decimal = (pixel - this._startPixel) / this._length;
  4227. return this._reversePixels ? 1 - decimal : decimal;
  4228. }
  4229. getBasePixel() {
  4230. return this.getPixelForValue(this.getBaseValue());
  4231. }
  4232. getBaseValue() {
  4233. const { min , max } = this;
  4234. return min < 0 && max < 0 ? max : min > 0 && max > 0 ? min : 0;
  4235. }
  4236. getContext(index) {
  4237. const ticks = this.ticks || [];
  4238. if (index >= 0 && index < ticks.length) {
  4239. const tick = ticks[index];
  4240. return tick.$context || (tick.$context = createTickContext(this.getContext(), index, tick));
  4241. }
  4242. return this.$context || (this.$context = createScaleContext(this.chart.getContext(), this));
  4243. }
  4244. _tickSize() {
  4245. const optionTicks = this.options.ticks;
  4246. const rot = helpers_segment.toRadians(this.labelRotation);
  4247. const cos = Math.abs(Math.cos(rot));
  4248. const sin = Math.abs(Math.sin(rot));
  4249. const labelSizes = this._getLabelSizes();
  4250. const padding = optionTicks.autoSkipPadding || 0;
  4251. const w = labelSizes ? labelSizes.widest.width + padding : 0;
  4252. const h = labelSizes ? labelSizes.highest.height + padding : 0;
  4253. return this.isHorizontal() ? h * cos > w * sin ? w / cos : h / sin : h * sin < w * cos ? h / cos : w / sin;
  4254. }
  4255. _isVisible() {
  4256. const display = this.options.display;
  4257. if (display !== 'auto') {
  4258. return !!display;
  4259. }
  4260. return this.getMatchingVisibleMetas().length > 0;
  4261. }
  4262. _computeGridLineItems(chartArea) {
  4263. const axis = this.axis;
  4264. const chart = this.chart;
  4265. const options = this.options;
  4266. const { grid , position , border } = options;
  4267. const offset = grid.offset;
  4268. const isHorizontal = this.isHorizontal();
  4269. const ticks = this.ticks;
  4270. const ticksLength = ticks.length + (offset ? 1 : 0);
  4271. const tl = getTickMarkLength(grid);
  4272. const items = [];
  4273. const borderOpts = border.setContext(this.getContext());
  4274. const axisWidth = borderOpts.display ? borderOpts.width : 0;
  4275. const axisHalfWidth = axisWidth / 2;
  4276. const alignBorderValue = function(pixel) {
  4277. return helpers_segment._alignPixel(chart, pixel, axisWidth);
  4278. };
  4279. let borderValue, i, lineValue, alignedLineValue;
  4280. let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
  4281. if (position === 'top') {
  4282. borderValue = alignBorderValue(this.bottom);
  4283. ty1 = this.bottom - tl;
  4284. ty2 = borderValue - axisHalfWidth;
  4285. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  4286. y2 = chartArea.bottom;
  4287. } else if (position === 'bottom') {
  4288. borderValue = alignBorderValue(this.top);
  4289. y1 = chartArea.top;
  4290. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  4291. ty1 = borderValue + axisHalfWidth;
  4292. ty2 = this.top + tl;
  4293. } else if (position === 'left') {
  4294. borderValue = alignBorderValue(this.right);
  4295. tx1 = this.right - tl;
  4296. tx2 = borderValue - axisHalfWidth;
  4297. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  4298. x2 = chartArea.right;
  4299. } else if (position === 'right') {
  4300. borderValue = alignBorderValue(this.left);
  4301. x1 = chartArea.left;
  4302. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  4303. tx1 = borderValue + axisHalfWidth;
  4304. tx2 = this.left + tl;
  4305. } else if (axis === 'x') {
  4306. if (position === 'center') {
  4307. borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);
  4308. } else if (helpers_segment.isObject(position)) {
  4309. const positionAxisID = Object.keys(position)[0];
  4310. const value = position[positionAxisID];
  4311. borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));
  4312. }
  4313. y1 = chartArea.top;
  4314. y2 = chartArea.bottom;
  4315. ty1 = borderValue + axisHalfWidth;
  4316. ty2 = ty1 + tl;
  4317. } else if (axis === 'y') {
  4318. if (position === 'center') {
  4319. borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
  4320. } else if (helpers_segment.isObject(position)) {
  4321. const positionAxisID = Object.keys(position)[0];
  4322. const value = position[positionAxisID];
  4323. borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));
  4324. }
  4325. tx1 = borderValue - axisHalfWidth;
  4326. tx2 = tx1 - tl;
  4327. x1 = chartArea.left;
  4328. x2 = chartArea.right;
  4329. }
  4330. const limit = helpers_segment.valueOrDefault(options.ticks.maxTicksLimit, ticksLength);
  4331. const step = Math.max(1, Math.ceil(ticksLength / limit));
  4332. for(i = 0; i < ticksLength; i += step){
  4333. const context = this.getContext(i);
  4334. const optsAtIndex = grid.setContext(context);
  4335. const optsAtIndexBorder = border.setContext(context);
  4336. const lineWidth = optsAtIndex.lineWidth;
  4337. const lineColor = optsAtIndex.color;
  4338. const borderDash = optsAtIndexBorder.dash || [];
  4339. const borderDashOffset = optsAtIndexBorder.dashOffset;
  4340. const tickWidth = optsAtIndex.tickWidth;
  4341. const tickColor = optsAtIndex.tickColor;
  4342. const tickBorderDash = optsAtIndex.tickBorderDash || [];
  4343. const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;
  4344. lineValue = getPixelForGridLine(this, i, offset);
  4345. if (lineValue === undefined) {
  4346. continue;
  4347. }
  4348. alignedLineValue = helpers_segment._alignPixel(chart, lineValue, lineWidth);
  4349. if (isHorizontal) {
  4350. tx1 = tx2 = x1 = x2 = alignedLineValue;
  4351. } else {
  4352. ty1 = ty2 = y1 = y2 = alignedLineValue;
  4353. }
  4354. items.push({
  4355. tx1,
  4356. ty1,
  4357. tx2,
  4358. ty2,
  4359. x1,
  4360. y1,
  4361. x2,
  4362. y2,
  4363. width: lineWidth,
  4364. color: lineColor,
  4365. borderDash,
  4366. borderDashOffset,
  4367. tickWidth,
  4368. tickColor,
  4369. tickBorderDash,
  4370. tickBorderDashOffset
  4371. });
  4372. }
  4373. this._ticksLength = ticksLength;
  4374. this._borderValue = borderValue;
  4375. return items;
  4376. }
  4377. _computeLabelItems(chartArea) {
  4378. const axis = this.axis;
  4379. const options = this.options;
  4380. const { position , ticks: optionTicks } = options;
  4381. const isHorizontal = this.isHorizontal();
  4382. const ticks = this.ticks;
  4383. const { align , crossAlign , padding , mirror } = optionTicks;
  4384. const tl = getTickMarkLength(options.grid);
  4385. const tickAndPadding = tl + padding;
  4386. const hTickAndPadding = mirror ? -padding : tickAndPadding;
  4387. const rotation = -helpers_segment.toRadians(this.labelRotation);
  4388. const items = [];
  4389. let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  4390. let textBaseline = 'middle';
  4391. if (position === 'top') {
  4392. y = this.bottom - hTickAndPadding;
  4393. textAlign = this._getXAxisLabelAlignment();
  4394. } else if (position === 'bottom') {
  4395. y = this.top + hTickAndPadding;
  4396. textAlign = this._getXAxisLabelAlignment();
  4397. } else if (position === 'left') {
  4398. const ret = this._getYAxisLabelAlignment(tl);
  4399. textAlign = ret.textAlign;
  4400. x = ret.x;
  4401. } else if (position === 'right') {
  4402. const ret = this._getYAxisLabelAlignment(tl);
  4403. textAlign = ret.textAlign;
  4404. x = ret.x;
  4405. } else if (axis === 'x') {
  4406. if (position === 'center') {
  4407. y = (chartArea.top + chartArea.bottom) / 2 + tickAndPadding;
  4408. } else if (helpers_segment.isObject(position)) {
  4409. const positionAxisID = Object.keys(position)[0];
  4410. const value = position[positionAxisID];
  4411. y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;
  4412. }
  4413. textAlign = this._getXAxisLabelAlignment();
  4414. } else if (axis === 'y') {
  4415. if (position === 'center') {
  4416. x = (chartArea.left + chartArea.right) / 2 - tickAndPadding;
  4417. } else if (helpers_segment.isObject(position)) {
  4418. const positionAxisID = Object.keys(position)[0];
  4419. const value = position[positionAxisID];
  4420. x = this.chart.scales[positionAxisID].getPixelForValue(value);
  4421. }
  4422. textAlign = this._getYAxisLabelAlignment(tl).textAlign;
  4423. }
  4424. if (axis === 'y') {
  4425. if (align === 'start') {
  4426. textBaseline = 'top';
  4427. } else if (align === 'end') {
  4428. textBaseline = 'bottom';
  4429. }
  4430. }
  4431. const labelSizes = this._getLabelSizes();
  4432. for(i = 0, ilen = ticks.length; i < ilen; ++i){
  4433. tick = ticks[i];
  4434. label = tick.label;
  4435. const optsAtIndex = optionTicks.setContext(this.getContext(i));
  4436. pixel = this.getPixelForTick(i) + optionTicks.labelOffset;
  4437. font = this._resolveTickFontOptions(i);
  4438. lineHeight = font.lineHeight;
  4439. lineCount = helpers_segment.isArray(label) ? label.length : 1;
  4440. const halfCount = lineCount / 2;
  4441. const color = optsAtIndex.color;
  4442. const strokeColor = optsAtIndex.textStrokeColor;
  4443. const strokeWidth = optsAtIndex.textStrokeWidth;
  4444. let tickTextAlign = textAlign;
  4445. if (isHorizontal) {
  4446. x = pixel;
  4447. if (textAlign === 'inner') {
  4448. if (i === ilen - 1) {
  4449. tickTextAlign = !this.options.reverse ? 'right' : 'left';
  4450. } else if (i === 0) {
  4451. tickTextAlign = !this.options.reverse ? 'left' : 'right';
  4452. } else {
  4453. tickTextAlign = 'center';
  4454. }
  4455. }
  4456. if (position === 'top') {
  4457. if (crossAlign === 'near' || rotation !== 0) {
  4458. textOffset = -lineCount * lineHeight + lineHeight / 2;
  4459. } else if (crossAlign === 'center') {
  4460. textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;
  4461. } else {
  4462. textOffset = -labelSizes.highest.height + lineHeight / 2;
  4463. }
  4464. } else {
  4465. if (crossAlign === 'near' || rotation !== 0) {
  4466. textOffset = lineHeight / 2;
  4467. } else if (crossAlign === 'center') {
  4468. textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;
  4469. } else {
  4470. textOffset = labelSizes.highest.height - lineCount * lineHeight;
  4471. }
  4472. }
  4473. if (mirror) {
  4474. textOffset *= -1;
  4475. }
  4476. if (rotation !== 0 && !optsAtIndex.showLabelBackdrop) {
  4477. x += lineHeight / 2 * Math.sin(rotation);
  4478. }
  4479. } else {
  4480. y = pixel;
  4481. textOffset = (1 - lineCount) * lineHeight / 2;
  4482. }
  4483. let backdrop;
  4484. if (optsAtIndex.showLabelBackdrop) {
  4485. const labelPadding = helpers_segment.toPadding(optsAtIndex.backdropPadding);
  4486. const height = labelSizes.heights[i];
  4487. const width = labelSizes.widths[i];
  4488. let top = textOffset - labelPadding.top;
  4489. let left = 0 - labelPadding.left;
  4490. switch(textBaseline){
  4491. case 'middle':
  4492. top -= height / 2;
  4493. break;
  4494. case 'bottom':
  4495. top -= height;
  4496. break;
  4497. }
  4498. switch(textAlign){
  4499. case 'center':
  4500. left -= width / 2;
  4501. break;
  4502. case 'right':
  4503. left -= width;
  4504. break;
  4505. case 'inner':
  4506. if (i === ilen - 1) {
  4507. left -= width;
  4508. } else if (i > 0) {
  4509. left -= width / 2;
  4510. }
  4511. break;
  4512. }
  4513. backdrop = {
  4514. left,
  4515. top,
  4516. width: width + labelPadding.width,
  4517. height: height + labelPadding.height,
  4518. color: optsAtIndex.backdropColor
  4519. };
  4520. }
  4521. items.push({
  4522. label,
  4523. font,
  4524. textOffset,
  4525. options: {
  4526. rotation,
  4527. color,
  4528. strokeColor,
  4529. strokeWidth,
  4530. textAlign: tickTextAlign,
  4531. textBaseline,
  4532. translation: [
  4533. x,
  4534. y
  4535. ],
  4536. backdrop
  4537. }
  4538. });
  4539. }
  4540. return items;
  4541. }
  4542. _getXAxisLabelAlignment() {
  4543. const { position , ticks } = this.options;
  4544. const rotation = -helpers_segment.toRadians(this.labelRotation);
  4545. if (rotation) {
  4546. return position === 'top' ? 'left' : 'right';
  4547. }
  4548. let align = 'center';
  4549. if (ticks.align === 'start') {
  4550. align = 'left';
  4551. } else if (ticks.align === 'end') {
  4552. align = 'right';
  4553. } else if (ticks.align === 'inner') {
  4554. align = 'inner';
  4555. }
  4556. return align;
  4557. }
  4558. _getYAxisLabelAlignment(tl) {
  4559. const { position , ticks: { crossAlign , mirror , padding } } = this.options;
  4560. const labelSizes = this._getLabelSizes();
  4561. const tickAndPadding = tl + padding;
  4562. const widest = labelSizes.widest.width;
  4563. let textAlign;
  4564. let x;
  4565. if (position === 'left') {
  4566. if (mirror) {
  4567. x = this.right + padding;
  4568. if (crossAlign === 'near') {
  4569. textAlign = 'left';
  4570. } else if (crossAlign === 'center') {
  4571. textAlign = 'center';
  4572. x += widest / 2;
  4573. } else {
  4574. textAlign = 'right';
  4575. x += widest;
  4576. }
  4577. } else {
  4578. x = this.right - tickAndPadding;
  4579. if (crossAlign === 'near') {
  4580. textAlign = 'right';
  4581. } else if (crossAlign === 'center') {
  4582. textAlign = 'center';
  4583. x -= widest / 2;
  4584. } else {
  4585. textAlign = 'left';
  4586. x = this.left;
  4587. }
  4588. }
  4589. } else if (position === 'right') {
  4590. if (mirror) {
  4591. x = this.left + padding;
  4592. if (crossAlign === 'near') {
  4593. textAlign = 'right';
  4594. } else if (crossAlign === 'center') {
  4595. textAlign = 'center';
  4596. x -= widest / 2;
  4597. } else {
  4598. textAlign = 'left';
  4599. x -= widest;
  4600. }
  4601. } else {
  4602. x = this.left + tickAndPadding;
  4603. if (crossAlign === 'near') {
  4604. textAlign = 'left';
  4605. } else if (crossAlign === 'center') {
  4606. textAlign = 'center';
  4607. x += widest / 2;
  4608. } else {
  4609. textAlign = 'right';
  4610. x = this.right;
  4611. }
  4612. }
  4613. } else {
  4614. textAlign = 'right';
  4615. }
  4616. return {
  4617. textAlign,
  4618. x
  4619. };
  4620. }
  4621. _computeLabelArea() {
  4622. if (this.options.ticks.mirror) {
  4623. return;
  4624. }
  4625. const chart = this.chart;
  4626. const position = this.options.position;
  4627. if (position === 'left' || position === 'right') {
  4628. return {
  4629. top: 0,
  4630. left: this.left,
  4631. bottom: chart.height,
  4632. right: this.right
  4633. };
  4634. }
  4635. if (position === 'top' || position === 'bottom') {
  4636. return {
  4637. top: this.top,
  4638. left: 0,
  4639. bottom: this.bottom,
  4640. right: chart.width
  4641. };
  4642. }
  4643. }
  4644. drawBackground() {
  4645. const { ctx , options: { backgroundColor } , left , top , width , height } = this;
  4646. if (backgroundColor) {
  4647. ctx.save();
  4648. ctx.fillStyle = backgroundColor;
  4649. ctx.fillRect(left, top, width, height);
  4650. ctx.restore();
  4651. }
  4652. }
  4653. getLineWidthForValue(value) {
  4654. const grid = this.options.grid;
  4655. if (!this._isVisible() || !grid.display) {
  4656. return 0;
  4657. }
  4658. const ticks = this.ticks;
  4659. const index = ticks.findIndex((t)=>t.value === value);
  4660. if (index >= 0) {
  4661. const opts = grid.setContext(this.getContext(index));
  4662. return opts.lineWidth;
  4663. }
  4664. return 0;
  4665. }
  4666. drawGrid(chartArea) {
  4667. const grid = this.options.grid;
  4668. const ctx = this.ctx;
  4669. const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea));
  4670. let i, ilen;
  4671. const drawLine = (p1, p2, style)=>{
  4672. if (!style.width || !style.color) {
  4673. return;
  4674. }
  4675. ctx.save();
  4676. ctx.lineWidth = style.width;
  4677. ctx.strokeStyle = style.color;
  4678. ctx.setLineDash(style.borderDash || []);
  4679. ctx.lineDashOffset = style.borderDashOffset;
  4680. ctx.beginPath();
  4681. ctx.moveTo(p1.x, p1.y);
  4682. ctx.lineTo(p2.x, p2.y);
  4683. ctx.stroke();
  4684. ctx.restore();
  4685. };
  4686. if (grid.display) {
  4687. for(i = 0, ilen = items.length; i < ilen; ++i){
  4688. const item = items[i];
  4689. if (grid.drawOnChartArea) {
  4690. drawLine({
  4691. x: item.x1,
  4692. y: item.y1
  4693. }, {
  4694. x: item.x2,
  4695. y: item.y2
  4696. }, item);
  4697. }
  4698. if (grid.drawTicks) {
  4699. drawLine({
  4700. x: item.tx1,
  4701. y: item.ty1
  4702. }, {
  4703. x: item.tx2,
  4704. y: item.ty2
  4705. }, {
  4706. color: item.tickColor,
  4707. width: item.tickWidth,
  4708. borderDash: item.tickBorderDash,
  4709. borderDashOffset: item.tickBorderDashOffset
  4710. });
  4711. }
  4712. }
  4713. }
  4714. }
  4715. drawBorder() {
  4716. const { chart , ctx , options: { border , grid } } = this;
  4717. const borderOpts = border.setContext(this.getContext());
  4718. const axisWidth = border.display ? borderOpts.width : 0;
  4719. if (!axisWidth) {
  4720. return;
  4721. }
  4722. const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth;
  4723. const borderValue = this._borderValue;
  4724. let x1, x2, y1, y2;
  4725. if (this.isHorizontal()) {
  4726. x1 = helpers_segment._alignPixel(chart, this.left, axisWidth) - axisWidth / 2;
  4727. x2 = helpers_segment._alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2;
  4728. y1 = y2 = borderValue;
  4729. } else {
  4730. y1 = helpers_segment._alignPixel(chart, this.top, axisWidth) - axisWidth / 2;
  4731. y2 = helpers_segment._alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2;
  4732. x1 = x2 = borderValue;
  4733. }
  4734. ctx.save();
  4735. ctx.lineWidth = borderOpts.width;
  4736. ctx.strokeStyle = borderOpts.color;
  4737. ctx.beginPath();
  4738. ctx.moveTo(x1, y1);
  4739. ctx.lineTo(x2, y2);
  4740. ctx.stroke();
  4741. ctx.restore();
  4742. }
  4743. drawLabels(chartArea) {
  4744. const optionTicks = this.options.ticks;
  4745. if (!optionTicks.display) {
  4746. return;
  4747. }
  4748. const ctx = this.ctx;
  4749. const area = this._computeLabelArea();
  4750. if (area) {
  4751. helpers_segment.clipArea(ctx, area);
  4752. }
  4753. const items = this.getLabelItems(chartArea);
  4754. for (const item of items){
  4755. const renderTextOptions = item.options;
  4756. const tickFont = item.font;
  4757. const label = item.label;
  4758. const y = item.textOffset;
  4759. helpers_segment.renderText(ctx, label, 0, y, tickFont, renderTextOptions);
  4760. }
  4761. if (area) {
  4762. helpers_segment.unclipArea(ctx);
  4763. }
  4764. }
  4765. drawTitle() {
  4766. const { ctx , options: { position , title , reverse } } = this;
  4767. if (!title.display) {
  4768. return;
  4769. }
  4770. const font = helpers_segment.toFont(title.font);
  4771. const padding = helpers_segment.toPadding(title.padding);
  4772. const align = title.align;
  4773. let offset = font.lineHeight / 2;
  4774. if (position === 'bottom' || position === 'center' || helpers_segment.isObject(position)) {
  4775. offset += padding.bottom;
  4776. if (helpers_segment.isArray(title.text)) {
  4777. offset += font.lineHeight * (title.text.length - 1);
  4778. }
  4779. } else {
  4780. offset += padding.top;
  4781. }
  4782. const { titleX , titleY , maxWidth , rotation } = titleArgs(this, offset, position, align);
  4783. helpers_segment.renderText(ctx, title.text, 0, 0, font, {
  4784. color: title.color,
  4785. maxWidth,
  4786. rotation,
  4787. textAlign: titleAlign(align, position, reverse),
  4788. textBaseline: 'middle',
  4789. translation: [
  4790. titleX,
  4791. titleY
  4792. ]
  4793. });
  4794. }
  4795. draw(chartArea) {
  4796. if (!this._isVisible()) {
  4797. return;
  4798. }
  4799. this.drawBackground();
  4800. this.drawGrid(chartArea);
  4801. this.drawBorder();
  4802. this.drawTitle();
  4803. this.drawLabels(chartArea);
  4804. }
  4805. _layers() {
  4806. const opts = this.options;
  4807. const tz = opts.ticks && opts.ticks.z || 0;
  4808. const gz = helpers_segment.valueOrDefault(opts.grid && opts.grid.z, -1);
  4809. const bz = helpers_segment.valueOrDefault(opts.border && opts.border.z, 0);
  4810. if (!this._isVisible() || this.draw !== Scale.prototype.draw) {
  4811. return [
  4812. {
  4813. z: tz,
  4814. draw: (chartArea)=>{
  4815. this.draw(chartArea);
  4816. }
  4817. }
  4818. ];
  4819. }
  4820. return [
  4821. {
  4822. z: gz,
  4823. draw: (chartArea)=>{
  4824. this.drawBackground();
  4825. this.drawGrid(chartArea);
  4826. this.drawTitle();
  4827. }
  4828. },
  4829. {
  4830. z: bz,
  4831. draw: ()=>{
  4832. this.drawBorder();
  4833. }
  4834. },
  4835. {
  4836. z: tz,
  4837. draw: (chartArea)=>{
  4838. this.drawLabels(chartArea);
  4839. }
  4840. }
  4841. ];
  4842. }
  4843. getMatchingVisibleMetas(type) {
  4844. const metas = this.chart.getSortedVisibleDatasetMetas();
  4845. const axisID = this.axis + 'AxisID';
  4846. const result = [];
  4847. let i, ilen;
  4848. for(i = 0, ilen = metas.length; i < ilen; ++i){
  4849. const meta = metas[i];
  4850. if (meta[axisID] === this.id && (!type || meta.type === type)) {
  4851. result.push(meta);
  4852. }
  4853. }
  4854. return result;
  4855. }
  4856. _resolveTickFontOptions(index) {
  4857. const opts = this.options.ticks.setContext(this.getContext(index));
  4858. return helpers_segment.toFont(opts.font);
  4859. }
  4860. _maxDigits() {
  4861. const fontSize = this._resolveTickFontOptions(0).lineHeight;
  4862. return (this.isHorizontal() ? this.width : this.height) / fontSize;
  4863. }
  4864. }
  4865. class TypedRegistry {
  4866. constructor(type, scope, override){
  4867. this.type = type;
  4868. this.scope = scope;
  4869. this.override = override;
  4870. this.items = Object.create(null);
  4871. }
  4872. isForType(type) {
  4873. return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);
  4874. }
  4875. register(item) {
  4876. const proto = Object.getPrototypeOf(item);
  4877. let parentScope;
  4878. if (isIChartComponent(proto)) {
  4879. parentScope = this.register(proto);
  4880. }
  4881. const items = this.items;
  4882. const id = item.id;
  4883. const scope = this.scope + '.' + id;
  4884. if (!id) {
  4885. throw new Error('class does not have id: ' + item);
  4886. }
  4887. if (id in items) {
  4888. return scope;
  4889. }
  4890. items[id] = item;
  4891. registerDefaults(item, scope, parentScope);
  4892. if (this.override) {
  4893. helpers_segment.defaults.override(item.id, item.overrides);
  4894. }
  4895. return scope;
  4896. }
  4897. get(id) {
  4898. return this.items[id];
  4899. }
  4900. unregister(item) {
  4901. const items = this.items;
  4902. const id = item.id;
  4903. const scope = this.scope;
  4904. if (id in items) {
  4905. delete items[id];
  4906. }
  4907. if (scope && id in helpers_segment.defaults[scope]) {
  4908. delete helpers_segment.defaults[scope][id];
  4909. if (this.override) {
  4910. delete helpers_segment.overrides[id];
  4911. }
  4912. }
  4913. }
  4914. }
  4915. function registerDefaults(item, scope, parentScope) {
  4916. const itemDefaults = helpers_segment.merge(Object.create(null), [
  4917. parentScope ? helpers_segment.defaults.get(parentScope) : {},
  4918. helpers_segment.defaults.get(scope),
  4919. item.defaults
  4920. ]);
  4921. helpers_segment.defaults.set(scope, itemDefaults);
  4922. if (item.defaultRoutes) {
  4923. routeDefaults(scope, item.defaultRoutes);
  4924. }
  4925. if (item.descriptors) {
  4926. helpers_segment.defaults.describe(scope, item.descriptors);
  4927. }
  4928. }
  4929. function routeDefaults(scope, routes) {
  4930. Object.keys(routes).forEach((property)=>{
  4931. const propertyParts = property.split('.');
  4932. const sourceName = propertyParts.pop();
  4933. const sourceScope = [
  4934. scope
  4935. ].concat(propertyParts).join('.');
  4936. const parts = routes[property].split('.');
  4937. const targetName = parts.pop();
  4938. const targetScope = parts.join('.');
  4939. helpers_segment.defaults.route(sourceScope, sourceName, targetScope, targetName);
  4940. });
  4941. }
  4942. function isIChartComponent(proto) {
  4943. return 'id' in proto && 'defaults' in proto;
  4944. }
  4945. class Registry {
  4946. constructor(){
  4947. this.controllers = new TypedRegistry(DatasetController, 'datasets', true);
  4948. this.elements = new TypedRegistry(Element, 'elements');
  4949. this.plugins = new TypedRegistry(Object, 'plugins');
  4950. this.scales = new TypedRegistry(Scale, 'scales');
  4951. this._typedRegistries = [
  4952. this.controllers,
  4953. this.scales,
  4954. this.elements
  4955. ];
  4956. }
  4957. add(...args) {
  4958. this._each('register', args);
  4959. }
  4960. remove(...args) {
  4961. this._each('unregister', args);
  4962. }
  4963. addControllers(...args) {
  4964. this._each('register', args, this.controllers);
  4965. }
  4966. addElements(...args) {
  4967. this._each('register', args, this.elements);
  4968. }
  4969. addPlugins(...args) {
  4970. this._each('register', args, this.plugins);
  4971. }
  4972. addScales(...args) {
  4973. this._each('register', args, this.scales);
  4974. }
  4975. getController(id) {
  4976. return this._get(id, this.controllers, 'controller');
  4977. }
  4978. getElement(id) {
  4979. return this._get(id, this.elements, 'element');
  4980. }
  4981. getPlugin(id) {
  4982. return this._get(id, this.plugins, 'plugin');
  4983. }
  4984. getScale(id) {
  4985. return this._get(id, this.scales, 'scale');
  4986. }
  4987. removeControllers(...args) {
  4988. this._each('unregister', args, this.controllers);
  4989. }
  4990. removeElements(...args) {
  4991. this._each('unregister', args, this.elements);
  4992. }
  4993. removePlugins(...args) {
  4994. this._each('unregister', args, this.plugins);
  4995. }
  4996. removeScales(...args) {
  4997. this._each('unregister', args, this.scales);
  4998. }
  4999. _each(method, args, typedRegistry) {
  5000. [
  5001. ...args
  5002. ].forEach((arg)=>{
  5003. const reg = typedRegistry || this._getRegistryForType(arg);
  5004. if (typedRegistry || reg.isForType(arg) || reg === this.plugins && arg.id) {
  5005. this._exec(method, reg, arg);
  5006. } else {
  5007. helpers_segment.each(arg, (item)=>{
  5008. const itemReg = typedRegistry || this._getRegistryForType(item);
  5009. this._exec(method, itemReg, item);
  5010. });
  5011. }
  5012. });
  5013. }
  5014. _exec(method, registry, component) {
  5015. const camelMethod = helpers_segment._capitalize(method);
  5016. helpers_segment.callback(component['before' + camelMethod], [], component);
  5017. registry[method](component);
  5018. helpers_segment.callback(component['after' + camelMethod], [], component);
  5019. }
  5020. _getRegistryForType(type) {
  5021. for(let i = 0; i < this._typedRegistries.length; i++){
  5022. const reg = this._typedRegistries[i];
  5023. if (reg.isForType(type)) {
  5024. return reg;
  5025. }
  5026. }
  5027. return this.plugins;
  5028. }
  5029. _get(id, typedRegistry, type) {
  5030. const item = typedRegistry.get(id);
  5031. if (item === undefined) {
  5032. throw new Error('"' + id + '" is not a registered ' + type + '.');
  5033. }
  5034. return item;
  5035. }
  5036. }
  5037. var registry = /* #__PURE__ */ new Registry();
  5038. class PluginService {
  5039. constructor(){
  5040. this._init = [];
  5041. }
  5042. notify(chart, hook, args, filter) {
  5043. if (hook === 'beforeInit') {
  5044. this._init = this._createDescriptors(chart, true);
  5045. this._notify(this._init, chart, 'install');
  5046. }
  5047. const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart);
  5048. const result = this._notify(descriptors, chart, hook, args);
  5049. if (hook === 'afterDestroy') {
  5050. this._notify(descriptors, chart, 'stop');
  5051. this._notify(this._init, chart, 'uninstall');
  5052. }
  5053. return result;
  5054. }
  5055. _notify(descriptors, chart, hook, args) {
  5056. args = args || {};
  5057. for (const descriptor of descriptors){
  5058. const plugin = descriptor.plugin;
  5059. const method = plugin[hook];
  5060. const params = [
  5061. chart,
  5062. args,
  5063. descriptor.options
  5064. ];
  5065. if (helpers_segment.callback(method, params, plugin) === false && args.cancelable) {
  5066. return false;
  5067. }
  5068. }
  5069. return true;
  5070. }
  5071. invalidate() {
  5072. if (!helpers_segment.isNullOrUndef(this._cache)) {
  5073. this._oldCache = this._cache;
  5074. this._cache = undefined;
  5075. }
  5076. }
  5077. _descriptors(chart) {
  5078. if (this._cache) {
  5079. return this._cache;
  5080. }
  5081. const descriptors = this._cache = this._createDescriptors(chart);
  5082. this._notifyStateChanges(chart);
  5083. return descriptors;
  5084. }
  5085. _createDescriptors(chart, all) {
  5086. const config = chart && chart.config;
  5087. const options = helpers_segment.valueOrDefault(config.options && config.options.plugins, {});
  5088. const plugins = allPlugins(config);
  5089. return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);
  5090. }
  5091. _notifyStateChanges(chart) {
  5092. const previousDescriptors = this._oldCache || [];
  5093. const descriptors = this._cache;
  5094. const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.plugin.id === y.plugin.id));
  5095. this._notify(diff(previousDescriptors, descriptors), chart, 'stop');
  5096. this._notify(diff(descriptors, previousDescriptors), chart, 'start');
  5097. }
  5098. }
  5099. function allPlugins(config) {
  5100. const localIds = {};
  5101. const plugins = [];
  5102. const keys = Object.keys(registry.plugins.items);
  5103. for(let i = 0; i < keys.length; i++){
  5104. plugins.push(registry.getPlugin(keys[i]));
  5105. }
  5106. const local = config.plugins || [];
  5107. for(let i = 0; i < local.length; i++){
  5108. const plugin = local[i];
  5109. if (plugins.indexOf(plugin) === -1) {
  5110. plugins.push(plugin);
  5111. localIds[plugin.id] = true;
  5112. }
  5113. }
  5114. return {
  5115. plugins,
  5116. localIds
  5117. };
  5118. }
  5119. function getOpts(options, all) {
  5120. if (!all && options === false) {
  5121. return null;
  5122. }
  5123. if (options === true) {
  5124. return {};
  5125. }
  5126. return options;
  5127. }
  5128. function createDescriptors(chart, { plugins , localIds }, options, all) {
  5129. const result = [];
  5130. const context = chart.getContext();
  5131. for (const plugin of plugins){
  5132. const id = plugin.id;
  5133. const opts = getOpts(options[id], all);
  5134. if (opts === null) {
  5135. continue;
  5136. }
  5137. result.push({
  5138. plugin,
  5139. options: pluginOpts(chart.config, {
  5140. plugin,
  5141. local: localIds[id]
  5142. }, opts, context)
  5143. });
  5144. }
  5145. return result;
  5146. }
  5147. function pluginOpts(config, { plugin , local }, opts, context) {
  5148. const keys = config.pluginScopeKeys(plugin);
  5149. const scopes = config.getOptionScopes(opts, keys);
  5150. if (local && plugin.defaults) {
  5151. scopes.push(plugin.defaults);
  5152. }
  5153. return config.createResolver(scopes, context, [
  5154. ''
  5155. ], {
  5156. scriptable: false,
  5157. indexable: false,
  5158. allKeys: true
  5159. });
  5160. }
  5161. function getIndexAxis(type, options) {
  5162. const datasetDefaults = helpers_segment.defaults.datasets[type] || {};
  5163. const datasetOptions = (options.datasets || {})[type] || {};
  5164. return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';
  5165. }
  5166. function getAxisFromDefaultScaleID(id, indexAxis) {
  5167. let axis = id;
  5168. if (id === '_index_') {
  5169. axis = indexAxis;
  5170. } else if (id === '_value_') {
  5171. axis = indexAxis === 'x' ? 'y' : 'x';
  5172. }
  5173. return axis;
  5174. }
  5175. function getDefaultScaleIDFromAxis(axis, indexAxis) {
  5176. return axis === indexAxis ? '_index_' : '_value_';
  5177. }
  5178. function idMatchesAxis(id) {
  5179. if (id === 'x' || id === 'y' || id === 'r') {
  5180. return id;
  5181. }
  5182. }
  5183. function axisFromPosition(position) {
  5184. if (position === 'top' || position === 'bottom') {
  5185. return 'x';
  5186. }
  5187. if (position === 'left' || position === 'right') {
  5188. return 'y';
  5189. }
  5190. }
  5191. function determineAxis(id, ...scaleOptions) {
  5192. if (idMatchesAxis(id)) {
  5193. return id;
  5194. }
  5195. for (const opts of scaleOptions){
  5196. const axis = opts.axis || axisFromPosition(opts.position) || id.length > 1 && idMatchesAxis(id[0].toLowerCase());
  5197. if (axis) {
  5198. return axis;
  5199. }
  5200. }
  5201. throw new Error(`Cannot determine type of '${id}' axis. Please provide 'axis' or 'position' option.`);
  5202. }
  5203. function getAxisFromDataset(id, axis, dataset) {
  5204. if (dataset[axis + 'AxisID'] === id) {
  5205. return {
  5206. axis
  5207. };
  5208. }
  5209. }
  5210. function retrieveAxisFromDatasets(id, config) {
  5211. if (config.data && config.data.datasets) {
  5212. const boundDs = config.data.datasets.filter((d)=>d.xAxisID === id || d.yAxisID === id);
  5213. if (boundDs.length) {
  5214. return getAxisFromDataset(id, 'x', boundDs[0]) || getAxisFromDataset(id, 'y', boundDs[0]);
  5215. }
  5216. }
  5217. return {};
  5218. }
  5219. function mergeScaleConfig(config, options) {
  5220. const chartDefaults = helpers_segment.overrides[config.type] || {
  5221. scales: {}
  5222. };
  5223. const configScales = options.scales || {};
  5224. const chartIndexAxis = getIndexAxis(config.type, options);
  5225. const scales = Object.create(null);
  5226. Object.keys(configScales).forEach((id)=>{
  5227. const scaleConf = configScales[id];
  5228. if (!helpers_segment.isObject(scaleConf)) {
  5229. return console.error(`Invalid scale configuration for scale: ${id}`);
  5230. }
  5231. if (scaleConf._proxy) {
  5232. return console.warn(`Ignoring resolver passed as options for scale: ${id}`);
  5233. }
  5234. const axis = determineAxis(id, scaleConf, retrieveAxisFromDatasets(id, config), helpers_segment.defaults.scales[scaleConf.type]);
  5235. const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
  5236. const defaultScaleOptions = chartDefaults.scales || {};
  5237. scales[id] = helpers_segment.mergeIf(Object.create(null), [
  5238. {
  5239. axis
  5240. },
  5241. scaleConf,
  5242. defaultScaleOptions[axis],
  5243. defaultScaleOptions[defaultId]
  5244. ]);
  5245. });
  5246. config.data.datasets.forEach((dataset)=>{
  5247. const type = dataset.type || config.type;
  5248. const indexAxis = dataset.indexAxis || getIndexAxis(type, options);
  5249. const datasetDefaults = helpers_segment.overrides[type] || {};
  5250. const defaultScaleOptions = datasetDefaults.scales || {};
  5251. Object.keys(defaultScaleOptions).forEach((defaultID)=>{
  5252. const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
  5253. const id = dataset[axis + 'AxisID'] || axis;
  5254. scales[id] = scales[id] || Object.create(null);
  5255. helpers_segment.mergeIf(scales[id], [
  5256. {
  5257. axis
  5258. },
  5259. configScales[id],
  5260. defaultScaleOptions[defaultID]
  5261. ]);
  5262. });
  5263. });
  5264. Object.keys(scales).forEach((key)=>{
  5265. const scale = scales[key];
  5266. helpers_segment.mergeIf(scale, [
  5267. helpers_segment.defaults.scales[scale.type],
  5268. helpers_segment.defaults.scale
  5269. ]);
  5270. });
  5271. return scales;
  5272. }
  5273. function initOptions(config) {
  5274. const options = config.options || (config.options = {});
  5275. options.plugins = helpers_segment.valueOrDefault(options.plugins, {});
  5276. options.scales = mergeScaleConfig(config, options);
  5277. }
  5278. function initData(data) {
  5279. data = data || {};
  5280. data.datasets = data.datasets || [];
  5281. data.labels = data.labels || [];
  5282. return data;
  5283. }
  5284. function initConfig(config) {
  5285. config = config || {};
  5286. config.data = initData(config.data);
  5287. initOptions(config);
  5288. return config;
  5289. }
  5290. const keyCache = new Map();
  5291. const keysCached = new Set();
  5292. function cachedKeys(cacheKey, generate) {
  5293. let keys = keyCache.get(cacheKey);
  5294. if (!keys) {
  5295. keys = generate();
  5296. keyCache.set(cacheKey, keys);
  5297. keysCached.add(keys);
  5298. }
  5299. return keys;
  5300. }
  5301. const addIfFound = (set, obj, key)=>{
  5302. const opts = helpers_segment.resolveObjectKey(obj, key);
  5303. if (opts !== undefined) {
  5304. set.add(opts);
  5305. }
  5306. };
  5307. class Config {
  5308. constructor(config){
  5309. this._config = initConfig(config);
  5310. this._scopeCache = new Map();
  5311. this._resolverCache = new Map();
  5312. }
  5313. get platform() {
  5314. return this._config.platform;
  5315. }
  5316. get type() {
  5317. return this._config.type;
  5318. }
  5319. set type(type) {
  5320. this._config.type = type;
  5321. }
  5322. get data() {
  5323. return this._config.data;
  5324. }
  5325. set data(data) {
  5326. this._config.data = initData(data);
  5327. }
  5328. get options() {
  5329. return this._config.options;
  5330. }
  5331. set options(options) {
  5332. this._config.options = options;
  5333. }
  5334. get plugins() {
  5335. return this._config.plugins;
  5336. }
  5337. update() {
  5338. const config = this._config;
  5339. this.clearCache();
  5340. initOptions(config);
  5341. }
  5342. clearCache() {
  5343. this._scopeCache.clear();
  5344. this._resolverCache.clear();
  5345. }
  5346. datasetScopeKeys(datasetType) {
  5347. return cachedKeys(datasetType, ()=>[
  5348. [
  5349. `datasets.${datasetType}`,
  5350. ''
  5351. ]
  5352. ]);
  5353. }
  5354. datasetAnimationScopeKeys(datasetType, transition) {
  5355. return cachedKeys(`${datasetType}.transition.${transition}`, ()=>[
  5356. [
  5357. `datasets.${datasetType}.transitions.${transition}`,
  5358. `transitions.${transition}`
  5359. ],
  5360. [
  5361. `datasets.${datasetType}`,
  5362. ''
  5363. ]
  5364. ]);
  5365. }
  5366. datasetElementScopeKeys(datasetType, elementType) {
  5367. return cachedKeys(`${datasetType}-${elementType}`, ()=>[
  5368. [
  5369. `datasets.${datasetType}.elements.${elementType}`,
  5370. `datasets.${datasetType}`,
  5371. `elements.${elementType}`,
  5372. ''
  5373. ]
  5374. ]);
  5375. }
  5376. pluginScopeKeys(plugin) {
  5377. const id = plugin.id;
  5378. const type = this.type;
  5379. return cachedKeys(`${type}-plugin-${id}`, ()=>[
  5380. [
  5381. `plugins.${id}`,
  5382. ...plugin.additionalOptionScopes || []
  5383. ]
  5384. ]);
  5385. }
  5386. _cachedScopes(mainScope, resetCache) {
  5387. const _scopeCache = this._scopeCache;
  5388. let cache = _scopeCache.get(mainScope);
  5389. if (!cache || resetCache) {
  5390. cache = new Map();
  5391. _scopeCache.set(mainScope, cache);
  5392. }
  5393. return cache;
  5394. }
  5395. getOptionScopes(mainScope, keyLists, resetCache) {
  5396. const { options , type } = this;
  5397. const cache = this._cachedScopes(mainScope, resetCache);
  5398. const cached = cache.get(keyLists);
  5399. if (cached) {
  5400. return cached;
  5401. }
  5402. const scopes = new Set();
  5403. keyLists.forEach((keys)=>{
  5404. if (mainScope) {
  5405. scopes.add(mainScope);
  5406. keys.forEach((key)=>addIfFound(scopes, mainScope, key));
  5407. }
  5408. keys.forEach((key)=>addIfFound(scopes, options, key));
  5409. keys.forEach((key)=>addIfFound(scopes, helpers_segment.overrides[type] || {}, key));
  5410. keys.forEach((key)=>addIfFound(scopes, helpers_segment.defaults, key));
  5411. keys.forEach((key)=>addIfFound(scopes, helpers_segment.descriptors, key));
  5412. });
  5413. const array = Array.from(scopes);
  5414. if (array.length === 0) {
  5415. array.push(Object.create(null));
  5416. }
  5417. if (keysCached.has(keyLists)) {
  5418. cache.set(keyLists, array);
  5419. }
  5420. return array;
  5421. }
  5422. chartOptionScopes() {
  5423. const { options , type } = this;
  5424. return [
  5425. options,
  5426. helpers_segment.overrides[type] || {},
  5427. helpers_segment.defaults.datasets[type] || {},
  5428. {
  5429. type
  5430. },
  5431. helpers_segment.defaults,
  5432. helpers_segment.descriptors
  5433. ];
  5434. }
  5435. resolveNamedOptions(scopes, names, context, prefixes = [
  5436. ''
  5437. ]) {
  5438. const result = {
  5439. $shared: true
  5440. };
  5441. const { resolver , subPrefixes } = getResolver(this._resolverCache, scopes, prefixes);
  5442. let options = resolver;
  5443. if (needContext(resolver, names)) {
  5444. result.$shared = false;
  5445. context = helpers_segment.isFunction(context) ? context() : context;
  5446. const subResolver = this.createResolver(scopes, context, subPrefixes);
  5447. options = helpers_segment._attachContext(resolver, context, subResolver);
  5448. }
  5449. for (const prop of names){
  5450. result[prop] = options[prop];
  5451. }
  5452. return result;
  5453. }
  5454. createResolver(scopes, context, prefixes = [
  5455. ''
  5456. ], descriptorDefaults) {
  5457. const { resolver } = getResolver(this._resolverCache, scopes, prefixes);
  5458. return helpers_segment.isObject(context) ? helpers_segment._attachContext(resolver, context, undefined, descriptorDefaults) : resolver;
  5459. }
  5460. }
  5461. function getResolver(resolverCache, scopes, prefixes) {
  5462. let cache = resolverCache.get(scopes);
  5463. if (!cache) {
  5464. cache = new Map();
  5465. resolverCache.set(scopes, cache);
  5466. }
  5467. const cacheKey = prefixes.join();
  5468. let cached = cache.get(cacheKey);
  5469. if (!cached) {
  5470. const resolver = helpers_segment._createResolver(scopes, prefixes);
  5471. cached = {
  5472. resolver,
  5473. subPrefixes: prefixes.filter((p)=>!p.toLowerCase().includes('hover'))
  5474. };
  5475. cache.set(cacheKey, cached);
  5476. }
  5477. return cached;
  5478. }
  5479. const hasFunction = (value)=>helpers_segment.isObject(value) && Object.getOwnPropertyNames(value).some((key)=>helpers_segment.isFunction(value[key]));
  5480. function needContext(proxy, names) {
  5481. const { isScriptable , isIndexable } = helpers_segment._descriptors(proxy);
  5482. for (const prop of names){
  5483. const scriptable = isScriptable(prop);
  5484. const indexable = isIndexable(prop);
  5485. const value = (indexable || scriptable) && proxy[prop];
  5486. if (scriptable && (helpers_segment.isFunction(value) || hasFunction(value)) || indexable && helpers_segment.isArray(value)) {
  5487. return true;
  5488. }
  5489. }
  5490. return false;
  5491. }
  5492. var version = "4.4.4";
  5493. const KNOWN_POSITIONS = [
  5494. 'top',
  5495. 'bottom',
  5496. 'left',
  5497. 'right',
  5498. 'chartArea'
  5499. ];
  5500. function positionIsHorizontal(position, axis) {
  5501. return position === 'top' || position === 'bottom' || KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x';
  5502. }
  5503. function compare2Level(l1, l2) {
  5504. return function(a, b) {
  5505. return a[l1] === b[l1] ? a[l2] - b[l2] : a[l1] - b[l1];
  5506. };
  5507. }
  5508. function onAnimationsComplete(context) {
  5509. const chart = context.chart;
  5510. const animationOptions = chart.options.animation;
  5511. chart.notifyPlugins('afterRender');
  5512. helpers_segment.callback(animationOptions && animationOptions.onComplete, [
  5513. context
  5514. ], chart);
  5515. }
  5516. function onAnimationProgress(context) {
  5517. const chart = context.chart;
  5518. const animationOptions = chart.options.animation;
  5519. helpers_segment.callback(animationOptions && animationOptions.onProgress, [
  5520. context
  5521. ], chart);
  5522. }
  5523. function getCanvas(item) {
  5524. if (helpers_segment._isDomSupported() && typeof item === 'string') {
  5525. item = document.getElementById(item);
  5526. } else if (item && item.length) {
  5527. item = item[0];
  5528. }
  5529. if (item && item.canvas) {
  5530. item = item.canvas;
  5531. }
  5532. return item;
  5533. }
  5534. const instances = {};
  5535. const getChart = (key)=>{
  5536. const canvas = getCanvas(key);
  5537. return Object.values(instances).filter((c)=>c.canvas === canvas).pop();
  5538. };
  5539. function moveNumericKeys(obj, start, move) {
  5540. const keys = Object.keys(obj);
  5541. for (const key of keys){
  5542. const intKey = +key;
  5543. if (intKey >= start) {
  5544. const value = obj[key];
  5545. delete obj[key];
  5546. if (move > 0 || intKey > start) {
  5547. obj[intKey + move] = value;
  5548. }
  5549. }
  5550. }
  5551. }
  5552. function determineLastEvent(e, lastEvent, inChartArea, isClick) {
  5553. if (!inChartArea || e.type === 'mouseout') {
  5554. return null;
  5555. }
  5556. if (isClick) {
  5557. return lastEvent;
  5558. }
  5559. return e;
  5560. }
  5561. function getSizeForArea(scale, chartArea, field) {
  5562. return scale.options.clip ? scale[field] : chartArea[field];
  5563. }
  5564. function getDatasetArea(meta, chartArea) {
  5565. const { xScale , yScale } = meta;
  5566. if (xScale && yScale) {
  5567. return {
  5568. left: getSizeForArea(xScale, chartArea, 'left'),
  5569. right: getSizeForArea(xScale, chartArea, 'right'),
  5570. top: getSizeForArea(yScale, chartArea, 'top'),
  5571. bottom: getSizeForArea(yScale, chartArea, 'bottom')
  5572. };
  5573. }
  5574. return chartArea;
  5575. }
  5576. class Chart {
  5577. static defaults = helpers_segment.defaults;
  5578. static instances = instances;
  5579. static overrides = helpers_segment.overrides;
  5580. static registry = registry;
  5581. static version = version;
  5582. static getChart = getChart;
  5583. static register(...items) {
  5584. registry.add(...items);
  5585. invalidatePlugins();
  5586. }
  5587. static unregister(...items) {
  5588. registry.remove(...items);
  5589. invalidatePlugins();
  5590. }
  5591. constructor(item, userConfig){
  5592. const config = this.config = new Config(userConfig);
  5593. const initialCanvas = getCanvas(item);
  5594. const existingChart = getChart(initialCanvas);
  5595. if (existingChart) {
  5596. 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.');
  5597. }
  5598. const options = config.createResolver(config.chartOptionScopes(), this.getContext());
  5599. this.platform = new (config.platform || _detectPlatform(initialCanvas))();
  5600. this.platform.updateConfig(config);
  5601. const context = this.platform.acquireContext(initialCanvas, options.aspectRatio);
  5602. const canvas = context && context.canvas;
  5603. const height = canvas && canvas.height;
  5604. const width = canvas && canvas.width;
  5605. this.id = helpers_segment.uid();
  5606. this.ctx = context;
  5607. this.canvas = canvas;
  5608. this.width = width;
  5609. this.height = height;
  5610. this._options = options;
  5611. this._aspectRatio = this.aspectRatio;
  5612. this._layers = [];
  5613. this._metasets = [];
  5614. this._stacks = undefined;
  5615. this.boxes = [];
  5616. this.currentDevicePixelRatio = undefined;
  5617. this.chartArea = undefined;
  5618. this._active = [];
  5619. this._lastEvent = undefined;
  5620. this._listeners = {};
  5621. this._responsiveListeners = undefined;
  5622. this._sortedMetasets = [];
  5623. this.scales = {};
  5624. this._plugins = new PluginService();
  5625. this.$proxies = {};
  5626. this._hiddenIndices = {};
  5627. this.attached = false;
  5628. this._animationsDisabled = undefined;
  5629. this.$context = undefined;
  5630. this._doResize = helpers_segment.debounce((mode)=>this.update(mode), options.resizeDelay || 0);
  5631. this._dataChanges = [];
  5632. instances[this.id] = this;
  5633. if (!context || !canvas) {
  5634. console.error("Failed to create chart: can't acquire context from the given item");
  5635. return;
  5636. }
  5637. animator.listen(this, 'complete', onAnimationsComplete);
  5638. animator.listen(this, 'progress', onAnimationProgress);
  5639. this._initialize();
  5640. if (this.attached) {
  5641. this.update();
  5642. }
  5643. }
  5644. get aspectRatio() {
  5645. const { options: { aspectRatio , maintainAspectRatio } , width , height , _aspectRatio } = this;
  5646. if (!helpers_segment.isNullOrUndef(aspectRatio)) {
  5647. return aspectRatio;
  5648. }
  5649. if (maintainAspectRatio && _aspectRatio) {
  5650. return _aspectRatio;
  5651. }
  5652. return height ? width / height : null;
  5653. }
  5654. get data() {
  5655. return this.config.data;
  5656. }
  5657. set data(data) {
  5658. this.config.data = data;
  5659. }
  5660. get options() {
  5661. return this._options;
  5662. }
  5663. set options(options) {
  5664. this.config.options = options;
  5665. }
  5666. get registry() {
  5667. return registry;
  5668. }
  5669. _initialize() {
  5670. this.notifyPlugins('beforeInit');
  5671. if (this.options.responsive) {
  5672. this.resize();
  5673. } else {
  5674. helpers_segment.retinaScale(this, this.options.devicePixelRatio);
  5675. }
  5676. this.bindEvents();
  5677. this.notifyPlugins('afterInit');
  5678. return this;
  5679. }
  5680. clear() {
  5681. helpers_segment.clearCanvas(this.canvas, this.ctx);
  5682. return this;
  5683. }
  5684. stop() {
  5685. animator.stop(this);
  5686. return this;
  5687. }
  5688. resize(width, height) {
  5689. if (!animator.running(this)) {
  5690. this._resize(width, height);
  5691. } else {
  5692. this._resizeBeforeDraw = {
  5693. width,
  5694. height
  5695. };
  5696. }
  5697. }
  5698. _resize(width, height) {
  5699. const options = this.options;
  5700. const canvas = this.canvas;
  5701. const aspectRatio = options.maintainAspectRatio && this.aspectRatio;
  5702. const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio);
  5703. const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio();
  5704. const mode = this.width ? 'resize' : 'attach';
  5705. this.width = newSize.width;
  5706. this.height = newSize.height;
  5707. this._aspectRatio = this.aspectRatio;
  5708. if (!helpers_segment.retinaScale(this, newRatio, true)) {
  5709. return;
  5710. }
  5711. this.notifyPlugins('resize', {
  5712. size: newSize
  5713. });
  5714. helpers_segment.callback(options.onResize, [
  5715. this,
  5716. newSize
  5717. ], this);
  5718. if (this.attached) {
  5719. if (this._doResize(mode)) {
  5720. this.render();
  5721. }
  5722. }
  5723. }
  5724. ensureScalesHaveIDs() {
  5725. const options = this.options;
  5726. const scalesOptions = options.scales || {};
  5727. helpers_segment.each(scalesOptions, (axisOptions, axisID)=>{
  5728. axisOptions.id = axisID;
  5729. });
  5730. }
  5731. buildOrUpdateScales() {
  5732. const options = this.options;
  5733. const scaleOpts = options.scales;
  5734. const scales = this.scales;
  5735. const updated = Object.keys(scales).reduce((obj, id)=>{
  5736. obj[id] = false;
  5737. return obj;
  5738. }, {});
  5739. let items = [];
  5740. if (scaleOpts) {
  5741. items = items.concat(Object.keys(scaleOpts).map((id)=>{
  5742. const scaleOptions = scaleOpts[id];
  5743. const axis = determineAxis(id, scaleOptions);
  5744. const isRadial = axis === 'r';
  5745. const isHorizontal = axis === 'x';
  5746. return {
  5747. options: scaleOptions,
  5748. dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',
  5749. dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'
  5750. };
  5751. }));
  5752. }
  5753. helpers_segment.each(items, (item)=>{
  5754. const scaleOptions = item.options;
  5755. const id = scaleOptions.id;
  5756. const axis = determineAxis(id, scaleOptions);
  5757. const scaleType = helpers_segment.valueOrDefault(scaleOptions.type, item.dtype);
  5758. if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {
  5759. scaleOptions.position = item.dposition;
  5760. }
  5761. updated[id] = true;
  5762. let scale = null;
  5763. if (id in scales && scales[id].type === scaleType) {
  5764. scale = scales[id];
  5765. } else {
  5766. const scaleClass = registry.getScale(scaleType);
  5767. scale = new scaleClass({
  5768. id,
  5769. type: scaleType,
  5770. ctx: this.ctx,
  5771. chart: this
  5772. });
  5773. scales[scale.id] = scale;
  5774. }
  5775. scale.init(scaleOptions, options);
  5776. });
  5777. helpers_segment.each(updated, (hasUpdated, id)=>{
  5778. if (!hasUpdated) {
  5779. delete scales[id];
  5780. }
  5781. });
  5782. helpers_segment.each(scales, (scale)=>{
  5783. layouts.configure(this, scale, scale.options);
  5784. layouts.addBox(this, scale);
  5785. });
  5786. }
  5787. _updateMetasets() {
  5788. const metasets = this._metasets;
  5789. const numData = this.data.datasets.length;
  5790. const numMeta = metasets.length;
  5791. metasets.sort((a, b)=>a.index - b.index);
  5792. if (numMeta > numData) {
  5793. for(let i = numData; i < numMeta; ++i){
  5794. this._destroyDatasetMeta(i);
  5795. }
  5796. metasets.splice(numData, numMeta - numData);
  5797. }
  5798. this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));
  5799. }
  5800. _removeUnreferencedMetasets() {
  5801. const { _metasets: metasets , data: { datasets } } = this;
  5802. if (metasets.length > datasets.length) {
  5803. delete this._stacks;
  5804. }
  5805. metasets.forEach((meta, index)=>{
  5806. if (datasets.filter((x)=>x === meta._dataset).length === 0) {
  5807. this._destroyDatasetMeta(index);
  5808. }
  5809. });
  5810. }
  5811. buildOrUpdateControllers() {
  5812. const newControllers = [];
  5813. const datasets = this.data.datasets;
  5814. let i, ilen;
  5815. this._removeUnreferencedMetasets();
  5816. for(i = 0, ilen = datasets.length; i < ilen; i++){
  5817. const dataset = datasets[i];
  5818. let meta = this.getDatasetMeta(i);
  5819. const type = dataset.type || this.config.type;
  5820. if (meta.type && meta.type !== type) {
  5821. this._destroyDatasetMeta(i);
  5822. meta = this.getDatasetMeta(i);
  5823. }
  5824. meta.type = type;
  5825. meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options);
  5826. meta.order = dataset.order || 0;
  5827. meta.index = i;
  5828. meta.label = '' + dataset.label;
  5829. meta.visible = this.isDatasetVisible(i);
  5830. if (meta.controller) {
  5831. meta.controller.updateIndex(i);
  5832. meta.controller.linkScales();
  5833. } else {
  5834. const ControllerClass = registry.getController(type);
  5835. const { datasetElementType , dataElementType } = helpers_segment.defaults.datasets[type];
  5836. Object.assign(ControllerClass, {
  5837. dataElementType: registry.getElement(dataElementType),
  5838. datasetElementType: datasetElementType && registry.getElement(datasetElementType)
  5839. });
  5840. meta.controller = new ControllerClass(this, i);
  5841. newControllers.push(meta.controller);
  5842. }
  5843. }
  5844. this._updateMetasets();
  5845. return newControllers;
  5846. }
  5847. _resetElements() {
  5848. helpers_segment.each(this.data.datasets, (dataset, datasetIndex)=>{
  5849. this.getDatasetMeta(datasetIndex).controller.reset();
  5850. }, this);
  5851. }
  5852. reset() {
  5853. this._resetElements();
  5854. this.notifyPlugins('reset');
  5855. }
  5856. update(mode) {
  5857. const config = this.config;
  5858. config.update();
  5859. const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext());
  5860. const animsDisabled = this._animationsDisabled = !options.animation;
  5861. this._updateScales();
  5862. this._checkEventBindings();
  5863. this._updateHiddenIndices();
  5864. this._plugins.invalidate();
  5865. if (this.notifyPlugins('beforeUpdate', {
  5866. mode,
  5867. cancelable: true
  5868. }) === false) {
  5869. return;
  5870. }
  5871. const newControllers = this.buildOrUpdateControllers();
  5872. this.notifyPlugins('beforeElementsUpdate');
  5873. let minPadding = 0;
  5874. for(let i = 0, ilen = this.data.datasets.length; i < ilen; i++){
  5875. const { controller } = this.getDatasetMeta(i);
  5876. const reset = !animsDisabled && newControllers.indexOf(controller) === -1;
  5877. controller.buildOrUpdateElements(reset);
  5878. minPadding = Math.max(+controller.getMaxOverflow(), minPadding);
  5879. }
  5880. minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0;
  5881. this._updateLayout(minPadding);
  5882. if (!animsDisabled) {
  5883. helpers_segment.each(newControllers, (controller)=>{
  5884. controller.reset();
  5885. });
  5886. }
  5887. this._updateDatasets(mode);
  5888. this.notifyPlugins('afterUpdate', {
  5889. mode
  5890. });
  5891. this._layers.sort(compare2Level('z', '_idx'));
  5892. const { _active , _lastEvent } = this;
  5893. if (_lastEvent) {
  5894. this._eventHandler(_lastEvent, true);
  5895. } else if (_active.length) {
  5896. this._updateHoverStyles(_active, _active, true);
  5897. }
  5898. this.render();
  5899. }
  5900. _updateScales() {
  5901. helpers_segment.each(this.scales, (scale)=>{
  5902. layouts.removeBox(this, scale);
  5903. });
  5904. this.ensureScalesHaveIDs();
  5905. this.buildOrUpdateScales();
  5906. }
  5907. _checkEventBindings() {
  5908. const options = this.options;
  5909. const existingEvents = new Set(Object.keys(this._listeners));
  5910. const newEvents = new Set(options.events);
  5911. if (!helpers_segment.setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) {
  5912. this.unbindEvents();
  5913. this.bindEvents();
  5914. }
  5915. }
  5916. _updateHiddenIndices() {
  5917. const { _hiddenIndices } = this;
  5918. const changes = this._getUniformDataChanges() || [];
  5919. for (const { method , start , count } of changes){
  5920. const move = method === '_removeElements' ? -count : count;
  5921. moveNumericKeys(_hiddenIndices, start, move);
  5922. }
  5923. }
  5924. _getUniformDataChanges() {
  5925. const _dataChanges = this._dataChanges;
  5926. if (!_dataChanges || !_dataChanges.length) {
  5927. return;
  5928. }
  5929. this._dataChanges = [];
  5930. const datasetCount = this.data.datasets.length;
  5931. const makeSet = (idx)=>new Set(_dataChanges.filter((c)=>c[0] === idx).map((c, i)=>i + ',' + c.splice(1).join(',')));
  5932. const changeSet = makeSet(0);
  5933. for(let i = 1; i < datasetCount; i++){
  5934. if (!helpers_segment.setsEqual(changeSet, makeSet(i))) {
  5935. return;
  5936. }
  5937. }
  5938. return Array.from(changeSet).map((c)=>c.split(',')).map((a)=>({
  5939. method: a[1],
  5940. start: +a[2],
  5941. count: +a[3]
  5942. }));
  5943. }
  5944. _updateLayout(minPadding) {
  5945. if (this.notifyPlugins('beforeLayout', {
  5946. cancelable: true
  5947. }) === false) {
  5948. return;
  5949. }
  5950. layouts.update(this, this.width, this.height, minPadding);
  5951. const area = this.chartArea;
  5952. const noArea = area.width <= 0 || area.height <= 0;
  5953. this._layers = [];
  5954. helpers_segment.each(this.boxes, (box)=>{
  5955. if (noArea && box.position === 'chartArea') {
  5956. return;
  5957. }
  5958. if (box.configure) {
  5959. box.configure();
  5960. }
  5961. this._layers.push(...box._layers());
  5962. }, this);
  5963. this._layers.forEach((item, index)=>{
  5964. item._idx = index;
  5965. });
  5966. this.notifyPlugins('afterLayout');
  5967. }
  5968. _updateDatasets(mode) {
  5969. if (this.notifyPlugins('beforeDatasetsUpdate', {
  5970. mode,
  5971. cancelable: true
  5972. }) === false) {
  5973. return;
  5974. }
  5975. for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
  5976. this.getDatasetMeta(i).controller.configure();
  5977. }
  5978. for(let i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
  5979. this._updateDataset(i, helpers_segment.isFunction(mode) ? mode({
  5980. datasetIndex: i
  5981. }) : mode);
  5982. }
  5983. this.notifyPlugins('afterDatasetsUpdate', {
  5984. mode
  5985. });
  5986. }
  5987. _updateDataset(index, mode) {
  5988. const meta = this.getDatasetMeta(index);
  5989. const args = {
  5990. meta,
  5991. index,
  5992. mode,
  5993. cancelable: true
  5994. };
  5995. if (this.notifyPlugins('beforeDatasetUpdate', args) === false) {
  5996. return;
  5997. }
  5998. meta.controller._update(mode);
  5999. args.cancelable = false;
  6000. this.notifyPlugins('afterDatasetUpdate', args);
  6001. }
  6002. render() {
  6003. if (this.notifyPlugins('beforeRender', {
  6004. cancelable: true
  6005. }) === false) {
  6006. return;
  6007. }
  6008. if (animator.has(this)) {
  6009. if (this.attached && !animator.running(this)) {
  6010. animator.start(this);
  6011. }
  6012. } else {
  6013. this.draw();
  6014. onAnimationsComplete({
  6015. chart: this
  6016. });
  6017. }
  6018. }
  6019. draw() {
  6020. let i;
  6021. if (this._resizeBeforeDraw) {
  6022. const { width , height } = this._resizeBeforeDraw;
  6023. this._resizeBeforeDraw = null;
  6024. this._resize(width, height);
  6025. }
  6026. this.clear();
  6027. if (this.width <= 0 || this.height <= 0) {
  6028. return;
  6029. }
  6030. if (this.notifyPlugins('beforeDraw', {
  6031. cancelable: true
  6032. }) === false) {
  6033. return;
  6034. }
  6035. const layers = this._layers;
  6036. for(i = 0; i < layers.length && layers[i].z <= 0; ++i){
  6037. layers[i].draw(this.chartArea);
  6038. }
  6039. this._drawDatasets();
  6040. for(; i < layers.length; ++i){
  6041. layers[i].draw(this.chartArea);
  6042. }
  6043. this.notifyPlugins('afterDraw');
  6044. }
  6045. _getSortedDatasetMetas(filterVisible) {
  6046. const metasets = this._sortedMetasets;
  6047. const result = [];
  6048. let i, ilen;
  6049. for(i = 0, ilen = metasets.length; i < ilen; ++i){
  6050. const meta = metasets[i];
  6051. if (!filterVisible || meta.visible) {
  6052. result.push(meta);
  6053. }
  6054. }
  6055. return result;
  6056. }
  6057. getSortedVisibleDatasetMetas() {
  6058. return this._getSortedDatasetMetas(true);
  6059. }
  6060. _drawDatasets() {
  6061. if (this.notifyPlugins('beforeDatasetsDraw', {
  6062. cancelable: true
  6063. }) === false) {
  6064. return;
  6065. }
  6066. const metasets = this.getSortedVisibleDatasetMetas();
  6067. for(let i = metasets.length - 1; i >= 0; --i){
  6068. this._drawDataset(metasets[i]);
  6069. }
  6070. this.notifyPlugins('afterDatasetsDraw');
  6071. }
  6072. _drawDataset(meta) {
  6073. const ctx = this.ctx;
  6074. const clip = meta._clip;
  6075. const useClip = !clip.disabled;
  6076. const area = getDatasetArea(meta, this.chartArea);
  6077. const args = {
  6078. meta,
  6079. index: meta.index,
  6080. cancelable: true
  6081. };
  6082. if (this.notifyPlugins('beforeDatasetDraw', args) === false) {
  6083. return;
  6084. }
  6085. if (useClip) {
  6086. helpers_segment.clipArea(ctx, {
  6087. left: clip.left === false ? 0 : area.left - clip.left,
  6088. right: clip.right === false ? this.width : area.right + clip.right,
  6089. top: clip.top === false ? 0 : area.top - clip.top,
  6090. bottom: clip.bottom === false ? this.height : area.bottom + clip.bottom
  6091. });
  6092. }
  6093. meta.controller.draw();
  6094. if (useClip) {
  6095. helpers_segment.unclipArea(ctx);
  6096. }
  6097. args.cancelable = false;
  6098. this.notifyPlugins('afterDatasetDraw', args);
  6099. }
  6100. isPointInArea(point) {
  6101. return helpers_segment._isPointInArea(point, this.chartArea, this._minPadding);
  6102. }
  6103. getElementsAtEventForMode(e, mode, options, useFinalPosition) {
  6104. const method = Interaction.modes[mode];
  6105. if (typeof method === 'function') {
  6106. return method(this, e, options, useFinalPosition);
  6107. }
  6108. return [];
  6109. }
  6110. getDatasetMeta(datasetIndex) {
  6111. const dataset = this.data.datasets[datasetIndex];
  6112. const metasets = this._metasets;
  6113. let meta = metasets.filter((x)=>x && x._dataset === dataset).pop();
  6114. if (!meta) {
  6115. meta = {
  6116. type: null,
  6117. data: [],
  6118. dataset: null,
  6119. controller: null,
  6120. hidden: null,
  6121. xAxisID: null,
  6122. yAxisID: null,
  6123. order: dataset && dataset.order || 0,
  6124. index: datasetIndex,
  6125. _dataset: dataset,
  6126. _parsed: [],
  6127. _sorted: false
  6128. };
  6129. metasets.push(meta);
  6130. }
  6131. return meta;
  6132. }
  6133. getContext() {
  6134. return this.$context || (this.$context = helpers_segment.createContext(null, {
  6135. chart: this,
  6136. type: 'chart'
  6137. }));
  6138. }
  6139. getVisibleDatasetCount() {
  6140. return this.getSortedVisibleDatasetMetas().length;
  6141. }
  6142. isDatasetVisible(datasetIndex) {
  6143. const dataset = this.data.datasets[datasetIndex];
  6144. if (!dataset) {
  6145. return false;
  6146. }
  6147. const meta = this.getDatasetMeta(datasetIndex);
  6148. return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;
  6149. }
  6150. setDatasetVisibility(datasetIndex, visible) {
  6151. const meta = this.getDatasetMeta(datasetIndex);
  6152. meta.hidden = !visible;
  6153. }
  6154. toggleDataVisibility(index) {
  6155. this._hiddenIndices[index] = !this._hiddenIndices[index];
  6156. }
  6157. getDataVisibility(index) {
  6158. return !this._hiddenIndices[index];
  6159. }
  6160. _updateVisibility(datasetIndex, dataIndex, visible) {
  6161. const mode = visible ? 'show' : 'hide';
  6162. const meta = this.getDatasetMeta(datasetIndex);
  6163. const anims = meta.controller._resolveAnimations(undefined, mode);
  6164. if (helpers_segment.defined(dataIndex)) {
  6165. meta.data[dataIndex].hidden = !visible;
  6166. this.update();
  6167. } else {
  6168. this.setDatasetVisibility(datasetIndex, visible);
  6169. anims.update(meta, {
  6170. visible
  6171. });
  6172. this.update((ctx)=>ctx.datasetIndex === datasetIndex ? mode : undefined);
  6173. }
  6174. }
  6175. hide(datasetIndex, dataIndex) {
  6176. this._updateVisibility(datasetIndex, dataIndex, false);
  6177. }
  6178. show(datasetIndex, dataIndex) {
  6179. this._updateVisibility(datasetIndex, dataIndex, true);
  6180. }
  6181. _destroyDatasetMeta(datasetIndex) {
  6182. const meta = this._metasets[datasetIndex];
  6183. if (meta && meta.controller) {
  6184. meta.controller._destroy();
  6185. }
  6186. delete this._metasets[datasetIndex];
  6187. }
  6188. _stop() {
  6189. let i, ilen;
  6190. this.stop();
  6191. animator.remove(this);
  6192. for(i = 0, ilen = this.data.datasets.length; i < ilen; ++i){
  6193. this._destroyDatasetMeta(i);
  6194. }
  6195. }
  6196. destroy() {
  6197. this.notifyPlugins('beforeDestroy');
  6198. const { canvas , ctx } = this;
  6199. this._stop();
  6200. this.config.clearCache();
  6201. if (canvas) {
  6202. this.unbindEvents();
  6203. helpers_segment.clearCanvas(canvas, ctx);
  6204. this.platform.releaseContext(ctx);
  6205. this.canvas = null;
  6206. this.ctx = null;
  6207. }
  6208. delete instances[this.id];
  6209. this.notifyPlugins('afterDestroy');
  6210. }
  6211. toBase64Image(...args) {
  6212. return this.canvas.toDataURL(...args);
  6213. }
  6214. bindEvents() {
  6215. this.bindUserEvents();
  6216. if (this.options.responsive) {
  6217. this.bindResponsiveEvents();
  6218. } else {
  6219. this.attached = true;
  6220. }
  6221. }
  6222. bindUserEvents() {
  6223. const listeners = this._listeners;
  6224. const platform = this.platform;
  6225. const _add = (type, listener)=>{
  6226. platform.addEventListener(this, type, listener);
  6227. listeners[type] = listener;
  6228. };
  6229. const listener = (e, x, y)=>{
  6230. e.offsetX = x;
  6231. e.offsetY = y;
  6232. this._eventHandler(e);
  6233. };
  6234. helpers_segment.each(this.options.events, (type)=>_add(type, listener));
  6235. }
  6236. bindResponsiveEvents() {
  6237. if (!this._responsiveListeners) {
  6238. this._responsiveListeners = {};
  6239. }
  6240. const listeners = this._responsiveListeners;
  6241. const platform = this.platform;
  6242. const _add = (type, listener)=>{
  6243. platform.addEventListener(this, type, listener);
  6244. listeners[type] = listener;
  6245. };
  6246. const _remove = (type, listener)=>{
  6247. if (listeners[type]) {
  6248. platform.removeEventListener(this, type, listener);
  6249. delete listeners[type];
  6250. }
  6251. };
  6252. const listener = (width, height)=>{
  6253. if (this.canvas) {
  6254. this.resize(width, height);
  6255. }
  6256. };
  6257. let detached;
  6258. const attached = ()=>{
  6259. _remove('attach', attached);
  6260. this.attached = true;
  6261. this.resize();
  6262. _add('resize', listener);
  6263. _add('detach', detached);
  6264. };
  6265. detached = ()=>{
  6266. this.attached = false;
  6267. _remove('resize', listener);
  6268. this._stop();
  6269. this._resize(0, 0);
  6270. _add('attach', attached);
  6271. };
  6272. if (platform.isAttached(this.canvas)) {
  6273. attached();
  6274. } else {
  6275. detached();
  6276. }
  6277. }
  6278. unbindEvents() {
  6279. helpers_segment.each(this._listeners, (listener, type)=>{
  6280. this.platform.removeEventListener(this, type, listener);
  6281. });
  6282. this._listeners = {};
  6283. helpers_segment.each(this._responsiveListeners, (listener, type)=>{
  6284. this.platform.removeEventListener(this, type, listener);
  6285. });
  6286. this._responsiveListeners = undefined;
  6287. }
  6288. updateHoverStyle(items, mode, enabled) {
  6289. const prefix = enabled ? 'set' : 'remove';
  6290. let meta, item, i, ilen;
  6291. if (mode === 'dataset') {
  6292. meta = this.getDatasetMeta(items[0].datasetIndex);
  6293. meta.controller['_' + prefix + 'DatasetHoverStyle']();
  6294. }
  6295. for(i = 0, ilen = items.length; i < ilen; ++i){
  6296. item = items[i];
  6297. const controller = item && this.getDatasetMeta(item.datasetIndex).controller;
  6298. if (controller) {
  6299. controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
  6300. }
  6301. }
  6302. }
  6303. getActiveElements() {
  6304. return this._active || [];
  6305. }
  6306. setActiveElements(activeElements) {
  6307. const lastActive = this._active || [];
  6308. const active = activeElements.map(({ datasetIndex , index })=>{
  6309. const meta = this.getDatasetMeta(datasetIndex);
  6310. if (!meta) {
  6311. throw new Error('No dataset found at index ' + datasetIndex);
  6312. }
  6313. return {
  6314. datasetIndex,
  6315. element: meta.data[index],
  6316. index
  6317. };
  6318. });
  6319. const changed = !helpers_segment._elementsEqual(active, lastActive);
  6320. if (changed) {
  6321. this._active = active;
  6322. this._lastEvent = null;
  6323. this._updateHoverStyles(active, lastActive);
  6324. }
  6325. }
  6326. notifyPlugins(hook, args, filter) {
  6327. return this._plugins.notify(this, hook, args, filter);
  6328. }
  6329. isPluginEnabled(pluginId) {
  6330. return this._plugins._cache.filter((p)=>p.plugin.id === pluginId).length === 1;
  6331. }
  6332. _updateHoverStyles(active, lastActive, replay) {
  6333. const hoverOptions = this.options.hover;
  6334. const diff = (a, b)=>a.filter((x)=>!b.some((y)=>x.datasetIndex === y.datasetIndex && x.index === y.index));
  6335. const deactivated = diff(lastActive, active);
  6336. const activated = replay ? active : diff(active, lastActive);
  6337. if (deactivated.length) {
  6338. this.updateHoverStyle(deactivated, hoverOptions.mode, false);
  6339. }
  6340. if (activated.length && hoverOptions.mode) {
  6341. this.updateHoverStyle(activated, hoverOptions.mode, true);
  6342. }
  6343. }
  6344. _eventHandler(e, replay) {
  6345. const args = {
  6346. event: e,
  6347. replay,
  6348. cancelable: true,
  6349. inChartArea: this.isPointInArea(e)
  6350. };
  6351. const eventFilter = (plugin)=>(plugin.options.events || this.options.events).includes(e.native.type);
  6352. if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) {
  6353. return;
  6354. }
  6355. const changed = this._handleEvent(e, replay, args.inChartArea);
  6356. args.cancelable = false;
  6357. this.notifyPlugins('afterEvent', args, eventFilter);
  6358. if (changed || args.changed) {
  6359. this.render();
  6360. }
  6361. return this;
  6362. }
  6363. _handleEvent(e, replay, inChartArea) {
  6364. const { _active: lastActive = [] , options } = this;
  6365. const useFinalPosition = replay;
  6366. const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition);
  6367. const isClick = helpers_segment._isClickEvent(e);
  6368. const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick);
  6369. if (inChartArea) {
  6370. this._lastEvent = null;
  6371. helpers_segment.callback(options.onHover, [
  6372. e,
  6373. active,
  6374. this
  6375. ], this);
  6376. if (isClick) {
  6377. helpers_segment.callback(options.onClick, [
  6378. e,
  6379. active,
  6380. this
  6381. ], this);
  6382. }
  6383. }
  6384. const changed = !helpers_segment._elementsEqual(active, lastActive);
  6385. if (changed || replay) {
  6386. this._active = active;
  6387. this._updateHoverStyles(active, lastActive, replay);
  6388. }
  6389. this._lastEvent = lastEvent;
  6390. return changed;
  6391. }
  6392. _getActiveElements(e, lastActive, inChartArea, useFinalPosition) {
  6393. if (e.type === 'mouseout') {
  6394. return [];
  6395. }
  6396. if (!inChartArea) {
  6397. return lastActive;
  6398. }
  6399. const hoverOptions = this.options.hover;
  6400. return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);
  6401. }
  6402. }
  6403. function invalidatePlugins() {
  6404. return helpers_segment.each(Chart.instances, (chart)=>chart._plugins.invalidate());
  6405. }
  6406. function clipArc(ctx, element, endAngle) {
  6407. const { startAngle , pixelMargin , x , y , outerRadius , innerRadius } = element;
  6408. let angleMargin = pixelMargin / outerRadius;
  6409. // Draw an inner border by clipping the arc and drawing a double-width border
  6410. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  6411. ctx.beginPath();
  6412. ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  6413. if (innerRadius > pixelMargin) {
  6414. angleMargin = pixelMargin / innerRadius;
  6415. ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);
  6416. } else {
  6417. ctx.arc(x, y, pixelMargin, endAngle + helpers_segment.HALF_PI, startAngle - helpers_segment.HALF_PI);
  6418. }
  6419. ctx.closePath();
  6420. ctx.clip();
  6421. }
  6422. function toRadiusCorners(value) {
  6423. return helpers_segment._readValueToProps(value, [
  6424. 'outerStart',
  6425. 'outerEnd',
  6426. 'innerStart',
  6427. 'innerEnd'
  6428. ]);
  6429. }
  6430. /**
  6431. * Parse border radius from the provided options
  6432. */ function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) {
  6433. const o = toRadiusCorners(arc.options.borderRadius);
  6434. const halfThickness = (outerRadius - innerRadius) / 2;
  6435. const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);
  6436. // Outer limits are complicated. We want to compute the available angular distance at
  6437. // a radius of outerRadius - borderRadius because for small angular distances, this term limits.
  6438. // We compute at r = outerRadius - borderRadius because this circle defines the center of the border corners.
  6439. //
  6440. // If the borderRadius is large, that value can become negative.
  6441. // This causes the outer borders to lose their radius entirely, which is rather unexpected. To solve that, if borderRadius > outerRadius
  6442. // we know that the thickness term will dominate and compute the limits at that point
  6443. const computeOuterLimit = (val)=>{
  6444. const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;
  6445. return helpers_segment._limitValue(val, 0, Math.min(halfThickness, outerArcLimit));
  6446. };
  6447. return {
  6448. outerStart: computeOuterLimit(o.outerStart),
  6449. outerEnd: computeOuterLimit(o.outerEnd),
  6450. innerStart: helpers_segment._limitValue(o.innerStart, 0, innerLimit),
  6451. innerEnd: helpers_segment._limitValue(o.innerEnd, 0, innerLimit)
  6452. };
  6453. }
  6454. /**
  6455. * Convert (r, 𝜃) to (x, y)
  6456. */ function rThetaToXY(r, theta, x, y) {
  6457. return {
  6458. x: x + r * Math.cos(theta),
  6459. y: y + r * Math.sin(theta)
  6460. };
  6461. }
  6462. /**
  6463. * Path the arc, respecting border radius by separating into left and right halves.
  6464. *
  6465. * Start End
  6466. *
  6467. * 1--->a--->2 Outer
  6468. * / \
  6469. * 8 3
  6470. * | |
  6471. * | |
  6472. * 7 4
  6473. * \ /
  6474. * 6<---b<---5 Inner
  6475. */ function pathArc(ctx, element, offset, spacing, end, circular) {
  6476. const { x , y , startAngle: start , pixelMargin , innerRadius: innerR } = element;
  6477. const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0);
  6478. const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0;
  6479. let spacingOffset = 0;
  6480. const alpha = end - start;
  6481. if (spacing) {
  6482. // When spacing is present, it is the same for all items
  6483. // So we adjust the start and end angle of the arc such that
  6484. // the distance is the same as it would be without the spacing
  6485. const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;
  6486. const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;
  6487. const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;
  6488. const adjustedAngle = avNogSpacingRadius !== 0 ? alpha * avNogSpacingRadius / (avNogSpacingRadius + spacing) : alpha;
  6489. spacingOffset = (alpha - adjustedAngle) / 2;
  6490. }
  6491. const beta = Math.max(0.001, alpha * outerRadius - offset / helpers_segment.PI) / outerRadius;
  6492. const angleOffset = (alpha - beta) / 2;
  6493. const startAngle = start + angleOffset + spacingOffset;
  6494. const endAngle = end - angleOffset - spacingOffset;
  6495. const { outerStart , outerEnd , innerStart , innerEnd } = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle);
  6496. const outerStartAdjustedRadius = outerRadius - outerStart;
  6497. const outerEndAdjustedRadius = outerRadius - outerEnd;
  6498. const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;
  6499. const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;
  6500. const innerStartAdjustedRadius = innerRadius + innerStart;
  6501. const innerEndAdjustedRadius = innerRadius + innerEnd;
  6502. const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;
  6503. const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;
  6504. ctx.beginPath();
  6505. if (circular) {
  6506. // The first arc segments from point 1 to point a to point 2
  6507. const outerMidAdjustedAngle = (outerStartAdjustedAngle + outerEndAdjustedAngle) / 2;
  6508. ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerMidAdjustedAngle);
  6509. ctx.arc(x, y, outerRadius, outerMidAdjustedAngle, outerEndAdjustedAngle);
  6510. // The corner segment from point 2 to point 3
  6511. if (outerEnd > 0) {
  6512. const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);
  6513. ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + helpers_segment.HALF_PI);
  6514. }
  6515. // The line from point 3 to point 4
  6516. const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);
  6517. ctx.lineTo(p4.x, p4.y);
  6518. // The corner segment from point 4 to point 5
  6519. if (innerEnd > 0) {
  6520. const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);
  6521. ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + helpers_segment.HALF_PI, innerEndAdjustedAngle + Math.PI);
  6522. }
  6523. // The inner arc from point 5 to point b to point 6
  6524. const innerMidAdjustedAngle = (endAngle - innerEnd / innerRadius + (startAngle + innerStart / innerRadius)) / 2;
  6525. ctx.arc(x, y, innerRadius, endAngle - innerEnd / innerRadius, innerMidAdjustedAngle, true);
  6526. ctx.arc(x, y, innerRadius, innerMidAdjustedAngle, startAngle + innerStart / innerRadius, true);
  6527. // The corner segment from point 6 to point 7
  6528. if (innerStart > 0) {
  6529. const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);
  6530. ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - helpers_segment.HALF_PI);
  6531. }
  6532. // The line from point 7 to point 8
  6533. const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);
  6534. ctx.lineTo(p8.x, p8.y);
  6535. // The corner segment from point 8 to point 1
  6536. if (outerStart > 0) {
  6537. const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);
  6538. ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - helpers_segment.HALF_PI, outerStartAdjustedAngle);
  6539. }
  6540. } else {
  6541. ctx.moveTo(x, y);
  6542. const outerStartX = Math.cos(outerStartAdjustedAngle) * outerRadius + x;
  6543. const outerStartY = Math.sin(outerStartAdjustedAngle) * outerRadius + y;
  6544. ctx.lineTo(outerStartX, outerStartY);
  6545. const outerEndX = Math.cos(outerEndAdjustedAngle) * outerRadius + x;
  6546. const outerEndY = Math.sin(outerEndAdjustedAngle) * outerRadius + y;
  6547. ctx.lineTo(outerEndX, outerEndY);
  6548. }
  6549. ctx.closePath();
  6550. }
  6551. function drawArc(ctx, element, offset, spacing, circular) {
  6552. const { fullCircles , startAngle , circumference } = element;
  6553. let endAngle = element.endAngle;
  6554. if (fullCircles) {
  6555. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6556. for(let i = 0; i < fullCircles; ++i){
  6557. ctx.fill();
  6558. }
  6559. if (!isNaN(circumference)) {
  6560. endAngle = startAngle + (circumference % helpers_segment.TAU || helpers_segment.TAU);
  6561. }
  6562. }
  6563. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6564. ctx.fill();
  6565. return endAngle;
  6566. }
  6567. function drawBorder(ctx, element, offset, spacing, circular) {
  6568. const { fullCircles , startAngle , circumference , options } = element;
  6569. const { borderWidth , borderJoinStyle , borderDash , borderDashOffset } = options;
  6570. const inner = options.borderAlign === 'inner';
  6571. if (!borderWidth) {
  6572. return;
  6573. }
  6574. ctx.setLineDash(borderDash || []);
  6575. ctx.lineDashOffset = borderDashOffset;
  6576. if (inner) {
  6577. ctx.lineWidth = borderWidth * 2;
  6578. ctx.lineJoin = borderJoinStyle || 'round';
  6579. } else {
  6580. ctx.lineWidth = borderWidth;
  6581. ctx.lineJoin = borderJoinStyle || 'bevel';
  6582. }
  6583. let endAngle = element.endAngle;
  6584. if (fullCircles) {
  6585. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6586. for(let i = 0; i < fullCircles; ++i){
  6587. ctx.stroke();
  6588. }
  6589. if (!isNaN(circumference)) {
  6590. endAngle = startAngle + (circumference % helpers_segment.TAU || helpers_segment.TAU);
  6591. }
  6592. }
  6593. if (inner) {
  6594. clipArc(ctx, element, endAngle);
  6595. }
  6596. if (!fullCircles) {
  6597. pathArc(ctx, element, offset, spacing, endAngle, circular);
  6598. ctx.stroke();
  6599. }
  6600. }
  6601. class ArcElement extends Element {
  6602. static id = 'arc';
  6603. static defaults = {
  6604. borderAlign: 'center',
  6605. borderColor: '#fff',
  6606. borderDash: [],
  6607. borderDashOffset: 0,
  6608. borderJoinStyle: undefined,
  6609. borderRadius: 0,
  6610. borderWidth: 2,
  6611. offset: 0,
  6612. spacing: 0,
  6613. angle: undefined,
  6614. circular: true
  6615. };
  6616. static defaultRoutes = {
  6617. backgroundColor: 'backgroundColor'
  6618. };
  6619. static descriptors = {
  6620. _scriptable: true,
  6621. _indexable: (name)=>name !== 'borderDash'
  6622. };
  6623. circumference;
  6624. endAngle;
  6625. fullCircles;
  6626. innerRadius;
  6627. outerRadius;
  6628. pixelMargin;
  6629. startAngle;
  6630. constructor(cfg){
  6631. super();
  6632. this.options = undefined;
  6633. this.circumference = undefined;
  6634. this.startAngle = undefined;
  6635. this.endAngle = undefined;
  6636. this.innerRadius = undefined;
  6637. this.outerRadius = undefined;
  6638. this.pixelMargin = 0;
  6639. this.fullCircles = 0;
  6640. if (cfg) {
  6641. Object.assign(this, cfg);
  6642. }
  6643. }
  6644. inRange(chartX, chartY, useFinalPosition) {
  6645. const point = this.getProps([
  6646. 'x',
  6647. 'y'
  6648. ], useFinalPosition);
  6649. const { angle , distance } = helpers_segment.getAngleFromPoint(point, {
  6650. x: chartX,
  6651. y: chartY
  6652. });
  6653. const { startAngle , endAngle , innerRadius , outerRadius , circumference } = this.getProps([
  6654. 'startAngle',
  6655. 'endAngle',
  6656. 'innerRadius',
  6657. 'outerRadius',
  6658. 'circumference'
  6659. ], useFinalPosition);
  6660. const rAdjust = (this.options.spacing + this.options.borderWidth) / 2;
  6661. const _circumference = helpers_segment.valueOrDefault(circumference, endAngle - startAngle);
  6662. const nonZeroBetween = helpers_segment._angleBetween(angle, startAngle, endAngle) && startAngle !== endAngle;
  6663. const betweenAngles = _circumference >= helpers_segment.TAU || nonZeroBetween;
  6664. const withinRadius = helpers_segment._isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust);
  6665. return betweenAngles && withinRadius;
  6666. }
  6667. getCenterPoint(useFinalPosition) {
  6668. const { x , y , startAngle , endAngle , innerRadius , outerRadius } = this.getProps([
  6669. 'x',
  6670. 'y',
  6671. 'startAngle',
  6672. 'endAngle',
  6673. 'innerRadius',
  6674. 'outerRadius'
  6675. ], useFinalPosition);
  6676. const { offset , spacing } = this.options;
  6677. const halfAngle = (startAngle + endAngle) / 2;
  6678. const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2;
  6679. return {
  6680. x: x + Math.cos(halfAngle) * halfRadius,
  6681. y: y + Math.sin(halfAngle) * halfRadius
  6682. };
  6683. }
  6684. tooltipPosition(useFinalPosition) {
  6685. return this.getCenterPoint(useFinalPosition);
  6686. }
  6687. draw(ctx) {
  6688. const { options , circumference } = this;
  6689. const offset = (options.offset || 0) / 4;
  6690. const spacing = (options.spacing || 0) / 2;
  6691. const circular = options.circular;
  6692. this.pixelMargin = options.borderAlign === 'inner' ? 0.33 : 0;
  6693. this.fullCircles = circumference > helpers_segment.TAU ? Math.floor(circumference / helpers_segment.TAU) : 0;
  6694. if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) {
  6695. return;
  6696. }
  6697. ctx.save();
  6698. const halfAngle = (this.startAngle + this.endAngle) / 2;
  6699. ctx.translate(Math.cos(halfAngle) * offset, Math.sin(halfAngle) * offset);
  6700. const fix = 1 - Math.sin(Math.min(helpers_segment.PI, circumference || 0));
  6701. const radiusOffset = offset * fix;
  6702. ctx.fillStyle = options.backgroundColor;
  6703. ctx.strokeStyle = options.borderColor;
  6704. drawArc(ctx, this, radiusOffset, spacing, circular);
  6705. drawBorder(ctx, this, radiusOffset, spacing, circular);
  6706. ctx.restore();
  6707. }
  6708. }
  6709. function setStyle(ctx, options, style = options) {
  6710. ctx.lineCap = helpers_segment.valueOrDefault(style.borderCapStyle, options.borderCapStyle);
  6711. ctx.setLineDash(helpers_segment.valueOrDefault(style.borderDash, options.borderDash));
  6712. ctx.lineDashOffset = helpers_segment.valueOrDefault(style.borderDashOffset, options.borderDashOffset);
  6713. ctx.lineJoin = helpers_segment.valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);
  6714. ctx.lineWidth = helpers_segment.valueOrDefault(style.borderWidth, options.borderWidth);
  6715. ctx.strokeStyle = helpers_segment.valueOrDefault(style.borderColor, options.borderColor);
  6716. }
  6717. function lineTo(ctx, previous, target) {
  6718. ctx.lineTo(target.x, target.y);
  6719. }
  6720. function getLineMethod(options) {
  6721. if (options.stepped) {
  6722. return helpers_segment._steppedLineTo;
  6723. }
  6724. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  6725. return helpers_segment._bezierCurveTo;
  6726. }
  6727. return lineTo;
  6728. }
  6729. function pathVars(points, segment, params = {}) {
  6730. const count = points.length;
  6731. const { start: paramsStart = 0 , end: paramsEnd = count - 1 } = params;
  6732. const { start: segmentStart , end: segmentEnd } = segment;
  6733. const start = Math.max(paramsStart, segmentStart);
  6734. const end = Math.min(paramsEnd, segmentEnd);
  6735. const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;
  6736. return {
  6737. count,
  6738. start,
  6739. loop: segment.loop,
  6740. ilen: end < start && !outside ? count + end - start : end - start
  6741. };
  6742. }
  6743. function pathSegment(ctx, line, segment, params) {
  6744. const { points , options } = line;
  6745. const { count , start , loop , ilen } = pathVars(points, segment, params);
  6746. const lineMethod = getLineMethod(options);
  6747. let { move =true , reverse } = params || {};
  6748. let i, point, prev;
  6749. for(i = 0; i <= ilen; ++i){
  6750. point = points[(start + (reverse ? ilen - i : i)) % count];
  6751. if (point.skip) {
  6752. continue;
  6753. } else if (move) {
  6754. ctx.moveTo(point.x, point.y);
  6755. move = false;
  6756. } else {
  6757. lineMethod(ctx, prev, point, reverse, options.stepped);
  6758. }
  6759. prev = point;
  6760. }
  6761. if (loop) {
  6762. point = points[(start + (reverse ? ilen : 0)) % count];
  6763. lineMethod(ctx, prev, point, reverse, options.stepped);
  6764. }
  6765. return !!loop;
  6766. }
  6767. function fastPathSegment(ctx, line, segment, params) {
  6768. const points = line.points;
  6769. const { count , start , ilen } = pathVars(points, segment, params);
  6770. const { move =true , reverse } = params || {};
  6771. let avgX = 0;
  6772. let countX = 0;
  6773. let i, point, prevX, minY, maxY, lastY;
  6774. const pointIndex = (index)=>(start + (reverse ? ilen - index : index)) % count;
  6775. const drawX = ()=>{
  6776. if (minY !== maxY) {
  6777. ctx.lineTo(avgX, maxY);
  6778. ctx.lineTo(avgX, minY);
  6779. ctx.lineTo(avgX, lastY);
  6780. }
  6781. };
  6782. if (move) {
  6783. point = points[pointIndex(0)];
  6784. ctx.moveTo(point.x, point.y);
  6785. }
  6786. for(i = 0; i <= ilen; ++i){
  6787. point = points[pointIndex(i)];
  6788. if (point.skip) {
  6789. continue;
  6790. }
  6791. const x = point.x;
  6792. const y = point.y;
  6793. const truncX = x | 0;
  6794. if (truncX === prevX) {
  6795. if (y < minY) {
  6796. minY = y;
  6797. } else if (y > maxY) {
  6798. maxY = y;
  6799. }
  6800. avgX = (countX * avgX + x) / ++countX;
  6801. } else {
  6802. drawX();
  6803. ctx.lineTo(x, y);
  6804. prevX = truncX;
  6805. countX = 0;
  6806. minY = maxY = y;
  6807. }
  6808. lastY = y;
  6809. }
  6810. drawX();
  6811. }
  6812. function _getSegmentMethod(line) {
  6813. const opts = line.options;
  6814. const borderDash = opts.borderDash && opts.borderDash.length;
  6815. const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;
  6816. return useFastPath ? fastPathSegment : pathSegment;
  6817. }
  6818. function _getInterpolationMethod(options) {
  6819. if (options.stepped) {
  6820. return helpers_segment._steppedInterpolation;
  6821. }
  6822. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  6823. return helpers_segment._bezierInterpolation;
  6824. }
  6825. return helpers_segment._pointInLine;
  6826. }
  6827. function strokePathWithCache(ctx, line, start, count) {
  6828. let path = line._path;
  6829. if (!path) {
  6830. path = line._path = new Path2D();
  6831. if (line.path(path, start, count)) {
  6832. path.closePath();
  6833. }
  6834. }
  6835. setStyle(ctx, line.options);
  6836. ctx.stroke(path);
  6837. }
  6838. function strokePathDirect(ctx, line, start, count) {
  6839. const { segments , options } = line;
  6840. const segmentMethod = _getSegmentMethod(line);
  6841. for (const segment of segments){
  6842. setStyle(ctx, options, segment.style);
  6843. ctx.beginPath();
  6844. if (segmentMethod(ctx, line, segment, {
  6845. start,
  6846. end: start + count - 1
  6847. })) {
  6848. ctx.closePath();
  6849. }
  6850. ctx.stroke();
  6851. }
  6852. }
  6853. const usePath2D = typeof Path2D === 'function';
  6854. function draw(ctx, line, start, count) {
  6855. if (usePath2D && !line.options.segment) {
  6856. strokePathWithCache(ctx, line, start, count);
  6857. } else {
  6858. strokePathDirect(ctx, line, start, count);
  6859. }
  6860. }
  6861. class LineElement extends Element {
  6862. static id = 'line';
  6863. static defaults = {
  6864. borderCapStyle: 'butt',
  6865. borderDash: [],
  6866. borderDashOffset: 0,
  6867. borderJoinStyle: 'miter',
  6868. borderWidth: 3,
  6869. capBezierPoints: true,
  6870. cubicInterpolationMode: 'default',
  6871. fill: false,
  6872. spanGaps: false,
  6873. stepped: false,
  6874. tension: 0
  6875. };
  6876. static defaultRoutes = {
  6877. backgroundColor: 'backgroundColor',
  6878. borderColor: 'borderColor'
  6879. };
  6880. static descriptors = {
  6881. _scriptable: true,
  6882. _indexable: (name)=>name !== 'borderDash' && name !== 'fill'
  6883. };
  6884. constructor(cfg){
  6885. super();
  6886. this.animated = true;
  6887. this.options = undefined;
  6888. this._chart = undefined;
  6889. this._loop = undefined;
  6890. this._fullLoop = undefined;
  6891. this._path = undefined;
  6892. this._points = undefined;
  6893. this._segments = undefined;
  6894. this._decimated = false;
  6895. this._pointsUpdated = false;
  6896. this._datasetIndex = undefined;
  6897. if (cfg) {
  6898. Object.assign(this, cfg);
  6899. }
  6900. }
  6901. updateControlPoints(chartArea, indexAxis) {
  6902. const options = this.options;
  6903. if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) {
  6904. const loop = options.spanGaps ? this._loop : this._fullLoop;
  6905. helpers_segment._updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis);
  6906. this._pointsUpdated = true;
  6907. }
  6908. }
  6909. set points(points) {
  6910. this._points = points;
  6911. delete this._segments;
  6912. delete this._path;
  6913. this._pointsUpdated = false;
  6914. }
  6915. get points() {
  6916. return this._points;
  6917. }
  6918. get segments() {
  6919. return this._segments || (this._segments = helpers_segment._computeSegments(this, this.options.segment));
  6920. }
  6921. first() {
  6922. const segments = this.segments;
  6923. const points = this.points;
  6924. return segments.length && points[segments[0].start];
  6925. }
  6926. last() {
  6927. const segments = this.segments;
  6928. const points = this.points;
  6929. const count = segments.length;
  6930. return count && points[segments[count - 1].end];
  6931. }
  6932. interpolate(point, property) {
  6933. const options = this.options;
  6934. const value = point[property];
  6935. const points = this.points;
  6936. const segments = helpers_segment._boundSegments(this, {
  6937. property,
  6938. start: value,
  6939. end: value
  6940. });
  6941. if (!segments.length) {
  6942. return;
  6943. }
  6944. const result = [];
  6945. const _interpolate = _getInterpolationMethod(options);
  6946. let i, ilen;
  6947. for(i = 0, ilen = segments.length; i < ilen; ++i){
  6948. const { start , end } = segments[i];
  6949. const p1 = points[start];
  6950. const p2 = points[end];
  6951. if (p1 === p2) {
  6952. result.push(p1);
  6953. continue;
  6954. }
  6955. const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));
  6956. const interpolated = _interpolate(p1, p2, t, options.stepped);
  6957. interpolated[property] = point[property];
  6958. result.push(interpolated);
  6959. }
  6960. return result.length === 1 ? result[0] : result;
  6961. }
  6962. pathSegment(ctx, segment, params) {
  6963. const segmentMethod = _getSegmentMethod(this);
  6964. return segmentMethod(ctx, this, segment, params);
  6965. }
  6966. path(ctx, start, count) {
  6967. const segments = this.segments;
  6968. const segmentMethod = _getSegmentMethod(this);
  6969. let loop = this._loop;
  6970. start = start || 0;
  6971. count = count || this.points.length - start;
  6972. for (const segment of segments){
  6973. loop &= segmentMethod(ctx, this, segment, {
  6974. start,
  6975. end: start + count - 1
  6976. });
  6977. }
  6978. return !!loop;
  6979. }
  6980. draw(ctx, chartArea, start, count) {
  6981. const options = this.options || {};
  6982. const points = this.points || [];
  6983. if (points.length && options.borderWidth) {
  6984. ctx.save();
  6985. draw(ctx, this, start, count);
  6986. ctx.restore();
  6987. }
  6988. if (this.animated) {
  6989. this._pointsUpdated = false;
  6990. this._path = undefined;
  6991. }
  6992. }
  6993. }
  6994. function inRange$1(el, pos, axis, useFinalPosition) {
  6995. const options = el.options;
  6996. const { [axis]: value } = el.getProps([
  6997. axis
  6998. ], useFinalPosition);
  6999. return Math.abs(pos - value) < options.radius + options.hitRadius;
  7000. }
  7001. class PointElement extends Element {
  7002. static id = 'point';
  7003. parsed;
  7004. skip;
  7005. stop;
  7006. /**
  7007. * @type {any}
  7008. */ static defaults = {
  7009. borderWidth: 1,
  7010. hitRadius: 1,
  7011. hoverBorderWidth: 1,
  7012. hoverRadius: 4,
  7013. pointStyle: 'circle',
  7014. radius: 3,
  7015. rotation: 0
  7016. };
  7017. /**
  7018. * @type {any}
  7019. */ static defaultRoutes = {
  7020. backgroundColor: 'backgroundColor',
  7021. borderColor: 'borderColor'
  7022. };
  7023. constructor(cfg){
  7024. super();
  7025. this.options = undefined;
  7026. this.parsed = undefined;
  7027. this.skip = undefined;
  7028. this.stop = undefined;
  7029. if (cfg) {
  7030. Object.assign(this, cfg);
  7031. }
  7032. }
  7033. inRange(mouseX, mouseY, useFinalPosition) {
  7034. const options = this.options;
  7035. const { x , y } = this.getProps([
  7036. 'x',
  7037. 'y'
  7038. ], useFinalPosition);
  7039. return Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2) < Math.pow(options.hitRadius + options.radius, 2);
  7040. }
  7041. inXRange(mouseX, useFinalPosition) {
  7042. return inRange$1(this, mouseX, 'x', useFinalPosition);
  7043. }
  7044. inYRange(mouseY, useFinalPosition) {
  7045. return inRange$1(this, mouseY, 'y', useFinalPosition);
  7046. }
  7047. getCenterPoint(useFinalPosition) {
  7048. const { x , y } = this.getProps([
  7049. 'x',
  7050. 'y'
  7051. ], useFinalPosition);
  7052. return {
  7053. x,
  7054. y
  7055. };
  7056. }
  7057. size(options) {
  7058. options = options || this.options || {};
  7059. let radius = options.radius || 0;
  7060. radius = Math.max(radius, radius && options.hoverRadius || 0);
  7061. const borderWidth = radius && options.borderWidth || 0;
  7062. return (radius + borderWidth) * 2;
  7063. }
  7064. draw(ctx, area) {
  7065. const options = this.options;
  7066. if (this.skip || options.radius < 0.1 || !helpers_segment._isPointInArea(this, area, this.size(options) / 2)) {
  7067. return;
  7068. }
  7069. ctx.strokeStyle = options.borderColor;
  7070. ctx.lineWidth = options.borderWidth;
  7071. ctx.fillStyle = options.backgroundColor;
  7072. helpers_segment.drawPoint(ctx, options, this.x, this.y);
  7073. }
  7074. getRange() {
  7075. const options = this.options || {};
  7076. // @ts-expect-error Fallbacks should never be hit in practice
  7077. return options.radius + options.hitRadius;
  7078. }
  7079. }
  7080. function getBarBounds(bar, useFinalPosition) {
  7081. const { x , y , base , width , height } = bar.getProps([
  7082. 'x',
  7083. 'y',
  7084. 'base',
  7085. 'width',
  7086. 'height'
  7087. ], useFinalPosition);
  7088. let left, right, top, bottom, half;
  7089. if (bar.horizontal) {
  7090. half = height / 2;
  7091. left = Math.min(x, base);
  7092. right = Math.max(x, base);
  7093. top = y - half;
  7094. bottom = y + half;
  7095. } else {
  7096. half = width / 2;
  7097. left = x - half;
  7098. right = x + half;
  7099. top = Math.min(y, base);
  7100. bottom = Math.max(y, base);
  7101. }
  7102. return {
  7103. left,
  7104. top,
  7105. right,
  7106. bottom
  7107. };
  7108. }
  7109. function skipOrLimit(skip, value, min, max) {
  7110. return skip ? 0 : helpers_segment._limitValue(value, min, max);
  7111. }
  7112. function parseBorderWidth(bar, maxW, maxH) {
  7113. const value = bar.options.borderWidth;
  7114. const skip = bar.borderSkipped;
  7115. const o = helpers_segment.toTRBL(value);
  7116. return {
  7117. t: skipOrLimit(skip.top, o.top, 0, maxH),
  7118. r: skipOrLimit(skip.right, o.right, 0, maxW),
  7119. b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),
  7120. l: skipOrLimit(skip.left, o.left, 0, maxW)
  7121. };
  7122. }
  7123. function parseBorderRadius(bar, maxW, maxH) {
  7124. const { enableBorderRadius } = bar.getProps([
  7125. 'enableBorderRadius'
  7126. ]);
  7127. const value = bar.options.borderRadius;
  7128. const o = helpers_segment.toTRBLCorners(value);
  7129. const maxR = Math.min(maxW, maxH);
  7130. const skip = bar.borderSkipped;
  7131. const enableBorder = enableBorderRadius || helpers_segment.isObject(value);
  7132. return {
  7133. topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),
  7134. topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),
  7135. bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),
  7136. bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)
  7137. };
  7138. }
  7139. function boundingRects(bar) {
  7140. const bounds = getBarBounds(bar);
  7141. const width = bounds.right - bounds.left;
  7142. const height = bounds.bottom - bounds.top;
  7143. const border = parseBorderWidth(bar, width / 2, height / 2);
  7144. const radius = parseBorderRadius(bar, width / 2, height / 2);
  7145. return {
  7146. outer: {
  7147. x: bounds.left,
  7148. y: bounds.top,
  7149. w: width,
  7150. h: height,
  7151. radius
  7152. },
  7153. inner: {
  7154. x: bounds.left + border.l,
  7155. y: bounds.top + border.t,
  7156. w: width - border.l - border.r,
  7157. h: height - border.t - border.b,
  7158. radius: {
  7159. topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),
  7160. topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),
  7161. bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),
  7162. bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r))
  7163. }
  7164. }
  7165. };
  7166. }
  7167. function inRange(bar, x, y, useFinalPosition) {
  7168. const skipX = x === null;
  7169. const skipY = y === null;
  7170. const skipBoth = skipX && skipY;
  7171. const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);
  7172. return bounds && (skipX || helpers_segment._isBetween(x, bounds.left, bounds.right)) && (skipY || helpers_segment._isBetween(y, bounds.top, bounds.bottom));
  7173. }
  7174. function hasRadius(radius) {
  7175. return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;
  7176. }
  7177. function addNormalRectPath(ctx, rect) {
  7178. ctx.rect(rect.x, rect.y, rect.w, rect.h);
  7179. }
  7180. function inflateRect(rect, amount, refRect = {}) {
  7181. const x = rect.x !== refRect.x ? -amount : 0;
  7182. const y = rect.y !== refRect.y ? -amount : 0;
  7183. const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x;
  7184. const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y;
  7185. return {
  7186. x: rect.x + x,
  7187. y: rect.y + y,
  7188. w: rect.w + w,
  7189. h: rect.h + h,
  7190. radius: rect.radius
  7191. };
  7192. }
  7193. class BarElement extends Element {
  7194. static id = 'bar';
  7195. static defaults = {
  7196. borderSkipped: 'start',
  7197. borderWidth: 0,
  7198. borderRadius: 0,
  7199. inflateAmount: 'auto',
  7200. pointStyle: undefined
  7201. };
  7202. static defaultRoutes = {
  7203. backgroundColor: 'backgroundColor',
  7204. borderColor: 'borderColor'
  7205. };
  7206. constructor(cfg){
  7207. super();
  7208. this.options = undefined;
  7209. this.horizontal = undefined;
  7210. this.base = undefined;
  7211. this.width = undefined;
  7212. this.height = undefined;
  7213. this.inflateAmount = undefined;
  7214. if (cfg) {
  7215. Object.assign(this, cfg);
  7216. }
  7217. }
  7218. draw(ctx) {
  7219. const { inflateAmount , options: { borderColor , backgroundColor } } = this;
  7220. const { inner , outer } = boundingRects(this);
  7221. const addRectPath = hasRadius(outer.radius) ? helpers_segment.addRoundedRectPath : addNormalRectPath;
  7222. ctx.save();
  7223. if (outer.w !== inner.w || outer.h !== inner.h) {
  7224. ctx.beginPath();
  7225. addRectPath(ctx, inflateRect(outer, inflateAmount, inner));
  7226. ctx.clip();
  7227. addRectPath(ctx, inflateRect(inner, -inflateAmount, outer));
  7228. ctx.fillStyle = borderColor;
  7229. ctx.fill('evenodd');
  7230. }
  7231. ctx.beginPath();
  7232. addRectPath(ctx, inflateRect(inner, inflateAmount));
  7233. ctx.fillStyle = backgroundColor;
  7234. ctx.fill();
  7235. ctx.restore();
  7236. }
  7237. inRange(mouseX, mouseY, useFinalPosition) {
  7238. return inRange(this, mouseX, mouseY, useFinalPosition);
  7239. }
  7240. inXRange(mouseX, useFinalPosition) {
  7241. return inRange(this, mouseX, null, useFinalPosition);
  7242. }
  7243. inYRange(mouseY, useFinalPosition) {
  7244. return inRange(this, null, mouseY, useFinalPosition);
  7245. }
  7246. getCenterPoint(useFinalPosition) {
  7247. const { x , y , base , horizontal } = this.getProps([
  7248. 'x',
  7249. 'y',
  7250. 'base',
  7251. 'horizontal'
  7252. ], useFinalPosition);
  7253. return {
  7254. x: horizontal ? (x + base) / 2 : x,
  7255. y: horizontal ? y : (y + base) / 2
  7256. };
  7257. }
  7258. getRange(axis) {
  7259. return axis === 'x' ? this.width / 2 : this.height / 2;
  7260. }
  7261. }
  7262. var elements = /*#__PURE__*/Object.freeze({
  7263. __proto__: null,
  7264. ArcElement: ArcElement,
  7265. BarElement: BarElement,
  7266. LineElement: LineElement,
  7267. PointElement: PointElement
  7268. });
  7269. const BORDER_COLORS = [
  7270. 'rgb(54, 162, 235)',
  7271. 'rgb(255, 99, 132)',
  7272. 'rgb(255, 159, 64)',
  7273. 'rgb(255, 205, 86)',
  7274. 'rgb(75, 192, 192)',
  7275. 'rgb(153, 102, 255)',
  7276. 'rgb(201, 203, 207)' // grey
  7277. ];
  7278. // Border colors with 50% transparency
  7279. const BACKGROUND_COLORS = /* #__PURE__ */ BORDER_COLORS.map((color)=>color.replace('rgb(', 'rgba(').replace(')', ', 0.5)'));
  7280. function getBorderColor(i) {
  7281. return BORDER_COLORS[i % BORDER_COLORS.length];
  7282. }
  7283. function getBackgroundColor(i) {
  7284. return BACKGROUND_COLORS[i % BACKGROUND_COLORS.length];
  7285. }
  7286. function colorizeDefaultDataset(dataset, i) {
  7287. dataset.borderColor = getBorderColor(i);
  7288. dataset.backgroundColor = getBackgroundColor(i);
  7289. return ++i;
  7290. }
  7291. function colorizeDoughnutDataset(dataset, i) {
  7292. dataset.backgroundColor = dataset.data.map(()=>getBorderColor(i++));
  7293. return i;
  7294. }
  7295. function colorizePolarAreaDataset(dataset, i) {
  7296. dataset.backgroundColor = dataset.data.map(()=>getBackgroundColor(i++));
  7297. return i;
  7298. }
  7299. function getColorizer(chart) {
  7300. let i = 0;
  7301. return (dataset, datasetIndex)=>{
  7302. const controller = chart.getDatasetMeta(datasetIndex).controller;
  7303. if (controller instanceof DoughnutController) {
  7304. i = colorizeDoughnutDataset(dataset, i);
  7305. } else if (controller instanceof PolarAreaController) {
  7306. i = colorizePolarAreaDataset(dataset, i);
  7307. } else if (controller) {
  7308. i = colorizeDefaultDataset(dataset, i);
  7309. }
  7310. };
  7311. }
  7312. function containsColorsDefinitions(descriptors) {
  7313. let k;
  7314. for(k in descriptors){
  7315. if (descriptors[k].borderColor || descriptors[k].backgroundColor) {
  7316. return true;
  7317. }
  7318. }
  7319. return false;
  7320. }
  7321. function containsColorsDefinition(descriptor) {
  7322. return descriptor && (descriptor.borderColor || descriptor.backgroundColor);
  7323. }
  7324. var plugin_colors = {
  7325. id: 'colors',
  7326. defaults: {
  7327. enabled: true,
  7328. forceOverride: false
  7329. },
  7330. beforeLayout (chart, _args, options) {
  7331. if (!options.enabled) {
  7332. return;
  7333. }
  7334. const { data: { datasets } , options: chartOptions } = chart.config;
  7335. const { elements } = chartOptions;
  7336. if (!options.forceOverride && (containsColorsDefinitions(datasets) || containsColorsDefinition(chartOptions) || elements && containsColorsDefinitions(elements))) {
  7337. return;
  7338. }
  7339. const colorizer = getColorizer(chart);
  7340. datasets.forEach(colorizer);
  7341. }
  7342. };
  7343. function lttbDecimation(data, start, count, availableWidth, options) {
  7344. const samples = options.samples || availableWidth;
  7345. if (samples >= count) {
  7346. return data.slice(start, start + count);
  7347. }
  7348. const decimated = [];
  7349. const bucketWidth = (count - 2) / (samples - 2);
  7350. let sampledIndex = 0;
  7351. const endIndex = start + count - 1;
  7352. let a = start;
  7353. let i, maxAreaPoint, maxArea, area, nextA;
  7354. decimated[sampledIndex++] = data[a];
  7355. for(i = 0; i < samples - 2; i++){
  7356. let avgX = 0;
  7357. let avgY = 0;
  7358. let j;
  7359. const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;
  7360. const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;
  7361. const avgRangeLength = avgRangeEnd - avgRangeStart;
  7362. for(j = avgRangeStart; j < avgRangeEnd; j++){
  7363. avgX += data[j].x;
  7364. avgY += data[j].y;
  7365. }
  7366. avgX /= avgRangeLength;
  7367. avgY /= avgRangeLength;
  7368. const rangeOffs = Math.floor(i * bucketWidth) + 1 + start;
  7369. const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start;
  7370. const { x: pointAx , y: pointAy } = data[a];
  7371. maxArea = area = -1;
  7372. for(j = rangeOffs; j < rangeTo; j++){
  7373. area = 0.5 * Math.abs((pointAx - avgX) * (data[j].y - pointAy) - (pointAx - data[j].x) * (avgY - pointAy));
  7374. if (area > maxArea) {
  7375. maxArea = area;
  7376. maxAreaPoint = data[j];
  7377. nextA = j;
  7378. }
  7379. }
  7380. decimated[sampledIndex++] = maxAreaPoint;
  7381. a = nextA;
  7382. }
  7383. decimated[sampledIndex++] = data[endIndex];
  7384. return decimated;
  7385. }
  7386. function minMaxDecimation(data, start, count, availableWidth) {
  7387. let avgX = 0;
  7388. let countX = 0;
  7389. let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;
  7390. const decimated = [];
  7391. const endIndex = start + count - 1;
  7392. const xMin = data[start].x;
  7393. const xMax = data[endIndex].x;
  7394. const dx = xMax - xMin;
  7395. for(i = start; i < start + count; ++i){
  7396. point = data[i];
  7397. x = (point.x - xMin) / dx * availableWidth;
  7398. y = point.y;
  7399. const truncX = x | 0;
  7400. if (truncX === prevX) {
  7401. if (y < minY) {
  7402. minY = y;
  7403. minIndex = i;
  7404. } else if (y > maxY) {
  7405. maxY = y;
  7406. maxIndex = i;
  7407. }
  7408. avgX = (countX * avgX + point.x) / ++countX;
  7409. } else {
  7410. const lastIndex = i - 1;
  7411. if (!helpers_segment.isNullOrUndef(minIndex) && !helpers_segment.isNullOrUndef(maxIndex)) {
  7412. const intermediateIndex1 = Math.min(minIndex, maxIndex);
  7413. const intermediateIndex2 = Math.max(minIndex, maxIndex);
  7414. if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {
  7415. decimated.push({
  7416. ...data[intermediateIndex1],
  7417. x: avgX
  7418. });
  7419. }
  7420. if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {
  7421. decimated.push({
  7422. ...data[intermediateIndex2],
  7423. x: avgX
  7424. });
  7425. }
  7426. }
  7427. if (i > 0 && lastIndex !== startIndex) {
  7428. decimated.push(data[lastIndex]);
  7429. }
  7430. decimated.push(point);
  7431. prevX = truncX;
  7432. countX = 0;
  7433. minY = maxY = y;
  7434. minIndex = maxIndex = startIndex = i;
  7435. }
  7436. }
  7437. return decimated;
  7438. }
  7439. function cleanDecimatedDataset(dataset) {
  7440. if (dataset._decimated) {
  7441. const data = dataset._data;
  7442. delete dataset._decimated;
  7443. delete dataset._data;
  7444. Object.defineProperty(dataset, 'data', {
  7445. configurable: true,
  7446. enumerable: true,
  7447. writable: true,
  7448. value: data
  7449. });
  7450. }
  7451. }
  7452. function cleanDecimatedData(chart) {
  7453. chart.data.datasets.forEach((dataset)=>{
  7454. cleanDecimatedDataset(dataset);
  7455. });
  7456. }
  7457. function getStartAndCountOfVisiblePointsSimplified(meta, points) {
  7458. const pointCount = points.length;
  7459. let start = 0;
  7460. let count;
  7461. const { iScale } = meta;
  7462. const { min , max , minDefined , maxDefined } = iScale.getUserBounds();
  7463. if (minDefined) {
  7464. start = helpers_segment._limitValue(helpers_segment._lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);
  7465. }
  7466. if (maxDefined) {
  7467. count = helpers_segment._limitValue(helpers_segment._lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;
  7468. } else {
  7469. count = pointCount - start;
  7470. }
  7471. return {
  7472. start,
  7473. count
  7474. };
  7475. }
  7476. var plugin_decimation = {
  7477. id: 'decimation',
  7478. defaults: {
  7479. algorithm: 'min-max',
  7480. enabled: false
  7481. },
  7482. beforeElementsUpdate: (chart, args, options)=>{
  7483. if (!options.enabled) {
  7484. cleanDecimatedData(chart);
  7485. return;
  7486. }
  7487. const availableWidth = chart.width;
  7488. chart.data.datasets.forEach((dataset, datasetIndex)=>{
  7489. const { _data , indexAxis } = dataset;
  7490. const meta = chart.getDatasetMeta(datasetIndex);
  7491. const data = _data || dataset.data;
  7492. if (helpers_segment.resolve([
  7493. indexAxis,
  7494. chart.options.indexAxis
  7495. ]) === 'y') {
  7496. return;
  7497. }
  7498. if (!meta.controller.supportsDecimation) {
  7499. return;
  7500. }
  7501. const xAxis = chart.scales[meta.xAxisID];
  7502. if (xAxis.type !== 'linear' && xAxis.type !== 'time') {
  7503. return;
  7504. }
  7505. if (chart.options.parsing) {
  7506. return;
  7507. }
  7508. let { start , count } = getStartAndCountOfVisiblePointsSimplified(meta, data);
  7509. const threshold = options.threshold || 4 * availableWidth;
  7510. if (count <= threshold) {
  7511. cleanDecimatedDataset(dataset);
  7512. return;
  7513. }
  7514. if (helpers_segment.isNullOrUndef(_data)) {
  7515. dataset._data = data;
  7516. delete dataset.data;
  7517. Object.defineProperty(dataset, 'data', {
  7518. configurable: true,
  7519. enumerable: true,
  7520. get: function() {
  7521. return this._decimated;
  7522. },
  7523. set: function(d) {
  7524. this._data = d;
  7525. }
  7526. });
  7527. }
  7528. let decimated;
  7529. switch(options.algorithm){
  7530. case 'lttb':
  7531. decimated = lttbDecimation(data, start, count, availableWidth, options);
  7532. break;
  7533. case 'min-max':
  7534. decimated = minMaxDecimation(data, start, count, availableWidth);
  7535. break;
  7536. default:
  7537. throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);
  7538. }
  7539. dataset._decimated = decimated;
  7540. });
  7541. },
  7542. destroy (chart) {
  7543. cleanDecimatedData(chart);
  7544. }
  7545. };
  7546. function _segments(line, target, property) {
  7547. const segments = line.segments;
  7548. const points = line.points;
  7549. const tpoints = target.points;
  7550. const parts = [];
  7551. for (const segment of segments){
  7552. let { start , end } = segment;
  7553. end = _findSegmentEnd(start, end, points);
  7554. const bounds = _getBounds(property, points[start], points[end], segment.loop);
  7555. if (!target.segments) {
  7556. parts.push({
  7557. source: segment,
  7558. target: bounds,
  7559. start: points[start],
  7560. end: points[end]
  7561. });
  7562. continue;
  7563. }
  7564. const targetSegments = helpers_segment._boundSegments(target, bounds);
  7565. for (const tgt of targetSegments){
  7566. const subBounds = _getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);
  7567. const fillSources = helpers_segment._boundSegment(segment, points, subBounds);
  7568. for (const fillSource of fillSources){
  7569. parts.push({
  7570. source: fillSource,
  7571. target: tgt,
  7572. start: {
  7573. [property]: _getEdge(bounds, subBounds, 'start', Math.max)
  7574. },
  7575. end: {
  7576. [property]: _getEdge(bounds, subBounds, 'end', Math.min)
  7577. }
  7578. });
  7579. }
  7580. }
  7581. }
  7582. return parts;
  7583. }
  7584. function _getBounds(property, first, last, loop) {
  7585. if (loop) {
  7586. return;
  7587. }
  7588. let start = first[property];
  7589. let end = last[property];
  7590. if (property === 'angle') {
  7591. start = helpers_segment._normalizeAngle(start);
  7592. end = helpers_segment._normalizeAngle(end);
  7593. }
  7594. return {
  7595. property,
  7596. start,
  7597. end
  7598. };
  7599. }
  7600. function _pointsFromSegments(boundary, line) {
  7601. const { x =null , y =null } = boundary || {};
  7602. const linePoints = line.points;
  7603. const points = [];
  7604. line.segments.forEach(({ start , end })=>{
  7605. end = _findSegmentEnd(start, end, linePoints);
  7606. const first = linePoints[start];
  7607. const last = linePoints[end];
  7608. if (y !== null) {
  7609. points.push({
  7610. x: first.x,
  7611. y
  7612. });
  7613. points.push({
  7614. x: last.x,
  7615. y
  7616. });
  7617. } else if (x !== null) {
  7618. points.push({
  7619. x,
  7620. y: first.y
  7621. });
  7622. points.push({
  7623. x,
  7624. y: last.y
  7625. });
  7626. }
  7627. });
  7628. return points;
  7629. }
  7630. function _findSegmentEnd(start, end, points) {
  7631. for(; end > start; end--){
  7632. const point = points[end];
  7633. if (!isNaN(point.x) && !isNaN(point.y)) {
  7634. break;
  7635. }
  7636. }
  7637. return end;
  7638. }
  7639. function _getEdge(a, b, prop, fn) {
  7640. if (a && b) {
  7641. return fn(a[prop], b[prop]);
  7642. }
  7643. return a ? a[prop] : b ? b[prop] : 0;
  7644. }
  7645. function _createBoundaryLine(boundary, line) {
  7646. let points = [];
  7647. let _loop = false;
  7648. if (helpers_segment.isArray(boundary)) {
  7649. _loop = true;
  7650. points = boundary;
  7651. } else {
  7652. points = _pointsFromSegments(boundary, line);
  7653. }
  7654. return points.length ? new LineElement({
  7655. points,
  7656. options: {
  7657. tension: 0
  7658. },
  7659. _loop,
  7660. _fullLoop: _loop
  7661. }) : null;
  7662. }
  7663. function _shouldApplyFill(source) {
  7664. return source && source.fill !== false;
  7665. }
  7666. function _resolveTarget(sources, index, propagate) {
  7667. const source = sources[index];
  7668. let fill = source.fill;
  7669. const visited = [
  7670. index
  7671. ];
  7672. let target;
  7673. if (!propagate) {
  7674. return fill;
  7675. }
  7676. while(fill !== false && visited.indexOf(fill) === -1){
  7677. if (!helpers_segment.isNumberFinite(fill)) {
  7678. return fill;
  7679. }
  7680. target = sources[fill];
  7681. if (!target) {
  7682. return false;
  7683. }
  7684. if (target.visible) {
  7685. return fill;
  7686. }
  7687. visited.push(fill);
  7688. fill = target.fill;
  7689. }
  7690. return false;
  7691. }
  7692. function _decodeFill(line, index, count) {
  7693. const fill = parseFillOption(line);
  7694. if (helpers_segment.isObject(fill)) {
  7695. return isNaN(fill.value) ? false : fill;
  7696. }
  7697. let target = parseFloat(fill);
  7698. if (helpers_segment.isNumberFinite(target) && Math.floor(target) === target) {
  7699. return decodeTargetIndex(fill[0], index, target, count);
  7700. }
  7701. return [
  7702. 'origin',
  7703. 'start',
  7704. 'end',
  7705. 'stack',
  7706. 'shape'
  7707. ].indexOf(fill) >= 0 && fill;
  7708. }
  7709. function decodeTargetIndex(firstCh, index, target, count) {
  7710. if (firstCh === '-' || firstCh === '+') {
  7711. target = index + target;
  7712. }
  7713. if (target === index || target < 0 || target >= count) {
  7714. return false;
  7715. }
  7716. return target;
  7717. }
  7718. function _getTargetPixel(fill, scale) {
  7719. let pixel = null;
  7720. if (fill === 'start') {
  7721. pixel = scale.bottom;
  7722. } else if (fill === 'end') {
  7723. pixel = scale.top;
  7724. } else if (helpers_segment.isObject(fill)) {
  7725. pixel = scale.getPixelForValue(fill.value);
  7726. } else if (scale.getBasePixel) {
  7727. pixel = scale.getBasePixel();
  7728. }
  7729. return pixel;
  7730. }
  7731. function _getTargetValue(fill, scale, startValue) {
  7732. let value;
  7733. if (fill === 'start') {
  7734. value = startValue;
  7735. } else if (fill === 'end') {
  7736. value = scale.options.reverse ? scale.min : scale.max;
  7737. } else if (helpers_segment.isObject(fill)) {
  7738. value = fill.value;
  7739. } else {
  7740. value = scale.getBaseValue();
  7741. }
  7742. return value;
  7743. }
  7744. function parseFillOption(line) {
  7745. const options = line.options;
  7746. const fillOption = options.fill;
  7747. let fill = helpers_segment.valueOrDefault(fillOption && fillOption.target, fillOption);
  7748. if (fill === undefined) {
  7749. fill = !!options.backgroundColor;
  7750. }
  7751. if (fill === false || fill === null) {
  7752. return false;
  7753. }
  7754. if (fill === true) {
  7755. return 'origin';
  7756. }
  7757. return fill;
  7758. }
  7759. function _buildStackLine(source) {
  7760. const { scale , index , line } = source;
  7761. const points = [];
  7762. const segments = line.segments;
  7763. const sourcePoints = line.points;
  7764. const linesBelow = getLinesBelow(scale, index);
  7765. linesBelow.push(_createBoundaryLine({
  7766. x: null,
  7767. y: scale.bottom
  7768. }, line));
  7769. for(let i = 0; i < segments.length; i++){
  7770. const segment = segments[i];
  7771. for(let j = segment.start; j <= segment.end; j++){
  7772. addPointsBelow(points, sourcePoints[j], linesBelow);
  7773. }
  7774. }
  7775. return new LineElement({
  7776. points,
  7777. options: {}
  7778. });
  7779. }
  7780. function getLinesBelow(scale, index) {
  7781. const below = [];
  7782. const metas = scale.getMatchingVisibleMetas('line');
  7783. for(let i = 0; i < metas.length; i++){
  7784. const meta = metas[i];
  7785. if (meta.index === index) {
  7786. break;
  7787. }
  7788. if (!meta.hidden) {
  7789. below.unshift(meta.dataset);
  7790. }
  7791. }
  7792. return below;
  7793. }
  7794. function addPointsBelow(points, sourcePoint, linesBelow) {
  7795. const postponed = [];
  7796. for(let j = 0; j < linesBelow.length; j++){
  7797. const line = linesBelow[j];
  7798. const { first , last , point } = findPoint(line, sourcePoint, 'x');
  7799. if (!point || first && last) {
  7800. continue;
  7801. }
  7802. if (first) {
  7803. postponed.unshift(point);
  7804. } else {
  7805. points.push(point);
  7806. if (!last) {
  7807. break;
  7808. }
  7809. }
  7810. }
  7811. points.push(...postponed);
  7812. }
  7813. function findPoint(line, sourcePoint, property) {
  7814. const point = line.interpolate(sourcePoint, property);
  7815. if (!point) {
  7816. return {};
  7817. }
  7818. const pointValue = point[property];
  7819. const segments = line.segments;
  7820. const linePoints = line.points;
  7821. let first = false;
  7822. let last = false;
  7823. for(let i = 0; i < segments.length; i++){
  7824. const segment = segments[i];
  7825. const firstValue = linePoints[segment.start][property];
  7826. const lastValue = linePoints[segment.end][property];
  7827. if (helpers_segment._isBetween(pointValue, firstValue, lastValue)) {
  7828. first = pointValue === firstValue;
  7829. last = pointValue === lastValue;
  7830. break;
  7831. }
  7832. }
  7833. return {
  7834. first,
  7835. last,
  7836. point
  7837. };
  7838. }
  7839. class simpleArc {
  7840. constructor(opts){
  7841. this.x = opts.x;
  7842. this.y = opts.y;
  7843. this.radius = opts.radius;
  7844. }
  7845. pathSegment(ctx, bounds, opts) {
  7846. const { x , y , radius } = this;
  7847. bounds = bounds || {
  7848. start: 0,
  7849. end: helpers_segment.TAU
  7850. };
  7851. ctx.arc(x, y, radius, bounds.end, bounds.start, true);
  7852. return !opts.bounds;
  7853. }
  7854. interpolate(point) {
  7855. const { x , y , radius } = this;
  7856. const angle = point.angle;
  7857. return {
  7858. x: x + Math.cos(angle) * radius,
  7859. y: y + Math.sin(angle) * radius,
  7860. angle
  7861. };
  7862. }
  7863. }
  7864. function _getTarget(source) {
  7865. const { chart , fill , line } = source;
  7866. if (helpers_segment.isNumberFinite(fill)) {
  7867. return getLineByIndex(chart, fill);
  7868. }
  7869. if (fill === 'stack') {
  7870. return _buildStackLine(source);
  7871. }
  7872. if (fill === 'shape') {
  7873. return true;
  7874. }
  7875. const boundary = computeBoundary(source);
  7876. if (boundary instanceof simpleArc) {
  7877. return boundary;
  7878. }
  7879. return _createBoundaryLine(boundary, line);
  7880. }
  7881. function getLineByIndex(chart, index) {
  7882. const meta = chart.getDatasetMeta(index);
  7883. const visible = meta && chart.isDatasetVisible(index);
  7884. return visible ? meta.dataset : null;
  7885. }
  7886. function computeBoundary(source) {
  7887. const scale = source.scale || {};
  7888. if (scale.getPointPositionForValue) {
  7889. return computeCircularBoundary(source);
  7890. }
  7891. return computeLinearBoundary(source);
  7892. }
  7893. function computeLinearBoundary(source) {
  7894. const { scale ={} , fill } = source;
  7895. const pixel = _getTargetPixel(fill, scale);
  7896. if (helpers_segment.isNumberFinite(pixel)) {
  7897. const horizontal = scale.isHorizontal();
  7898. return {
  7899. x: horizontal ? pixel : null,
  7900. y: horizontal ? null : pixel
  7901. };
  7902. }
  7903. return null;
  7904. }
  7905. function computeCircularBoundary(source) {
  7906. const { scale , fill } = source;
  7907. const options = scale.options;
  7908. const length = scale.getLabels().length;
  7909. const start = options.reverse ? scale.max : scale.min;
  7910. const value = _getTargetValue(fill, scale, start);
  7911. const target = [];
  7912. if (options.grid.circular) {
  7913. const center = scale.getPointPositionForValue(0, start);
  7914. return new simpleArc({
  7915. x: center.x,
  7916. y: center.y,
  7917. radius: scale.getDistanceFromCenterForValue(value)
  7918. });
  7919. }
  7920. for(let i = 0; i < length; ++i){
  7921. target.push(scale.getPointPositionForValue(i, value));
  7922. }
  7923. return target;
  7924. }
  7925. function _drawfill(ctx, source, area) {
  7926. const target = _getTarget(source);
  7927. const { line , scale , axis } = source;
  7928. const lineOpts = line.options;
  7929. const fillOption = lineOpts.fill;
  7930. const color = lineOpts.backgroundColor;
  7931. const { above =color , below =color } = fillOption || {};
  7932. if (target && line.points.length) {
  7933. helpers_segment.clipArea(ctx, area);
  7934. doFill(ctx, {
  7935. line,
  7936. target,
  7937. above,
  7938. below,
  7939. area,
  7940. scale,
  7941. axis
  7942. });
  7943. helpers_segment.unclipArea(ctx);
  7944. }
  7945. }
  7946. function doFill(ctx, cfg) {
  7947. const { line , target , above , below , area , scale } = cfg;
  7948. const property = line._loop ? 'angle' : cfg.axis;
  7949. ctx.save();
  7950. if (property === 'x' && below !== above) {
  7951. clipVertical(ctx, target, area.top);
  7952. fill(ctx, {
  7953. line,
  7954. target,
  7955. color: above,
  7956. scale,
  7957. property
  7958. });
  7959. ctx.restore();
  7960. ctx.save();
  7961. clipVertical(ctx, target, area.bottom);
  7962. }
  7963. fill(ctx, {
  7964. line,
  7965. target,
  7966. color: below,
  7967. scale,
  7968. property
  7969. });
  7970. ctx.restore();
  7971. }
  7972. function clipVertical(ctx, target, clipY) {
  7973. const { segments , points } = target;
  7974. let first = true;
  7975. let lineLoop = false;
  7976. ctx.beginPath();
  7977. for (const segment of segments){
  7978. const { start , end } = segment;
  7979. const firstPoint = points[start];
  7980. const lastPoint = points[_findSegmentEnd(start, end, points)];
  7981. if (first) {
  7982. ctx.moveTo(firstPoint.x, firstPoint.y);
  7983. first = false;
  7984. } else {
  7985. ctx.lineTo(firstPoint.x, clipY);
  7986. ctx.lineTo(firstPoint.x, firstPoint.y);
  7987. }
  7988. lineLoop = !!target.pathSegment(ctx, segment, {
  7989. move: lineLoop
  7990. });
  7991. if (lineLoop) {
  7992. ctx.closePath();
  7993. } else {
  7994. ctx.lineTo(lastPoint.x, clipY);
  7995. }
  7996. }
  7997. ctx.lineTo(target.first().x, clipY);
  7998. ctx.closePath();
  7999. ctx.clip();
  8000. }
  8001. function fill(ctx, cfg) {
  8002. const { line , target , property , color , scale } = cfg;
  8003. const segments = _segments(line, target, property);
  8004. for (const { source: src , target: tgt , start , end } of segments){
  8005. const { style: { backgroundColor =color } = {} } = src;
  8006. const notShape = target !== true;
  8007. ctx.save();
  8008. ctx.fillStyle = backgroundColor;
  8009. clipBounds(ctx, scale, notShape && _getBounds(property, start, end));
  8010. ctx.beginPath();
  8011. const lineLoop = !!line.pathSegment(ctx, src);
  8012. let loop;
  8013. if (notShape) {
  8014. if (lineLoop) {
  8015. ctx.closePath();
  8016. } else {
  8017. interpolatedLineTo(ctx, target, end, property);
  8018. }
  8019. const targetLoop = !!target.pathSegment(ctx, tgt, {
  8020. move: lineLoop,
  8021. reverse: true
  8022. });
  8023. loop = lineLoop && targetLoop;
  8024. if (!loop) {
  8025. interpolatedLineTo(ctx, target, start, property);
  8026. }
  8027. }
  8028. ctx.closePath();
  8029. ctx.fill(loop ? 'evenodd' : 'nonzero');
  8030. ctx.restore();
  8031. }
  8032. }
  8033. function clipBounds(ctx, scale, bounds) {
  8034. const { top , bottom } = scale.chart.chartArea;
  8035. const { property , start , end } = bounds || {};
  8036. if (property === 'x') {
  8037. ctx.beginPath();
  8038. ctx.rect(start, top, end - start, bottom - top);
  8039. ctx.clip();
  8040. }
  8041. }
  8042. function interpolatedLineTo(ctx, target, point, property) {
  8043. const interpolatedPoint = target.interpolate(point, property);
  8044. if (interpolatedPoint) {
  8045. ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);
  8046. }
  8047. }
  8048. var index = {
  8049. id: 'filler',
  8050. afterDatasetsUpdate (chart, _args, options) {
  8051. const count = (chart.data.datasets || []).length;
  8052. const sources = [];
  8053. let meta, i, line, source;
  8054. for(i = 0; i < count; ++i){
  8055. meta = chart.getDatasetMeta(i);
  8056. line = meta.dataset;
  8057. source = null;
  8058. if (line && line.options && line instanceof LineElement) {
  8059. source = {
  8060. visible: chart.isDatasetVisible(i),
  8061. index: i,
  8062. fill: _decodeFill(line, i, count),
  8063. chart,
  8064. axis: meta.controller.options.indexAxis,
  8065. scale: meta.vScale,
  8066. line
  8067. };
  8068. }
  8069. meta.$filler = source;
  8070. sources.push(source);
  8071. }
  8072. for(i = 0; i < count; ++i){
  8073. source = sources[i];
  8074. if (!source || source.fill === false) {
  8075. continue;
  8076. }
  8077. source.fill = _resolveTarget(sources, i, options.propagate);
  8078. }
  8079. },
  8080. beforeDraw (chart, _args, options) {
  8081. const draw = options.drawTime === 'beforeDraw';
  8082. const metasets = chart.getSortedVisibleDatasetMetas();
  8083. const area = chart.chartArea;
  8084. for(let i = metasets.length - 1; i >= 0; --i){
  8085. const source = metasets[i].$filler;
  8086. if (!source) {
  8087. continue;
  8088. }
  8089. source.line.updateControlPoints(area, source.axis);
  8090. if (draw && source.fill) {
  8091. _drawfill(chart.ctx, source, area);
  8092. }
  8093. }
  8094. },
  8095. beforeDatasetsDraw (chart, _args, options) {
  8096. if (options.drawTime !== 'beforeDatasetsDraw') {
  8097. return;
  8098. }
  8099. const metasets = chart.getSortedVisibleDatasetMetas();
  8100. for(let i = metasets.length - 1; i >= 0; --i){
  8101. const source = metasets[i].$filler;
  8102. if (_shouldApplyFill(source)) {
  8103. _drawfill(chart.ctx, source, chart.chartArea);
  8104. }
  8105. }
  8106. },
  8107. beforeDatasetDraw (chart, args, options) {
  8108. const source = args.meta.$filler;
  8109. if (!_shouldApplyFill(source) || options.drawTime !== 'beforeDatasetDraw') {
  8110. return;
  8111. }
  8112. _drawfill(chart.ctx, source, chart.chartArea);
  8113. },
  8114. defaults: {
  8115. propagate: true,
  8116. drawTime: 'beforeDatasetDraw'
  8117. }
  8118. };
  8119. const getBoxSize = (labelOpts, fontSize)=>{
  8120. let { boxHeight =fontSize , boxWidth =fontSize } = labelOpts;
  8121. if (labelOpts.usePointStyle) {
  8122. boxHeight = Math.min(boxHeight, fontSize);
  8123. boxWidth = labelOpts.pointStyleWidth || Math.min(boxWidth, fontSize);
  8124. }
  8125. return {
  8126. boxWidth,
  8127. boxHeight,
  8128. itemHeight: Math.max(fontSize, boxHeight)
  8129. };
  8130. };
  8131. const itemsEqual = (a, b)=>a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;
  8132. class Legend extends Element {
  8133. constructor(config){
  8134. super();
  8135. this._added = false;
  8136. this.legendHitBoxes = [];
  8137. this._hoveredItem = null;
  8138. this.doughnutMode = false;
  8139. this.chart = config.chart;
  8140. this.options = config.options;
  8141. this.ctx = config.ctx;
  8142. this.legendItems = undefined;
  8143. this.columnSizes = undefined;
  8144. this.lineWidths = undefined;
  8145. this.maxHeight = undefined;
  8146. this.maxWidth = undefined;
  8147. this.top = undefined;
  8148. this.bottom = undefined;
  8149. this.left = undefined;
  8150. this.right = undefined;
  8151. this.height = undefined;
  8152. this.width = undefined;
  8153. this._margins = undefined;
  8154. this.position = undefined;
  8155. this.weight = undefined;
  8156. this.fullSize = undefined;
  8157. }
  8158. update(maxWidth, maxHeight, margins) {
  8159. this.maxWidth = maxWidth;
  8160. this.maxHeight = maxHeight;
  8161. this._margins = margins;
  8162. this.setDimensions();
  8163. this.buildLabels();
  8164. this.fit();
  8165. }
  8166. setDimensions() {
  8167. if (this.isHorizontal()) {
  8168. this.width = this.maxWidth;
  8169. this.left = this._margins.left;
  8170. this.right = this.width;
  8171. } else {
  8172. this.height = this.maxHeight;
  8173. this.top = this._margins.top;
  8174. this.bottom = this.height;
  8175. }
  8176. }
  8177. buildLabels() {
  8178. const labelOpts = this.options.labels || {};
  8179. let legendItems = helpers_segment.callback(labelOpts.generateLabels, [
  8180. this.chart
  8181. ], this) || [];
  8182. if (labelOpts.filter) {
  8183. legendItems = legendItems.filter((item)=>labelOpts.filter(item, this.chart.data));
  8184. }
  8185. if (labelOpts.sort) {
  8186. legendItems = legendItems.sort((a, b)=>labelOpts.sort(a, b, this.chart.data));
  8187. }
  8188. if (this.options.reverse) {
  8189. legendItems.reverse();
  8190. }
  8191. this.legendItems = legendItems;
  8192. }
  8193. fit() {
  8194. const { options , ctx } = this;
  8195. if (!options.display) {
  8196. this.width = this.height = 0;
  8197. return;
  8198. }
  8199. const labelOpts = options.labels;
  8200. const labelFont = helpers_segment.toFont(labelOpts.font);
  8201. const fontSize = labelFont.size;
  8202. const titleHeight = this._computeTitleHeight();
  8203. const { boxWidth , itemHeight } = getBoxSize(labelOpts, fontSize);
  8204. let width, height;
  8205. ctx.font = labelFont.string;
  8206. if (this.isHorizontal()) {
  8207. width = this.maxWidth;
  8208. height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;
  8209. } else {
  8210. height = this.maxHeight;
  8211. width = this._fitCols(titleHeight, labelFont, boxWidth, itemHeight) + 10;
  8212. }
  8213. this.width = Math.min(width, options.maxWidth || this.maxWidth);
  8214. this.height = Math.min(height, options.maxHeight || this.maxHeight);
  8215. }
  8216. _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {
  8217. const { ctx , maxWidth , options: { labels: { padding } } } = this;
  8218. const hitboxes = this.legendHitBoxes = [];
  8219. const lineWidths = this.lineWidths = [
  8220. 0
  8221. ];
  8222. const lineHeight = itemHeight + padding;
  8223. let totalHeight = titleHeight;
  8224. ctx.textAlign = 'left';
  8225. ctx.textBaseline = 'middle';
  8226. let row = -1;
  8227. let top = -lineHeight;
  8228. this.legendItems.forEach((legendItem, i)=>{
  8229. const itemWidth = boxWidth + fontSize / 2 + ctx.measureText(legendItem.text).width;
  8230. if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {
  8231. totalHeight += lineHeight;
  8232. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  8233. top += lineHeight;
  8234. row++;
  8235. }
  8236. hitboxes[i] = {
  8237. left: 0,
  8238. top,
  8239. row,
  8240. width: itemWidth,
  8241. height: itemHeight
  8242. };
  8243. lineWidths[lineWidths.length - 1] += itemWidth + padding;
  8244. });
  8245. return totalHeight;
  8246. }
  8247. _fitCols(titleHeight, labelFont, boxWidth, _itemHeight) {
  8248. const { ctx , maxHeight , options: { labels: { padding } } } = this;
  8249. const hitboxes = this.legendHitBoxes = [];
  8250. const columnSizes = this.columnSizes = [];
  8251. const heightLimit = maxHeight - titleHeight;
  8252. let totalWidth = padding;
  8253. let currentColWidth = 0;
  8254. let currentColHeight = 0;
  8255. let left = 0;
  8256. let col = 0;
  8257. this.legendItems.forEach((legendItem, i)=>{
  8258. const { itemWidth , itemHeight } = calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight);
  8259. if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) {
  8260. totalWidth += currentColWidth + padding;
  8261. columnSizes.push({
  8262. width: currentColWidth,
  8263. height: currentColHeight
  8264. });
  8265. left += currentColWidth + padding;
  8266. col++;
  8267. currentColWidth = currentColHeight = 0;
  8268. }
  8269. hitboxes[i] = {
  8270. left,
  8271. top: currentColHeight,
  8272. col,
  8273. width: itemWidth,
  8274. height: itemHeight
  8275. };
  8276. currentColWidth = Math.max(currentColWidth, itemWidth);
  8277. currentColHeight += itemHeight + padding;
  8278. });
  8279. totalWidth += currentColWidth;
  8280. columnSizes.push({
  8281. width: currentColWidth,
  8282. height: currentColHeight
  8283. });
  8284. return totalWidth;
  8285. }
  8286. adjustHitBoxes() {
  8287. if (!this.options.display) {
  8288. return;
  8289. }
  8290. const titleHeight = this._computeTitleHeight();
  8291. const { legendHitBoxes: hitboxes , options: { align , labels: { padding } , rtl } } = this;
  8292. const rtlHelper = helpers_segment.getRtlAdapter(rtl, this.left, this.width);
  8293. if (this.isHorizontal()) {
  8294. let row = 0;
  8295. let left = helpers_segment._alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);
  8296. for (const hitbox of hitboxes){
  8297. if (row !== hitbox.row) {
  8298. row = hitbox.row;
  8299. left = helpers_segment._alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);
  8300. }
  8301. hitbox.top += this.top + titleHeight + padding;
  8302. hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width);
  8303. left += hitbox.width + padding;
  8304. }
  8305. } else {
  8306. let col = 0;
  8307. let top = helpers_segment._alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);
  8308. for (const hitbox of hitboxes){
  8309. if (hitbox.col !== col) {
  8310. col = hitbox.col;
  8311. top = helpers_segment._alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);
  8312. }
  8313. hitbox.top = top;
  8314. hitbox.left += this.left + padding;
  8315. hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width);
  8316. top += hitbox.height + padding;
  8317. }
  8318. }
  8319. }
  8320. isHorizontal() {
  8321. return this.options.position === 'top' || this.options.position === 'bottom';
  8322. }
  8323. draw() {
  8324. if (this.options.display) {
  8325. const ctx = this.ctx;
  8326. helpers_segment.clipArea(ctx, this);
  8327. this._draw();
  8328. helpers_segment.unclipArea(ctx);
  8329. }
  8330. }
  8331. _draw() {
  8332. const { options: opts , columnSizes , lineWidths , ctx } = this;
  8333. const { align , labels: labelOpts } = opts;
  8334. const defaultColor = helpers_segment.defaults.color;
  8335. const rtlHelper = helpers_segment.getRtlAdapter(opts.rtl, this.left, this.width);
  8336. const labelFont = helpers_segment.toFont(labelOpts.font);
  8337. const { padding } = labelOpts;
  8338. const fontSize = labelFont.size;
  8339. const halfFontSize = fontSize / 2;
  8340. let cursor;
  8341. this.drawTitle();
  8342. ctx.textAlign = rtlHelper.textAlign('left');
  8343. ctx.textBaseline = 'middle';
  8344. ctx.lineWidth = 0.5;
  8345. ctx.font = labelFont.string;
  8346. const { boxWidth , boxHeight , itemHeight } = getBoxSize(labelOpts, fontSize);
  8347. const drawLegendBox = function(x, y, legendItem) {
  8348. if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {
  8349. return;
  8350. }
  8351. ctx.save();
  8352. const lineWidth = helpers_segment.valueOrDefault(legendItem.lineWidth, 1);
  8353. ctx.fillStyle = helpers_segment.valueOrDefault(legendItem.fillStyle, defaultColor);
  8354. ctx.lineCap = helpers_segment.valueOrDefault(legendItem.lineCap, 'butt');
  8355. ctx.lineDashOffset = helpers_segment.valueOrDefault(legendItem.lineDashOffset, 0);
  8356. ctx.lineJoin = helpers_segment.valueOrDefault(legendItem.lineJoin, 'miter');
  8357. ctx.lineWidth = lineWidth;
  8358. ctx.strokeStyle = helpers_segment.valueOrDefault(legendItem.strokeStyle, defaultColor);
  8359. ctx.setLineDash(helpers_segment.valueOrDefault(legendItem.lineDash, []));
  8360. if (labelOpts.usePointStyle) {
  8361. const drawOptions = {
  8362. radius: boxHeight * Math.SQRT2 / 2,
  8363. pointStyle: legendItem.pointStyle,
  8364. rotation: legendItem.rotation,
  8365. borderWidth: lineWidth
  8366. };
  8367. const centerX = rtlHelper.xPlus(x, boxWidth / 2);
  8368. const centerY = y + halfFontSize;
  8369. helpers_segment.drawPointLegend(ctx, drawOptions, centerX, centerY, labelOpts.pointStyleWidth && boxWidth);
  8370. } else {
  8371. const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);
  8372. const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);
  8373. const borderRadius = helpers_segment.toTRBLCorners(legendItem.borderRadius);
  8374. ctx.beginPath();
  8375. if (Object.values(borderRadius).some((v)=>v !== 0)) {
  8376. helpers_segment.addRoundedRectPath(ctx, {
  8377. x: xBoxLeft,
  8378. y: yBoxTop,
  8379. w: boxWidth,
  8380. h: boxHeight,
  8381. radius: borderRadius
  8382. });
  8383. } else {
  8384. ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);
  8385. }
  8386. ctx.fill();
  8387. if (lineWidth !== 0) {
  8388. ctx.stroke();
  8389. }
  8390. }
  8391. ctx.restore();
  8392. };
  8393. const fillText = function(x, y, legendItem) {
  8394. helpers_segment.renderText(ctx, legendItem.text, x, y + itemHeight / 2, labelFont, {
  8395. strikethrough: legendItem.hidden,
  8396. textAlign: rtlHelper.textAlign(legendItem.textAlign)
  8397. });
  8398. };
  8399. const isHorizontal = this.isHorizontal();
  8400. const titleHeight = this._computeTitleHeight();
  8401. if (isHorizontal) {
  8402. cursor = {
  8403. x: helpers_segment._alignStartEnd(align, this.left + padding, this.right - lineWidths[0]),
  8404. y: this.top + padding + titleHeight,
  8405. line: 0
  8406. };
  8407. } else {
  8408. cursor = {
  8409. x: this.left + padding,
  8410. y: helpers_segment._alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height),
  8411. line: 0
  8412. };
  8413. }
  8414. helpers_segment.overrideTextDirection(this.ctx, opts.textDirection);
  8415. const lineHeight = itemHeight + padding;
  8416. this.legendItems.forEach((legendItem, i)=>{
  8417. ctx.strokeStyle = legendItem.fontColor;
  8418. ctx.fillStyle = legendItem.fontColor;
  8419. const textWidth = ctx.measureText(legendItem.text).width;
  8420. const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));
  8421. const width = boxWidth + halfFontSize + textWidth;
  8422. let x = cursor.x;
  8423. let y = cursor.y;
  8424. rtlHelper.setWidth(this.width);
  8425. if (isHorizontal) {
  8426. if (i > 0 && x + width + padding > this.right) {
  8427. y = cursor.y += lineHeight;
  8428. cursor.line++;
  8429. x = cursor.x = helpers_segment._alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]);
  8430. }
  8431. } else if (i > 0 && y + lineHeight > this.bottom) {
  8432. x = cursor.x = x + columnSizes[cursor.line].width + padding;
  8433. cursor.line++;
  8434. y = cursor.y = helpers_segment._alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height);
  8435. }
  8436. const realX = rtlHelper.x(x);
  8437. drawLegendBox(realX, y, legendItem);
  8438. x = helpers_segment._textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl);
  8439. fillText(rtlHelper.x(x), y, legendItem);
  8440. if (isHorizontal) {
  8441. cursor.x += width + padding;
  8442. } else if (typeof legendItem.text !== 'string') {
  8443. const fontLineHeight = labelFont.lineHeight;
  8444. cursor.y += calculateLegendItemHeight(legendItem, fontLineHeight) + padding;
  8445. } else {
  8446. cursor.y += lineHeight;
  8447. }
  8448. });
  8449. helpers_segment.restoreTextDirection(this.ctx, opts.textDirection);
  8450. }
  8451. drawTitle() {
  8452. const opts = this.options;
  8453. const titleOpts = opts.title;
  8454. const titleFont = helpers_segment.toFont(titleOpts.font);
  8455. const titlePadding = helpers_segment.toPadding(titleOpts.padding);
  8456. if (!titleOpts.display) {
  8457. return;
  8458. }
  8459. const rtlHelper = helpers_segment.getRtlAdapter(opts.rtl, this.left, this.width);
  8460. const ctx = this.ctx;
  8461. const position = titleOpts.position;
  8462. const halfFontSize = titleFont.size / 2;
  8463. const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;
  8464. let y;
  8465. let left = this.left;
  8466. let maxWidth = this.width;
  8467. if (this.isHorizontal()) {
  8468. maxWidth = Math.max(...this.lineWidths);
  8469. y = this.top + topPaddingPlusHalfFontSize;
  8470. left = helpers_segment._alignStartEnd(opts.align, left, this.right - maxWidth);
  8471. } else {
  8472. const maxHeight = this.columnSizes.reduce((acc, size)=>Math.max(acc, size.height), 0);
  8473. y = topPaddingPlusHalfFontSize + helpers_segment._alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight());
  8474. }
  8475. const x = helpers_segment._alignStartEnd(position, left, left + maxWidth);
  8476. ctx.textAlign = rtlHelper.textAlign(helpers_segment._toLeftRightCenter(position));
  8477. ctx.textBaseline = 'middle';
  8478. ctx.strokeStyle = titleOpts.color;
  8479. ctx.fillStyle = titleOpts.color;
  8480. ctx.font = titleFont.string;
  8481. helpers_segment.renderText(ctx, titleOpts.text, x, y, titleFont);
  8482. }
  8483. _computeTitleHeight() {
  8484. const titleOpts = this.options.title;
  8485. const titleFont = helpers_segment.toFont(titleOpts.font);
  8486. const titlePadding = helpers_segment.toPadding(titleOpts.padding);
  8487. return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
  8488. }
  8489. _getLegendItemAt(x, y) {
  8490. let i, hitBox, lh;
  8491. if (helpers_segment._isBetween(x, this.left, this.right) && helpers_segment._isBetween(y, this.top, this.bottom)) {
  8492. lh = this.legendHitBoxes;
  8493. for(i = 0; i < lh.length; ++i){
  8494. hitBox = lh[i];
  8495. if (helpers_segment._isBetween(x, hitBox.left, hitBox.left + hitBox.width) && helpers_segment._isBetween(y, hitBox.top, hitBox.top + hitBox.height)) {
  8496. return this.legendItems[i];
  8497. }
  8498. }
  8499. }
  8500. return null;
  8501. }
  8502. handleEvent(e) {
  8503. const opts = this.options;
  8504. if (!isListened(e.type, opts)) {
  8505. return;
  8506. }
  8507. const hoveredItem = this._getLegendItemAt(e.x, e.y);
  8508. if (e.type === 'mousemove' || e.type === 'mouseout') {
  8509. const previous = this._hoveredItem;
  8510. const sameItem = itemsEqual(previous, hoveredItem);
  8511. if (previous && !sameItem) {
  8512. helpers_segment.callback(opts.onLeave, [
  8513. e,
  8514. previous,
  8515. this
  8516. ], this);
  8517. }
  8518. this._hoveredItem = hoveredItem;
  8519. if (hoveredItem && !sameItem) {
  8520. helpers_segment.callback(opts.onHover, [
  8521. e,
  8522. hoveredItem,
  8523. this
  8524. ], this);
  8525. }
  8526. } else if (hoveredItem) {
  8527. helpers_segment.callback(opts.onClick, [
  8528. e,
  8529. hoveredItem,
  8530. this
  8531. ], this);
  8532. }
  8533. }
  8534. }
  8535. function calculateItemSize(boxWidth, labelFont, ctx, legendItem, _itemHeight) {
  8536. const itemWidth = calculateItemWidth(legendItem, boxWidth, labelFont, ctx);
  8537. const itemHeight = calculateItemHeight(_itemHeight, legendItem, labelFont.lineHeight);
  8538. return {
  8539. itemWidth,
  8540. itemHeight
  8541. };
  8542. }
  8543. function calculateItemWidth(legendItem, boxWidth, labelFont, ctx) {
  8544. let legendItemText = legendItem.text;
  8545. if (legendItemText && typeof legendItemText !== 'string') {
  8546. legendItemText = legendItemText.reduce((a, b)=>a.length > b.length ? a : b);
  8547. }
  8548. return boxWidth + labelFont.size / 2 + ctx.measureText(legendItemText).width;
  8549. }
  8550. function calculateItemHeight(_itemHeight, legendItem, fontLineHeight) {
  8551. let itemHeight = _itemHeight;
  8552. if (typeof legendItem.text !== 'string') {
  8553. itemHeight = calculateLegendItemHeight(legendItem, fontLineHeight);
  8554. }
  8555. return itemHeight;
  8556. }
  8557. function calculateLegendItemHeight(legendItem, fontLineHeight) {
  8558. const labelHeight = legendItem.text ? legendItem.text.length : 0;
  8559. return fontLineHeight * labelHeight;
  8560. }
  8561. function isListened(type, opts) {
  8562. if ((type === 'mousemove' || type === 'mouseout') && (opts.onHover || opts.onLeave)) {
  8563. return true;
  8564. }
  8565. if (opts.onClick && (type === 'click' || type === 'mouseup')) {
  8566. return true;
  8567. }
  8568. return false;
  8569. }
  8570. var plugin_legend = {
  8571. id: 'legend',
  8572. _element: Legend,
  8573. start (chart, _args, options) {
  8574. const legend = chart.legend = new Legend({
  8575. ctx: chart.ctx,
  8576. options,
  8577. chart
  8578. });
  8579. layouts.configure(chart, legend, options);
  8580. layouts.addBox(chart, legend);
  8581. },
  8582. stop (chart) {
  8583. layouts.removeBox(chart, chart.legend);
  8584. delete chart.legend;
  8585. },
  8586. beforeUpdate (chart, _args, options) {
  8587. const legend = chart.legend;
  8588. layouts.configure(chart, legend, options);
  8589. legend.options = options;
  8590. },
  8591. afterUpdate (chart) {
  8592. const legend = chart.legend;
  8593. legend.buildLabels();
  8594. legend.adjustHitBoxes();
  8595. },
  8596. afterEvent (chart, args) {
  8597. if (!args.replay) {
  8598. chart.legend.handleEvent(args.event);
  8599. }
  8600. },
  8601. defaults: {
  8602. display: true,
  8603. position: 'top',
  8604. align: 'center',
  8605. fullSize: true,
  8606. reverse: false,
  8607. weight: 1000,
  8608. onClick (e, legendItem, legend) {
  8609. const index = legendItem.datasetIndex;
  8610. const ci = legend.chart;
  8611. if (ci.isDatasetVisible(index)) {
  8612. ci.hide(index);
  8613. legendItem.hidden = true;
  8614. } else {
  8615. ci.show(index);
  8616. legendItem.hidden = false;
  8617. }
  8618. },
  8619. onHover: null,
  8620. onLeave: null,
  8621. labels: {
  8622. color: (ctx)=>ctx.chart.options.color,
  8623. boxWidth: 40,
  8624. padding: 10,
  8625. generateLabels (chart) {
  8626. const datasets = chart.data.datasets;
  8627. const { labels: { usePointStyle , pointStyle , textAlign , color , useBorderRadius , borderRadius } } = chart.legend.options;
  8628. return chart._getSortedDatasetMetas().map((meta)=>{
  8629. const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  8630. const borderWidth = helpers_segment.toPadding(style.borderWidth);
  8631. return {
  8632. text: datasets[meta.index].label,
  8633. fillStyle: style.backgroundColor,
  8634. fontColor: color,
  8635. hidden: !meta.visible,
  8636. lineCap: style.borderCapStyle,
  8637. lineDash: style.borderDash,
  8638. lineDashOffset: style.borderDashOffset,
  8639. lineJoin: style.borderJoinStyle,
  8640. lineWidth: (borderWidth.width + borderWidth.height) / 4,
  8641. strokeStyle: style.borderColor,
  8642. pointStyle: pointStyle || style.pointStyle,
  8643. rotation: style.rotation,
  8644. textAlign: textAlign || style.textAlign,
  8645. borderRadius: useBorderRadius && (borderRadius || style.borderRadius),
  8646. datasetIndex: meta.index
  8647. };
  8648. }, this);
  8649. }
  8650. },
  8651. title: {
  8652. color: (ctx)=>ctx.chart.options.color,
  8653. display: false,
  8654. position: 'center',
  8655. text: ''
  8656. }
  8657. },
  8658. descriptors: {
  8659. _scriptable: (name)=>!name.startsWith('on'),
  8660. labels: {
  8661. _scriptable: (name)=>![
  8662. 'generateLabels',
  8663. 'filter',
  8664. 'sort'
  8665. ].includes(name)
  8666. }
  8667. }
  8668. };
  8669. class Title extends Element {
  8670. constructor(config){
  8671. super();
  8672. this.chart = config.chart;
  8673. this.options = config.options;
  8674. this.ctx = config.ctx;
  8675. this._padding = undefined;
  8676. this.top = undefined;
  8677. this.bottom = undefined;
  8678. this.left = undefined;
  8679. this.right = undefined;
  8680. this.width = undefined;
  8681. this.height = undefined;
  8682. this.position = undefined;
  8683. this.weight = undefined;
  8684. this.fullSize = undefined;
  8685. }
  8686. update(maxWidth, maxHeight) {
  8687. const opts = this.options;
  8688. this.left = 0;
  8689. this.top = 0;
  8690. if (!opts.display) {
  8691. this.width = this.height = this.right = this.bottom = 0;
  8692. return;
  8693. }
  8694. this.width = this.right = maxWidth;
  8695. this.height = this.bottom = maxHeight;
  8696. const lineCount = helpers_segment.isArray(opts.text) ? opts.text.length : 1;
  8697. this._padding = helpers_segment.toPadding(opts.padding);
  8698. const textSize = lineCount * helpers_segment.toFont(opts.font).lineHeight + this._padding.height;
  8699. if (this.isHorizontal()) {
  8700. this.height = textSize;
  8701. } else {
  8702. this.width = textSize;
  8703. }
  8704. }
  8705. isHorizontal() {
  8706. const pos = this.options.position;
  8707. return pos === 'top' || pos === 'bottom';
  8708. }
  8709. _drawArgs(offset) {
  8710. const { top , left , bottom , right , options } = this;
  8711. const align = options.align;
  8712. let rotation = 0;
  8713. let maxWidth, titleX, titleY;
  8714. if (this.isHorizontal()) {
  8715. titleX = helpers_segment._alignStartEnd(align, left, right);
  8716. titleY = top + offset;
  8717. maxWidth = right - left;
  8718. } else {
  8719. if (options.position === 'left') {
  8720. titleX = left + offset;
  8721. titleY = helpers_segment._alignStartEnd(align, bottom, top);
  8722. rotation = helpers_segment.PI * -0.5;
  8723. } else {
  8724. titleX = right - offset;
  8725. titleY = helpers_segment._alignStartEnd(align, top, bottom);
  8726. rotation = helpers_segment.PI * 0.5;
  8727. }
  8728. maxWidth = bottom - top;
  8729. }
  8730. return {
  8731. titleX,
  8732. titleY,
  8733. maxWidth,
  8734. rotation
  8735. };
  8736. }
  8737. draw() {
  8738. const ctx = this.ctx;
  8739. const opts = this.options;
  8740. if (!opts.display) {
  8741. return;
  8742. }
  8743. const fontOpts = helpers_segment.toFont(opts.font);
  8744. const lineHeight = fontOpts.lineHeight;
  8745. const offset = lineHeight / 2 + this._padding.top;
  8746. const { titleX , titleY , maxWidth , rotation } = this._drawArgs(offset);
  8747. helpers_segment.renderText(ctx, opts.text, 0, 0, fontOpts, {
  8748. color: opts.color,
  8749. maxWidth,
  8750. rotation,
  8751. textAlign: helpers_segment._toLeftRightCenter(opts.align),
  8752. textBaseline: 'middle',
  8753. translation: [
  8754. titleX,
  8755. titleY
  8756. ]
  8757. });
  8758. }
  8759. }
  8760. function createTitle(chart, titleOpts) {
  8761. const title = new Title({
  8762. ctx: chart.ctx,
  8763. options: titleOpts,
  8764. chart
  8765. });
  8766. layouts.configure(chart, title, titleOpts);
  8767. layouts.addBox(chart, title);
  8768. chart.titleBlock = title;
  8769. }
  8770. var plugin_title = {
  8771. id: 'title',
  8772. _element: Title,
  8773. start (chart, _args, options) {
  8774. createTitle(chart, options);
  8775. },
  8776. stop (chart) {
  8777. const titleBlock = chart.titleBlock;
  8778. layouts.removeBox(chart, titleBlock);
  8779. delete chart.titleBlock;
  8780. },
  8781. beforeUpdate (chart, _args, options) {
  8782. const title = chart.titleBlock;
  8783. layouts.configure(chart, title, options);
  8784. title.options = options;
  8785. },
  8786. defaults: {
  8787. align: 'center',
  8788. display: false,
  8789. font: {
  8790. weight: 'bold'
  8791. },
  8792. fullSize: true,
  8793. padding: 10,
  8794. position: 'top',
  8795. text: '',
  8796. weight: 2000
  8797. },
  8798. defaultRoutes: {
  8799. color: 'color'
  8800. },
  8801. descriptors: {
  8802. _scriptable: true,
  8803. _indexable: false
  8804. }
  8805. };
  8806. const map = new WeakMap();
  8807. var plugin_subtitle = {
  8808. id: 'subtitle',
  8809. start (chart, _args, options) {
  8810. const title = new Title({
  8811. ctx: chart.ctx,
  8812. options,
  8813. chart
  8814. });
  8815. layouts.configure(chart, title, options);
  8816. layouts.addBox(chart, title);
  8817. map.set(chart, title);
  8818. },
  8819. stop (chart) {
  8820. layouts.removeBox(chart, map.get(chart));
  8821. map.delete(chart);
  8822. },
  8823. beforeUpdate (chart, _args, options) {
  8824. const title = map.get(chart);
  8825. layouts.configure(chart, title, options);
  8826. title.options = options;
  8827. },
  8828. defaults: {
  8829. align: 'center',
  8830. display: false,
  8831. font: {
  8832. weight: 'normal'
  8833. },
  8834. fullSize: true,
  8835. padding: 0,
  8836. position: 'top',
  8837. text: '',
  8838. weight: 1500
  8839. },
  8840. defaultRoutes: {
  8841. color: 'color'
  8842. },
  8843. descriptors: {
  8844. _scriptable: true,
  8845. _indexable: false
  8846. }
  8847. };
  8848. const positioners = {
  8849. average (items) {
  8850. if (!items.length) {
  8851. return false;
  8852. }
  8853. let i, len;
  8854. let xSet = new Set();
  8855. let y = 0;
  8856. let count = 0;
  8857. for(i = 0, len = items.length; i < len; ++i){
  8858. const el = items[i].element;
  8859. if (el && el.hasValue()) {
  8860. const pos = el.tooltipPosition();
  8861. xSet.add(pos.x);
  8862. y += pos.y;
  8863. ++count;
  8864. }
  8865. }
  8866. if (count === 0 || xSet.size === 0) {
  8867. return false;
  8868. }
  8869. const xAverage = [
  8870. ...xSet
  8871. ].reduce((a, b)=>a + b) / xSet.size;
  8872. return {
  8873. x: xAverage,
  8874. y: y / count
  8875. };
  8876. },
  8877. nearest (items, eventPosition) {
  8878. if (!items.length) {
  8879. return false;
  8880. }
  8881. let x = eventPosition.x;
  8882. let y = eventPosition.y;
  8883. let minDistance = Number.POSITIVE_INFINITY;
  8884. let i, len, nearestElement;
  8885. for(i = 0, len = items.length; i < len; ++i){
  8886. const el = items[i].element;
  8887. if (el && el.hasValue()) {
  8888. const center = el.getCenterPoint();
  8889. const d = helpers_segment.distanceBetweenPoints(eventPosition, center);
  8890. if (d < minDistance) {
  8891. minDistance = d;
  8892. nearestElement = el;
  8893. }
  8894. }
  8895. }
  8896. if (nearestElement) {
  8897. const tp = nearestElement.tooltipPosition();
  8898. x = tp.x;
  8899. y = tp.y;
  8900. }
  8901. return {
  8902. x,
  8903. y
  8904. };
  8905. }
  8906. };
  8907. function pushOrConcat(base, toPush) {
  8908. if (toPush) {
  8909. if (helpers_segment.isArray(toPush)) {
  8910. Array.prototype.push.apply(base, toPush);
  8911. } else {
  8912. base.push(toPush);
  8913. }
  8914. }
  8915. return base;
  8916. }
  8917. function splitNewlines(str) {
  8918. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  8919. return str.split('\n');
  8920. }
  8921. return str;
  8922. }
  8923. function createTooltipItem(chart, item) {
  8924. const { element , datasetIndex , index } = item;
  8925. const controller = chart.getDatasetMeta(datasetIndex).controller;
  8926. const { label , value } = controller.getLabelAndValue(index);
  8927. return {
  8928. chart,
  8929. label,
  8930. parsed: controller.getParsed(index),
  8931. raw: chart.data.datasets[datasetIndex].data[index],
  8932. formattedValue: value,
  8933. dataset: controller.getDataset(),
  8934. dataIndex: index,
  8935. datasetIndex,
  8936. element
  8937. };
  8938. }
  8939. function getTooltipSize(tooltip, options) {
  8940. const ctx = tooltip.chart.ctx;
  8941. const { body , footer , title } = tooltip;
  8942. const { boxWidth , boxHeight } = options;
  8943. const bodyFont = helpers_segment.toFont(options.bodyFont);
  8944. const titleFont = helpers_segment.toFont(options.titleFont);
  8945. const footerFont = helpers_segment.toFont(options.footerFont);
  8946. const titleLineCount = title.length;
  8947. const footerLineCount = footer.length;
  8948. const bodyLineItemCount = body.length;
  8949. const padding = helpers_segment.toPadding(options.padding);
  8950. let height = padding.height;
  8951. let width = 0;
  8952. let combinedBodyLength = body.reduce((count, bodyItem)=>count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);
  8953. combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;
  8954. if (titleLineCount) {
  8955. height += titleLineCount * titleFont.lineHeight + (titleLineCount - 1) * options.titleSpacing + options.titleMarginBottom;
  8956. }
  8957. if (combinedBodyLength) {
  8958. const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;
  8959. height += bodyLineItemCount * bodyLineHeight + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight + (combinedBodyLength - 1) * options.bodySpacing;
  8960. }
  8961. if (footerLineCount) {
  8962. height += options.footerMarginTop + footerLineCount * footerFont.lineHeight + (footerLineCount - 1) * options.footerSpacing;
  8963. }
  8964. let widthPadding = 0;
  8965. const maxLineWidth = function(line) {
  8966. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  8967. };
  8968. ctx.save();
  8969. ctx.font = titleFont.string;
  8970. helpers_segment.each(tooltip.title, maxLineWidth);
  8971. ctx.font = bodyFont.string;
  8972. helpers_segment.each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);
  8973. widthPadding = options.displayColors ? boxWidth + 2 + options.boxPadding : 0;
  8974. helpers_segment.each(body, (bodyItem)=>{
  8975. helpers_segment.each(bodyItem.before, maxLineWidth);
  8976. helpers_segment.each(bodyItem.lines, maxLineWidth);
  8977. helpers_segment.each(bodyItem.after, maxLineWidth);
  8978. });
  8979. widthPadding = 0;
  8980. ctx.font = footerFont.string;
  8981. helpers_segment.each(tooltip.footer, maxLineWidth);
  8982. ctx.restore();
  8983. width += padding.width;
  8984. return {
  8985. width,
  8986. height
  8987. };
  8988. }
  8989. function determineYAlign(chart, size) {
  8990. const { y , height } = size;
  8991. if (y < height / 2) {
  8992. return 'top';
  8993. } else if (y > chart.height - height / 2) {
  8994. return 'bottom';
  8995. }
  8996. return 'center';
  8997. }
  8998. function doesNotFitWithAlign(xAlign, chart, options, size) {
  8999. const { x , width } = size;
  9000. const caret = options.caretSize + options.caretPadding;
  9001. if (xAlign === 'left' && x + width + caret > chart.width) {
  9002. return true;
  9003. }
  9004. if (xAlign === 'right' && x - width - caret < 0) {
  9005. return true;
  9006. }
  9007. }
  9008. function determineXAlign(chart, options, size, yAlign) {
  9009. const { x , width } = size;
  9010. const { width: chartWidth , chartArea: { left , right } } = chart;
  9011. let xAlign = 'center';
  9012. if (yAlign === 'center') {
  9013. xAlign = x <= (left + right) / 2 ? 'left' : 'right';
  9014. } else if (x <= width / 2) {
  9015. xAlign = 'left';
  9016. } else if (x >= chartWidth - width / 2) {
  9017. xAlign = 'right';
  9018. }
  9019. if (doesNotFitWithAlign(xAlign, chart, options, size)) {
  9020. xAlign = 'center';
  9021. }
  9022. return xAlign;
  9023. }
  9024. function determineAlignment(chart, options, size) {
  9025. const yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size);
  9026. return {
  9027. xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign),
  9028. yAlign
  9029. };
  9030. }
  9031. function alignX(size, xAlign) {
  9032. let { x , width } = size;
  9033. if (xAlign === 'right') {
  9034. x -= width;
  9035. } else if (xAlign === 'center') {
  9036. x -= width / 2;
  9037. }
  9038. return x;
  9039. }
  9040. function alignY(size, yAlign, paddingAndSize) {
  9041. let { y , height } = size;
  9042. if (yAlign === 'top') {
  9043. y += paddingAndSize;
  9044. } else if (yAlign === 'bottom') {
  9045. y -= height + paddingAndSize;
  9046. } else {
  9047. y -= height / 2;
  9048. }
  9049. return y;
  9050. }
  9051. function getBackgroundPoint(options, size, alignment, chart) {
  9052. const { caretSize , caretPadding , cornerRadius } = options;
  9053. const { xAlign , yAlign } = alignment;
  9054. const paddingAndSize = caretSize + caretPadding;
  9055. const { topLeft , topRight , bottomLeft , bottomRight } = helpers_segment.toTRBLCorners(cornerRadius);
  9056. let x = alignX(size, xAlign);
  9057. const y = alignY(size, yAlign, paddingAndSize);
  9058. if (yAlign === 'center') {
  9059. if (xAlign === 'left') {
  9060. x += paddingAndSize;
  9061. } else if (xAlign === 'right') {
  9062. x -= paddingAndSize;
  9063. }
  9064. } else if (xAlign === 'left') {
  9065. x -= Math.max(topLeft, bottomLeft) + caretSize;
  9066. } else if (xAlign === 'right') {
  9067. x += Math.max(topRight, bottomRight) + caretSize;
  9068. }
  9069. return {
  9070. x: helpers_segment._limitValue(x, 0, chart.width - size.width),
  9071. y: helpers_segment._limitValue(y, 0, chart.height - size.height)
  9072. };
  9073. }
  9074. function getAlignedX(tooltip, align, options) {
  9075. const padding = helpers_segment.toPadding(options.padding);
  9076. return align === 'center' ? tooltip.x + tooltip.width / 2 : align === 'right' ? tooltip.x + tooltip.width - padding.right : tooltip.x + padding.left;
  9077. }
  9078. function getBeforeAfterBodyLines(callback) {
  9079. return pushOrConcat([], splitNewlines(callback));
  9080. }
  9081. function createTooltipContext(parent, tooltip, tooltipItems) {
  9082. return helpers_segment.createContext(parent, {
  9083. tooltip,
  9084. tooltipItems,
  9085. type: 'tooltip'
  9086. });
  9087. }
  9088. function overrideCallbacks(callbacks, context) {
  9089. const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;
  9090. return override ? callbacks.override(override) : callbacks;
  9091. }
  9092. const defaultCallbacks = {
  9093. beforeTitle: helpers_segment.noop,
  9094. title (tooltipItems) {
  9095. if (tooltipItems.length > 0) {
  9096. const item = tooltipItems[0];
  9097. const labels = item.chart.data.labels;
  9098. const labelCount = labels ? labels.length : 0;
  9099. if (this && this.options && this.options.mode === 'dataset') {
  9100. return item.dataset.label || '';
  9101. } else if (item.label) {
  9102. return item.label;
  9103. } else if (labelCount > 0 && item.dataIndex < labelCount) {
  9104. return labels[item.dataIndex];
  9105. }
  9106. }
  9107. return '';
  9108. },
  9109. afterTitle: helpers_segment.noop,
  9110. beforeBody: helpers_segment.noop,
  9111. beforeLabel: helpers_segment.noop,
  9112. label (tooltipItem) {
  9113. if (this && this.options && this.options.mode === 'dataset') {
  9114. return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;
  9115. }
  9116. let label = tooltipItem.dataset.label || '';
  9117. if (label) {
  9118. label += ': ';
  9119. }
  9120. const value = tooltipItem.formattedValue;
  9121. if (!helpers_segment.isNullOrUndef(value)) {
  9122. label += value;
  9123. }
  9124. return label;
  9125. },
  9126. labelColor (tooltipItem) {
  9127. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  9128. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  9129. return {
  9130. borderColor: options.borderColor,
  9131. backgroundColor: options.backgroundColor,
  9132. borderWidth: options.borderWidth,
  9133. borderDash: options.borderDash,
  9134. borderDashOffset: options.borderDashOffset,
  9135. borderRadius: 0
  9136. };
  9137. },
  9138. labelTextColor () {
  9139. return this.options.bodyColor;
  9140. },
  9141. labelPointStyle (tooltipItem) {
  9142. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  9143. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  9144. return {
  9145. pointStyle: options.pointStyle,
  9146. rotation: options.rotation
  9147. };
  9148. },
  9149. afterLabel: helpers_segment.noop,
  9150. afterBody: helpers_segment.noop,
  9151. beforeFooter: helpers_segment.noop,
  9152. footer: helpers_segment.noop,
  9153. afterFooter: helpers_segment.noop
  9154. };
  9155. function invokeCallbackWithFallback(callbacks, name, ctx, arg) {
  9156. const result = callbacks[name].call(ctx, arg);
  9157. if (typeof result === 'undefined') {
  9158. return defaultCallbacks[name].call(ctx, arg);
  9159. }
  9160. return result;
  9161. }
  9162. class Tooltip extends Element {
  9163. static positioners = positioners;
  9164. constructor(config){
  9165. super();
  9166. this.opacity = 0;
  9167. this._active = [];
  9168. this._eventPosition = undefined;
  9169. this._size = undefined;
  9170. this._cachedAnimations = undefined;
  9171. this._tooltipItems = [];
  9172. this.$animations = undefined;
  9173. this.$context = undefined;
  9174. this.chart = config.chart;
  9175. this.options = config.options;
  9176. this.dataPoints = undefined;
  9177. this.title = undefined;
  9178. this.beforeBody = undefined;
  9179. this.body = undefined;
  9180. this.afterBody = undefined;
  9181. this.footer = undefined;
  9182. this.xAlign = undefined;
  9183. this.yAlign = undefined;
  9184. this.x = undefined;
  9185. this.y = undefined;
  9186. this.height = undefined;
  9187. this.width = undefined;
  9188. this.caretX = undefined;
  9189. this.caretY = undefined;
  9190. this.labelColors = undefined;
  9191. this.labelPointStyles = undefined;
  9192. this.labelTextColors = undefined;
  9193. }
  9194. initialize(options) {
  9195. this.options = options;
  9196. this._cachedAnimations = undefined;
  9197. this.$context = undefined;
  9198. }
  9199. _resolveAnimations() {
  9200. const cached = this._cachedAnimations;
  9201. if (cached) {
  9202. return cached;
  9203. }
  9204. const chart = this.chart;
  9205. const options = this.options.setContext(this.getContext());
  9206. const opts = options.enabled && chart.options.animation && options.animations;
  9207. const animations = new Animations(this.chart, opts);
  9208. if (opts._cacheable) {
  9209. this._cachedAnimations = Object.freeze(animations);
  9210. }
  9211. return animations;
  9212. }
  9213. getContext() {
  9214. return this.$context || (this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems));
  9215. }
  9216. getTitle(context, options) {
  9217. const { callbacks } = options;
  9218. const beforeTitle = invokeCallbackWithFallback(callbacks, 'beforeTitle', this, context);
  9219. const title = invokeCallbackWithFallback(callbacks, 'title', this, context);
  9220. const afterTitle = invokeCallbackWithFallback(callbacks, 'afterTitle', this, context);
  9221. let lines = [];
  9222. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  9223. lines = pushOrConcat(lines, splitNewlines(title));
  9224. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  9225. return lines;
  9226. }
  9227. getBeforeBody(tooltipItems, options) {
  9228. return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'beforeBody', this, tooltipItems));
  9229. }
  9230. getBody(tooltipItems, options) {
  9231. const { callbacks } = options;
  9232. const bodyItems = [];
  9233. helpers_segment.each(tooltipItems, (context)=>{
  9234. const bodyItem = {
  9235. before: [],
  9236. lines: [],
  9237. after: []
  9238. };
  9239. const scoped = overrideCallbacks(callbacks, context);
  9240. pushOrConcat(bodyItem.before, splitNewlines(invokeCallbackWithFallback(scoped, 'beforeLabel', this, context)));
  9241. pushOrConcat(bodyItem.lines, invokeCallbackWithFallback(scoped, 'label', this, context));
  9242. pushOrConcat(bodyItem.after, splitNewlines(invokeCallbackWithFallback(scoped, 'afterLabel', this, context)));
  9243. bodyItems.push(bodyItem);
  9244. });
  9245. return bodyItems;
  9246. }
  9247. getAfterBody(tooltipItems, options) {
  9248. return getBeforeAfterBodyLines(invokeCallbackWithFallback(options.callbacks, 'afterBody', this, tooltipItems));
  9249. }
  9250. getFooter(tooltipItems, options) {
  9251. const { callbacks } = options;
  9252. const beforeFooter = invokeCallbackWithFallback(callbacks, 'beforeFooter', this, tooltipItems);
  9253. const footer = invokeCallbackWithFallback(callbacks, 'footer', this, tooltipItems);
  9254. const afterFooter = invokeCallbackWithFallback(callbacks, 'afterFooter', this, tooltipItems);
  9255. let lines = [];
  9256. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  9257. lines = pushOrConcat(lines, splitNewlines(footer));
  9258. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  9259. return lines;
  9260. }
  9261. _createItems(options) {
  9262. const active = this._active;
  9263. const data = this.chart.data;
  9264. const labelColors = [];
  9265. const labelPointStyles = [];
  9266. const labelTextColors = [];
  9267. let tooltipItems = [];
  9268. let i, len;
  9269. for(i = 0, len = active.length; i < len; ++i){
  9270. tooltipItems.push(createTooltipItem(this.chart, active[i]));
  9271. }
  9272. if (options.filter) {
  9273. tooltipItems = tooltipItems.filter((element, index, array)=>options.filter(element, index, array, data));
  9274. }
  9275. if (options.itemSort) {
  9276. tooltipItems = tooltipItems.sort((a, b)=>options.itemSort(a, b, data));
  9277. }
  9278. helpers_segment.each(tooltipItems, (context)=>{
  9279. const scoped = overrideCallbacks(options.callbacks, context);
  9280. labelColors.push(invokeCallbackWithFallback(scoped, 'labelColor', this, context));
  9281. labelPointStyles.push(invokeCallbackWithFallback(scoped, 'labelPointStyle', this, context));
  9282. labelTextColors.push(invokeCallbackWithFallback(scoped, 'labelTextColor', this, context));
  9283. });
  9284. this.labelColors = labelColors;
  9285. this.labelPointStyles = labelPointStyles;
  9286. this.labelTextColors = labelTextColors;
  9287. this.dataPoints = tooltipItems;
  9288. return tooltipItems;
  9289. }
  9290. update(changed, replay) {
  9291. const options = this.options.setContext(this.getContext());
  9292. const active = this._active;
  9293. let properties;
  9294. let tooltipItems = [];
  9295. if (!active.length) {
  9296. if (this.opacity !== 0) {
  9297. properties = {
  9298. opacity: 0
  9299. };
  9300. }
  9301. } else {
  9302. const position = positioners[options.position].call(this, active, this._eventPosition);
  9303. tooltipItems = this._createItems(options);
  9304. this.title = this.getTitle(tooltipItems, options);
  9305. this.beforeBody = this.getBeforeBody(tooltipItems, options);
  9306. this.body = this.getBody(tooltipItems, options);
  9307. this.afterBody = this.getAfterBody(tooltipItems, options);
  9308. this.footer = this.getFooter(tooltipItems, options);
  9309. const size = this._size = getTooltipSize(this, options);
  9310. const positionAndSize = Object.assign({}, position, size);
  9311. const alignment = determineAlignment(this.chart, options, positionAndSize);
  9312. const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart);
  9313. this.xAlign = alignment.xAlign;
  9314. this.yAlign = alignment.yAlign;
  9315. properties = {
  9316. opacity: 1,
  9317. x: backgroundPoint.x,
  9318. y: backgroundPoint.y,
  9319. width: size.width,
  9320. height: size.height,
  9321. caretX: position.x,
  9322. caretY: position.y
  9323. };
  9324. }
  9325. this._tooltipItems = tooltipItems;
  9326. this.$context = undefined;
  9327. if (properties) {
  9328. this._resolveAnimations().update(this, properties);
  9329. }
  9330. if (changed && options.external) {
  9331. options.external.call(this, {
  9332. chart: this.chart,
  9333. tooltip: this,
  9334. replay
  9335. });
  9336. }
  9337. }
  9338. drawCaret(tooltipPoint, ctx, size, options) {
  9339. const caretPosition = this.getCaretPosition(tooltipPoint, size, options);
  9340. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  9341. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  9342. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  9343. }
  9344. getCaretPosition(tooltipPoint, size, options) {
  9345. const { xAlign , yAlign } = this;
  9346. const { caretSize , cornerRadius } = options;
  9347. const { topLeft , topRight , bottomLeft , bottomRight } = helpers_segment.toTRBLCorners(cornerRadius);
  9348. const { x: ptX , y: ptY } = tooltipPoint;
  9349. const { width , height } = size;
  9350. let x1, x2, x3, y1, y2, y3;
  9351. if (yAlign === 'center') {
  9352. y2 = ptY + height / 2;
  9353. if (xAlign === 'left') {
  9354. x1 = ptX;
  9355. x2 = x1 - caretSize;
  9356. y1 = y2 + caretSize;
  9357. y3 = y2 - caretSize;
  9358. } else {
  9359. x1 = ptX + width;
  9360. x2 = x1 + caretSize;
  9361. y1 = y2 - caretSize;
  9362. y3 = y2 + caretSize;
  9363. }
  9364. x3 = x1;
  9365. } else {
  9366. if (xAlign === 'left') {
  9367. x2 = ptX + Math.max(topLeft, bottomLeft) + caretSize;
  9368. } else if (xAlign === 'right') {
  9369. x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize;
  9370. } else {
  9371. x2 = this.caretX;
  9372. }
  9373. if (yAlign === 'top') {
  9374. y1 = ptY;
  9375. y2 = y1 - caretSize;
  9376. x1 = x2 - caretSize;
  9377. x3 = x2 + caretSize;
  9378. } else {
  9379. y1 = ptY + height;
  9380. y2 = y1 + caretSize;
  9381. x1 = x2 + caretSize;
  9382. x3 = x2 - caretSize;
  9383. }
  9384. y3 = y1;
  9385. }
  9386. return {
  9387. x1,
  9388. x2,
  9389. x3,
  9390. y1,
  9391. y2,
  9392. y3
  9393. };
  9394. }
  9395. drawTitle(pt, ctx, options) {
  9396. const title = this.title;
  9397. const length = title.length;
  9398. let titleFont, titleSpacing, i;
  9399. if (length) {
  9400. const rtlHelper = helpers_segment.getRtlAdapter(options.rtl, this.x, this.width);
  9401. pt.x = getAlignedX(this, options.titleAlign, options);
  9402. ctx.textAlign = rtlHelper.textAlign(options.titleAlign);
  9403. ctx.textBaseline = 'middle';
  9404. titleFont = helpers_segment.toFont(options.titleFont);
  9405. titleSpacing = options.titleSpacing;
  9406. ctx.fillStyle = options.titleColor;
  9407. ctx.font = titleFont.string;
  9408. for(i = 0; i < length; ++i){
  9409. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);
  9410. pt.y += titleFont.lineHeight + titleSpacing;
  9411. if (i + 1 === length) {
  9412. pt.y += options.titleMarginBottom - titleSpacing;
  9413. }
  9414. }
  9415. }
  9416. }
  9417. _drawColorBox(ctx, pt, i, rtlHelper, options) {
  9418. const labelColor = this.labelColors[i];
  9419. const labelPointStyle = this.labelPointStyles[i];
  9420. const { boxHeight , boxWidth } = options;
  9421. const bodyFont = helpers_segment.toFont(options.bodyFont);
  9422. const colorX = getAlignedX(this, 'left', options);
  9423. const rtlColorX = rtlHelper.x(colorX);
  9424. const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;
  9425. const colorY = pt.y + yOffSet;
  9426. if (options.usePointStyle) {
  9427. const drawOptions = {
  9428. radius: Math.min(boxWidth, boxHeight) / 2,
  9429. pointStyle: labelPointStyle.pointStyle,
  9430. rotation: labelPointStyle.rotation,
  9431. borderWidth: 1
  9432. };
  9433. const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;
  9434. const centerY = colorY + boxHeight / 2;
  9435. ctx.strokeStyle = options.multiKeyBackground;
  9436. ctx.fillStyle = options.multiKeyBackground;
  9437. helpers_segment.drawPoint(ctx, drawOptions, centerX, centerY);
  9438. ctx.strokeStyle = labelColor.borderColor;
  9439. ctx.fillStyle = labelColor.backgroundColor;
  9440. helpers_segment.drawPoint(ctx, drawOptions, centerX, centerY);
  9441. } else {
  9442. ctx.lineWidth = helpers_segment.isObject(labelColor.borderWidth) ? Math.max(...Object.values(labelColor.borderWidth)) : labelColor.borderWidth || 1;
  9443. ctx.strokeStyle = labelColor.borderColor;
  9444. ctx.setLineDash(labelColor.borderDash || []);
  9445. ctx.lineDashOffset = labelColor.borderDashOffset || 0;
  9446. const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth);
  9447. const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2);
  9448. const borderRadius = helpers_segment.toTRBLCorners(labelColor.borderRadius);
  9449. if (Object.values(borderRadius).some((v)=>v !== 0)) {
  9450. ctx.beginPath();
  9451. ctx.fillStyle = options.multiKeyBackground;
  9452. helpers_segment.addRoundedRectPath(ctx, {
  9453. x: outerX,
  9454. y: colorY,
  9455. w: boxWidth,
  9456. h: boxHeight,
  9457. radius: borderRadius
  9458. });
  9459. ctx.fill();
  9460. ctx.stroke();
  9461. ctx.fillStyle = labelColor.backgroundColor;
  9462. ctx.beginPath();
  9463. helpers_segment.addRoundedRectPath(ctx, {
  9464. x: innerX,
  9465. y: colorY + 1,
  9466. w: boxWidth - 2,
  9467. h: boxHeight - 2,
  9468. radius: borderRadius
  9469. });
  9470. ctx.fill();
  9471. } else {
  9472. ctx.fillStyle = options.multiKeyBackground;
  9473. ctx.fillRect(outerX, colorY, boxWidth, boxHeight);
  9474. ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);
  9475. ctx.fillStyle = labelColor.backgroundColor;
  9476. ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);
  9477. }
  9478. }
  9479. ctx.fillStyle = this.labelTextColors[i];
  9480. }
  9481. drawBody(pt, ctx, options) {
  9482. const { body } = this;
  9483. const { bodySpacing , bodyAlign , displayColors , boxHeight , boxWidth , boxPadding } = options;
  9484. const bodyFont = helpers_segment.toFont(options.bodyFont);
  9485. let bodyLineHeight = bodyFont.lineHeight;
  9486. let xLinePadding = 0;
  9487. const rtlHelper = helpers_segment.getRtlAdapter(options.rtl, this.x, this.width);
  9488. const fillLineOfText = function(line) {
  9489. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);
  9490. pt.y += bodyLineHeight + bodySpacing;
  9491. };
  9492. const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  9493. let bodyItem, textColor, lines, i, j, ilen, jlen;
  9494. ctx.textAlign = bodyAlign;
  9495. ctx.textBaseline = 'middle';
  9496. ctx.font = bodyFont.string;
  9497. pt.x = getAlignedX(this, bodyAlignForCalculation, options);
  9498. ctx.fillStyle = options.bodyColor;
  9499. helpers_segment.each(this.beforeBody, fillLineOfText);
  9500. xLinePadding = displayColors && bodyAlignForCalculation !== 'right' ? bodyAlign === 'center' ? boxWidth / 2 + boxPadding : boxWidth + 2 + boxPadding : 0;
  9501. for(i = 0, ilen = body.length; i < ilen; ++i){
  9502. bodyItem = body[i];
  9503. textColor = this.labelTextColors[i];
  9504. ctx.fillStyle = textColor;
  9505. helpers_segment.each(bodyItem.before, fillLineOfText);
  9506. lines = bodyItem.lines;
  9507. if (displayColors && lines.length) {
  9508. this._drawColorBox(ctx, pt, i, rtlHelper, options);
  9509. bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);
  9510. }
  9511. for(j = 0, jlen = lines.length; j < jlen; ++j){
  9512. fillLineOfText(lines[j]);
  9513. bodyLineHeight = bodyFont.lineHeight;
  9514. }
  9515. helpers_segment.each(bodyItem.after, fillLineOfText);
  9516. }
  9517. xLinePadding = 0;
  9518. bodyLineHeight = bodyFont.lineHeight;
  9519. helpers_segment.each(this.afterBody, fillLineOfText);
  9520. pt.y -= bodySpacing;
  9521. }
  9522. drawFooter(pt, ctx, options) {
  9523. const footer = this.footer;
  9524. const length = footer.length;
  9525. let footerFont, i;
  9526. if (length) {
  9527. const rtlHelper = helpers_segment.getRtlAdapter(options.rtl, this.x, this.width);
  9528. pt.x = getAlignedX(this, options.footerAlign, options);
  9529. pt.y += options.footerMarginTop;
  9530. ctx.textAlign = rtlHelper.textAlign(options.footerAlign);
  9531. ctx.textBaseline = 'middle';
  9532. footerFont = helpers_segment.toFont(options.footerFont);
  9533. ctx.fillStyle = options.footerColor;
  9534. ctx.font = footerFont.string;
  9535. for(i = 0; i < length; ++i){
  9536. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);
  9537. pt.y += footerFont.lineHeight + options.footerSpacing;
  9538. }
  9539. }
  9540. }
  9541. drawBackground(pt, ctx, tooltipSize, options) {
  9542. const { xAlign , yAlign } = this;
  9543. const { x , y } = pt;
  9544. const { width , height } = tooltipSize;
  9545. const { topLeft , topRight , bottomLeft , bottomRight } = helpers_segment.toTRBLCorners(options.cornerRadius);
  9546. ctx.fillStyle = options.backgroundColor;
  9547. ctx.strokeStyle = options.borderColor;
  9548. ctx.lineWidth = options.borderWidth;
  9549. ctx.beginPath();
  9550. ctx.moveTo(x + topLeft, y);
  9551. if (yAlign === 'top') {
  9552. this.drawCaret(pt, ctx, tooltipSize, options);
  9553. }
  9554. ctx.lineTo(x + width - topRight, y);
  9555. ctx.quadraticCurveTo(x + width, y, x + width, y + topRight);
  9556. if (yAlign === 'center' && xAlign === 'right') {
  9557. this.drawCaret(pt, ctx, tooltipSize, options);
  9558. }
  9559. ctx.lineTo(x + width, y + height - bottomRight);
  9560. ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height);
  9561. if (yAlign === 'bottom') {
  9562. this.drawCaret(pt, ctx, tooltipSize, options);
  9563. }
  9564. ctx.lineTo(x + bottomLeft, y + height);
  9565. ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft);
  9566. if (yAlign === 'center' && xAlign === 'left') {
  9567. this.drawCaret(pt, ctx, tooltipSize, options);
  9568. }
  9569. ctx.lineTo(x, y + topLeft);
  9570. ctx.quadraticCurveTo(x, y, x + topLeft, y);
  9571. ctx.closePath();
  9572. ctx.fill();
  9573. if (options.borderWidth > 0) {
  9574. ctx.stroke();
  9575. }
  9576. }
  9577. _updateAnimationTarget(options) {
  9578. const chart = this.chart;
  9579. const anims = this.$animations;
  9580. const animX = anims && anims.x;
  9581. const animY = anims && anims.y;
  9582. if (animX || animY) {
  9583. const position = positioners[options.position].call(this, this._active, this._eventPosition);
  9584. if (!position) {
  9585. return;
  9586. }
  9587. const size = this._size = getTooltipSize(this, options);
  9588. const positionAndSize = Object.assign({}, position, this._size);
  9589. const alignment = determineAlignment(chart, options, positionAndSize);
  9590. const point = getBackgroundPoint(options, positionAndSize, alignment, chart);
  9591. if (animX._to !== point.x || animY._to !== point.y) {
  9592. this.xAlign = alignment.xAlign;
  9593. this.yAlign = alignment.yAlign;
  9594. this.width = size.width;
  9595. this.height = size.height;
  9596. this.caretX = position.x;
  9597. this.caretY = position.y;
  9598. this._resolveAnimations().update(this, point);
  9599. }
  9600. }
  9601. }
  9602. _willRender() {
  9603. return !!this.opacity;
  9604. }
  9605. draw(ctx) {
  9606. const options = this.options.setContext(this.getContext());
  9607. let opacity = this.opacity;
  9608. if (!opacity) {
  9609. return;
  9610. }
  9611. this._updateAnimationTarget(options);
  9612. const tooltipSize = {
  9613. width: this.width,
  9614. height: this.height
  9615. };
  9616. const pt = {
  9617. x: this.x,
  9618. y: this.y
  9619. };
  9620. opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
  9621. const padding = helpers_segment.toPadding(options.padding);
  9622. const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length;
  9623. if (options.enabled && hasTooltipContent) {
  9624. ctx.save();
  9625. ctx.globalAlpha = opacity;
  9626. this.drawBackground(pt, ctx, tooltipSize, options);
  9627. helpers_segment.overrideTextDirection(ctx, options.textDirection);
  9628. pt.y += padding.top;
  9629. this.drawTitle(pt, ctx, options);
  9630. this.drawBody(pt, ctx, options);
  9631. this.drawFooter(pt, ctx, options);
  9632. helpers_segment.restoreTextDirection(ctx, options.textDirection);
  9633. ctx.restore();
  9634. }
  9635. }
  9636. getActiveElements() {
  9637. return this._active || [];
  9638. }
  9639. setActiveElements(activeElements, eventPosition) {
  9640. const lastActive = this._active;
  9641. const active = activeElements.map(({ datasetIndex , index })=>{
  9642. const meta = this.chart.getDatasetMeta(datasetIndex);
  9643. if (!meta) {
  9644. throw new Error('Cannot find a dataset at index ' + datasetIndex);
  9645. }
  9646. return {
  9647. datasetIndex,
  9648. element: meta.data[index],
  9649. index
  9650. };
  9651. });
  9652. const changed = !helpers_segment._elementsEqual(lastActive, active);
  9653. const positionChanged = this._positionChanged(active, eventPosition);
  9654. if (changed || positionChanged) {
  9655. this._active = active;
  9656. this._eventPosition = eventPosition;
  9657. this._ignoreReplayEvents = true;
  9658. this.update(true);
  9659. }
  9660. }
  9661. handleEvent(e, replay, inChartArea = true) {
  9662. if (replay && this._ignoreReplayEvents) {
  9663. return false;
  9664. }
  9665. this._ignoreReplayEvents = false;
  9666. const options = this.options;
  9667. const lastActive = this._active || [];
  9668. const active = this._getActiveElements(e, lastActive, replay, inChartArea);
  9669. const positionChanged = this._positionChanged(active, e);
  9670. const changed = replay || !helpers_segment._elementsEqual(active, lastActive) || positionChanged;
  9671. if (changed) {
  9672. this._active = active;
  9673. if (options.enabled || options.external) {
  9674. this._eventPosition = {
  9675. x: e.x,
  9676. y: e.y
  9677. };
  9678. this.update(true, replay);
  9679. }
  9680. }
  9681. return changed;
  9682. }
  9683. _getActiveElements(e, lastActive, replay, inChartArea) {
  9684. const options = this.options;
  9685. if (e.type === 'mouseout') {
  9686. return [];
  9687. }
  9688. if (!inChartArea) {
  9689. return lastActive.filter((i)=>this.chart.data.datasets[i.datasetIndex] && this.chart.getDatasetMeta(i.datasetIndex).controller.getParsed(i.index) !== undefined);
  9690. }
  9691. const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay);
  9692. if (options.reverse) {
  9693. active.reverse();
  9694. }
  9695. return active;
  9696. }
  9697. _positionChanged(active, e) {
  9698. const { caretX , caretY , options } = this;
  9699. const position = positioners[options.position].call(this, active, e);
  9700. return position !== false && (caretX !== position.x || caretY !== position.y);
  9701. }
  9702. }
  9703. var plugin_tooltip = {
  9704. id: 'tooltip',
  9705. _element: Tooltip,
  9706. positioners,
  9707. afterInit (chart, _args, options) {
  9708. if (options) {
  9709. chart.tooltip = new Tooltip({
  9710. chart,
  9711. options
  9712. });
  9713. }
  9714. },
  9715. beforeUpdate (chart, _args, options) {
  9716. if (chart.tooltip) {
  9717. chart.tooltip.initialize(options);
  9718. }
  9719. },
  9720. reset (chart, _args, options) {
  9721. if (chart.tooltip) {
  9722. chart.tooltip.initialize(options);
  9723. }
  9724. },
  9725. afterDraw (chart) {
  9726. const tooltip = chart.tooltip;
  9727. if (tooltip && tooltip._willRender()) {
  9728. const args = {
  9729. tooltip
  9730. };
  9731. if (chart.notifyPlugins('beforeTooltipDraw', {
  9732. ...args,
  9733. cancelable: true
  9734. }) === false) {
  9735. return;
  9736. }
  9737. tooltip.draw(chart.ctx);
  9738. chart.notifyPlugins('afterTooltipDraw', args);
  9739. }
  9740. },
  9741. afterEvent (chart, args) {
  9742. if (chart.tooltip) {
  9743. const useFinalPosition = args.replay;
  9744. if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) {
  9745. args.changed = true;
  9746. }
  9747. }
  9748. },
  9749. defaults: {
  9750. enabled: true,
  9751. external: null,
  9752. position: 'average',
  9753. backgroundColor: 'rgba(0,0,0,0.8)',
  9754. titleColor: '#fff',
  9755. titleFont: {
  9756. weight: 'bold'
  9757. },
  9758. titleSpacing: 2,
  9759. titleMarginBottom: 6,
  9760. titleAlign: 'left',
  9761. bodyColor: '#fff',
  9762. bodySpacing: 2,
  9763. bodyFont: {},
  9764. bodyAlign: 'left',
  9765. footerColor: '#fff',
  9766. footerSpacing: 2,
  9767. footerMarginTop: 6,
  9768. footerFont: {
  9769. weight: 'bold'
  9770. },
  9771. footerAlign: 'left',
  9772. padding: 6,
  9773. caretPadding: 2,
  9774. caretSize: 5,
  9775. cornerRadius: 6,
  9776. boxHeight: (ctx, opts)=>opts.bodyFont.size,
  9777. boxWidth: (ctx, opts)=>opts.bodyFont.size,
  9778. multiKeyBackground: '#fff',
  9779. displayColors: true,
  9780. boxPadding: 0,
  9781. borderColor: 'rgba(0,0,0,0)',
  9782. borderWidth: 0,
  9783. animation: {
  9784. duration: 400,
  9785. easing: 'easeOutQuart'
  9786. },
  9787. animations: {
  9788. numbers: {
  9789. type: 'number',
  9790. properties: [
  9791. 'x',
  9792. 'y',
  9793. 'width',
  9794. 'height',
  9795. 'caretX',
  9796. 'caretY'
  9797. ]
  9798. },
  9799. opacity: {
  9800. easing: 'linear',
  9801. duration: 200
  9802. }
  9803. },
  9804. callbacks: defaultCallbacks
  9805. },
  9806. defaultRoutes: {
  9807. bodyFont: 'font',
  9808. footerFont: 'font',
  9809. titleFont: 'font'
  9810. },
  9811. descriptors: {
  9812. _scriptable: (name)=>name !== 'filter' && name !== 'itemSort' && name !== 'external',
  9813. _indexable: false,
  9814. callbacks: {
  9815. _scriptable: false,
  9816. _indexable: false
  9817. },
  9818. animation: {
  9819. _fallback: false
  9820. },
  9821. animations: {
  9822. _fallback: 'animation'
  9823. }
  9824. },
  9825. additionalOptionScopes: [
  9826. 'interaction'
  9827. ]
  9828. };
  9829. var plugins = /*#__PURE__*/Object.freeze({
  9830. __proto__: null,
  9831. Colors: plugin_colors,
  9832. Decimation: plugin_decimation,
  9833. Filler: index,
  9834. Legend: plugin_legend,
  9835. SubTitle: plugin_subtitle,
  9836. Title: plugin_title,
  9837. Tooltip: plugin_tooltip
  9838. });
  9839. const addIfString = (labels, raw, index, addedLabels)=>{
  9840. if (typeof raw === 'string') {
  9841. index = labels.push(raw) - 1;
  9842. addedLabels.unshift({
  9843. index,
  9844. label: raw
  9845. });
  9846. } else if (isNaN(raw)) {
  9847. index = null;
  9848. }
  9849. return index;
  9850. };
  9851. function findOrAddLabel(labels, raw, index, addedLabels) {
  9852. const first = labels.indexOf(raw);
  9853. if (first === -1) {
  9854. return addIfString(labels, raw, index, addedLabels);
  9855. }
  9856. const last = labels.lastIndexOf(raw);
  9857. return first !== last ? index : first;
  9858. }
  9859. const validIndex = (index, max)=>index === null ? null : helpers_segment._limitValue(Math.round(index), 0, max);
  9860. function _getLabelForValue(value) {
  9861. const labels = this.getLabels();
  9862. if (value >= 0 && value < labels.length) {
  9863. return labels[value];
  9864. }
  9865. return value;
  9866. }
  9867. class CategoryScale extends Scale {
  9868. static id = 'category';
  9869. static defaults = {
  9870. ticks: {
  9871. callback: _getLabelForValue
  9872. }
  9873. };
  9874. constructor(cfg){
  9875. super(cfg);
  9876. this._startValue = undefined;
  9877. this._valueRange = 0;
  9878. this._addedLabels = [];
  9879. }
  9880. init(scaleOptions) {
  9881. const added = this._addedLabels;
  9882. if (added.length) {
  9883. const labels = this.getLabels();
  9884. for (const { index , label } of added){
  9885. if (labels[index] === label) {
  9886. labels.splice(index, 1);
  9887. }
  9888. }
  9889. this._addedLabels = [];
  9890. }
  9891. super.init(scaleOptions);
  9892. }
  9893. parse(raw, index) {
  9894. if (helpers_segment.isNullOrUndef(raw)) {
  9895. return null;
  9896. }
  9897. const labels = this.getLabels();
  9898. index = isFinite(index) && labels[index] === raw ? index : findOrAddLabel(labels, raw, helpers_segment.valueOrDefault(index, raw), this._addedLabels);
  9899. return validIndex(index, labels.length - 1);
  9900. }
  9901. determineDataLimits() {
  9902. const { minDefined , maxDefined } = this.getUserBounds();
  9903. let { min , max } = this.getMinMax(true);
  9904. if (this.options.bounds === 'ticks') {
  9905. if (!minDefined) {
  9906. min = 0;
  9907. }
  9908. if (!maxDefined) {
  9909. max = this.getLabels().length - 1;
  9910. }
  9911. }
  9912. this.min = min;
  9913. this.max = max;
  9914. }
  9915. buildTicks() {
  9916. const min = this.min;
  9917. const max = this.max;
  9918. const offset = this.options.offset;
  9919. const ticks = [];
  9920. let labels = this.getLabels();
  9921. labels = min === 0 && max === labels.length - 1 ? labels : labels.slice(min, max + 1);
  9922. this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);
  9923. this._startValue = this.min - (offset ? 0.5 : 0);
  9924. for(let value = min; value <= max; value++){
  9925. ticks.push({
  9926. value
  9927. });
  9928. }
  9929. return ticks;
  9930. }
  9931. getLabelForValue(value) {
  9932. return _getLabelForValue.call(this, value);
  9933. }
  9934. configure() {
  9935. super.configure();
  9936. if (!this.isHorizontal()) {
  9937. this._reversePixels = !this._reversePixels;
  9938. }
  9939. }
  9940. getPixelForValue(value) {
  9941. if (typeof value !== 'number') {
  9942. value = this.parse(value);
  9943. }
  9944. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  9945. }
  9946. getPixelForTick(index) {
  9947. const ticks = this.ticks;
  9948. if (index < 0 || index > ticks.length - 1) {
  9949. return null;
  9950. }
  9951. return this.getPixelForValue(ticks[index].value);
  9952. }
  9953. getValueForPixel(pixel) {
  9954. return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange);
  9955. }
  9956. getBasePixel() {
  9957. return this.bottom;
  9958. }
  9959. }
  9960. function generateTicks$1(generationOptions, dataRange) {
  9961. const ticks = [];
  9962. const MIN_SPACING = 1e-14;
  9963. const { bounds , step , min , max , precision , count , maxTicks , maxDigits , includeBounds } = generationOptions;
  9964. const unit = step || 1;
  9965. const maxSpaces = maxTicks - 1;
  9966. const { min: rmin , max: rmax } = dataRange;
  9967. const minDefined = !helpers_segment.isNullOrUndef(min);
  9968. const maxDefined = !helpers_segment.isNullOrUndef(max);
  9969. const countDefined = !helpers_segment.isNullOrUndef(count);
  9970. const minSpacing = (rmax - rmin) / (maxDigits + 1);
  9971. let spacing = helpers_segment.niceNum((rmax - rmin) / maxSpaces / unit) * unit;
  9972. let factor, niceMin, niceMax, numSpaces;
  9973. if (spacing < MIN_SPACING && !minDefined && !maxDefined) {
  9974. return [
  9975. {
  9976. value: rmin
  9977. },
  9978. {
  9979. value: rmax
  9980. }
  9981. ];
  9982. }
  9983. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  9984. if (numSpaces > maxSpaces) {
  9985. spacing = helpers_segment.niceNum(numSpaces * spacing / maxSpaces / unit) * unit;
  9986. }
  9987. if (!helpers_segment.isNullOrUndef(precision)) {
  9988. factor = Math.pow(10, precision);
  9989. spacing = Math.ceil(spacing * factor) / factor;
  9990. }
  9991. if (bounds === 'ticks') {
  9992. niceMin = Math.floor(rmin / spacing) * spacing;
  9993. niceMax = Math.ceil(rmax / spacing) * spacing;
  9994. } else {
  9995. niceMin = rmin;
  9996. niceMax = rmax;
  9997. }
  9998. if (minDefined && maxDefined && step && helpers_segment.almostWhole((max - min) / step, spacing / 1000)) {
  9999. numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks));
  10000. spacing = (max - min) / numSpaces;
  10001. niceMin = min;
  10002. niceMax = max;
  10003. } else if (countDefined) {
  10004. niceMin = minDefined ? min : niceMin;
  10005. niceMax = maxDefined ? max : niceMax;
  10006. numSpaces = count - 1;
  10007. spacing = (niceMax - niceMin) / numSpaces;
  10008. } else {
  10009. numSpaces = (niceMax - niceMin) / spacing;
  10010. if (helpers_segment.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  10011. numSpaces = Math.round(numSpaces);
  10012. } else {
  10013. numSpaces = Math.ceil(numSpaces);
  10014. }
  10015. }
  10016. const decimalPlaces = Math.max(helpers_segment._decimalPlaces(spacing), helpers_segment._decimalPlaces(niceMin));
  10017. factor = Math.pow(10, helpers_segment.isNullOrUndef(precision) ? decimalPlaces : precision);
  10018. niceMin = Math.round(niceMin * factor) / factor;
  10019. niceMax = Math.round(niceMax * factor) / factor;
  10020. let j = 0;
  10021. if (minDefined) {
  10022. if (includeBounds && niceMin !== min) {
  10023. ticks.push({
  10024. value: min
  10025. });
  10026. if (niceMin < min) {
  10027. j++;
  10028. }
  10029. if (helpers_segment.almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) {
  10030. j++;
  10031. }
  10032. } else if (niceMin < min) {
  10033. j++;
  10034. }
  10035. }
  10036. for(; j < numSpaces; ++j){
  10037. const tickValue = Math.round((niceMin + j * spacing) * factor) / factor;
  10038. if (maxDefined && tickValue > max) {
  10039. break;
  10040. }
  10041. ticks.push({
  10042. value: tickValue
  10043. });
  10044. }
  10045. if (maxDefined && includeBounds && niceMax !== max) {
  10046. if (ticks.length && helpers_segment.almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) {
  10047. ticks[ticks.length - 1].value = max;
  10048. } else {
  10049. ticks.push({
  10050. value: max
  10051. });
  10052. }
  10053. } else if (!maxDefined || niceMax === max) {
  10054. ticks.push({
  10055. value: niceMax
  10056. });
  10057. }
  10058. return ticks;
  10059. }
  10060. function relativeLabelSize(value, minSpacing, { horizontal , minRotation }) {
  10061. const rad = helpers_segment.toRadians(minRotation);
  10062. const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001;
  10063. const length = 0.75 * minSpacing * ('' + value).length;
  10064. return Math.min(minSpacing / ratio, length);
  10065. }
  10066. class LinearScaleBase extends Scale {
  10067. constructor(cfg){
  10068. super(cfg);
  10069. this.start = undefined;
  10070. this.end = undefined;
  10071. this._startValue = undefined;
  10072. this._endValue = undefined;
  10073. this._valueRange = 0;
  10074. }
  10075. parse(raw, index) {
  10076. if (helpers_segment.isNullOrUndef(raw)) {
  10077. return null;
  10078. }
  10079. if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {
  10080. return null;
  10081. }
  10082. return +raw;
  10083. }
  10084. handleTickRangeOptions() {
  10085. const { beginAtZero } = this.options;
  10086. const { minDefined , maxDefined } = this.getUserBounds();
  10087. let { min , max } = this;
  10088. const setMin = (v)=>min = minDefined ? min : v;
  10089. const setMax = (v)=>max = maxDefined ? max : v;
  10090. if (beginAtZero) {
  10091. const minSign = helpers_segment.sign(min);
  10092. const maxSign = helpers_segment.sign(max);
  10093. if (minSign < 0 && maxSign < 0) {
  10094. setMax(0);
  10095. } else if (minSign > 0 && maxSign > 0) {
  10096. setMin(0);
  10097. }
  10098. }
  10099. if (min === max) {
  10100. let offset = max === 0 ? 1 : Math.abs(max * 0.05);
  10101. setMax(max + offset);
  10102. if (!beginAtZero) {
  10103. setMin(min - offset);
  10104. }
  10105. }
  10106. this.min = min;
  10107. this.max = max;
  10108. }
  10109. getTickLimit() {
  10110. const tickOpts = this.options.ticks;
  10111. let { maxTicksLimit , stepSize } = tickOpts;
  10112. let maxTicks;
  10113. if (stepSize) {
  10114. maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1;
  10115. if (maxTicks > 1000) {
  10116. console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`);
  10117. maxTicks = 1000;
  10118. }
  10119. } else {
  10120. maxTicks = this.computeTickLimit();
  10121. maxTicksLimit = maxTicksLimit || 11;
  10122. }
  10123. if (maxTicksLimit) {
  10124. maxTicks = Math.min(maxTicksLimit, maxTicks);
  10125. }
  10126. return maxTicks;
  10127. }
  10128. computeTickLimit() {
  10129. return Number.POSITIVE_INFINITY;
  10130. }
  10131. buildTicks() {
  10132. const opts = this.options;
  10133. const tickOpts = opts.ticks;
  10134. let maxTicks = this.getTickLimit();
  10135. maxTicks = Math.max(2, maxTicks);
  10136. const numericGeneratorOptions = {
  10137. maxTicks,
  10138. bounds: opts.bounds,
  10139. min: opts.min,
  10140. max: opts.max,
  10141. precision: tickOpts.precision,
  10142. step: tickOpts.stepSize,
  10143. count: tickOpts.count,
  10144. maxDigits: this._maxDigits(),
  10145. horizontal: this.isHorizontal(),
  10146. minRotation: tickOpts.minRotation || 0,
  10147. includeBounds: tickOpts.includeBounds !== false
  10148. };
  10149. const dataRange = this._range || this;
  10150. const ticks = generateTicks$1(numericGeneratorOptions, dataRange);
  10151. if (opts.bounds === 'ticks') {
  10152. helpers_segment._setMinAndMaxByKey(ticks, this, 'value');
  10153. }
  10154. if (opts.reverse) {
  10155. ticks.reverse();
  10156. this.start = this.max;
  10157. this.end = this.min;
  10158. } else {
  10159. this.start = this.min;
  10160. this.end = this.max;
  10161. }
  10162. return ticks;
  10163. }
  10164. configure() {
  10165. const ticks = this.ticks;
  10166. let start = this.min;
  10167. let end = this.max;
  10168. super.configure();
  10169. if (this.options.offset && ticks.length) {
  10170. const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  10171. start -= offset;
  10172. end += offset;
  10173. }
  10174. this._startValue = start;
  10175. this._endValue = end;
  10176. this._valueRange = end - start;
  10177. }
  10178. getLabelForValue(value) {
  10179. return helpers_segment.formatNumber(value, this.chart.options.locale, this.options.ticks.format);
  10180. }
  10181. }
  10182. class LinearScale extends LinearScaleBase {
  10183. static id = 'linear';
  10184. static defaults = {
  10185. ticks: {
  10186. callback: helpers_segment.Ticks.formatters.numeric
  10187. }
  10188. };
  10189. determineDataLimits() {
  10190. const { min , max } = this.getMinMax(true);
  10191. this.min = helpers_segment.isNumberFinite(min) ? min : 0;
  10192. this.max = helpers_segment.isNumberFinite(max) ? max : 1;
  10193. this.handleTickRangeOptions();
  10194. }
  10195. computeTickLimit() {
  10196. const horizontal = this.isHorizontal();
  10197. const length = horizontal ? this.width : this.height;
  10198. const minRotation = helpers_segment.toRadians(this.options.ticks.minRotation);
  10199. const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001;
  10200. const tickFont = this._resolveTickFontOptions(0);
  10201. return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio));
  10202. }
  10203. getPixelForValue(value) {
  10204. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  10205. }
  10206. getValueForPixel(pixel) {
  10207. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  10208. }
  10209. }
  10210. const log10Floor = (v)=>Math.floor(helpers_segment.log10(v));
  10211. const changeExponent = (v, m)=>Math.pow(10, log10Floor(v) + m);
  10212. function isMajor(tickVal) {
  10213. const remain = tickVal / Math.pow(10, log10Floor(tickVal));
  10214. return remain === 1;
  10215. }
  10216. function steps(min, max, rangeExp) {
  10217. const rangeStep = Math.pow(10, rangeExp);
  10218. const start = Math.floor(min / rangeStep);
  10219. const end = Math.ceil(max / rangeStep);
  10220. return end - start;
  10221. }
  10222. function startExp(min, max) {
  10223. const range = max - min;
  10224. let rangeExp = log10Floor(range);
  10225. while(steps(min, max, rangeExp) > 10){
  10226. rangeExp++;
  10227. }
  10228. while(steps(min, max, rangeExp) < 10){
  10229. rangeExp--;
  10230. }
  10231. return Math.min(rangeExp, log10Floor(min));
  10232. }
  10233. function generateTicks(generationOptions, { min , max }) {
  10234. min = helpers_segment.finiteOrDefault(generationOptions.min, min);
  10235. const ticks = [];
  10236. const minExp = log10Floor(min);
  10237. let exp = startExp(min, max);
  10238. let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  10239. const stepSize = Math.pow(10, exp);
  10240. const base = minExp > exp ? Math.pow(10, minExp) : 0;
  10241. const start = Math.round((min - base) * precision) / precision;
  10242. const offset = Math.floor((min - base) / stepSize / 10) * stepSize * 10;
  10243. let significand = Math.floor((start - offset) / Math.pow(10, exp));
  10244. let value = helpers_segment.finiteOrDefault(generationOptions.min, Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision);
  10245. while(value < max){
  10246. ticks.push({
  10247. value,
  10248. major: isMajor(value),
  10249. significand
  10250. });
  10251. if (significand >= 10) {
  10252. significand = significand < 15 ? 15 : 20;
  10253. } else {
  10254. significand++;
  10255. }
  10256. if (significand >= 20) {
  10257. exp++;
  10258. significand = 2;
  10259. precision = exp >= 0 ? 1 : precision;
  10260. }
  10261. value = Math.round((base + offset + significand * Math.pow(10, exp)) * precision) / precision;
  10262. }
  10263. const lastTick = helpers_segment.finiteOrDefault(generationOptions.max, value);
  10264. ticks.push({
  10265. value: lastTick,
  10266. major: isMajor(lastTick),
  10267. significand
  10268. });
  10269. return ticks;
  10270. }
  10271. class LogarithmicScale extends Scale {
  10272. static id = 'logarithmic';
  10273. static defaults = {
  10274. ticks: {
  10275. callback: helpers_segment.Ticks.formatters.logarithmic,
  10276. major: {
  10277. enabled: true
  10278. }
  10279. }
  10280. };
  10281. constructor(cfg){
  10282. super(cfg);
  10283. this.start = undefined;
  10284. this.end = undefined;
  10285. this._startValue = undefined;
  10286. this._valueRange = 0;
  10287. }
  10288. parse(raw, index) {
  10289. const value = LinearScaleBase.prototype.parse.apply(this, [
  10290. raw,
  10291. index
  10292. ]);
  10293. if (value === 0) {
  10294. this._zero = true;
  10295. return undefined;
  10296. }
  10297. return helpers_segment.isNumberFinite(value) && value > 0 ? value : null;
  10298. }
  10299. determineDataLimits() {
  10300. const { min , max } = this.getMinMax(true);
  10301. this.min = helpers_segment.isNumberFinite(min) ? Math.max(0, min) : null;
  10302. this.max = helpers_segment.isNumberFinite(max) ? Math.max(0, max) : null;
  10303. if (this.options.beginAtZero) {
  10304. this._zero = true;
  10305. }
  10306. if (this._zero && this.min !== this._suggestedMin && !helpers_segment.isNumberFinite(this._userMin)) {
  10307. this.min = min === changeExponent(this.min, 0) ? changeExponent(this.min, -1) : changeExponent(this.min, 0);
  10308. }
  10309. this.handleTickRangeOptions();
  10310. }
  10311. handleTickRangeOptions() {
  10312. const { minDefined , maxDefined } = this.getUserBounds();
  10313. let min = this.min;
  10314. let max = this.max;
  10315. const setMin = (v)=>min = minDefined ? min : v;
  10316. const setMax = (v)=>max = maxDefined ? max : v;
  10317. if (min === max) {
  10318. if (min <= 0) {
  10319. setMin(1);
  10320. setMax(10);
  10321. } else {
  10322. setMin(changeExponent(min, -1));
  10323. setMax(changeExponent(max, +1));
  10324. }
  10325. }
  10326. if (min <= 0) {
  10327. setMin(changeExponent(max, -1));
  10328. }
  10329. if (max <= 0) {
  10330. setMax(changeExponent(min, +1));
  10331. }
  10332. this.min = min;
  10333. this.max = max;
  10334. }
  10335. buildTicks() {
  10336. const opts = this.options;
  10337. const generationOptions = {
  10338. min: this._userMin,
  10339. max: this._userMax
  10340. };
  10341. const ticks = generateTicks(generationOptions, this);
  10342. if (opts.bounds === 'ticks') {
  10343. helpers_segment._setMinAndMaxByKey(ticks, this, 'value');
  10344. }
  10345. if (opts.reverse) {
  10346. ticks.reverse();
  10347. this.start = this.max;
  10348. this.end = this.min;
  10349. } else {
  10350. this.start = this.min;
  10351. this.end = this.max;
  10352. }
  10353. return ticks;
  10354. }
  10355. getLabelForValue(value) {
  10356. return value === undefined ? '0' : helpers_segment.formatNumber(value, this.chart.options.locale, this.options.ticks.format);
  10357. }
  10358. configure() {
  10359. const start = this.min;
  10360. super.configure();
  10361. this._startValue = helpers_segment.log10(start);
  10362. this._valueRange = helpers_segment.log10(this.max) - helpers_segment.log10(start);
  10363. }
  10364. getPixelForValue(value) {
  10365. if (value === undefined || value === 0) {
  10366. value = this.min;
  10367. }
  10368. if (value === null || isNaN(value)) {
  10369. return NaN;
  10370. }
  10371. return this.getPixelForDecimal(value === this.min ? 0 : (helpers_segment.log10(value) - this._startValue) / this._valueRange);
  10372. }
  10373. getValueForPixel(pixel) {
  10374. const decimal = this.getDecimalForPixel(pixel);
  10375. return Math.pow(10, this._startValue + decimal * this._valueRange);
  10376. }
  10377. }
  10378. function getTickBackdropHeight(opts) {
  10379. const tickOpts = opts.ticks;
  10380. if (tickOpts.display && opts.display) {
  10381. const padding = helpers_segment.toPadding(tickOpts.backdropPadding);
  10382. return helpers_segment.valueOrDefault(tickOpts.font && tickOpts.font.size, helpers_segment.defaults.font.size) + padding.height;
  10383. }
  10384. return 0;
  10385. }
  10386. function measureLabelSize(ctx, font, label) {
  10387. label = helpers_segment.isArray(label) ? label : [
  10388. label
  10389. ];
  10390. return {
  10391. w: helpers_segment._longestText(ctx, font.string, label),
  10392. h: label.length * font.lineHeight
  10393. };
  10394. }
  10395. function determineLimits(angle, pos, size, min, max) {
  10396. if (angle === min || angle === max) {
  10397. return {
  10398. start: pos - size / 2,
  10399. end: pos + size / 2
  10400. };
  10401. } else if (angle < min || angle > max) {
  10402. return {
  10403. start: pos - size,
  10404. end: pos
  10405. };
  10406. }
  10407. return {
  10408. start: pos,
  10409. end: pos + size
  10410. };
  10411. }
  10412. function fitWithPointLabels(scale) {
  10413. const orig = {
  10414. l: scale.left + scale._padding.left,
  10415. r: scale.right - scale._padding.right,
  10416. t: scale.top + scale._padding.top,
  10417. b: scale.bottom - scale._padding.bottom
  10418. };
  10419. const limits = Object.assign({}, orig);
  10420. const labelSizes = [];
  10421. const padding = [];
  10422. const valueCount = scale._pointLabels.length;
  10423. const pointLabelOpts = scale.options.pointLabels;
  10424. const additionalAngle = pointLabelOpts.centerPointLabels ? helpers_segment.PI / valueCount : 0;
  10425. for(let i = 0; i < valueCount; i++){
  10426. const opts = pointLabelOpts.setContext(scale.getPointLabelContext(i));
  10427. padding[i] = opts.padding;
  10428. const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle);
  10429. const plFont = helpers_segment.toFont(opts.font);
  10430. const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]);
  10431. labelSizes[i] = textSize;
  10432. const angleRadians = helpers_segment._normalizeAngle(scale.getIndexAngle(i) + additionalAngle);
  10433. const angle = Math.round(helpers_segment.toDegrees(angleRadians));
  10434. const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  10435. const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  10436. updateLimits(limits, orig, angleRadians, hLimits, vLimits);
  10437. }
  10438. scale.setCenterPoint(orig.l - limits.l, limits.r - orig.r, orig.t - limits.t, limits.b - orig.b);
  10439. scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding);
  10440. }
  10441. function updateLimits(limits, orig, angle, hLimits, vLimits) {
  10442. const sin = Math.abs(Math.sin(angle));
  10443. const cos = Math.abs(Math.cos(angle));
  10444. let x = 0;
  10445. let y = 0;
  10446. if (hLimits.start < orig.l) {
  10447. x = (orig.l - hLimits.start) / sin;
  10448. limits.l = Math.min(limits.l, orig.l - x);
  10449. } else if (hLimits.end > orig.r) {
  10450. x = (hLimits.end - orig.r) / sin;
  10451. limits.r = Math.max(limits.r, orig.r + x);
  10452. }
  10453. if (vLimits.start < orig.t) {
  10454. y = (orig.t - vLimits.start) / cos;
  10455. limits.t = Math.min(limits.t, orig.t - y);
  10456. } else if (vLimits.end > orig.b) {
  10457. y = (vLimits.end - orig.b) / cos;
  10458. limits.b = Math.max(limits.b, orig.b + y);
  10459. }
  10460. }
  10461. function createPointLabelItem(scale, index, itemOpts) {
  10462. const outerDistance = scale.drawingArea;
  10463. const { extra , additionalAngle , padding , size } = itemOpts;
  10464. const pointLabelPosition = scale.getPointPosition(index, outerDistance + extra + padding, additionalAngle);
  10465. const angle = Math.round(helpers_segment.toDegrees(helpers_segment._normalizeAngle(pointLabelPosition.angle + helpers_segment.HALF_PI)));
  10466. const y = yForAngle(pointLabelPosition.y, size.h, angle);
  10467. const textAlign = getTextAlignForAngle(angle);
  10468. const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign);
  10469. return {
  10470. visible: true,
  10471. x: pointLabelPosition.x,
  10472. y,
  10473. textAlign,
  10474. left,
  10475. top: y,
  10476. right: left + size.w,
  10477. bottom: y + size.h
  10478. };
  10479. }
  10480. function isNotOverlapped(item, area) {
  10481. if (!area) {
  10482. return true;
  10483. }
  10484. const { left , top , right , bottom } = item;
  10485. const apexesInArea = helpers_segment._isPointInArea({
  10486. x: left,
  10487. y: top
  10488. }, area) || helpers_segment._isPointInArea({
  10489. x: left,
  10490. y: bottom
  10491. }, area) || helpers_segment._isPointInArea({
  10492. x: right,
  10493. y: top
  10494. }, area) || helpers_segment._isPointInArea({
  10495. x: right,
  10496. y: bottom
  10497. }, area);
  10498. return !apexesInArea;
  10499. }
  10500. function buildPointLabelItems(scale, labelSizes, padding) {
  10501. const items = [];
  10502. const valueCount = scale._pointLabels.length;
  10503. const opts = scale.options;
  10504. const { centerPointLabels , display } = opts.pointLabels;
  10505. const itemOpts = {
  10506. extra: getTickBackdropHeight(opts) / 2,
  10507. additionalAngle: centerPointLabels ? helpers_segment.PI / valueCount : 0
  10508. };
  10509. let area;
  10510. for(let i = 0; i < valueCount; i++){
  10511. itemOpts.padding = padding[i];
  10512. itemOpts.size = labelSizes[i];
  10513. const item = createPointLabelItem(scale, i, itemOpts);
  10514. items.push(item);
  10515. if (display === 'auto') {
  10516. item.visible = isNotOverlapped(item, area);
  10517. if (item.visible) {
  10518. area = item;
  10519. }
  10520. }
  10521. }
  10522. return items;
  10523. }
  10524. function getTextAlignForAngle(angle) {
  10525. if (angle === 0 || angle === 180) {
  10526. return 'center';
  10527. } else if (angle < 180) {
  10528. return 'left';
  10529. }
  10530. return 'right';
  10531. }
  10532. function leftForTextAlign(x, w, align) {
  10533. if (align === 'right') {
  10534. x -= w;
  10535. } else if (align === 'center') {
  10536. x -= w / 2;
  10537. }
  10538. return x;
  10539. }
  10540. function yForAngle(y, h, angle) {
  10541. if (angle === 90 || angle === 270) {
  10542. y -= h / 2;
  10543. } else if (angle > 270 || angle < 90) {
  10544. y -= h;
  10545. }
  10546. return y;
  10547. }
  10548. function drawPointLabelBox(ctx, opts, item) {
  10549. const { left , top , right , bottom } = item;
  10550. const { backdropColor } = opts;
  10551. if (!helpers_segment.isNullOrUndef(backdropColor)) {
  10552. const borderRadius = helpers_segment.toTRBLCorners(opts.borderRadius);
  10553. const padding = helpers_segment.toPadding(opts.backdropPadding);
  10554. ctx.fillStyle = backdropColor;
  10555. const backdropLeft = left - padding.left;
  10556. const backdropTop = top - padding.top;
  10557. const backdropWidth = right - left + padding.width;
  10558. const backdropHeight = bottom - top + padding.height;
  10559. if (Object.values(borderRadius).some((v)=>v !== 0)) {
  10560. ctx.beginPath();
  10561. helpers_segment.addRoundedRectPath(ctx, {
  10562. x: backdropLeft,
  10563. y: backdropTop,
  10564. w: backdropWidth,
  10565. h: backdropHeight,
  10566. radius: borderRadius
  10567. });
  10568. ctx.fill();
  10569. } else {
  10570. ctx.fillRect(backdropLeft, backdropTop, backdropWidth, backdropHeight);
  10571. }
  10572. }
  10573. }
  10574. function drawPointLabels(scale, labelCount) {
  10575. const { ctx , options: { pointLabels } } = scale;
  10576. for(let i = labelCount - 1; i >= 0; i--){
  10577. const item = scale._pointLabelItems[i];
  10578. if (!item.visible) {
  10579. continue;
  10580. }
  10581. const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i));
  10582. drawPointLabelBox(ctx, optsAtIndex, item);
  10583. const plFont = helpers_segment.toFont(optsAtIndex.font);
  10584. const { x , y , textAlign } = item;
  10585. helpers_segment.renderText(ctx, scale._pointLabels[i], x, y + plFont.lineHeight / 2, plFont, {
  10586. color: optsAtIndex.color,
  10587. textAlign: textAlign,
  10588. textBaseline: 'middle'
  10589. });
  10590. }
  10591. }
  10592. function pathRadiusLine(scale, radius, circular, labelCount) {
  10593. const { ctx } = scale;
  10594. if (circular) {
  10595. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, helpers_segment.TAU);
  10596. } else {
  10597. let pointPosition = scale.getPointPosition(0, radius);
  10598. ctx.moveTo(pointPosition.x, pointPosition.y);
  10599. for(let i = 1; i < labelCount; i++){
  10600. pointPosition = scale.getPointPosition(i, radius);
  10601. ctx.lineTo(pointPosition.x, pointPosition.y);
  10602. }
  10603. }
  10604. }
  10605. function drawRadiusLine(scale, gridLineOpts, radius, labelCount, borderOpts) {
  10606. const ctx = scale.ctx;
  10607. const circular = gridLineOpts.circular;
  10608. const { color , lineWidth } = gridLineOpts;
  10609. if (!circular && !labelCount || !color || !lineWidth || radius < 0) {
  10610. return;
  10611. }
  10612. ctx.save();
  10613. ctx.strokeStyle = color;
  10614. ctx.lineWidth = lineWidth;
  10615. ctx.setLineDash(borderOpts.dash);
  10616. ctx.lineDashOffset = borderOpts.dashOffset;
  10617. ctx.beginPath();
  10618. pathRadiusLine(scale, radius, circular, labelCount);
  10619. ctx.closePath();
  10620. ctx.stroke();
  10621. ctx.restore();
  10622. }
  10623. function createPointLabelContext(parent, index, label) {
  10624. return helpers_segment.createContext(parent, {
  10625. label,
  10626. index,
  10627. type: 'pointLabel'
  10628. });
  10629. }
  10630. class RadialLinearScale extends LinearScaleBase {
  10631. static id = 'radialLinear';
  10632. static defaults = {
  10633. display: true,
  10634. animate: true,
  10635. position: 'chartArea',
  10636. angleLines: {
  10637. display: true,
  10638. lineWidth: 1,
  10639. borderDash: [],
  10640. borderDashOffset: 0.0
  10641. },
  10642. grid: {
  10643. circular: false
  10644. },
  10645. startAngle: 0,
  10646. ticks: {
  10647. showLabelBackdrop: true,
  10648. callback: helpers_segment.Ticks.formatters.numeric
  10649. },
  10650. pointLabels: {
  10651. backdropColor: undefined,
  10652. backdropPadding: 2,
  10653. display: true,
  10654. font: {
  10655. size: 10
  10656. },
  10657. callback (label) {
  10658. return label;
  10659. },
  10660. padding: 5,
  10661. centerPointLabels: false
  10662. }
  10663. };
  10664. static defaultRoutes = {
  10665. 'angleLines.color': 'borderColor',
  10666. 'pointLabels.color': 'color',
  10667. 'ticks.color': 'color'
  10668. };
  10669. static descriptors = {
  10670. angleLines: {
  10671. _fallback: 'grid'
  10672. }
  10673. };
  10674. constructor(cfg){
  10675. super(cfg);
  10676. this.xCenter = undefined;
  10677. this.yCenter = undefined;
  10678. this.drawingArea = undefined;
  10679. this._pointLabels = [];
  10680. this._pointLabelItems = [];
  10681. }
  10682. setDimensions() {
  10683. const padding = this._padding = helpers_segment.toPadding(getTickBackdropHeight(this.options) / 2);
  10684. const w = this.width = this.maxWidth - padding.width;
  10685. const h = this.height = this.maxHeight - padding.height;
  10686. this.xCenter = Math.floor(this.left + w / 2 + padding.left);
  10687. this.yCenter = Math.floor(this.top + h / 2 + padding.top);
  10688. this.drawingArea = Math.floor(Math.min(w, h) / 2);
  10689. }
  10690. determineDataLimits() {
  10691. const { min , max } = this.getMinMax(false);
  10692. this.min = helpers_segment.isNumberFinite(min) && !isNaN(min) ? min : 0;
  10693. this.max = helpers_segment.isNumberFinite(max) && !isNaN(max) ? max : 0;
  10694. this.handleTickRangeOptions();
  10695. }
  10696. computeTickLimit() {
  10697. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  10698. }
  10699. generateTickLabels(ticks) {
  10700. LinearScaleBase.prototype.generateTickLabels.call(this, ticks);
  10701. this._pointLabels = this.getLabels().map((value, index)=>{
  10702. const label = helpers_segment.callback(this.options.pointLabels.callback, [
  10703. value,
  10704. index
  10705. ], this);
  10706. return label || label === 0 ? label : '';
  10707. }).filter((v, i)=>this.chart.getDataVisibility(i));
  10708. }
  10709. fit() {
  10710. const opts = this.options;
  10711. if (opts.display && opts.pointLabels.display) {
  10712. fitWithPointLabels(this);
  10713. } else {
  10714. this.setCenterPoint(0, 0, 0, 0);
  10715. }
  10716. }
  10717. setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {
  10718. this.xCenter += Math.floor((leftMovement - rightMovement) / 2);
  10719. this.yCenter += Math.floor((topMovement - bottomMovement) / 2);
  10720. this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement));
  10721. }
  10722. getIndexAngle(index) {
  10723. const angleMultiplier = helpers_segment.TAU / (this._pointLabels.length || 1);
  10724. const startAngle = this.options.startAngle || 0;
  10725. return helpers_segment._normalizeAngle(index * angleMultiplier + helpers_segment.toRadians(startAngle));
  10726. }
  10727. getDistanceFromCenterForValue(value) {
  10728. if (helpers_segment.isNullOrUndef(value)) {
  10729. return NaN;
  10730. }
  10731. const scalingFactor = this.drawingArea / (this.max - this.min);
  10732. if (this.options.reverse) {
  10733. return (this.max - value) * scalingFactor;
  10734. }
  10735. return (value - this.min) * scalingFactor;
  10736. }
  10737. getValueForDistanceFromCenter(distance) {
  10738. if (helpers_segment.isNullOrUndef(distance)) {
  10739. return NaN;
  10740. }
  10741. const scaledDistance = distance / (this.drawingArea / (this.max - this.min));
  10742. return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance;
  10743. }
  10744. getPointLabelContext(index) {
  10745. const pointLabels = this._pointLabels || [];
  10746. if (index >= 0 && index < pointLabels.length) {
  10747. const pointLabel = pointLabels[index];
  10748. return createPointLabelContext(this.getContext(), index, pointLabel);
  10749. }
  10750. }
  10751. getPointPosition(index, distanceFromCenter, additionalAngle = 0) {
  10752. const angle = this.getIndexAngle(index) - helpers_segment.HALF_PI + additionalAngle;
  10753. return {
  10754. x: Math.cos(angle) * distanceFromCenter + this.xCenter,
  10755. y: Math.sin(angle) * distanceFromCenter + this.yCenter,
  10756. angle
  10757. };
  10758. }
  10759. getPointPositionForValue(index, value) {
  10760. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  10761. }
  10762. getBasePosition(index) {
  10763. return this.getPointPositionForValue(index || 0, this.getBaseValue());
  10764. }
  10765. getPointLabelPosition(index) {
  10766. const { left , top , right , bottom } = this._pointLabelItems[index];
  10767. return {
  10768. left,
  10769. top,
  10770. right,
  10771. bottom
  10772. };
  10773. }
  10774. drawBackground() {
  10775. const { backgroundColor , grid: { circular } } = this.options;
  10776. if (backgroundColor) {
  10777. const ctx = this.ctx;
  10778. ctx.save();
  10779. ctx.beginPath();
  10780. pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length);
  10781. ctx.closePath();
  10782. ctx.fillStyle = backgroundColor;
  10783. ctx.fill();
  10784. ctx.restore();
  10785. }
  10786. }
  10787. drawGrid() {
  10788. const ctx = this.ctx;
  10789. const opts = this.options;
  10790. const { angleLines , grid , border } = opts;
  10791. const labelCount = this._pointLabels.length;
  10792. let i, offset, position;
  10793. if (opts.pointLabels.display) {
  10794. drawPointLabels(this, labelCount);
  10795. }
  10796. if (grid.display) {
  10797. this.ticks.forEach((tick, index)=>{
  10798. if (index !== 0 || index === 0 && this.min < 0) {
  10799. offset = this.getDistanceFromCenterForValue(tick.value);
  10800. const context = this.getContext(index);
  10801. const optsAtIndex = grid.setContext(context);
  10802. const optsAtIndexBorder = border.setContext(context);
  10803. drawRadiusLine(this, optsAtIndex, offset, labelCount, optsAtIndexBorder);
  10804. }
  10805. });
  10806. }
  10807. if (angleLines.display) {
  10808. ctx.save();
  10809. for(i = labelCount - 1; i >= 0; i--){
  10810. const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i));
  10811. const { color , lineWidth } = optsAtIndex;
  10812. if (!lineWidth || !color) {
  10813. continue;
  10814. }
  10815. ctx.lineWidth = lineWidth;
  10816. ctx.strokeStyle = color;
  10817. ctx.setLineDash(optsAtIndex.borderDash);
  10818. ctx.lineDashOffset = optsAtIndex.borderDashOffset;
  10819. offset = this.getDistanceFromCenterForValue(opts.reverse ? this.min : this.max);
  10820. position = this.getPointPosition(i, offset);
  10821. ctx.beginPath();
  10822. ctx.moveTo(this.xCenter, this.yCenter);
  10823. ctx.lineTo(position.x, position.y);
  10824. ctx.stroke();
  10825. }
  10826. ctx.restore();
  10827. }
  10828. }
  10829. drawBorder() {}
  10830. drawLabels() {
  10831. const ctx = this.ctx;
  10832. const opts = this.options;
  10833. const tickOpts = opts.ticks;
  10834. if (!tickOpts.display) {
  10835. return;
  10836. }
  10837. const startAngle = this.getIndexAngle(0);
  10838. let offset, width;
  10839. ctx.save();
  10840. ctx.translate(this.xCenter, this.yCenter);
  10841. ctx.rotate(startAngle);
  10842. ctx.textAlign = 'center';
  10843. ctx.textBaseline = 'middle';
  10844. this.ticks.forEach((tick, index)=>{
  10845. if (index === 0 && this.min >= 0 && !opts.reverse) {
  10846. return;
  10847. }
  10848. const optsAtIndex = tickOpts.setContext(this.getContext(index));
  10849. const tickFont = helpers_segment.toFont(optsAtIndex.font);
  10850. offset = this.getDistanceFromCenterForValue(this.ticks[index].value);
  10851. if (optsAtIndex.showLabelBackdrop) {
  10852. ctx.font = tickFont.string;
  10853. width = ctx.measureText(tick.label).width;
  10854. ctx.fillStyle = optsAtIndex.backdropColor;
  10855. const padding = helpers_segment.toPadding(optsAtIndex.backdropPadding);
  10856. ctx.fillRect(-width / 2 - padding.left, -offset - tickFont.size / 2 - padding.top, width + padding.width, tickFont.size + padding.height);
  10857. }
  10858. helpers_segment.renderText(ctx, tick.label, 0, -offset, tickFont, {
  10859. color: optsAtIndex.color,
  10860. strokeColor: optsAtIndex.textStrokeColor,
  10861. strokeWidth: optsAtIndex.textStrokeWidth
  10862. });
  10863. });
  10864. ctx.restore();
  10865. }
  10866. drawTitle() {}
  10867. }
  10868. const INTERVALS = {
  10869. millisecond: {
  10870. common: true,
  10871. size: 1,
  10872. steps: 1000
  10873. },
  10874. second: {
  10875. common: true,
  10876. size: 1000,
  10877. steps: 60
  10878. },
  10879. minute: {
  10880. common: true,
  10881. size: 60000,
  10882. steps: 60
  10883. },
  10884. hour: {
  10885. common: true,
  10886. size: 3600000,
  10887. steps: 24
  10888. },
  10889. day: {
  10890. common: true,
  10891. size: 86400000,
  10892. steps: 30
  10893. },
  10894. week: {
  10895. common: false,
  10896. size: 604800000,
  10897. steps: 4
  10898. },
  10899. month: {
  10900. common: true,
  10901. size: 2.628e9,
  10902. steps: 12
  10903. },
  10904. quarter: {
  10905. common: false,
  10906. size: 7.884e9,
  10907. steps: 4
  10908. },
  10909. year: {
  10910. common: true,
  10911. size: 3.154e10
  10912. }
  10913. };
  10914. const UNITS = /* #__PURE__ */ Object.keys(INTERVALS);
  10915. function sorter(a, b) {
  10916. return a - b;
  10917. }
  10918. function parse(scale, input) {
  10919. if (helpers_segment.isNullOrUndef(input)) {
  10920. return null;
  10921. }
  10922. const adapter = scale._adapter;
  10923. const { parser , round , isoWeekday } = scale._parseOpts;
  10924. let value = input;
  10925. if (typeof parser === 'function') {
  10926. value = parser(value);
  10927. }
  10928. if (!helpers_segment.isNumberFinite(value)) {
  10929. value = typeof parser === 'string' ? adapter.parse(value, parser) : adapter.parse(value);
  10930. }
  10931. if (value === null) {
  10932. return null;
  10933. }
  10934. if (round) {
  10935. value = round === 'week' && (helpers_segment.isNumber(isoWeekday) || isoWeekday === true) ? adapter.startOf(value, 'isoWeek', isoWeekday) : adapter.startOf(value, round);
  10936. }
  10937. return +value;
  10938. }
  10939. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  10940. const ilen = UNITS.length;
  10941. for(let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i){
  10942. const interval = INTERVALS[UNITS[i]];
  10943. const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;
  10944. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  10945. return UNITS[i];
  10946. }
  10947. }
  10948. return UNITS[ilen - 1];
  10949. }
  10950. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  10951. for(let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--){
  10952. const unit = UNITS[i];
  10953. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  10954. return unit;
  10955. }
  10956. }
  10957. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  10958. }
  10959. function determineMajorUnit(unit) {
  10960. for(let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i){
  10961. if (INTERVALS[UNITS[i]].common) {
  10962. return UNITS[i];
  10963. }
  10964. }
  10965. }
  10966. function addTick(ticks, time, timestamps) {
  10967. if (!timestamps) {
  10968. ticks[time] = true;
  10969. } else if (timestamps.length) {
  10970. const { lo , hi } = helpers_segment._lookup(timestamps, time);
  10971. const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];
  10972. ticks[timestamp] = true;
  10973. }
  10974. }
  10975. function setMajorTicks(scale, ticks, map, majorUnit) {
  10976. const adapter = scale._adapter;
  10977. const first = +adapter.startOf(ticks[0].value, majorUnit);
  10978. const last = ticks[ticks.length - 1].value;
  10979. let major, index;
  10980. for(major = first; major <= last; major = +adapter.add(major, 1, majorUnit)){
  10981. index = map[major];
  10982. if (index >= 0) {
  10983. ticks[index].major = true;
  10984. }
  10985. }
  10986. return ticks;
  10987. }
  10988. function ticksFromTimestamps(scale, values, majorUnit) {
  10989. const ticks = [];
  10990. const map = {};
  10991. const ilen = values.length;
  10992. let i, value;
  10993. for(i = 0; i < ilen; ++i){
  10994. value = values[i];
  10995. map[value] = i;
  10996. ticks.push({
  10997. value,
  10998. major: false
  10999. });
  11000. }
  11001. return ilen === 0 || !majorUnit ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  11002. }
  11003. class TimeScale extends Scale {
  11004. static id = 'time';
  11005. static defaults = {
  11006. bounds: 'data',
  11007. adapters: {},
  11008. time: {
  11009. parser: false,
  11010. unit: false,
  11011. round: false,
  11012. isoWeekday: false,
  11013. minUnit: 'millisecond',
  11014. displayFormats: {}
  11015. },
  11016. ticks: {
  11017. source: 'auto',
  11018. callback: false,
  11019. major: {
  11020. enabled: false
  11021. }
  11022. }
  11023. };
  11024. constructor(props){
  11025. super(props);
  11026. this._cache = {
  11027. data: [],
  11028. labels: [],
  11029. all: []
  11030. };
  11031. this._unit = 'day';
  11032. this._majorUnit = undefined;
  11033. this._offsets = {};
  11034. this._normalized = false;
  11035. this._parseOpts = undefined;
  11036. }
  11037. init(scaleOpts, opts = {}) {
  11038. const time = scaleOpts.time || (scaleOpts.time = {});
  11039. const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);
  11040. adapter.init(opts);
  11041. helpers_segment.mergeIf(time.displayFormats, adapter.formats());
  11042. this._parseOpts = {
  11043. parser: time.parser,
  11044. round: time.round,
  11045. isoWeekday: time.isoWeekday
  11046. };
  11047. super.init(scaleOpts);
  11048. this._normalized = opts.normalized;
  11049. }
  11050. parse(raw, index) {
  11051. if (raw === undefined) {
  11052. return null;
  11053. }
  11054. return parse(this, raw);
  11055. }
  11056. beforeLayout() {
  11057. super.beforeLayout();
  11058. this._cache = {
  11059. data: [],
  11060. labels: [],
  11061. all: []
  11062. };
  11063. }
  11064. determineDataLimits() {
  11065. const options = this.options;
  11066. const adapter = this._adapter;
  11067. const unit = options.time.unit || 'day';
  11068. let { min , max , minDefined , maxDefined } = this.getUserBounds();
  11069. function _applyBounds(bounds) {
  11070. if (!minDefined && !isNaN(bounds.min)) {
  11071. min = Math.min(min, bounds.min);
  11072. }
  11073. if (!maxDefined && !isNaN(bounds.max)) {
  11074. max = Math.max(max, bounds.max);
  11075. }
  11076. }
  11077. if (!minDefined || !maxDefined) {
  11078. _applyBounds(this._getLabelBounds());
  11079. if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {
  11080. _applyBounds(this.getMinMax(false));
  11081. }
  11082. }
  11083. min = helpers_segment.isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);
  11084. max = helpers_segment.isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;
  11085. this.min = Math.min(min, max - 1);
  11086. this.max = Math.max(min + 1, max);
  11087. }
  11088. _getLabelBounds() {
  11089. const arr = this.getLabelTimestamps();
  11090. let min = Number.POSITIVE_INFINITY;
  11091. let max = Number.NEGATIVE_INFINITY;
  11092. if (arr.length) {
  11093. min = arr[0];
  11094. max = arr[arr.length - 1];
  11095. }
  11096. return {
  11097. min,
  11098. max
  11099. };
  11100. }
  11101. buildTicks() {
  11102. const options = this.options;
  11103. const timeOpts = options.time;
  11104. const tickOpts = options.ticks;
  11105. const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate();
  11106. if (options.bounds === 'ticks' && timestamps.length) {
  11107. this.min = this._userMin || timestamps[0];
  11108. this.max = this._userMax || timestamps[timestamps.length - 1];
  11109. }
  11110. const min = this.min;
  11111. const max = this.max;
  11112. const ticks = helpers_segment._filterBetween(timestamps, min, max);
  11113. 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));
  11114. this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined : determineMajorUnit(this._unit);
  11115. this.initOffsets(timestamps);
  11116. if (options.reverse) {
  11117. ticks.reverse();
  11118. }
  11119. return ticksFromTimestamps(this, ticks, this._majorUnit);
  11120. }
  11121. afterAutoSkip() {
  11122. if (this.options.offsetAfterAutoskip) {
  11123. this.initOffsets(this.ticks.map((tick)=>+tick.value));
  11124. }
  11125. }
  11126. initOffsets(timestamps = []) {
  11127. let start = 0;
  11128. let end = 0;
  11129. let first, last;
  11130. if (this.options.offset && timestamps.length) {
  11131. first = this.getDecimalForValue(timestamps[0]);
  11132. if (timestamps.length === 1) {
  11133. start = 1 - first;
  11134. } else {
  11135. start = (this.getDecimalForValue(timestamps[1]) - first) / 2;
  11136. }
  11137. last = this.getDecimalForValue(timestamps[timestamps.length - 1]);
  11138. if (timestamps.length === 1) {
  11139. end = last;
  11140. } else {
  11141. end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;
  11142. }
  11143. }
  11144. const limit = timestamps.length < 3 ? 0.5 : 0.25;
  11145. start = helpers_segment._limitValue(start, 0, limit);
  11146. end = helpers_segment._limitValue(end, 0, limit);
  11147. this._offsets = {
  11148. start,
  11149. end,
  11150. factor: 1 / (start + 1 + end)
  11151. };
  11152. }
  11153. _generate() {
  11154. const adapter = this._adapter;
  11155. const min = this.min;
  11156. const max = this.max;
  11157. const options = this.options;
  11158. const timeOpts = options.time;
  11159. const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min));
  11160. const stepSize = helpers_segment.valueOrDefault(options.ticks.stepSize, 1);
  11161. const weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  11162. const hasWeekday = helpers_segment.isNumber(weekday) || weekday === true;
  11163. const ticks = {};
  11164. let first = min;
  11165. let time, count;
  11166. if (hasWeekday) {
  11167. first = +adapter.startOf(first, 'isoWeek', weekday);
  11168. }
  11169. first = +adapter.startOf(first, hasWeekday ? 'day' : minor);
  11170. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  11171. throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);
  11172. }
  11173. const timestamps = options.ticks.source === 'data' && this.getDataTimestamps();
  11174. for(time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++){
  11175. addTick(ticks, time, timestamps);
  11176. }
  11177. if (time === max || options.bounds === 'ticks' || count === 1) {
  11178. addTick(ticks, time, timestamps);
  11179. }
  11180. return Object.keys(ticks).sort(sorter).map((x)=>+x);
  11181. }
  11182. getLabelForValue(value) {
  11183. const adapter = this._adapter;
  11184. const timeOpts = this.options.time;
  11185. if (timeOpts.tooltipFormat) {
  11186. return adapter.format(value, timeOpts.tooltipFormat);
  11187. }
  11188. return adapter.format(value, timeOpts.displayFormats.datetime);
  11189. }
  11190. format(value, format) {
  11191. const options = this.options;
  11192. const formats = options.time.displayFormats;
  11193. const unit = this._unit;
  11194. const fmt = format || formats[unit];
  11195. return this._adapter.format(value, fmt);
  11196. }
  11197. _tickFormatFunction(time, index, ticks, format) {
  11198. const options = this.options;
  11199. const formatter = options.ticks.callback;
  11200. if (formatter) {
  11201. return helpers_segment.callback(formatter, [
  11202. time,
  11203. index,
  11204. ticks
  11205. ], this);
  11206. }
  11207. const formats = options.time.displayFormats;
  11208. const unit = this._unit;
  11209. const majorUnit = this._majorUnit;
  11210. const minorFormat = unit && formats[unit];
  11211. const majorFormat = majorUnit && formats[majorUnit];
  11212. const tick = ticks[index];
  11213. const major = majorUnit && majorFormat && tick && tick.major;
  11214. return this._adapter.format(time, format || (major ? majorFormat : minorFormat));
  11215. }
  11216. generateTickLabels(ticks) {
  11217. let i, ilen, tick;
  11218. for(i = 0, ilen = ticks.length; i < ilen; ++i){
  11219. tick = ticks[i];
  11220. tick.label = this._tickFormatFunction(tick.value, i, ticks);
  11221. }
  11222. }
  11223. getDecimalForValue(value) {
  11224. return value === null ? NaN : (value - this.min) / (this.max - this.min);
  11225. }
  11226. getPixelForValue(value) {
  11227. const offsets = this._offsets;
  11228. const pos = this.getDecimalForValue(value);
  11229. return this.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  11230. }
  11231. getValueForPixel(pixel) {
  11232. const offsets = this._offsets;
  11233. const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  11234. return this.min + pos * (this.max - this.min);
  11235. }
  11236. _getLabelSize(label) {
  11237. const ticksOpts = this.options.ticks;
  11238. const tickLabelWidth = this.ctx.measureText(label).width;
  11239. const angle = helpers_segment.toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  11240. const cosRotation = Math.cos(angle);
  11241. const sinRotation = Math.sin(angle);
  11242. const tickFontSize = this._resolveTickFontOptions(0).size;
  11243. return {
  11244. w: tickLabelWidth * cosRotation + tickFontSize * sinRotation,
  11245. h: tickLabelWidth * sinRotation + tickFontSize * cosRotation
  11246. };
  11247. }
  11248. _getLabelCapacity(exampleTime) {
  11249. const timeOpts = this.options.time;
  11250. const displayFormats = timeOpts.displayFormats;
  11251. const format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  11252. const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [
  11253. exampleTime
  11254. ], this._majorUnit), format);
  11255. const size = this._getLabelSize(exampleLabel);
  11256. const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1;
  11257. return capacity > 0 ? capacity : 1;
  11258. }
  11259. getDataTimestamps() {
  11260. let timestamps = this._cache.data || [];
  11261. let i, ilen;
  11262. if (timestamps.length) {
  11263. return timestamps;
  11264. }
  11265. const metas = this.getMatchingVisibleMetas();
  11266. if (this._normalized && metas.length) {
  11267. return this._cache.data = metas[0].controller.getAllParsedValues(this);
  11268. }
  11269. for(i = 0, ilen = metas.length; i < ilen; ++i){
  11270. timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this));
  11271. }
  11272. return this._cache.data = this.normalize(timestamps);
  11273. }
  11274. getLabelTimestamps() {
  11275. const timestamps = this._cache.labels || [];
  11276. let i, ilen;
  11277. if (timestamps.length) {
  11278. return timestamps;
  11279. }
  11280. const labels = this.getLabels();
  11281. for(i = 0, ilen = labels.length; i < ilen; ++i){
  11282. timestamps.push(parse(this, labels[i]));
  11283. }
  11284. return this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps);
  11285. }
  11286. normalize(values) {
  11287. return helpers_segment._arrayUnique(values.sort(sorter));
  11288. }
  11289. }
  11290. function interpolate(table, val, reverse) {
  11291. let lo = 0;
  11292. let hi = table.length - 1;
  11293. let prevSource, nextSource, prevTarget, nextTarget;
  11294. if (reverse) {
  11295. if (val >= table[lo].pos && val <= table[hi].pos) {
  11296. ({ lo , hi } = helpers_segment._lookupByKey(table, 'pos', val));
  11297. }
  11298. ({ pos: prevSource , time: prevTarget } = table[lo]);
  11299. ({ pos: nextSource , time: nextTarget } = table[hi]);
  11300. } else {
  11301. if (val >= table[lo].time && val <= table[hi].time) {
  11302. ({ lo , hi } = helpers_segment._lookupByKey(table, 'time', val));
  11303. }
  11304. ({ time: prevSource , pos: prevTarget } = table[lo]);
  11305. ({ time: nextSource , pos: nextTarget } = table[hi]);
  11306. }
  11307. const span = nextSource - prevSource;
  11308. return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;
  11309. }
  11310. class TimeSeriesScale extends TimeScale {
  11311. static id = 'timeseries';
  11312. static defaults = TimeScale.defaults;
  11313. constructor(props){
  11314. super(props);
  11315. this._table = [];
  11316. this._minPos = undefined;
  11317. this._tableRange = undefined;
  11318. }
  11319. initOffsets() {
  11320. const timestamps = this._getTimestampsForTable();
  11321. const table = this._table = this.buildLookupTable(timestamps);
  11322. this._minPos = interpolate(table, this.min);
  11323. this._tableRange = interpolate(table, this.max) - this._minPos;
  11324. super.initOffsets(timestamps);
  11325. }
  11326. buildLookupTable(timestamps) {
  11327. const { min , max } = this;
  11328. const items = [];
  11329. const table = [];
  11330. let i, ilen, prev, curr, next;
  11331. for(i = 0, ilen = timestamps.length; i < ilen; ++i){
  11332. curr = timestamps[i];
  11333. if (curr >= min && curr <= max) {
  11334. items.push(curr);
  11335. }
  11336. }
  11337. if (items.length < 2) {
  11338. return [
  11339. {
  11340. time: min,
  11341. pos: 0
  11342. },
  11343. {
  11344. time: max,
  11345. pos: 1
  11346. }
  11347. ];
  11348. }
  11349. for(i = 0, ilen = items.length; i < ilen; ++i){
  11350. next = items[i + 1];
  11351. prev = items[i - 1];
  11352. curr = items[i];
  11353. if (Math.round((next + prev) / 2) !== curr) {
  11354. table.push({
  11355. time: curr,
  11356. pos: i / (ilen - 1)
  11357. });
  11358. }
  11359. }
  11360. return table;
  11361. }
  11362. _generate() {
  11363. const min = this.min;
  11364. const max = this.max;
  11365. let timestamps = super.getDataTimestamps();
  11366. if (!timestamps.includes(min) || !timestamps.length) {
  11367. timestamps.splice(0, 0, min);
  11368. }
  11369. if (!timestamps.includes(max) || timestamps.length === 1) {
  11370. timestamps.push(max);
  11371. }
  11372. return timestamps.sort((a, b)=>a - b);
  11373. }
  11374. _getTimestampsForTable() {
  11375. let timestamps = this._cache.all || [];
  11376. if (timestamps.length) {
  11377. return timestamps;
  11378. }
  11379. const data = this.getDataTimestamps();
  11380. const label = this.getLabelTimestamps();
  11381. if (data.length && label.length) {
  11382. timestamps = this.normalize(data.concat(label));
  11383. } else {
  11384. timestamps = data.length ? data : label;
  11385. }
  11386. timestamps = this._cache.all = timestamps;
  11387. return timestamps;
  11388. }
  11389. getDecimalForValue(value) {
  11390. return (interpolate(this._table, value) - this._minPos) / this._tableRange;
  11391. }
  11392. getValueForPixel(pixel) {
  11393. const offsets = this._offsets;
  11394. const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  11395. return interpolate(this._table, decimal * this._tableRange + this._minPos, true);
  11396. }
  11397. }
  11398. var scales = /*#__PURE__*/Object.freeze({
  11399. __proto__: null,
  11400. CategoryScale: CategoryScale,
  11401. LinearScale: LinearScale,
  11402. LogarithmicScale: LogarithmicScale,
  11403. RadialLinearScale: RadialLinearScale,
  11404. TimeScale: TimeScale,
  11405. TimeSeriesScale: TimeSeriesScale
  11406. });
  11407. const registerables = [
  11408. controllers,
  11409. elements,
  11410. plugins,
  11411. scales
  11412. ];
  11413. exports.Ticks = helpers_segment.Ticks;
  11414. exports.defaults = helpers_segment.defaults;
  11415. exports.Animation = Animation;
  11416. exports.Animations = Animations;
  11417. exports.ArcElement = ArcElement;
  11418. exports.BarController = BarController;
  11419. exports.BarElement = BarElement;
  11420. exports.BasePlatform = BasePlatform;
  11421. exports.BasicPlatform = BasicPlatform;
  11422. exports.BubbleController = BubbleController;
  11423. exports.CategoryScale = CategoryScale;
  11424. exports.Chart = Chart;
  11425. exports.Colors = plugin_colors;
  11426. exports.DatasetController = DatasetController;
  11427. exports.Decimation = plugin_decimation;
  11428. exports.DomPlatform = DomPlatform;
  11429. exports.DoughnutController = DoughnutController;
  11430. exports.Element = Element;
  11431. exports.Filler = index;
  11432. exports.Interaction = Interaction;
  11433. exports.Legend = plugin_legend;
  11434. exports.LineController = LineController;
  11435. exports.LineElement = LineElement;
  11436. exports.LinearScale = LinearScale;
  11437. exports.LogarithmicScale = LogarithmicScale;
  11438. exports.PieController = PieController;
  11439. exports.PointElement = PointElement;
  11440. exports.PolarAreaController = PolarAreaController;
  11441. exports.RadarController = RadarController;
  11442. exports.RadialLinearScale = RadialLinearScale;
  11443. exports.Scale = Scale;
  11444. exports.ScatterController = ScatterController;
  11445. exports.SubTitle = plugin_subtitle;
  11446. exports.TimeScale = TimeScale;
  11447. exports.TimeSeriesScale = TimeSeriesScale;
  11448. exports.Title = plugin_title;
  11449. exports.Tooltip = plugin_tooltip;
  11450. exports._adapters = adapters;
  11451. exports._detectPlatform = _detectPlatform;
  11452. exports.animator = animator;
  11453. exports.controllers = controllers;
  11454. exports.elements = elements;
  11455. exports.layouts = layouts;
  11456. exports.plugins = plugins;
  11457. exports.registerables = registerables;
  11458. exports.registry = registry;
  11459. exports.scales = scales;
  11460. //# sourceMappingURL=chart.cjs.map