chart.esm.js 330 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645
  1. /*!
  2. * Chart.js v3.7.1
  3. * https://www.chartjs.org
  4. * (c) 2022 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. import { r as requestAnimFrame, a as resolve, e as effects, c as color, d as defaults, i as isObject, b as isArray, v as valueOrDefault, u as unlistenArrayEvents, l as listenArrayEvents, f as resolveObjectKey, g as isNumberFinite, h as createContext, j as defined, s as sign, k as isNullOrUndef, _ as _arrayUnique, t as toRadians, m as toPercentage, n as toDimension, T as TAU, o as formatNumber, p as _angleBetween, H as HALF_PI, P as PI, q as isNumber, w as _limitValue, x as _lookupByKey, y as _parseObjectDataRadialScale, z as getRelativePosition, A as _rlookupByKey, B as getAngleFromPoint, C as toPadding, D as each, E as getMaximumSize, F as _getParentNode, G as readUsedSize, I as throttled, J as supportsEventListenerOptions, K as _isDomSupported, L as log10, M as _factorize, N as finiteOrDefault, O as callback, Q as _addGrace, R as toDegrees, S as _measureText, U as _int16Range, V as _alignPixel, W as clipArea, X as renderText, Y as unclipArea, Z as toFont, $ as _toLeftRightCenter, a0 as _alignStartEnd, a1 as overrides, a2 as merge, a3 as _capitalize, a4 as descriptors, a5 as isFunction, a6 as _attachContext, a7 as _createResolver, a8 as _descriptors, a9 as mergeIf, aa as uid, ab as debounce, ac as retinaScale, ad as clearCanvas, ae as setsEqual, af as _isPointInArea, ag as _elementsEqual, ah as _isClickEvent, ai as _isBetween, aj as _readValueToProps, ak as _updateBezierControlPoints, al as _computeSegments, am as _boundSegments, an as _steppedInterpolation, ao as _bezierInterpolation, ap as _pointInLine, aq as _steppedLineTo, ar as _bezierCurveTo, as as drawPoint, at as addRoundedRectPath, au as toTRBL, av as toTRBLCorners, aw as _boundSegment, ax as _normalizeAngle, ay as getRtlAdapter, az as overrideTextDirection, aA as _textX, aB as restoreTextDirection, aC as noop, aD as distanceBetweenPoints, aE as _setMinAndMaxByKey, aF as niceNum, aG as almostWhole, aH as almostEquals, aI as _decimalPlaces, aJ as _longestText, aK as _filterBetween, aL as _lookup } from './chunks/helpers.segment.js';
  8. export { d as defaults } from './chunks/helpers.segment.js';
  9. class Animator {
  10. constructor() {
  11. this._request = null;
  12. this._charts = new Map();
  13. this._running = false;
  14. this._lastDate = undefined;
  15. }
  16. _notify(chart, anims, date, type) {
  17. const callbacks = anims.listeners[type];
  18. const numSteps = anims.duration;
  19. callbacks.forEach(fn => fn({
  20. chart,
  21. initial: anims.initial,
  22. numSteps,
  23. currentStep: Math.min(date - anims.start, numSteps)
  24. }));
  25. }
  26. _refresh() {
  27. if (this._request) {
  28. return;
  29. }
  30. this._running = true;
  31. this._request = requestAnimFrame.call(window, () => {
  32. this._update();
  33. this._request = null;
  34. if (this._running) {
  35. this._refresh();
  36. }
  37. });
  38. }
  39. _update(date = Date.now()) {
  40. let remaining = 0;
  41. this._charts.forEach((anims, chart) => {
  42. if (!anims.running || !anims.items.length) {
  43. return;
  44. }
  45. const items = anims.items;
  46. let i = items.length - 1;
  47. let draw = false;
  48. let item;
  49. for (; i >= 0; --i) {
  50. item = items[i];
  51. if (item._active) {
  52. if (item._total > anims.duration) {
  53. anims.duration = item._total;
  54. }
  55. item.tick(date);
  56. draw = true;
  57. } else {
  58. items[i] = items[items.length - 1];
  59. items.pop();
  60. }
  61. }
  62. if (draw) {
  63. chart.draw();
  64. this._notify(chart, anims, date, 'progress');
  65. }
  66. if (!items.length) {
  67. anims.running = false;
  68. this._notify(chart, anims, date, 'complete');
  69. anims.initial = false;
  70. }
  71. remaining += items.length;
  72. });
  73. this._lastDate = date;
  74. if (remaining === 0) {
  75. this._running = false;
  76. }
  77. }
  78. _getAnims(chart) {
  79. const charts = this._charts;
  80. let anims = charts.get(chart);
  81. if (!anims) {
  82. anims = {
  83. running: false,
  84. initial: true,
  85. items: [],
  86. listeners: {
  87. complete: [],
  88. progress: []
  89. }
  90. };
  91. charts.set(chart, anims);
  92. }
  93. return anims;
  94. }
  95. listen(chart, event, cb) {
  96. this._getAnims(chart).listeners[event].push(cb);
  97. }
  98. add(chart, items) {
  99. if (!items || !items.length) {
  100. return;
  101. }
  102. this._getAnims(chart).items.push(...items);
  103. }
  104. has(chart) {
  105. return this._getAnims(chart).items.length > 0;
  106. }
  107. start(chart) {
  108. const anims = this._charts.get(chart);
  109. if (!anims) {
  110. return;
  111. }
  112. anims.running = true;
  113. anims.start = Date.now();
  114. anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0);
  115. this._refresh();
  116. }
  117. running(chart) {
  118. if (!this._running) {
  119. return false;
  120. }
  121. const anims = this._charts.get(chart);
  122. if (!anims || !anims.running || !anims.items.length) {
  123. return false;
  124. }
  125. return true;
  126. }
  127. stop(chart) {
  128. const anims = this._charts.get(chart);
  129. if (!anims || !anims.items.length) {
  130. return;
  131. }
  132. const items = anims.items;
  133. let i = items.length - 1;
  134. for (; i >= 0; --i) {
  135. items[i].cancel();
  136. }
  137. anims.items = [];
  138. this._notify(chart, anims, Date.now(), 'complete');
  139. }
  140. remove(chart) {
  141. return this._charts.delete(chart);
  142. }
  143. }
  144. var animator = new Animator();
  145. const transparent = 'transparent';
  146. const interpolators = {
  147. boolean(from, to, factor) {
  148. return factor > 0.5 ? to : from;
  149. },
  150. color(from, to, factor) {
  151. const c0 = color(from || transparent);
  152. const c1 = c0.valid && color(to || transparent);
  153. return c1 && c1.valid
  154. ? c1.mix(c0, factor).hexString()
  155. : to;
  156. },
  157. number(from, to, factor) {
  158. return from + (to - from) * factor;
  159. }
  160. };
  161. class Animation {
  162. constructor(cfg, target, prop, to) {
  163. const currentValue = target[prop];
  164. to = resolve([cfg.to, to, currentValue, cfg.from]);
  165. const from = resolve([cfg.from, currentValue, to]);
  166. this._active = true;
  167. this._fn = cfg.fn || interpolators[cfg.type || typeof from];
  168. this._easing = effects[cfg.easing] || effects.linear;
  169. this._start = Math.floor(Date.now() + (cfg.delay || 0));
  170. this._duration = this._total = Math.floor(cfg.duration);
  171. this._loop = !!cfg.loop;
  172. this._target = target;
  173. this._prop = prop;
  174. this._from = from;
  175. this._to = to;
  176. this._promises = undefined;
  177. }
  178. active() {
  179. return this._active;
  180. }
  181. update(cfg, to, date) {
  182. if (this._active) {
  183. this._notify(false);
  184. const currentValue = this._target[this._prop];
  185. const elapsed = date - this._start;
  186. const remain = this._duration - elapsed;
  187. this._start = date;
  188. this._duration = Math.floor(Math.max(remain, cfg.duration));
  189. this._total += elapsed;
  190. this._loop = !!cfg.loop;
  191. this._to = resolve([cfg.to, to, currentValue, cfg.from]);
  192. this._from = resolve([cfg.from, currentValue, to]);
  193. }
  194. }
  195. cancel() {
  196. if (this._active) {
  197. this.tick(Date.now());
  198. this._active = false;
  199. this._notify(false);
  200. }
  201. }
  202. tick(date) {
  203. const elapsed = date - this._start;
  204. const duration = this._duration;
  205. const prop = this._prop;
  206. const from = this._from;
  207. const loop = this._loop;
  208. const to = this._to;
  209. let factor;
  210. this._active = from !== to && (loop || (elapsed < duration));
  211. if (!this._active) {
  212. this._target[prop] = to;
  213. this._notify(true);
  214. return;
  215. }
  216. if (elapsed < 0) {
  217. this._target[prop] = from;
  218. return;
  219. }
  220. factor = (elapsed / duration) % 2;
  221. factor = loop && factor > 1 ? 2 - factor : factor;
  222. factor = this._easing(Math.min(1, Math.max(0, factor)));
  223. this._target[prop] = this._fn(from, to, factor);
  224. }
  225. wait() {
  226. const promises = this._promises || (this._promises = []);
  227. return new Promise((res, rej) => {
  228. promises.push({res, rej});
  229. });
  230. }
  231. _notify(resolved) {
  232. const method = resolved ? 'res' : 'rej';
  233. const promises = this._promises || [];
  234. for (let i = 0; i < promises.length; i++) {
  235. promises[i][method]();
  236. }
  237. }
  238. }
  239. const numbers = ['x', 'y', 'borderWidth', 'radius', 'tension'];
  240. const colors = ['color', 'borderColor', 'backgroundColor'];
  241. defaults.set('animation', {
  242. delay: undefined,
  243. duration: 1000,
  244. easing: 'easeOutQuart',
  245. fn: undefined,
  246. from: undefined,
  247. loop: undefined,
  248. to: undefined,
  249. type: undefined,
  250. });
  251. const animationOptions = Object.keys(defaults.animation);
  252. defaults.describe('animation', {
  253. _fallback: false,
  254. _indexable: false,
  255. _scriptable: (name) => name !== 'onProgress' && name !== 'onComplete' && name !== 'fn',
  256. });
  257. defaults.set('animations', {
  258. colors: {
  259. type: 'color',
  260. properties: colors
  261. },
  262. numbers: {
  263. type: 'number',
  264. properties: numbers
  265. },
  266. });
  267. defaults.describe('animations', {
  268. _fallback: 'animation',
  269. });
  270. defaults.set('transitions', {
  271. active: {
  272. animation: {
  273. duration: 400
  274. }
  275. },
  276. resize: {
  277. animation: {
  278. duration: 0
  279. }
  280. },
  281. show: {
  282. animations: {
  283. colors: {
  284. from: 'transparent'
  285. },
  286. visible: {
  287. type: 'boolean',
  288. duration: 0
  289. },
  290. }
  291. },
  292. hide: {
  293. animations: {
  294. colors: {
  295. to: 'transparent'
  296. },
  297. visible: {
  298. type: 'boolean',
  299. easing: 'linear',
  300. fn: v => v | 0
  301. },
  302. }
  303. }
  304. });
  305. class Animations {
  306. constructor(chart, config) {
  307. this._chart = chart;
  308. this._properties = new Map();
  309. this.configure(config);
  310. }
  311. configure(config) {
  312. if (!isObject(config)) {
  313. return;
  314. }
  315. const animatedProps = this._properties;
  316. Object.getOwnPropertyNames(config).forEach(key => {
  317. const cfg = config[key];
  318. if (!isObject(cfg)) {
  319. return;
  320. }
  321. const resolved = {};
  322. for (const option of animationOptions) {
  323. resolved[option] = cfg[option];
  324. }
  325. (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => {
  326. if (prop === key || !animatedProps.has(prop)) {
  327. animatedProps.set(prop, resolved);
  328. }
  329. });
  330. });
  331. }
  332. _animateOptions(target, values) {
  333. const newOptions = values.options;
  334. const options = resolveTargetOptions(target, newOptions);
  335. if (!options) {
  336. return [];
  337. }
  338. const animations = this._createAnimations(options, newOptions);
  339. if (newOptions.$shared) {
  340. awaitAll(target.options.$animations, newOptions).then(() => {
  341. target.options = newOptions;
  342. }, () => {
  343. });
  344. }
  345. return animations;
  346. }
  347. _createAnimations(target, values) {
  348. const animatedProps = this._properties;
  349. const animations = [];
  350. const running = target.$animations || (target.$animations = {});
  351. const props = Object.keys(values);
  352. const date = Date.now();
  353. let i;
  354. for (i = props.length - 1; i >= 0; --i) {
  355. const prop = props[i];
  356. if (prop.charAt(0) === '$') {
  357. continue;
  358. }
  359. if (prop === 'options') {
  360. animations.push(...this._animateOptions(target, values));
  361. continue;
  362. }
  363. const value = values[prop];
  364. let animation = running[prop];
  365. const cfg = animatedProps.get(prop);
  366. if (animation) {
  367. if (cfg && animation.active()) {
  368. animation.update(cfg, value, date);
  369. continue;
  370. } else {
  371. animation.cancel();
  372. }
  373. }
  374. if (!cfg || !cfg.duration) {
  375. target[prop] = value;
  376. continue;
  377. }
  378. running[prop] = animation = new Animation(cfg, target, prop, value);
  379. animations.push(animation);
  380. }
  381. return animations;
  382. }
  383. update(target, values) {
  384. if (this._properties.size === 0) {
  385. Object.assign(target, values);
  386. return;
  387. }
  388. const animations = this._createAnimations(target, values);
  389. if (animations.length) {
  390. animator.add(this._chart, animations);
  391. return true;
  392. }
  393. }
  394. }
  395. function awaitAll(animations, properties) {
  396. const running = [];
  397. const keys = Object.keys(properties);
  398. for (let i = 0; i < keys.length; i++) {
  399. const anim = animations[keys[i]];
  400. if (anim && anim.active()) {
  401. running.push(anim.wait());
  402. }
  403. }
  404. return Promise.all(running);
  405. }
  406. function resolveTargetOptions(target, newOptions) {
  407. if (!newOptions) {
  408. return;
  409. }
  410. let options = target.options;
  411. if (!options) {
  412. target.options = newOptions;
  413. return;
  414. }
  415. if (options.$shared) {
  416. target.options = options = Object.assign({}, options, {$shared: false, $animations: {}});
  417. }
  418. return options;
  419. }
  420. function scaleClip(scale, allowedOverflow) {
  421. const opts = scale && scale.options || {};
  422. const reverse = opts.reverse;
  423. const min = opts.min === undefined ? allowedOverflow : 0;
  424. const max = opts.max === undefined ? allowedOverflow : 0;
  425. return {
  426. start: reverse ? max : min,
  427. end: reverse ? min : max
  428. };
  429. }
  430. function defaultClip(xScale, yScale, allowedOverflow) {
  431. if (allowedOverflow === false) {
  432. return false;
  433. }
  434. const x = scaleClip(xScale, allowedOverflow);
  435. const y = scaleClip(yScale, allowedOverflow);
  436. return {
  437. top: y.end,
  438. right: x.end,
  439. bottom: y.start,
  440. left: x.start
  441. };
  442. }
  443. function toClip(value) {
  444. let t, r, b, l;
  445. if (isObject(value)) {
  446. t = value.top;
  447. r = value.right;
  448. b = value.bottom;
  449. l = value.left;
  450. } else {
  451. t = r = b = l = value;
  452. }
  453. return {
  454. top: t,
  455. right: r,
  456. bottom: b,
  457. left: l,
  458. disabled: value === false
  459. };
  460. }
  461. function getSortedDatasetIndices(chart, filterVisible) {
  462. const keys = [];
  463. const metasets = chart._getSortedDatasetMetas(filterVisible);
  464. let i, ilen;
  465. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  466. keys.push(metasets[i].index);
  467. }
  468. return keys;
  469. }
  470. function applyStack(stack, value, dsIndex, options = {}) {
  471. const keys = stack.keys;
  472. const singleMode = options.mode === 'single';
  473. let i, ilen, datasetIndex, otherValue;
  474. if (value === null) {
  475. return;
  476. }
  477. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  478. datasetIndex = +keys[i];
  479. if (datasetIndex === dsIndex) {
  480. if (options.all) {
  481. continue;
  482. }
  483. break;
  484. }
  485. otherValue = stack.values[datasetIndex];
  486. if (isNumberFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) {
  487. value += otherValue;
  488. }
  489. }
  490. return value;
  491. }
  492. function convertObjectDataToArray(data) {
  493. const keys = Object.keys(data);
  494. const adata = new Array(keys.length);
  495. let i, ilen, key;
  496. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  497. key = keys[i];
  498. adata[i] = {
  499. x: key,
  500. y: data[key]
  501. };
  502. }
  503. return adata;
  504. }
  505. function isStacked(scale, meta) {
  506. const stacked = scale && scale.options.stacked;
  507. return stacked || (stacked === undefined && meta.stack !== undefined);
  508. }
  509. function getStackKey(indexScale, valueScale, meta) {
  510. return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;
  511. }
  512. function getUserBounds(scale) {
  513. const {min, max, minDefined, maxDefined} = scale.getUserBounds();
  514. return {
  515. min: minDefined ? min : Number.NEGATIVE_INFINITY,
  516. max: maxDefined ? max : Number.POSITIVE_INFINITY
  517. };
  518. }
  519. function getOrCreateStack(stacks, stackKey, indexValue) {
  520. const subStack = stacks[stackKey] || (stacks[stackKey] = {});
  521. return subStack[indexValue] || (subStack[indexValue] = {});
  522. }
  523. function getLastIndexInStack(stack, vScale, positive, type) {
  524. for (const meta of vScale.getMatchingVisibleMetas(type).reverse()) {
  525. const value = stack[meta.index];
  526. if ((positive && value > 0) || (!positive && value < 0)) {
  527. return meta.index;
  528. }
  529. }
  530. return null;
  531. }
  532. function updateStacks(controller, parsed) {
  533. const {chart, _cachedMeta: meta} = controller;
  534. const stacks = chart._stacks || (chart._stacks = {});
  535. const {iScale, vScale, index: datasetIndex} = meta;
  536. const iAxis = iScale.axis;
  537. const vAxis = vScale.axis;
  538. const key = getStackKey(iScale, vScale, meta);
  539. const ilen = parsed.length;
  540. let stack;
  541. for (let i = 0; i < ilen; ++i) {
  542. const item = parsed[i];
  543. const {[iAxis]: index, [vAxis]: value} = item;
  544. const itemStacks = item._stacks || (item._stacks = {});
  545. stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);
  546. stack[datasetIndex] = value;
  547. stack._top = getLastIndexInStack(stack, vScale, true, meta.type);
  548. stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type);
  549. }
  550. }
  551. function getFirstScaleId(chart, axis) {
  552. const scales = chart.scales;
  553. return Object.keys(scales).filter(key => scales[key].axis === axis).shift();
  554. }
  555. function createDatasetContext(parent, index) {
  556. return createContext(parent,
  557. {
  558. active: false,
  559. dataset: undefined,
  560. datasetIndex: index,
  561. index,
  562. mode: 'default',
  563. type: 'dataset'
  564. }
  565. );
  566. }
  567. function createDataContext(parent, index, element) {
  568. return createContext(parent, {
  569. active: false,
  570. dataIndex: index,
  571. parsed: undefined,
  572. raw: undefined,
  573. element,
  574. index,
  575. mode: 'default',
  576. type: 'data'
  577. });
  578. }
  579. function clearStacks(meta, items) {
  580. const datasetIndex = meta.controller.index;
  581. const axis = meta.vScale && meta.vScale.axis;
  582. if (!axis) {
  583. return;
  584. }
  585. items = items || meta._parsed;
  586. for (const parsed of items) {
  587. const stacks = parsed._stacks;
  588. if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {
  589. return;
  590. }
  591. delete stacks[axis][datasetIndex];
  592. }
  593. }
  594. const isDirectUpdateMode = (mode) => mode === 'reset' || mode === 'none';
  595. const cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached);
  596. const createStack = (canStack, meta, chart) => canStack && !meta.hidden && meta._stacked
  597. && {keys: getSortedDatasetIndices(chart, true), values: null};
  598. class DatasetController {
  599. constructor(chart, datasetIndex) {
  600. this.chart = chart;
  601. this._ctx = chart.ctx;
  602. this.index = datasetIndex;
  603. this._cachedDataOpts = {};
  604. this._cachedMeta = this.getMeta();
  605. this._type = this._cachedMeta.type;
  606. this.options = undefined;
  607. this._parsing = false;
  608. this._data = undefined;
  609. this._objectData = undefined;
  610. this._sharedOptions = undefined;
  611. this._drawStart = undefined;
  612. this._drawCount = undefined;
  613. this.enableOptionSharing = false;
  614. this.supportsDecimation = false;
  615. this.$context = undefined;
  616. this._syncList = [];
  617. this.initialize();
  618. }
  619. initialize() {
  620. const meta = this._cachedMeta;
  621. this.configure();
  622. this.linkScales();
  623. meta._stacked = isStacked(meta.vScale, meta);
  624. this.addElements();
  625. }
  626. updateIndex(datasetIndex) {
  627. if (this.index !== datasetIndex) {
  628. clearStacks(this._cachedMeta);
  629. }
  630. this.index = datasetIndex;
  631. }
  632. linkScales() {
  633. const chart = this.chart;
  634. const meta = this._cachedMeta;
  635. const dataset = this.getDataset();
  636. const chooseId = (axis, x, y, r) => axis === 'x' ? x : axis === 'r' ? r : y;
  637. const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));
  638. const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));
  639. const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));
  640. const indexAxis = meta.indexAxis;
  641. const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);
  642. const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);
  643. meta.xScale = this.getScaleForId(xid);
  644. meta.yScale = this.getScaleForId(yid);
  645. meta.rScale = this.getScaleForId(rid);
  646. meta.iScale = this.getScaleForId(iid);
  647. meta.vScale = this.getScaleForId(vid);
  648. }
  649. getDataset() {
  650. return this.chart.data.datasets[this.index];
  651. }
  652. getMeta() {
  653. return this.chart.getDatasetMeta(this.index);
  654. }
  655. getScaleForId(scaleID) {
  656. return this.chart.scales[scaleID];
  657. }
  658. _getOtherScale(scale) {
  659. const meta = this._cachedMeta;
  660. return scale === meta.iScale
  661. ? meta.vScale
  662. : meta.iScale;
  663. }
  664. reset() {
  665. this._update('reset');
  666. }
  667. _destroy() {
  668. const meta = this._cachedMeta;
  669. if (this._data) {
  670. unlistenArrayEvents(this._data, this);
  671. }
  672. if (meta._stacked) {
  673. clearStacks(meta);
  674. }
  675. }
  676. _dataCheck() {
  677. const dataset = this.getDataset();
  678. const data = dataset.data || (dataset.data = []);
  679. const _data = this._data;
  680. if (isObject(data)) {
  681. this._data = convertObjectDataToArray(data);
  682. } else if (_data !== data) {
  683. if (_data) {
  684. unlistenArrayEvents(_data, this);
  685. const meta = this._cachedMeta;
  686. clearStacks(meta);
  687. meta._parsed = [];
  688. }
  689. if (data && Object.isExtensible(data)) {
  690. listenArrayEvents(data, this);
  691. }
  692. this._syncList = [];
  693. this._data = data;
  694. }
  695. }
  696. addElements() {
  697. const meta = this._cachedMeta;
  698. this._dataCheck();
  699. if (this.datasetElementType) {
  700. meta.dataset = new this.datasetElementType();
  701. }
  702. }
  703. buildOrUpdateElements(resetNewElements) {
  704. const meta = this._cachedMeta;
  705. const dataset = this.getDataset();
  706. let stackChanged = false;
  707. this._dataCheck();
  708. const oldStacked = meta._stacked;
  709. meta._stacked = isStacked(meta.vScale, meta);
  710. if (meta.stack !== dataset.stack) {
  711. stackChanged = true;
  712. clearStacks(meta);
  713. meta.stack = dataset.stack;
  714. }
  715. this._resyncElements(resetNewElements);
  716. if (stackChanged || oldStacked !== meta._stacked) {
  717. updateStacks(this, meta._parsed);
  718. }
  719. }
  720. configure() {
  721. const config = this.chart.config;
  722. const scopeKeys = config.datasetScopeKeys(this._type);
  723. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true);
  724. this.options = config.createResolver(scopes, this.getContext());
  725. this._parsing = this.options.parsing;
  726. this._cachedDataOpts = {};
  727. }
  728. parse(start, count) {
  729. const {_cachedMeta: meta, _data: data} = this;
  730. const {iScale, _stacked} = meta;
  731. const iAxis = iScale.axis;
  732. let sorted = start === 0 && count === data.length ? true : meta._sorted;
  733. let prev = start > 0 && meta._parsed[start - 1];
  734. let i, cur, parsed;
  735. if (this._parsing === false) {
  736. meta._parsed = data;
  737. meta._sorted = true;
  738. parsed = data;
  739. } else {
  740. if (isArray(data[start])) {
  741. parsed = this.parseArrayData(meta, data, start, count);
  742. } else if (isObject(data[start])) {
  743. parsed = this.parseObjectData(meta, data, start, count);
  744. } else {
  745. parsed = this.parsePrimitiveData(meta, data, start, count);
  746. }
  747. const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]);
  748. for (i = 0; i < count; ++i) {
  749. meta._parsed[i + start] = cur = parsed[i];
  750. if (sorted) {
  751. if (isNotInOrderComparedToPrev()) {
  752. sorted = false;
  753. }
  754. prev = cur;
  755. }
  756. }
  757. meta._sorted = sorted;
  758. }
  759. if (_stacked) {
  760. updateStacks(this, parsed);
  761. }
  762. }
  763. parsePrimitiveData(meta, data, start, count) {
  764. const {iScale, vScale} = meta;
  765. const iAxis = iScale.axis;
  766. const vAxis = vScale.axis;
  767. const labels = iScale.getLabels();
  768. const singleScale = iScale === vScale;
  769. const parsed = new Array(count);
  770. let i, ilen, index;
  771. for (i = 0, ilen = count; i < ilen; ++i) {
  772. index = i + start;
  773. parsed[i] = {
  774. [iAxis]: singleScale || iScale.parse(labels[index], index),
  775. [vAxis]: vScale.parse(data[index], index)
  776. };
  777. }
  778. return parsed;
  779. }
  780. parseArrayData(meta, data, start, count) {
  781. const {xScale, yScale} = meta;
  782. const parsed = new Array(count);
  783. let i, ilen, index, item;
  784. for (i = 0, ilen = count; i < ilen; ++i) {
  785. index = i + start;
  786. item = data[index];
  787. parsed[i] = {
  788. x: xScale.parse(item[0], index),
  789. y: yScale.parse(item[1], index)
  790. };
  791. }
  792. return parsed;
  793. }
  794. parseObjectData(meta, data, start, count) {
  795. const {xScale, yScale} = meta;
  796. const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;
  797. const parsed = new Array(count);
  798. let i, ilen, index, item;
  799. for (i = 0, ilen = count; i < ilen; ++i) {
  800. index = i + start;
  801. item = data[index];
  802. parsed[i] = {
  803. x: xScale.parse(resolveObjectKey(item, xAxisKey), index),
  804. y: yScale.parse(resolveObjectKey(item, yAxisKey), index)
  805. };
  806. }
  807. return parsed;
  808. }
  809. getParsed(index) {
  810. return this._cachedMeta._parsed[index];
  811. }
  812. getDataElement(index) {
  813. return this._cachedMeta.data[index];
  814. }
  815. applyStack(scale, parsed, mode) {
  816. const chart = this.chart;
  817. const meta = this._cachedMeta;
  818. const value = parsed[scale.axis];
  819. const stack = {
  820. keys: getSortedDatasetIndices(chart, true),
  821. values: parsed._stacks[scale.axis]
  822. };
  823. return applyStack(stack, value, meta.index, {mode});
  824. }
  825. updateRangeFromParsed(range, scale, parsed, stack) {
  826. const parsedValue = parsed[scale.axis];
  827. let value = parsedValue === null ? NaN : parsedValue;
  828. const values = stack && parsed._stacks[scale.axis];
  829. if (stack && values) {
  830. stack.values = values;
  831. value = applyStack(stack, parsedValue, this._cachedMeta.index);
  832. }
  833. range.min = Math.min(range.min, value);
  834. range.max = Math.max(range.max, value);
  835. }
  836. getMinMax(scale, canStack) {
  837. const meta = this._cachedMeta;
  838. const _parsed = meta._parsed;
  839. const sorted = meta._sorted && scale === meta.iScale;
  840. const ilen = _parsed.length;
  841. const otherScale = this._getOtherScale(scale);
  842. const stack = createStack(canStack, meta, this.chart);
  843. const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};
  844. const {min: otherMin, max: otherMax} = getUserBounds(otherScale);
  845. let i, parsed;
  846. function _skip() {
  847. parsed = _parsed[i];
  848. const otherValue = parsed[otherScale.axis];
  849. return !isNumberFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue;
  850. }
  851. for (i = 0; i < ilen; ++i) {
  852. if (_skip()) {
  853. continue;
  854. }
  855. this.updateRangeFromParsed(range, scale, parsed, stack);
  856. if (sorted) {
  857. break;
  858. }
  859. }
  860. if (sorted) {
  861. for (i = ilen - 1; i >= 0; --i) {
  862. if (_skip()) {
  863. continue;
  864. }
  865. this.updateRangeFromParsed(range, scale, parsed, stack);
  866. break;
  867. }
  868. }
  869. return range;
  870. }
  871. getAllParsedValues(scale) {
  872. const parsed = this._cachedMeta._parsed;
  873. const values = [];
  874. let i, ilen, value;
  875. for (i = 0, ilen = parsed.length; i < ilen; ++i) {
  876. value = parsed[i][scale.axis];
  877. if (isNumberFinite(value)) {
  878. values.push(value);
  879. }
  880. }
  881. return values;
  882. }
  883. getMaxOverflow() {
  884. return false;
  885. }
  886. getLabelAndValue(index) {
  887. const meta = this._cachedMeta;
  888. const iScale = meta.iScale;
  889. const vScale = meta.vScale;
  890. const parsed = this.getParsed(index);
  891. return {
  892. label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',
  893. value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''
  894. };
  895. }
  896. _update(mode) {
  897. const meta = this._cachedMeta;
  898. this.update(mode || 'default');
  899. meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow())));
  900. }
  901. update(mode) {}
  902. draw() {
  903. const ctx = this._ctx;
  904. const chart = this.chart;
  905. const meta = this._cachedMeta;
  906. const elements = meta.data || [];
  907. const area = chart.chartArea;
  908. const active = [];
  909. const start = this._drawStart || 0;
  910. const count = this._drawCount || (elements.length - start);
  911. const drawActiveElementsOnTop = this.options.drawActiveElementsOnTop;
  912. let i;
  913. if (meta.dataset) {
  914. meta.dataset.draw(ctx, area, start, count);
  915. }
  916. for (i = start; i < start + count; ++i) {
  917. const element = elements[i];
  918. if (element.hidden) {
  919. continue;
  920. }
  921. if (element.active && drawActiveElementsOnTop) {
  922. active.push(element);
  923. } else {
  924. element.draw(ctx, area);
  925. }
  926. }
  927. for (i = 0; i < active.length; ++i) {
  928. active[i].draw(ctx, area);
  929. }
  930. }
  931. getStyle(index, active) {
  932. const mode = active ? 'active' : 'default';
  933. return index === undefined && this._cachedMeta.dataset
  934. ? this.resolveDatasetElementOptions(mode)
  935. : this.resolveDataElementOptions(index || 0, mode);
  936. }
  937. getContext(index, active, mode) {
  938. const dataset = this.getDataset();
  939. let context;
  940. if (index >= 0 && index < this._cachedMeta.data.length) {
  941. const element = this._cachedMeta.data[index];
  942. context = element.$context ||
  943. (element.$context = createDataContext(this.getContext(), index, element));
  944. context.parsed = this.getParsed(index);
  945. context.raw = dataset.data[index];
  946. context.index = context.dataIndex = index;
  947. } else {
  948. context = this.$context ||
  949. (this.$context = createDatasetContext(this.chart.getContext(), this.index));
  950. context.dataset = dataset;
  951. context.index = context.datasetIndex = this.index;
  952. }
  953. context.active = !!active;
  954. context.mode = mode;
  955. return context;
  956. }
  957. resolveDatasetElementOptions(mode) {
  958. return this._resolveElementOptions(this.datasetElementType.id, mode);
  959. }
  960. resolveDataElementOptions(index, mode) {
  961. return this._resolveElementOptions(this.dataElementType.id, mode, index);
  962. }
  963. _resolveElementOptions(elementType, mode = 'default', index) {
  964. const active = mode === 'active';
  965. const cache = this._cachedDataOpts;
  966. const cacheKey = elementType + '-' + mode;
  967. const cached = cache[cacheKey];
  968. const sharing = this.enableOptionSharing && defined(index);
  969. if (cached) {
  970. return cloneIfNotShared(cached, sharing);
  971. }
  972. const config = this.chart.config;
  973. const scopeKeys = config.datasetElementScopeKeys(this._type, elementType);
  974. const prefixes = active ? [`${elementType}Hover`, 'hover', elementType, ''] : [elementType, ''];
  975. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);
  976. const names = Object.keys(defaults.elements[elementType]);
  977. const context = () => this.getContext(index, active);
  978. const values = config.resolveNamedOptions(scopes, names, context, prefixes);
  979. if (values.$shared) {
  980. values.$shared = sharing;
  981. cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));
  982. }
  983. return values;
  984. }
  985. _resolveAnimations(index, transition, active) {
  986. const chart = this.chart;
  987. const cache = this._cachedDataOpts;
  988. const cacheKey = `animation-${transition}`;
  989. const cached = cache[cacheKey];
  990. if (cached) {
  991. return cached;
  992. }
  993. let options;
  994. if (chart.options.animation !== false) {
  995. const config = this.chart.config;
  996. const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition);
  997. const scopes = config.getOptionScopes(this.getDataset(), scopeKeys);
  998. options = config.createResolver(scopes, this.getContext(index, active, transition));
  999. }
  1000. const animations = new Animations(chart, options && options.animations);
  1001. if (options && options._cacheable) {
  1002. cache[cacheKey] = Object.freeze(animations);
  1003. }
  1004. return animations;
  1005. }
  1006. getSharedOptions(options) {
  1007. if (!options.$shared) {
  1008. return;
  1009. }
  1010. return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));
  1011. }
  1012. includeOptions(mode, sharedOptions) {
  1013. return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;
  1014. }
  1015. updateElement(element, index, properties, mode) {
  1016. if (isDirectUpdateMode(mode)) {
  1017. Object.assign(element, properties);
  1018. } else {
  1019. this._resolveAnimations(index, mode).update(element, properties);
  1020. }
  1021. }
  1022. updateSharedOptions(sharedOptions, mode, newOptions) {
  1023. if (sharedOptions && !isDirectUpdateMode(mode)) {
  1024. this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);
  1025. }
  1026. }
  1027. _setStyle(element, index, mode, active) {
  1028. element.active = active;
  1029. const options = this.getStyle(index, active);
  1030. this._resolveAnimations(index, mode, active).update(element, {
  1031. options: (!active && this.getSharedOptions(options)) || options
  1032. });
  1033. }
  1034. removeHoverStyle(element, datasetIndex, index) {
  1035. this._setStyle(element, index, 'active', false);
  1036. }
  1037. setHoverStyle(element, datasetIndex, index) {
  1038. this._setStyle(element, index, 'active', true);
  1039. }
  1040. _removeDatasetHoverStyle() {
  1041. const element = this._cachedMeta.dataset;
  1042. if (element) {
  1043. this._setStyle(element, undefined, 'active', false);
  1044. }
  1045. }
  1046. _setDatasetHoverStyle() {
  1047. const element = this._cachedMeta.dataset;
  1048. if (element) {
  1049. this._setStyle(element, undefined, 'active', true);
  1050. }
  1051. }
  1052. _resyncElements(resetNewElements) {
  1053. const data = this._data;
  1054. const elements = this._cachedMeta.data;
  1055. for (const [method, arg1, arg2] of this._syncList) {
  1056. this[method](arg1, arg2);
  1057. }
  1058. this._syncList = [];
  1059. const numMeta = elements.length;
  1060. const numData = data.length;
  1061. const count = Math.min(numData, numMeta);
  1062. if (count) {
  1063. this.parse(0, count);
  1064. }
  1065. if (numData > numMeta) {
  1066. this._insertElements(numMeta, numData - numMeta, resetNewElements);
  1067. } else if (numData < numMeta) {
  1068. this._removeElements(numData, numMeta - numData);
  1069. }
  1070. }
  1071. _insertElements(start, count, resetNewElements = true) {
  1072. const meta = this._cachedMeta;
  1073. const data = meta.data;
  1074. const end = start + count;
  1075. let i;
  1076. const move = (arr) => {
  1077. arr.length += count;
  1078. for (i = arr.length - 1; i >= end; i--) {
  1079. arr[i] = arr[i - count];
  1080. }
  1081. };
  1082. move(data);
  1083. for (i = start; i < end; ++i) {
  1084. data[i] = new this.dataElementType();
  1085. }
  1086. if (this._parsing) {
  1087. move(meta._parsed);
  1088. }
  1089. this.parse(start, count);
  1090. if (resetNewElements) {
  1091. this.updateElements(data, start, count, 'reset');
  1092. }
  1093. }
  1094. updateElements(element, start, count, mode) {}
  1095. _removeElements(start, count) {
  1096. const meta = this._cachedMeta;
  1097. if (this._parsing) {
  1098. const removed = meta._parsed.splice(start, count);
  1099. if (meta._stacked) {
  1100. clearStacks(meta, removed);
  1101. }
  1102. }
  1103. meta.data.splice(start, count);
  1104. }
  1105. _sync(args) {
  1106. if (this._parsing) {
  1107. this._syncList.push(args);
  1108. } else {
  1109. const [method, arg1, arg2] = args;
  1110. this[method](arg1, arg2);
  1111. }
  1112. this.chart._dataChanges.push([this.index, ...args]);
  1113. }
  1114. _onDataPush() {
  1115. const count = arguments.length;
  1116. this._sync(['_insertElements', this.getDataset().data.length - count, count]);
  1117. }
  1118. _onDataPop() {
  1119. this._sync(['_removeElements', this._cachedMeta.data.length - 1, 1]);
  1120. }
  1121. _onDataShift() {
  1122. this._sync(['_removeElements', 0, 1]);
  1123. }
  1124. _onDataSplice(start, count) {
  1125. if (count) {
  1126. this._sync(['_removeElements', start, count]);
  1127. }
  1128. const newCount = arguments.length - 2;
  1129. if (newCount) {
  1130. this._sync(['_insertElements', start, newCount]);
  1131. }
  1132. }
  1133. _onDataUnshift() {
  1134. this._sync(['_insertElements', 0, arguments.length]);
  1135. }
  1136. }
  1137. DatasetController.defaults = {};
  1138. DatasetController.prototype.datasetElementType = null;
  1139. DatasetController.prototype.dataElementType = null;
  1140. function getAllScaleValues(scale, type) {
  1141. if (!scale._cache.$bar) {
  1142. const visibleMetas = scale.getMatchingVisibleMetas(type);
  1143. let values = [];
  1144. for (let i = 0, ilen = visibleMetas.length; i < ilen; i++) {
  1145. values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale));
  1146. }
  1147. scale._cache.$bar = _arrayUnique(values.sort((a, b) => a - b));
  1148. }
  1149. return scale._cache.$bar;
  1150. }
  1151. function computeMinSampleSize(meta) {
  1152. const scale = meta.iScale;
  1153. const values = getAllScaleValues(scale, meta.type);
  1154. let min = scale._length;
  1155. let i, ilen, curr, prev;
  1156. const updateMinAndPrev = () => {
  1157. if (curr === 32767 || curr === -32768) {
  1158. return;
  1159. }
  1160. if (defined(prev)) {
  1161. min = Math.min(min, Math.abs(curr - prev) || min);
  1162. }
  1163. prev = curr;
  1164. };
  1165. for (i = 0, ilen = values.length; i < ilen; ++i) {
  1166. curr = scale.getPixelForValue(values[i]);
  1167. updateMinAndPrev();
  1168. }
  1169. prev = undefined;
  1170. for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {
  1171. curr = scale.getPixelForTick(i);
  1172. updateMinAndPrev();
  1173. }
  1174. return min;
  1175. }
  1176. function computeFitCategoryTraits(index, ruler, options, stackCount) {
  1177. const thickness = options.barThickness;
  1178. let size, ratio;
  1179. if (isNullOrUndef(thickness)) {
  1180. size = ruler.min * options.categoryPercentage;
  1181. ratio = options.barPercentage;
  1182. } else {
  1183. size = thickness * stackCount;
  1184. ratio = 1;
  1185. }
  1186. return {
  1187. chunk: size / stackCount,
  1188. ratio,
  1189. start: ruler.pixels[index] - (size / 2)
  1190. };
  1191. }
  1192. function computeFlexCategoryTraits(index, ruler, options, stackCount) {
  1193. const pixels = ruler.pixels;
  1194. const curr = pixels[index];
  1195. let prev = index > 0 ? pixels[index - 1] : null;
  1196. let next = index < pixels.length - 1 ? pixels[index + 1] : null;
  1197. const percent = options.categoryPercentage;
  1198. if (prev === null) {
  1199. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  1200. }
  1201. if (next === null) {
  1202. next = curr + curr - prev;
  1203. }
  1204. const start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  1205. const size = Math.abs(next - prev) / 2 * percent;
  1206. return {
  1207. chunk: size / stackCount,
  1208. ratio: options.barPercentage,
  1209. start
  1210. };
  1211. }
  1212. function parseFloatBar(entry, item, vScale, i) {
  1213. const startValue = vScale.parse(entry[0], i);
  1214. const endValue = vScale.parse(entry[1], i);
  1215. const min = Math.min(startValue, endValue);
  1216. const max = Math.max(startValue, endValue);
  1217. let barStart = min;
  1218. let barEnd = max;
  1219. if (Math.abs(min) > Math.abs(max)) {
  1220. barStart = max;
  1221. barEnd = min;
  1222. }
  1223. item[vScale.axis] = barEnd;
  1224. item._custom = {
  1225. barStart,
  1226. barEnd,
  1227. start: startValue,
  1228. end: endValue,
  1229. min,
  1230. max
  1231. };
  1232. }
  1233. function parseValue(entry, item, vScale, i) {
  1234. if (isArray(entry)) {
  1235. parseFloatBar(entry, item, vScale, i);
  1236. } else {
  1237. item[vScale.axis] = vScale.parse(entry, i);
  1238. }
  1239. return item;
  1240. }
  1241. function parseArrayOrPrimitive(meta, data, start, count) {
  1242. const iScale = meta.iScale;
  1243. const vScale = meta.vScale;
  1244. const labels = iScale.getLabels();
  1245. const singleScale = iScale === vScale;
  1246. const parsed = [];
  1247. let i, ilen, item, entry;
  1248. for (i = start, ilen = start + count; i < ilen; ++i) {
  1249. entry = data[i];
  1250. item = {};
  1251. item[iScale.axis] = singleScale || iScale.parse(labels[i], i);
  1252. parsed.push(parseValue(entry, item, vScale, i));
  1253. }
  1254. return parsed;
  1255. }
  1256. function isFloatBar(custom) {
  1257. return custom && custom.barStart !== undefined && custom.barEnd !== undefined;
  1258. }
  1259. function barSign(size, vScale, actualBase) {
  1260. if (size !== 0) {
  1261. return sign(size);
  1262. }
  1263. return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);
  1264. }
  1265. function borderProps(properties) {
  1266. let reverse, start, end, top, bottom;
  1267. if (properties.horizontal) {
  1268. reverse = properties.base > properties.x;
  1269. start = 'left';
  1270. end = 'right';
  1271. } else {
  1272. reverse = properties.base < properties.y;
  1273. start = 'bottom';
  1274. end = 'top';
  1275. }
  1276. if (reverse) {
  1277. top = 'end';
  1278. bottom = 'start';
  1279. } else {
  1280. top = 'start';
  1281. bottom = 'end';
  1282. }
  1283. return {start, end, reverse, top, bottom};
  1284. }
  1285. function setBorderSkipped(properties, options, stack, index) {
  1286. let edge = options.borderSkipped;
  1287. const res = {};
  1288. if (!edge) {
  1289. properties.borderSkipped = res;
  1290. return;
  1291. }
  1292. const {start, end, reverse, top, bottom} = borderProps(properties);
  1293. if (edge === 'middle' && stack) {
  1294. properties.enableBorderRadius = true;
  1295. if ((stack._top || 0) === index) {
  1296. edge = top;
  1297. } else if ((stack._bottom || 0) === index) {
  1298. edge = bottom;
  1299. } else {
  1300. res[parseEdge(bottom, start, end, reverse)] = true;
  1301. edge = top;
  1302. }
  1303. }
  1304. res[parseEdge(edge, start, end, reverse)] = true;
  1305. properties.borderSkipped = res;
  1306. }
  1307. function parseEdge(edge, a, b, reverse) {
  1308. if (reverse) {
  1309. edge = swap(edge, a, b);
  1310. edge = startEnd(edge, b, a);
  1311. } else {
  1312. edge = startEnd(edge, a, b);
  1313. }
  1314. return edge;
  1315. }
  1316. function swap(orig, v1, v2) {
  1317. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  1318. }
  1319. function startEnd(v, start, end) {
  1320. return v === 'start' ? start : v === 'end' ? end : v;
  1321. }
  1322. function setInflateAmount(properties, {inflateAmount}, ratio) {
  1323. properties.inflateAmount = inflateAmount === 'auto'
  1324. ? ratio === 1 ? 0.33 : 0
  1325. : inflateAmount;
  1326. }
  1327. class BarController extends DatasetController {
  1328. parsePrimitiveData(meta, data, start, count) {
  1329. return parseArrayOrPrimitive(meta, data, start, count);
  1330. }
  1331. parseArrayData(meta, data, start, count) {
  1332. return parseArrayOrPrimitive(meta, data, start, count);
  1333. }
  1334. parseObjectData(meta, data, start, count) {
  1335. const {iScale, vScale} = meta;
  1336. const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;
  1337. const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;
  1338. const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;
  1339. const parsed = [];
  1340. let i, ilen, item, obj;
  1341. for (i = start, ilen = start + count; i < ilen; ++i) {
  1342. obj = data[i];
  1343. item = {};
  1344. item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);
  1345. parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));
  1346. }
  1347. return parsed;
  1348. }
  1349. updateRangeFromParsed(range, scale, parsed, stack) {
  1350. super.updateRangeFromParsed(range, scale, parsed, stack);
  1351. const custom = parsed._custom;
  1352. if (custom && scale === this._cachedMeta.vScale) {
  1353. range.min = Math.min(range.min, custom.min);
  1354. range.max = Math.max(range.max, custom.max);
  1355. }
  1356. }
  1357. getMaxOverflow() {
  1358. return 0;
  1359. }
  1360. getLabelAndValue(index) {
  1361. const meta = this._cachedMeta;
  1362. const {iScale, vScale} = meta;
  1363. const parsed = this.getParsed(index);
  1364. const custom = parsed._custom;
  1365. const value = isFloatBar(custom)
  1366. ? '[' + custom.start + ', ' + custom.end + ']'
  1367. : '' + vScale.getLabelForValue(parsed[vScale.axis]);
  1368. return {
  1369. label: '' + iScale.getLabelForValue(parsed[iScale.axis]),
  1370. value
  1371. };
  1372. }
  1373. initialize() {
  1374. this.enableOptionSharing = true;
  1375. super.initialize();
  1376. const meta = this._cachedMeta;
  1377. meta.stack = this.getDataset().stack;
  1378. }
  1379. update(mode) {
  1380. const meta = this._cachedMeta;
  1381. this.updateElements(meta.data, 0, meta.data.length, mode);
  1382. }
  1383. updateElements(bars, start, count, mode) {
  1384. const reset = mode === 'reset';
  1385. const {index, _cachedMeta: {vScale}} = this;
  1386. const base = vScale.getBasePixel();
  1387. const horizontal = vScale.isHorizontal();
  1388. const ruler = this._getRuler();
  1389. const firstOpts = this.resolveDataElementOptions(start, mode);
  1390. const sharedOptions = this.getSharedOptions(firstOpts);
  1391. const includeOptions = this.includeOptions(mode, sharedOptions);
  1392. this.updateSharedOptions(sharedOptions, mode, firstOpts);
  1393. for (let i = start; i < start + count; i++) {
  1394. const parsed = this.getParsed(i);
  1395. const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {base, head: base} : this._calculateBarValuePixels(i);
  1396. const ipixels = this._calculateBarIndexPixels(i, ruler);
  1397. const stack = (parsed._stacks || {})[vScale.axis];
  1398. const properties = {
  1399. horizontal,
  1400. base: vpixels.base,
  1401. enableBorderRadius: !stack || isFloatBar(parsed._custom) || (index === stack._top || index === stack._bottom),
  1402. x: horizontal ? vpixels.head : ipixels.center,
  1403. y: horizontal ? ipixels.center : vpixels.head,
  1404. height: horizontal ? ipixels.size : Math.abs(vpixels.size),
  1405. width: horizontal ? Math.abs(vpixels.size) : ipixels.size
  1406. };
  1407. if (includeOptions) {
  1408. properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);
  1409. }
  1410. const options = properties.options || bars[i].options;
  1411. setBorderSkipped(properties, options, stack, index);
  1412. setInflateAmount(properties, options, ruler.ratio);
  1413. this.updateElement(bars[i], i, properties, mode);
  1414. }
  1415. }
  1416. _getStacks(last, dataIndex) {
  1417. const meta = this._cachedMeta;
  1418. const iScale = meta.iScale;
  1419. const metasets = iScale.getMatchingVisibleMetas(this._type);
  1420. const stacked = iScale.options.stacked;
  1421. const ilen = metasets.length;
  1422. const stacks = [];
  1423. let i, item;
  1424. for (i = 0; i < ilen; ++i) {
  1425. item = metasets[i];
  1426. if (!item.controller.options.grouped) {
  1427. continue;
  1428. }
  1429. if (typeof dataIndex !== 'undefined') {
  1430. const val = item.controller.getParsed(dataIndex)[
  1431. item.controller._cachedMeta.vScale.axis
  1432. ];
  1433. if (isNullOrUndef(val) || isNaN(val)) {
  1434. continue;
  1435. }
  1436. }
  1437. if (stacked === false || stacks.indexOf(item.stack) === -1 ||
  1438. (stacked === undefined && item.stack === undefined)) {
  1439. stacks.push(item.stack);
  1440. }
  1441. if (item.index === last) {
  1442. break;
  1443. }
  1444. }
  1445. if (!stacks.length) {
  1446. stacks.push(undefined);
  1447. }
  1448. return stacks;
  1449. }
  1450. _getStackCount(index) {
  1451. return this._getStacks(undefined, index).length;
  1452. }
  1453. _getStackIndex(datasetIndex, name, dataIndex) {
  1454. const stacks = this._getStacks(datasetIndex, dataIndex);
  1455. const index = (name !== undefined)
  1456. ? stacks.indexOf(name)
  1457. : -1;
  1458. return (index === -1)
  1459. ? stacks.length - 1
  1460. : index;
  1461. }
  1462. _getRuler() {
  1463. const opts = this.options;
  1464. const meta = this._cachedMeta;
  1465. const iScale = meta.iScale;
  1466. const pixels = [];
  1467. let i, ilen;
  1468. for (i = 0, ilen = meta.data.length; i < ilen; ++i) {
  1469. pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i));
  1470. }
  1471. const barThickness = opts.barThickness;
  1472. const min = barThickness || computeMinSampleSize(meta);
  1473. return {
  1474. min,
  1475. pixels,
  1476. start: iScale._startPixel,
  1477. end: iScale._endPixel,
  1478. stackCount: this._getStackCount(),
  1479. scale: iScale,
  1480. grouped: opts.grouped,
  1481. ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage
  1482. };
  1483. }
  1484. _calculateBarValuePixels(index) {
  1485. const {_cachedMeta: {vScale, _stacked}, options: {base: baseValue, minBarLength}} = this;
  1486. const actualBase = baseValue || 0;
  1487. const parsed = this.getParsed(index);
  1488. const custom = parsed._custom;
  1489. const floating = isFloatBar(custom);
  1490. let value = parsed[vScale.axis];
  1491. let start = 0;
  1492. let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value;
  1493. let head, size;
  1494. if (length !== value) {
  1495. start = length - value;
  1496. length = value;
  1497. }
  1498. if (floating) {
  1499. value = custom.barStart;
  1500. length = custom.barEnd - custom.barStart;
  1501. if (value !== 0 && sign(value) !== sign(custom.barEnd)) {
  1502. start = 0;
  1503. }
  1504. start += value;
  1505. }
  1506. const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;
  1507. let base = vScale.getPixelForValue(startValue);
  1508. if (this.chart.getDataVisibility(index)) {
  1509. head = vScale.getPixelForValue(start + length);
  1510. } else {
  1511. head = base;
  1512. }
  1513. size = head - base;
  1514. if (Math.abs(size) < minBarLength) {
  1515. size = barSign(size, vScale, actualBase) * minBarLength;
  1516. if (value === actualBase) {
  1517. base -= size / 2;
  1518. }
  1519. const startPixel = vScale.getPixelForDecimal(0);
  1520. const endPixel = vScale.getPixelForDecimal(1);
  1521. const min = Math.min(startPixel, endPixel);
  1522. const max = Math.max(startPixel, endPixel);
  1523. base = Math.max(Math.min(base, max), min);
  1524. head = base + size;
  1525. }
  1526. if (base === vScale.getPixelForValue(actualBase)) {
  1527. const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2;
  1528. base += halfGrid;
  1529. size -= halfGrid;
  1530. }
  1531. return {
  1532. size,
  1533. base,
  1534. head,
  1535. center: head + size / 2
  1536. };
  1537. }
  1538. _calculateBarIndexPixels(index, ruler) {
  1539. const scale = ruler.scale;
  1540. const options = this.options;
  1541. const skipNull = options.skipNull;
  1542. const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);
  1543. let center, size;
  1544. if (ruler.grouped) {
  1545. const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount;
  1546. const range = options.barThickness === 'flex'
  1547. ? computeFlexCategoryTraits(index, ruler, options, stackCount)
  1548. : computeFitCategoryTraits(index, ruler, options, stackCount);
  1549. const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined);
  1550. center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  1551. size = Math.min(maxBarThickness, range.chunk * range.ratio);
  1552. } else {
  1553. center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index);
  1554. size = Math.min(maxBarThickness, ruler.min * ruler.ratio);
  1555. }
  1556. return {
  1557. base: center - size / 2,
  1558. head: center + size / 2,
  1559. center,
  1560. size
  1561. };
  1562. }
  1563. draw() {
  1564. const meta = this._cachedMeta;
  1565. const vScale = meta.vScale;
  1566. const rects = meta.data;
  1567. const ilen = rects.length;
  1568. let i = 0;
  1569. for (; i < ilen; ++i) {
  1570. if (this.getParsed(i)[vScale.axis] !== null) {
  1571. rects[i].draw(this._ctx);
  1572. }
  1573. }
  1574. }
  1575. }
  1576. BarController.id = 'bar';
  1577. BarController.defaults = {
  1578. datasetElementType: false,
  1579. dataElementType: 'bar',
  1580. categoryPercentage: 0.8,
  1581. barPercentage: 0.9,
  1582. grouped: true,
  1583. animations: {
  1584. numbers: {
  1585. type: 'number',
  1586. properties: ['x', 'y', 'base', 'width', 'height']
  1587. }
  1588. }
  1589. };
  1590. BarController.overrides = {
  1591. scales: {
  1592. _index_: {
  1593. type: 'category',
  1594. offset: true,
  1595. grid: {
  1596. offset: true
  1597. }
  1598. },
  1599. _value_: {
  1600. type: 'linear',
  1601. beginAtZero: true,
  1602. }
  1603. }
  1604. };
  1605. class BubbleController extends DatasetController {
  1606. initialize() {
  1607. this.enableOptionSharing = true;
  1608. super.initialize();
  1609. }
  1610. parsePrimitiveData(meta, data, start, count) {
  1611. const parsed = super.parsePrimitiveData(meta, data, start, count);
  1612. for (let i = 0; i < parsed.length; i++) {
  1613. parsed[i]._custom = this.resolveDataElementOptions(i + start).radius;
  1614. }
  1615. return parsed;
  1616. }
  1617. parseArrayData(meta, data, start, count) {
  1618. const parsed = super.parseArrayData(meta, data, start, count);
  1619. for (let i = 0; i < parsed.length; i++) {
  1620. const item = data[start + i];
  1621. parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius);
  1622. }
  1623. return parsed;
  1624. }
  1625. parseObjectData(meta, data, start, count) {
  1626. const parsed = super.parseObjectData(meta, data, start, count);
  1627. for (let i = 0; i < parsed.length; i++) {
  1628. const item = data[start + i];
  1629. parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius);
  1630. }
  1631. return parsed;
  1632. }
  1633. getMaxOverflow() {
  1634. const data = this._cachedMeta.data;
  1635. let max = 0;
  1636. for (let i = data.length - 1; i >= 0; --i) {
  1637. max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2);
  1638. }
  1639. return max > 0 && max;
  1640. }
  1641. getLabelAndValue(index) {
  1642. const meta = this._cachedMeta;
  1643. const {xScale, yScale} = meta;
  1644. const parsed = this.getParsed(index);
  1645. const x = xScale.getLabelForValue(parsed.x);
  1646. const y = yScale.getLabelForValue(parsed.y);
  1647. const r = parsed._custom;
  1648. return {
  1649. label: meta.label,
  1650. value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'
  1651. };
  1652. }
  1653. update(mode) {
  1654. const points = this._cachedMeta.data;
  1655. this.updateElements(points, 0, points.length, mode);
  1656. }
  1657. updateElements(points, start, count, mode) {
  1658. const reset = mode === 'reset';
  1659. const {iScale, vScale} = this._cachedMeta;
  1660. const firstOpts = this.resolveDataElementOptions(start, mode);
  1661. const sharedOptions = this.getSharedOptions(firstOpts);
  1662. const includeOptions = this.includeOptions(mode, sharedOptions);
  1663. const iAxis = iScale.axis;
  1664. const vAxis = vScale.axis;
  1665. for (let i = start; i < start + count; i++) {
  1666. const point = points[i];
  1667. const parsed = !reset && this.getParsed(i);
  1668. const properties = {};
  1669. const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);
  1670. const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);
  1671. properties.skip = isNaN(iPixel) || isNaN(vPixel);
  1672. if (includeOptions) {
  1673. properties.options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  1674. if (reset) {
  1675. properties.options.radius = 0;
  1676. }
  1677. }
  1678. this.updateElement(point, i, properties, mode);
  1679. }
  1680. this.updateSharedOptions(sharedOptions, mode, firstOpts);
  1681. }
  1682. resolveDataElementOptions(index, mode) {
  1683. const parsed = this.getParsed(index);
  1684. let values = super.resolveDataElementOptions(index, mode);
  1685. if (values.$shared) {
  1686. values = Object.assign({}, values, {$shared: false});
  1687. }
  1688. const radius = values.radius;
  1689. if (mode !== 'active') {
  1690. values.radius = 0;
  1691. }
  1692. values.radius += valueOrDefault(parsed && parsed._custom, radius);
  1693. return values;
  1694. }
  1695. }
  1696. BubbleController.id = 'bubble';
  1697. BubbleController.defaults = {
  1698. datasetElementType: false,
  1699. dataElementType: 'point',
  1700. animations: {
  1701. numbers: {
  1702. type: 'number',
  1703. properties: ['x', 'y', 'borderWidth', 'radius']
  1704. }
  1705. }
  1706. };
  1707. BubbleController.overrides = {
  1708. scales: {
  1709. x: {
  1710. type: 'linear'
  1711. },
  1712. y: {
  1713. type: 'linear'
  1714. }
  1715. },
  1716. plugins: {
  1717. tooltip: {
  1718. callbacks: {
  1719. title() {
  1720. return '';
  1721. }
  1722. }
  1723. }
  1724. }
  1725. };
  1726. function getRatioAndOffset(rotation, circumference, cutout) {
  1727. let ratioX = 1;
  1728. let ratioY = 1;
  1729. let offsetX = 0;
  1730. let offsetY = 0;
  1731. if (circumference < TAU) {
  1732. const startAngle = rotation;
  1733. const endAngle = startAngle + circumference;
  1734. const startX = Math.cos(startAngle);
  1735. const startY = Math.sin(startAngle);
  1736. const endX = Math.cos(endAngle);
  1737. const endY = Math.sin(endAngle);
  1738. const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);
  1739. const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);
  1740. const maxX = calcMax(0, startX, endX);
  1741. const maxY = calcMax(HALF_PI, startY, endY);
  1742. const minX = calcMin(PI, startX, endX);
  1743. const minY = calcMin(PI + HALF_PI, startY, endY);
  1744. ratioX = (maxX - minX) / 2;
  1745. ratioY = (maxY - minY) / 2;
  1746. offsetX = -(maxX + minX) / 2;
  1747. offsetY = -(maxY + minY) / 2;
  1748. }
  1749. return {ratioX, ratioY, offsetX, offsetY};
  1750. }
  1751. class DoughnutController extends DatasetController {
  1752. constructor(chart, datasetIndex) {
  1753. super(chart, datasetIndex);
  1754. this.enableOptionSharing = true;
  1755. this.innerRadius = undefined;
  1756. this.outerRadius = undefined;
  1757. this.offsetX = undefined;
  1758. this.offsetY = undefined;
  1759. }
  1760. linkScales() {}
  1761. parse(start, count) {
  1762. const data = this.getDataset().data;
  1763. const meta = this._cachedMeta;
  1764. if (this._parsing === false) {
  1765. meta._parsed = data;
  1766. } else {
  1767. let getter = (i) => +data[i];
  1768. if (isObject(data[start])) {
  1769. const {key = 'value'} = this._parsing;
  1770. getter = (i) => +resolveObjectKey(data[i], key);
  1771. }
  1772. let i, ilen;
  1773. for (i = start, ilen = start + count; i < ilen; ++i) {
  1774. meta._parsed[i] = getter(i);
  1775. }
  1776. }
  1777. }
  1778. _getRotation() {
  1779. return toRadians(this.options.rotation - 90);
  1780. }
  1781. _getCircumference() {
  1782. return toRadians(this.options.circumference);
  1783. }
  1784. _getRotationExtents() {
  1785. let min = TAU;
  1786. let max = -TAU;
  1787. for (let i = 0; i < this.chart.data.datasets.length; ++i) {
  1788. if (this.chart.isDatasetVisible(i)) {
  1789. const controller = this.chart.getDatasetMeta(i).controller;
  1790. const rotation = controller._getRotation();
  1791. const circumference = controller._getCircumference();
  1792. min = Math.min(min, rotation);
  1793. max = Math.max(max, rotation + circumference);
  1794. }
  1795. }
  1796. return {
  1797. rotation: min,
  1798. circumference: max - min,
  1799. };
  1800. }
  1801. update(mode) {
  1802. const chart = this.chart;
  1803. const {chartArea} = chart;
  1804. const meta = this._cachedMeta;
  1805. const arcs = meta.data;
  1806. const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing;
  1807. const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);
  1808. const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1);
  1809. const chartWeight = this._getRingWeight(this.index);
  1810. const {circumference, rotation} = this._getRotationExtents();
  1811. const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout);
  1812. const maxWidth = (chartArea.width - spacing) / ratioX;
  1813. const maxHeight = (chartArea.height - spacing) / ratioY;
  1814. const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  1815. const outerRadius = toDimension(this.options.radius, maxRadius);
  1816. const innerRadius = Math.max(outerRadius * cutout, 0);
  1817. const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal();
  1818. this.offsetX = offsetX * outerRadius;
  1819. this.offsetY = offsetY * outerRadius;
  1820. meta.total = this.calculateTotal();
  1821. this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index);
  1822. this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0);
  1823. this.updateElements(arcs, 0, arcs.length, mode);
  1824. }
  1825. _circumference(i, reset) {
  1826. const opts = this.options;
  1827. const meta = this._cachedMeta;
  1828. const circumference = this._getCircumference();
  1829. if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {
  1830. return 0;
  1831. }
  1832. return this.calculateCircumference(meta._parsed[i] * circumference / TAU);
  1833. }
  1834. updateElements(arcs, start, count, mode) {
  1835. const reset = mode === 'reset';
  1836. const chart = this.chart;
  1837. const chartArea = chart.chartArea;
  1838. const opts = chart.options;
  1839. const animationOpts = opts.animation;
  1840. const centerX = (chartArea.left + chartArea.right) / 2;
  1841. const centerY = (chartArea.top + chartArea.bottom) / 2;
  1842. const animateScale = reset && animationOpts.animateScale;
  1843. const innerRadius = animateScale ? 0 : this.innerRadius;
  1844. const outerRadius = animateScale ? 0 : this.outerRadius;
  1845. const firstOpts = this.resolveDataElementOptions(start, mode);
  1846. const sharedOptions = this.getSharedOptions(firstOpts);
  1847. const includeOptions = this.includeOptions(mode, sharedOptions);
  1848. let startAngle = this._getRotation();
  1849. let i;
  1850. for (i = 0; i < start; ++i) {
  1851. startAngle += this._circumference(i, reset);
  1852. }
  1853. for (i = start; i < start + count; ++i) {
  1854. const circumference = this._circumference(i, reset);
  1855. const arc = arcs[i];
  1856. const properties = {
  1857. x: centerX + this.offsetX,
  1858. y: centerY + this.offsetY,
  1859. startAngle,
  1860. endAngle: startAngle + circumference,
  1861. circumference,
  1862. outerRadius,
  1863. innerRadius
  1864. };
  1865. if (includeOptions) {
  1866. properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode);
  1867. }
  1868. startAngle += circumference;
  1869. this.updateElement(arc, i, properties, mode);
  1870. }
  1871. this.updateSharedOptions(sharedOptions, mode, firstOpts);
  1872. }
  1873. calculateTotal() {
  1874. const meta = this._cachedMeta;
  1875. const metaData = meta.data;
  1876. let total = 0;
  1877. let i;
  1878. for (i = 0; i < metaData.length; i++) {
  1879. const value = meta._parsed[i];
  1880. if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {
  1881. total += Math.abs(value);
  1882. }
  1883. }
  1884. return total;
  1885. }
  1886. calculateCircumference(value) {
  1887. const total = this._cachedMeta.total;
  1888. if (total > 0 && !isNaN(value)) {
  1889. return TAU * (Math.abs(value) / total);
  1890. }
  1891. return 0;
  1892. }
  1893. getLabelAndValue(index) {
  1894. const meta = this._cachedMeta;
  1895. const chart = this.chart;
  1896. const labels = chart.data.labels || [];
  1897. const value = formatNumber(meta._parsed[index], chart.options.locale);
  1898. return {
  1899. label: labels[index] || '',
  1900. value,
  1901. };
  1902. }
  1903. getMaxBorderWidth(arcs) {
  1904. let max = 0;
  1905. const chart = this.chart;
  1906. let i, ilen, meta, controller, options;
  1907. if (!arcs) {
  1908. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  1909. if (chart.isDatasetVisible(i)) {
  1910. meta = chart.getDatasetMeta(i);
  1911. arcs = meta.data;
  1912. controller = meta.controller;
  1913. break;
  1914. }
  1915. }
  1916. }
  1917. if (!arcs) {
  1918. return 0;
  1919. }
  1920. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  1921. options = controller.resolveDataElementOptions(i);
  1922. if (options.borderAlign !== 'inner') {
  1923. max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);
  1924. }
  1925. }
  1926. return max;
  1927. }
  1928. getMaxOffset(arcs) {
  1929. let max = 0;
  1930. for (let i = 0, ilen = arcs.length; i < ilen; ++i) {
  1931. const options = this.resolveDataElementOptions(i);
  1932. max = Math.max(max, options.offset || 0, options.hoverOffset || 0);
  1933. }
  1934. return max;
  1935. }
  1936. _getRingWeightOffset(datasetIndex) {
  1937. let ringWeightOffset = 0;
  1938. for (let i = 0; i < datasetIndex; ++i) {
  1939. if (this.chart.isDatasetVisible(i)) {
  1940. ringWeightOffset += this._getRingWeight(i);
  1941. }
  1942. }
  1943. return ringWeightOffset;
  1944. }
  1945. _getRingWeight(datasetIndex) {
  1946. return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);
  1947. }
  1948. _getVisibleDatasetWeightTotal() {
  1949. return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;
  1950. }
  1951. }
  1952. DoughnutController.id = 'doughnut';
  1953. DoughnutController.defaults = {
  1954. datasetElementType: false,
  1955. dataElementType: 'arc',
  1956. animation: {
  1957. animateRotate: true,
  1958. animateScale: false
  1959. },
  1960. animations: {
  1961. numbers: {
  1962. type: 'number',
  1963. properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing']
  1964. },
  1965. },
  1966. cutout: '50%',
  1967. rotation: 0,
  1968. circumference: 360,
  1969. radius: '100%',
  1970. spacing: 0,
  1971. indexAxis: 'r',
  1972. };
  1973. DoughnutController.descriptors = {
  1974. _scriptable: (name) => name !== 'spacing',
  1975. _indexable: (name) => name !== 'spacing',
  1976. };
  1977. DoughnutController.overrides = {
  1978. aspectRatio: 1,
  1979. plugins: {
  1980. legend: {
  1981. labels: {
  1982. generateLabels(chart) {
  1983. const data = chart.data;
  1984. if (data.labels.length && data.datasets.length) {
  1985. const {labels: {pointStyle}} = chart.legend.options;
  1986. return data.labels.map((label, i) => {
  1987. const meta = chart.getDatasetMeta(0);
  1988. const style = meta.controller.getStyle(i);
  1989. return {
  1990. text: label,
  1991. fillStyle: style.backgroundColor,
  1992. strokeStyle: style.borderColor,
  1993. lineWidth: style.borderWidth,
  1994. pointStyle: pointStyle,
  1995. hidden: !chart.getDataVisibility(i),
  1996. index: i
  1997. };
  1998. });
  1999. }
  2000. return [];
  2001. }
  2002. },
  2003. onClick(e, legendItem, legend) {
  2004. legend.chart.toggleDataVisibility(legendItem.index);
  2005. legend.chart.update();
  2006. }
  2007. },
  2008. tooltip: {
  2009. callbacks: {
  2010. title() {
  2011. return '';
  2012. },
  2013. label(tooltipItem) {
  2014. let dataLabel = tooltipItem.label;
  2015. const value = ': ' + tooltipItem.formattedValue;
  2016. if (isArray(dataLabel)) {
  2017. dataLabel = dataLabel.slice();
  2018. dataLabel[0] += value;
  2019. } else {
  2020. dataLabel += value;
  2021. }
  2022. return dataLabel;
  2023. }
  2024. }
  2025. }
  2026. }
  2027. };
  2028. class LineController extends DatasetController {
  2029. initialize() {
  2030. this.enableOptionSharing = true;
  2031. this.supportsDecimation = true;
  2032. super.initialize();
  2033. }
  2034. update(mode) {
  2035. const meta = this._cachedMeta;
  2036. const {dataset: line, data: points = [], _dataset} = meta;
  2037. const animationsDisabled = this.chart._animationsDisabled;
  2038. let {start, count} = getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
  2039. this._drawStart = start;
  2040. this._drawCount = count;
  2041. if (scaleRangesChanged(meta)) {
  2042. start = 0;
  2043. count = points.length;
  2044. }
  2045. line._chart = this.chart;
  2046. line._datasetIndex = this.index;
  2047. line._decimated = !!_dataset._decimated;
  2048. line.points = points;
  2049. const options = this.resolveDatasetElementOptions(mode);
  2050. if (!this.options.showLine) {
  2051. options.borderWidth = 0;
  2052. }
  2053. options.segment = this.options.segment;
  2054. this.updateElement(line, undefined, {
  2055. animated: !animationsDisabled,
  2056. options
  2057. }, mode);
  2058. this.updateElements(points, start, count, mode);
  2059. }
  2060. updateElements(points, start, count, mode) {
  2061. const reset = mode === 'reset';
  2062. const {iScale, vScale, _stacked, _dataset} = this._cachedMeta;
  2063. const firstOpts = this.resolveDataElementOptions(start, mode);
  2064. const sharedOptions = this.getSharedOptions(firstOpts);
  2065. const includeOptions = this.includeOptions(mode, sharedOptions);
  2066. const iAxis = iScale.axis;
  2067. const vAxis = vScale.axis;
  2068. const {spanGaps, segment} = this.options;
  2069. const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
  2070. const directUpdate = this.chart._animationsDisabled || reset || mode === 'none';
  2071. let prevParsed = start > 0 && this.getParsed(start - 1);
  2072. for (let i = start; i < start + count; ++i) {
  2073. const point = points[i];
  2074. const parsed = this.getParsed(i);
  2075. const properties = directUpdate ? point : {};
  2076. const nullData = isNullOrUndef(parsed[vAxis]);
  2077. const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
  2078. const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
  2079. properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
  2080. properties.stop = i > 0 && (parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;
  2081. if (segment) {
  2082. properties.parsed = parsed;
  2083. properties.raw = _dataset.data[i];
  2084. }
  2085. if (includeOptions) {
  2086. properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2087. }
  2088. if (!directUpdate) {
  2089. this.updateElement(point, i, properties, mode);
  2090. }
  2091. prevParsed = parsed;
  2092. }
  2093. this.updateSharedOptions(sharedOptions, mode, firstOpts);
  2094. }
  2095. getMaxOverflow() {
  2096. const meta = this._cachedMeta;
  2097. const dataset = meta.dataset;
  2098. const border = dataset.options && dataset.options.borderWidth || 0;
  2099. const data = meta.data || [];
  2100. if (!data.length) {
  2101. return border;
  2102. }
  2103. const firstPoint = data[0].size(this.resolveDataElementOptions(0));
  2104. const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1));
  2105. return Math.max(border, firstPoint, lastPoint) / 2;
  2106. }
  2107. draw() {
  2108. const meta = this._cachedMeta;
  2109. meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);
  2110. super.draw();
  2111. }
  2112. }
  2113. LineController.id = 'line';
  2114. LineController.defaults = {
  2115. datasetElementType: 'line',
  2116. dataElementType: 'point',
  2117. showLine: true,
  2118. spanGaps: false,
  2119. };
  2120. LineController.overrides = {
  2121. scales: {
  2122. _index_: {
  2123. type: 'category',
  2124. },
  2125. _value_: {
  2126. type: 'linear',
  2127. },
  2128. }
  2129. };
  2130. function getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) {
  2131. const pointCount = points.length;
  2132. let start = 0;
  2133. let count = pointCount;
  2134. if (meta._sorted) {
  2135. const {iScale, _parsed} = meta;
  2136. const axis = iScale.axis;
  2137. const {min, max, minDefined, maxDefined} = iScale.getUserBounds();
  2138. if (minDefined) {
  2139. start = _limitValue(Math.min(
  2140. _lookupByKey(_parsed, iScale.axis, min).lo,
  2141. animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo),
  2142. 0, pointCount - 1);
  2143. }
  2144. if (maxDefined) {
  2145. count = _limitValue(Math.max(
  2146. _lookupByKey(_parsed, iScale.axis, max).hi + 1,
  2147. animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max)).hi + 1),
  2148. start, pointCount) - start;
  2149. } else {
  2150. count = pointCount - start;
  2151. }
  2152. }
  2153. return {start, count};
  2154. }
  2155. function scaleRangesChanged(meta) {
  2156. const {xScale, yScale, _scaleRanges} = meta;
  2157. const newRanges = {
  2158. xmin: xScale.min,
  2159. xmax: xScale.max,
  2160. ymin: yScale.min,
  2161. ymax: yScale.max
  2162. };
  2163. if (!_scaleRanges) {
  2164. meta._scaleRanges = newRanges;
  2165. return true;
  2166. }
  2167. const changed = _scaleRanges.xmin !== xScale.min
  2168. || _scaleRanges.xmax !== xScale.max
  2169. || _scaleRanges.ymin !== yScale.min
  2170. || _scaleRanges.ymax !== yScale.max;
  2171. Object.assign(_scaleRanges, newRanges);
  2172. return changed;
  2173. }
  2174. class PolarAreaController extends DatasetController {
  2175. constructor(chart, datasetIndex) {
  2176. super(chart, datasetIndex);
  2177. this.innerRadius = undefined;
  2178. this.outerRadius = undefined;
  2179. }
  2180. getLabelAndValue(index) {
  2181. const meta = this._cachedMeta;
  2182. const chart = this.chart;
  2183. const labels = chart.data.labels || [];
  2184. const value = formatNumber(meta._parsed[index].r, chart.options.locale);
  2185. return {
  2186. label: labels[index] || '',
  2187. value,
  2188. };
  2189. }
  2190. parseObjectData(meta, data, start, count) {
  2191. return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);
  2192. }
  2193. update(mode) {
  2194. const arcs = this._cachedMeta.data;
  2195. this._updateRadius();
  2196. this.updateElements(arcs, 0, arcs.length, mode);
  2197. }
  2198. _updateRadius() {
  2199. const chart = this.chart;
  2200. const chartArea = chart.chartArea;
  2201. const opts = chart.options;
  2202. const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  2203. const outerRadius = Math.max(minSize / 2, 0);
  2204. const innerRadius = Math.max(opts.cutoutPercentage ? (outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  2205. const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();
  2206. this.outerRadius = outerRadius - (radiusLength * this.index);
  2207. this.innerRadius = this.outerRadius - radiusLength;
  2208. }
  2209. updateElements(arcs, start, count, mode) {
  2210. const reset = mode === 'reset';
  2211. const chart = this.chart;
  2212. const opts = chart.options;
  2213. const animationOpts = opts.animation;
  2214. const scale = this._cachedMeta.rScale;
  2215. const centerX = scale.xCenter;
  2216. const centerY = scale.yCenter;
  2217. const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;
  2218. let angle = datasetStartAngle;
  2219. let i;
  2220. const defaultAngle = 360 / this.countVisibleElements();
  2221. for (i = 0; i < start; ++i) {
  2222. angle += this._computeAngle(i, mode, defaultAngle);
  2223. }
  2224. for (i = start; i < start + count; i++) {
  2225. const arc = arcs[i];
  2226. let startAngle = angle;
  2227. let endAngle = angle + this._computeAngle(i, mode, defaultAngle);
  2228. let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(this.getParsed(i).r) : 0;
  2229. angle = endAngle;
  2230. if (reset) {
  2231. if (animationOpts.animateScale) {
  2232. outerRadius = 0;
  2233. }
  2234. if (animationOpts.animateRotate) {
  2235. startAngle = endAngle = datasetStartAngle;
  2236. }
  2237. }
  2238. const properties = {
  2239. x: centerX,
  2240. y: centerY,
  2241. innerRadius: 0,
  2242. outerRadius,
  2243. startAngle,
  2244. endAngle,
  2245. options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode)
  2246. };
  2247. this.updateElement(arc, i, properties, mode);
  2248. }
  2249. }
  2250. countVisibleElements() {
  2251. const meta = this._cachedMeta;
  2252. let count = 0;
  2253. meta.data.forEach((element, index) => {
  2254. if (!isNaN(this.getParsed(index).r) && this.chart.getDataVisibility(index)) {
  2255. count++;
  2256. }
  2257. });
  2258. return count;
  2259. }
  2260. _computeAngle(index, mode, defaultAngle) {
  2261. return this.chart.getDataVisibility(index)
  2262. ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle)
  2263. : 0;
  2264. }
  2265. }
  2266. PolarAreaController.id = 'polarArea';
  2267. PolarAreaController.defaults = {
  2268. dataElementType: 'arc',
  2269. animation: {
  2270. animateRotate: true,
  2271. animateScale: true
  2272. },
  2273. animations: {
  2274. numbers: {
  2275. type: 'number',
  2276. properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius']
  2277. },
  2278. },
  2279. indexAxis: 'r',
  2280. startAngle: 0,
  2281. };
  2282. PolarAreaController.overrides = {
  2283. aspectRatio: 1,
  2284. plugins: {
  2285. legend: {
  2286. labels: {
  2287. generateLabels(chart) {
  2288. const data = chart.data;
  2289. if (data.labels.length && data.datasets.length) {
  2290. const {labels: {pointStyle}} = chart.legend.options;
  2291. return data.labels.map((label, i) => {
  2292. const meta = chart.getDatasetMeta(0);
  2293. const style = meta.controller.getStyle(i);
  2294. return {
  2295. text: label,
  2296. fillStyle: style.backgroundColor,
  2297. strokeStyle: style.borderColor,
  2298. lineWidth: style.borderWidth,
  2299. pointStyle: pointStyle,
  2300. hidden: !chart.getDataVisibility(i),
  2301. index: i
  2302. };
  2303. });
  2304. }
  2305. return [];
  2306. }
  2307. },
  2308. onClick(e, legendItem, legend) {
  2309. legend.chart.toggleDataVisibility(legendItem.index);
  2310. legend.chart.update();
  2311. }
  2312. },
  2313. tooltip: {
  2314. callbacks: {
  2315. title() {
  2316. return '';
  2317. },
  2318. label(context) {
  2319. return context.chart.data.labels[context.dataIndex] + ': ' + context.formattedValue;
  2320. }
  2321. }
  2322. }
  2323. },
  2324. scales: {
  2325. r: {
  2326. type: 'radialLinear',
  2327. angleLines: {
  2328. display: false
  2329. },
  2330. beginAtZero: true,
  2331. grid: {
  2332. circular: true
  2333. },
  2334. pointLabels: {
  2335. display: false
  2336. },
  2337. startAngle: 0
  2338. }
  2339. }
  2340. };
  2341. class PieController extends DoughnutController {
  2342. }
  2343. PieController.id = 'pie';
  2344. PieController.defaults = {
  2345. cutout: 0,
  2346. rotation: 0,
  2347. circumference: 360,
  2348. radius: '100%'
  2349. };
  2350. class RadarController extends DatasetController {
  2351. getLabelAndValue(index) {
  2352. const vScale = this._cachedMeta.vScale;
  2353. const parsed = this.getParsed(index);
  2354. return {
  2355. label: vScale.getLabels()[index],
  2356. value: '' + vScale.getLabelForValue(parsed[vScale.axis])
  2357. };
  2358. }
  2359. parseObjectData(meta, data, start, count) {
  2360. return _parseObjectDataRadialScale.bind(this)(meta, data, start, count);
  2361. }
  2362. update(mode) {
  2363. const meta = this._cachedMeta;
  2364. const line = meta.dataset;
  2365. const points = meta.data || [];
  2366. const labels = meta.iScale.getLabels();
  2367. line.points = points;
  2368. if (mode !== 'resize') {
  2369. const options = this.resolveDatasetElementOptions(mode);
  2370. if (!this.options.showLine) {
  2371. options.borderWidth = 0;
  2372. }
  2373. const properties = {
  2374. _loop: true,
  2375. _fullLoop: labels.length === points.length,
  2376. options
  2377. };
  2378. this.updateElement(line, undefined, properties, mode);
  2379. }
  2380. this.updateElements(points, 0, points.length, mode);
  2381. }
  2382. updateElements(points, start, count, mode) {
  2383. const scale = this._cachedMeta.rScale;
  2384. const reset = mode === 'reset';
  2385. for (let i = start; i < start + count; i++) {
  2386. const point = points[i];
  2387. const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode);
  2388. const pointPosition = scale.getPointPositionForValue(i, this.getParsed(i).r);
  2389. const x = reset ? scale.xCenter : pointPosition.x;
  2390. const y = reset ? scale.yCenter : pointPosition.y;
  2391. const properties = {
  2392. x,
  2393. y,
  2394. angle: pointPosition.angle,
  2395. skip: isNaN(x) || isNaN(y),
  2396. options
  2397. };
  2398. this.updateElement(point, i, properties, mode);
  2399. }
  2400. }
  2401. }
  2402. RadarController.id = 'radar';
  2403. RadarController.defaults = {
  2404. datasetElementType: 'line',
  2405. dataElementType: 'point',
  2406. indexAxis: 'r',
  2407. showLine: true,
  2408. elements: {
  2409. line: {
  2410. fill: 'start'
  2411. }
  2412. },
  2413. };
  2414. RadarController.overrides = {
  2415. aspectRatio: 1,
  2416. scales: {
  2417. r: {
  2418. type: 'radialLinear',
  2419. }
  2420. }
  2421. };
  2422. class ScatterController extends LineController {
  2423. }
  2424. ScatterController.id = 'scatter';
  2425. ScatterController.defaults = {
  2426. showLine: false,
  2427. fill: false
  2428. };
  2429. ScatterController.overrides = {
  2430. interaction: {
  2431. mode: 'point'
  2432. },
  2433. plugins: {
  2434. tooltip: {
  2435. callbacks: {
  2436. title() {
  2437. return '';
  2438. },
  2439. label(item) {
  2440. return '(' + item.label + ', ' + item.formattedValue + ')';
  2441. }
  2442. }
  2443. }
  2444. },
  2445. scales: {
  2446. x: {
  2447. type: 'linear'
  2448. },
  2449. y: {
  2450. type: 'linear'
  2451. }
  2452. }
  2453. };
  2454. var controllers = /*#__PURE__*/Object.freeze({
  2455. __proto__: null,
  2456. BarController: BarController,
  2457. BubbleController: BubbleController,
  2458. DoughnutController: DoughnutController,
  2459. LineController: LineController,
  2460. PolarAreaController: PolarAreaController,
  2461. PieController: PieController,
  2462. RadarController: RadarController,
  2463. ScatterController: ScatterController
  2464. });
  2465. function abstract() {
  2466. throw new Error('This method is not implemented: Check that a complete date adapter is provided.');
  2467. }
  2468. class DateAdapter {
  2469. constructor(options) {
  2470. this.options = options || {};
  2471. }
  2472. formats() {
  2473. return abstract();
  2474. }
  2475. parse(value, format) {
  2476. return abstract();
  2477. }
  2478. format(timestamp, format) {
  2479. return abstract();
  2480. }
  2481. add(timestamp, amount, unit) {
  2482. return abstract();
  2483. }
  2484. diff(a, b, unit) {
  2485. return abstract();
  2486. }
  2487. startOf(timestamp, unit, weekday) {
  2488. return abstract();
  2489. }
  2490. endOf(timestamp, unit) {
  2491. return abstract();
  2492. }
  2493. }
  2494. DateAdapter.override = function(members) {
  2495. Object.assign(DateAdapter.prototype, members);
  2496. };
  2497. var adapters = {
  2498. _date: DateAdapter
  2499. };
  2500. function binarySearch(metaset, axis, value, intersect) {
  2501. const {controller, data, _sorted} = metaset;
  2502. const iScale = controller._cachedMeta.iScale;
  2503. if (iScale && axis === iScale.axis && axis !== 'r' && _sorted && data.length) {
  2504. const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;
  2505. if (!intersect) {
  2506. return lookupMethod(data, axis, value);
  2507. } else if (controller._sharedOptions) {
  2508. const el = data[0];
  2509. const range = typeof el.getRange === 'function' && el.getRange(axis);
  2510. if (range) {
  2511. const start = lookupMethod(data, axis, value - range);
  2512. const end = lookupMethod(data, axis, value + range);
  2513. return {lo: start.lo, hi: end.hi};
  2514. }
  2515. }
  2516. }
  2517. return {lo: 0, hi: data.length - 1};
  2518. }
  2519. function evaluateInteractionItems(chart, axis, position, handler, intersect) {
  2520. const metasets = chart.getSortedVisibleDatasetMetas();
  2521. const value = position[axis];
  2522. for (let i = 0, ilen = metasets.length; i < ilen; ++i) {
  2523. const {index, data} = metasets[i];
  2524. const {lo, hi} = binarySearch(metasets[i], axis, value, intersect);
  2525. for (let j = lo; j <= hi; ++j) {
  2526. const element = data[j];
  2527. if (!element.skip) {
  2528. handler(element, index, j);
  2529. }
  2530. }
  2531. }
  2532. }
  2533. function getDistanceMetricForAxis(axis) {
  2534. const useX = axis.indexOf('x') !== -1;
  2535. const useY = axis.indexOf('y') !== -1;
  2536. return function(pt1, pt2) {
  2537. const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  2538. const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  2539. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  2540. };
  2541. }
  2542. function getIntersectItems(chart, position, axis, useFinalPosition) {
  2543. const items = [];
  2544. if (!chart.isPointInArea(position)) {
  2545. return items;
  2546. }
  2547. const evaluationFunc = function(element, datasetIndex, index) {
  2548. if (element.inRange(position.x, position.y, useFinalPosition)) {
  2549. items.push({element, datasetIndex, index});
  2550. }
  2551. };
  2552. evaluateInteractionItems(chart, axis, position, evaluationFunc, true);
  2553. return items;
  2554. }
  2555. function getNearestRadialItems(chart, position, axis, useFinalPosition) {
  2556. let items = [];
  2557. function evaluationFunc(element, datasetIndex, index) {
  2558. const {startAngle, endAngle} = element.getProps(['startAngle', 'endAngle'], useFinalPosition);
  2559. const {angle} = getAngleFromPoint(element, {x: position.x, y: position.y});
  2560. if (_angleBetween(angle, startAngle, endAngle)) {
  2561. items.push({element, datasetIndex, index});
  2562. }
  2563. }
  2564. evaluateInteractionItems(chart, axis, position, evaluationFunc);
  2565. return items;
  2566. }
  2567. function getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition) {
  2568. let items = [];
  2569. const distanceMetric = getDistanceMetricForAxis(axis);
  2570. let minDistance = Number.POSITIVE_INFINITY;
  2571. function evaluationFunc(element, datasetIndex, index) {
  2572. const inRange = element.inRange(position.x, position.y, useFinalPosition);
  2573. if (intersect && !inRange) {
  2574. return;
  2575. }
  2576. const center = element.getCenterPoint(useFinalPosition);
  2577. const pointInArea = chart.isPointInArea(center);
  2578. if (!pointInArea && !inRange) {
  2579. return;
  2580. }
  2581. const distance = distanceMetric(position, center);
  2582. if (distance < minDistance) {
  2583. items = [{element, datasetIndex, index}];
  2584. minDistance = distance;
  2585. } else if (distance === minDistance) {
  2586. items.push({element, datasetIndex, index});
  2587. }
  2588. }
  2589. evaluateInteractionItems(chart, axis, position, evaluationFunc);
  2590. return items;
  2591. }
  2592. function getNearestItems(chart, position, axis, intersect, useFinalPosition) {
  2593. if (!chart.isPointInArea(position)) {
  2594. return [];
  2595. }
  2596. return axis === 'r' && !intersect
  2597. ? getNearestRadialItems(chart, position, axis, useFinalPosition)
  2598. : getNearestCartesianItems(chart, position, axis, intersect, useFinalPosition);
  2599. }
  2600. function getAxisItems(chart, position, axis, intersect, useFinalPosition) {
  2601. const items = [];
  2602. const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';
  2603. let intersectsItem = false;
  2604. evaluateInteractionItems(chart, axis, position, (element, datasetIndex, index) => {
  2605. if (element[rangeMethod](position[axis], useFinalPosition)) {
  2606. items.push({element, datasetIndex, index});
  2607. intersectsItem = intersectsItem || element.inRange(position.x, position.y, useFinalPosition);
  2608. }
  2609. });
  2610. if (intersect && !intersectsItem) {
  2611. return [];
  2612. }
  2613. return items;
  2614. }
  2615. var Interaction = {
  2616. evaluateInteractionItems,
  2617. modes: {
  2618. index(chart, e, options, useFinalPosition) {
  2619. const position = getRelativePosition(e, chart);
  2620. const axis = options.axis || 'x';
  2621. const items = options.intersect
  2622. ? getIntersectItems(chart, position, axis, useFinalPosition)
  2623. : getNearestItems(chart, position, axis, false, useFinalPosition);
  2624. const elements = [];
  2625. if (!items.length) {
  2626. return [];
  2627. }
  2628. chart.getSortedVisibleDatasetMetas().forEach((meta) => {
  2629. const index = items[0].index;
  2630. const element = meta.data[index];
  2631. if (element && !element.skip) {
  2632. elements.push({element, datasetIndex: meta.index, index});
  2633. }
  2634. });
  2635. return elements;
  2636. },
  2637. dataset(chart, e, options, useFinalPosition) {
  2638. const position = getRelativePosition(e, chart);
  2639. const axis = options.axis || 'xy';
  2640. let items = options.intersect
  2641. ? getIntersectItems(chart, position, axis, useFinalPosition) :
  2642. getNearestItems(chart, position, axis, false, useFinalPosition);
  2643. if (items.length > 0) {
  2644. const datasetIndex = items[0].datasetIndex;
  2645. const data = chart.getDatasetMeta(datasetIndex).data;
  2646. items = [];
  2647. for (let i = 0; i < data.length; ++i) {
  2648. items.push({element: data[i], datasetIndex, index: i});
  2649. }
  2650. }
  2651. return items;
  2652. },
  2653. point(chart, e, options, useFinalPosition) {
  2654. const position = getRelativePosition(e, chart);
  2655. const axis = options.axis || 'xy';
  2656. return getIntersectItems(chart, position, axis, useFinalPosition);
  2657. },
  2658. nearest(chart, e, options, useFinalPosition) {
  2659. const position = getRelativePosition(e, chart);
  2660. const axis = options.axis || 'xy';
  2661. return getNearestItems(chart, position, axis, options.intersect, useFinalPosition);
  2662. },
  2663. x(chart, e, options, useFinalPosition) {
  2664. const position = getRelativePosition(e, chart);
  2665. return getAxisItems(chart, position, 'x', options.intersect, useFinalPosition);
  2666. },
  2667. y(chart, e, options, useFinalPosition) {
  2668. const position = getRelativePosition(e, chart);
  2669. return getAxisItems(chart, position, 'y', options.intersect, useFinalPosition);
  2670. }
  2671. }
  2672. };
  2673. const STATIC_POSITIONS = ['left', 'top', 'right', 'bottom'];
  2674. function filterByPosition(array, position) {
  2675. return array.filter(v => v.pos === position);
  2676. }
  2677. function filterDynamicPositionByAxis(array, axis) {
  2678. return array.filter(v => STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);
  2679. }
  2680. function sortByWeight(array, reverse) {
  2681. return array.sort((a, b) => {
  2682. const v0 = reverse ? b : a;
  2683. const v1 = reverse ? a : b;
  2684. return v0.weight === v1.weight ?
  2685. v0.index - v1.index :
  2686. v0.weight - v1.weight;
  2687. });
  2688. }
  2689. function wrapBoxes(boxes) {
  2690. const layoutBoxes = [];
  2691. let i, ilen, box, pos, stack, stackWeight;
  2692. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  2693. box = boxes[i];
  2694. ({position: pos, options: {stack, stackWeight = 1}} = box);
  2695. layoutBoxes.push({
  2696. index: i,
  2697. box,
  2698. pos,
  2699. horizontal: box.isHorizontal(),
  2700. weight: box.weight,
  2701. stack: stack && (pos + stack),
  2702. stackWeight
  2703. });
  2704. }
  2705. return layoutBoxes;
  2706. }
  2707. function buildStacks(layouts) {
  2708. const stacks = {};
  2709. for (const wrap of layouts) {
  2710. const {stack, pos, stackWeight} = wrap;
  2711. if (!stack || !STATIC_POSITIONS.includes(pos)) {
  2712. continue;
  2713. }
  2714. const _stack = stacks[stack] || (stacks[stack] = {count: 0, placed: 0, weight: 0, size: 0});
  2715. _stack.count++;
  2716. _stack.weight += stackWeight;
  2717. }
  2718. return stacks;
  2719. }
  2720. function setLayoutDims(layouts, params) {
  2721. const stacks = buildStacks(layouts);
  2722. const {vBoxMaxWidth, hBoxMaxHeight} = params;
  2723. let i, ilen, layout;
  2724. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  2725. layout = layouts[i];
  2726. const {fullSize} = layout.box;
  2727. const stack = stacks[layout.stack];
  2728. const factor = stack && layout.stackWeight / stack.weight;
  2729. if (layout.horizontal) {
  2730. layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;
  2731. layout.height = hBoxMaxHeight;
  2732. } else {
  2733. layout.width = vBoxMaxWidth;
  2734. layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;
  2735. }
  2736. }
  2737. return stacks;
  2738. }
  2739. function buildLayoutBoxes(boxes) {
  2740. const layoutBoxes = wrapBoxes(boxes);
  2741. const fullSize = sortByWeight(layoutBoxes.filter(wrap => wrap.box.fullSize), true);
  2742. const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  2743. const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  2744. const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  2745. const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  2746. const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');
  2747. const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');
  2748. return {
  2749. fullSize,
  2750. leftAndTop: left.concat(top),
  2751. rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),
  2752. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  2753. vertical: left.concat(right).concat(centerVertical),
  2754. horizontal: top.concat(bottom).concat(centerHorizontal)
  2755. };
  2756. }
  2757. function getCombinedMax(maxPadding, chartArea, a, b) {
  2758. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  2759. }
  2760. function updateMaxPadding(maxPadding, boxPadding) {
  2761. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  2762. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  2763. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  2764. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  2765. }
  2766. function updateDims(chartArea, params, layout, stacks) {
  2767. const {pos, box} = layout;
  2768. const maxPadding = chartArea.maxPadding;
  2769. if (!isObject(pos)) {
  2770. if (layout.size) {
  2771. chartArea[pos] -= layout.size;
  2772. }
  2773. const stack = stacks[layout.stack] || {size: 0, count: 1};
  2774. stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);
  2775. layout.size = stack.size / stack.count;
  2776. chartArea[pos] += layout.size;
  2777. }
  2778. if (box.getPadding) {
  2779. updateMaxPadding(maxPadding, box.getPadding());
  2780. }
  2781. const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));
  2782. const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));
  2783. const widthChanged = newWidth !== chartArea.w;
  2784. const heightChanged = newHeight !== chartArea.h;
  2785. chartArea.w = newWidth;
  2786. chartArea.h = newHeight;
  2787. return layout.horizontal
  2788. ? {same: widthChanged, other: heightChanged}
  2789. : {same: heightChanged, other: widthChanged};
  2790. }
  2791. function handleMaxPadding(chartArea) {
  2792. const maxPadding = chartArea.maxPadding;
  2793. function updatePos(pos) {
  2794. const change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  2795. chartArea[pos] += change;
  2796. return change;
  2797. }
  2798. chartArea.y += updatePos('top');
  2799. chartArea.x += updatePos('left');
  2800. updatePos('right');
  2801. updatePos('bottom');
  2802. }
  2803. function getMargins(horizontal, chartArea) {
  2804. const maxPadding = chartArea.maxPadding;
  2805. function marginForPositions(positions) {
  2806. const margin = {left: 0, top: 0, right: 0, bottom: 0};
  2807. positions.forEach((pos) => {
  2808. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  2809. });
  2810. return margin;
  2811. }
  2812. return horizontal
  2813. ? marginForPositions(['left', 'right'])
  2814. : marginForPositions(['top', 'bottom']);
  2815. }
  2816. function fitBoxes(boxes, chartArea, params, stacks) {
  2817. const refitBoxes = [];
  2818. let i, ilen, layout, box, refit, changed;
  2819. for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) {
  2820. layout = boxes[i];
  2821. box = layout.box;
  2822. box.update(
  2823. layout.width || chartArea.w,
  2824. layout.height || chartArea.h,
  2825. getMargins(layout.horizontal, chartArea)
  2826. );
  2827. const {same, other} = updateDims(chartArea, params, layout, stacks);
  2828. refit |= same && refitBoxes.length;
  2829. changed = changed || other;
  2830. if (!box.fullSize) {
  2831. refitBoxes.push(layout);
  2832. }
  2833. }
  2834. return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;
  2835. }
  2836. function setBoxDims(box, left, top, width, height) {
  2837. box.top = top;
  2838. box.left = left;
  2839. box.right = left + width;
  2840. box.bottom = top + height;
  2841. box.width = width;
  2842. box.height = height;
  2843. }
  2844. function placeBoxes(boxes, chartArea, params, stacks) {
  2845. const userPadding = params.padding;
  2846. let {x, y} = chartArea;
  2847. for (const layout of boxes) {
  2848. const box = layout.box;
  2849. const stack = stacks[layout.stack] || {count: 1, placed: 0, weight: 1};
  2850. const weight = (layout.stackWeight / stack.weight) || 1;
  2851. if (layout.horizontal) {
  2852. const width = chartArea.w * weight;
  2853. const height = stack.size || box.height;
  2854. if (defined(stack.start)) {
  2855. y = stack.start;
  2856. }
  2857. if (box.fullSize) {
  2858. setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);
  2859. } else {
  2860. setBoxDims(box, chartArea.left + stack.placed, y, width, height);
  2861. }
  2862. stack.start = y;
  2863. stack.placed += width;
  2864. y = box.bottom;
  2865. } else {
  2866. const height = chartArea.h * weight;
  2867. const width = stack.size || box.width;
  2868. if (defined(stack.start)) {
  2869. x = stack.start;
  2870. }
  2871. if (box.fullSize) {
  2872. setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);
  2873. } else {
  2874. setBoxDims(box, x, chartArea.top + stack.placed, width, height);
  2875. }
  2876. stack.start = x;
  2877. stack.placed += height;
  2878. x = box.right;
  2879. }
  2880. }
  2881. chartArea.x = x;
  2882. chartArea.y = y;
  2883. }
  2884. defaults.set('layout', {
  2885. autoPadding: true,
  2886. padding: {
  2887. top: 0,
  2888. right: 0,
  2889. bottom: 0,
  2890. left: 0
  2891. }
  2892. });
  2893. var layouts = {
  2894. addBox(chart, item) {
  2895. if (!chart.boxes) {
  2896. chart.boxes = [];
  2897. }
  2898. item.fullSize = item.fullSize || false;
  2899. item.position = item.position || 'top';
  2900. item.weight = item.weight || 0;
  2901. item._layers = item._layers || function() {
  2902. return [{
  2903. z: 0,
  2904. draw(chartArea) {
  2905. item.draw(chartArea);
  2906. }
  2907. }];
  2908. };
  2909. chart.boxes.push(item);
  2910. },
  2911. removeBox(chart, layoutItem) {
  2912. const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  2913. if (index !== -1) {
  2914. chart.boxes.splice(index, 1);
  2915. }
  2916. },
  2917. configure(chart, item, options) {
  2918. item.fullSize = options.fullSize;
  2919. item.position = options.position;
  2920. item.weight = options.weight;
  2921. },
  2922. update(chart, width, height, minPadding) {
  2923. if (!chart) {
  2924. return;
  2925. }
  2926. const padding = toPadding(chart.options.layout.padding);
  2927. const availableWidth = Math.max(width - padding.width, 0);
  2928. const availableHeight = Math.max(height - padding.height, 0);
  2929. const boxes = buildLayoutBoxes(chart.boxes);
  2930. const verticalBoxes = boxes.vertical;
  2931. const horizontalBoxes = boxes.horizontal;
  2932. each(chart.boxes, box => {
  2933. if (typeof box.beforeLayout === 'function') {
  2934. box.beforeLayout();
  2935. }
  2936. });
  2937. const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) =>
  2938. wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;
  2939. const params = Object.freeze({
  2940. outerWidth: width,
  2941. outerHeight: height,
  2942. padding,
  2943. availableWidth,
  2944. availableHeight,
  2945. vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,
  2946. hBoxMaxHeight: availableHeight / 2
  2947. });
  2948. const maxPadding = Object.assign({}, padding);
  2949. updateMaxPadding(maxPadding, toPadding(minPadding));
  2950. const chartArea = Object.assign({
  2951. maxPadding,
  2952. w: availableWidth,
  2953. h: availableHeight,
  2954. x: padding.left,
  2955. y: padding.top
  2956. }, padding);
  2957. const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  2958. fitBoxes(boxes.fullSize, chartArea, params, stacks);
  2959. fitBoxes(verticalBoxes, chartArea, params, stacks);
  2960. if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {
  2961. fitBoxes(verticalBoxes, chartArea, params, stacks);
  2962. }
  2963. handleMaxPadding(chartArea);
  2964. placeBoxes(boxes.leftAndTop, chartArea, params, stacks);
  2965. chartArea.x += chartArea.w;
  2966. chartArea.y += chartArea.h;
  2967. placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);
  2968. chart.chartArea = {
  2969. left: chartArea.left,
  2970. top: chartArea.top,
  2971. right: chartArea.left + chartArea.w,
  2972. bottom: chartArea.top + chartArea.h,
  2973. height: chartArea.h,
  2974. width: chartArea.w,
  2975. };
  2976. each(boxes.chartArea, (layout) => {
  2977. const box = layout.box;
  2978. Object.assign(box, chart.chartArea);
  2979. box.update(chartArea.w, chartArea.h, {left: 0, top: 0, right: 0, bottom: 0});
  2980. });
  2981. }
  2982. };
  2983. class BasePlatform {
  2984. acquireContext(canvas, aspectRatio) {}
  2985. releaseContext(context) {
  2986. return false;
  2987. }
  2988. addEventListener(chart, type, listener) {}
  2989. removeEventListener(chart, type, listener) {}
  2990. getDevicePixelRatio() {
  2991. return 1;
  2992. }
  2993. getMaximumSize(element, width, height, aspectRatio) {
  2994. width = Math.max(0, width || element.width);
  2995. height = height || element.height;
  2996. return {
  2997. width,
  2998. height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)
  2999. };
  3000. }
  3001. isAttached(canvas) {
  3002. return true;
  3003. }
  3004. updateConfig(config) {
  3005. }
  3006. }
  3007. class BasicPlatform extends BasePlatform {
  3008. acquireContext(item) {
  3009. return item && item.getContext && item.getContext('2d') || null;
  3010. }
  3011. updateConfig(config) {
  3012. config.options.animation = false;
  3013. }
  3014. }
  3015. const EXPANDO_KEY = '$chartjs';
  3016. const EVENT_TYPES = {
  3017. touchstart: 'mousedown',
  3018. touchmove: 'mousemove',
  3019. touchend: 'mouseup',
  3020. pointerenter: 'mouseenter',
  3021. pointerdown: 'mousedown',
  3022. pointermove: 'mousemove',
  3023. pointerup: 'mouseup',
  3024. pointerleave: 'mouseout',
  3025. pointerout: 'mouseout'
  3026. };
  3027. const isNullOrEmpty = value => value === null || value === '';
  3028. function initCanvas(canvas, aspectRatio) {
  3029. const style = canvas.style;
  3030. const renderHeight = canvas.getAttribute('height');
  3031. const renderWidth = canvas.getAttribute('width');
  3032. canvas[EXPANDO_KEY] = {
  3033. initial: {
  3034. height: renderHeight,
  3035. width: renderWidth,
  3036. style: {
  3037. display: style.display,
  3038. height: style.height,
  3039. width: style.width
  3040. }
  3041. }
  3042. };
  3043. style.display = style.display || 'block';
  3044. style.boxSizing = style.boxSizing || 'border-box';
  3045. if (isNullOrEmpty(renderWidth)) {
  3046. const displayWidth = readUsedSize(canvas, 'width');
  3047. if (displayWidth !== undefined) {
  3048. canvas.width = displayWidth;
  3049. }
  3050. }
  3051. if (isNullOrEmpty(renderHeight)) {
  3052. if (canvas.style.height === '') {
  3053. canvas.height = canvas.width / (aspectRatio || 2);
  3054. } else {
  3055. const displayHeight = readUsedSize(canvas, 'height');
  3056. if (displayHeight !== undefined) {
  3057. canvas.height = displayHeight;
  3058. }
  3059. }
  3060. }
  3061. return canvas;
  3062. }
  3063. const eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  3064. function addListener(node, type, listener) {
  3065. node.addEventListener(type, listener, eventListenerOptions);
  3066. }
  3067. function removeListener(chart, type, listener) {
  3068. chart.canvas.removeEventListener(type, listener, eventListenerOptions);
  3069. }
  3070. function fromNativeEvent(event, chart) {
  3071. const type = EVENT_TYPES[event.type] || event.type;
  3072. const {x, y} = getRelativePosition(event, chart);
  3073. return {
  3074. type,
  3075. chart,
  3076. native: event,
  3077. x: x !== undefined ? x : null,
  3078. y: y !== undefined ? y : null,
  3079. };
  3080. }
  3081. function nodeListContains(nodeList, canvas) {
  3082. for (const node of nodeList) {
  3083. if (node === canvas || node.contains(canvas)) {
  3084. return true;
  3085. }
  3086. }
  3087. }
  3088. function createAttachObserver(chart, type, listener) {
  3089. const canvas = chart.canvas;
  3090. const observer = new MutationObserver(entries => {
  3091. let trigger = false;
  3092. for (const entry of entries) {
  3093. trigger = trigger || nodeListContains(entry.addedNodes, canvas);
  3094. trigger = trigger && !nodeListContains(entry.removedNodes, canvas);
  3095. }
  3096. if (trigger) {
  3097. listener();
  3098. }
  3099. });
  3100. observer.observe(document, {childList: true, subtree: true});
  3101. return observer;
  3102. }
  3103. function createDetachObserver(chart, type, listener) {
  3104. const canvas = chart.canvas;
  3105. const observer = new MutationObserver(entries => {
  3106. let trigger = false;
  3107. for (const entry of entries) {
  3108. trigger = trigger || nodeListContains(entry.removedNodes, canvas);
  3109. trigger = trigger && !nodeListContains(entry.addedNodes, canvas);
  3110. }
  3111. if (trigger) {
  3112. listener();
  3113. }
  3114. });
  3115. observer.observe(document, {childList: true, subtree: true});
  3116. return observer;
  3117. }
  3118. const drpListeningCharts = new Map();
  3119. let oldDevicePixelRatio = 0;
  3120. function onWindowResize() {
  3121. const dpr = window.devicePixelRatio;
  3122. if (dpr === oldDevicePixelRatio) {
  3123. return;
  3124. }
  3125. oldDevicePixelRatio = dpr;
  3126. drpListeningCharts.forEach((resize, chart) => {
  3127. if (chart.currentDevicePixelRatio !== dpr) {
  3128. resize();
  3129. }
  3130. });
  3131. }
  3132. function listenDevicePixelRatioChanges(chart, resize) {
  3133. if (!drpListeningCharts.size) {
  3134. window.addEventListener('resize', onWindowResize);
  3135. }
  3136. drpListeningCharts.set(chart, resize);
  3137. }
  3138. function unlistenDevicePixelRatioChanges(chart) {
  3139. drpListeningCharts.delete(chart);
  3140. if (!drpListeningCharts.size) {
  3141. window.removeEventListener('resize', onWindowResize);
  3142. }
  3143. }
  3144. function createResizeObserver(chart, type, listener) {
  3145. const canvas = chart.canvas;
  3146. const container = canvas && _getParentNode(canvas);
  3147. if (!container) {
  3148. return;
  3149. }
  3150. const resize = throttled((width, height) => {
  3151. const w = container.clientWidth;
  3152. listener(width, height);
  3153. if (w < container.clientWidth) {
  3154. listener();
  3155. }
  3156. }, window);
  3157. const observer = new ResizeObserver(entries => {
  3158. const entry = entries[0];
  3159. const width = entry.contentRect.width;
  3160. const height = entry.contentRect.height;
  3161. if (width === 0 && height === 0) {
  3162. return;
  3163. }
  3164. resize(width, height);
  3165. });
  3166. observer.observe(container);
  3167. listenDevicePixelRatioChanges(chart, resize);
  3168. return observer;
  3169. }
  3170. function releaseObserver(chart, type, observer) {
  3171. if (observer) {
  3172. observer.disconnect();
  3173. }
  3174. if (type === 'resize') {
  3175. unlistenDevicePixelRatioChanges(chart);
  3176. }
  3177. }
  3178. function createProxyAndListen(chart, type, listener) {
  3179. const canvas = chart.canvas;
  3180. const proxy = throttled((event) => {
  3181. if (chart.ctx !== null) {
  3182. listener(fromNativeEvent(event, chart));
  3183. }
  3184. }, chart, (args) => {
  3185. const event = args[0];
  3186. return [event, event.offsetX, event.offsetY];
  3187. });
  3188. addListener(canvas, type, proxy);
  3189. return proxy;
  3190. }
  3191. class DomPlatform extends BasePlatform {
  3192. acquireContext(canvas, aspectRatio) {
  3193. const context = canvas && canvas.getContext && canvas.getContext('2d');
  3194. if (context && context.canvas === canvas) {
  3195. initCanvas(canvas, aspectRatio);
  3196. return context;
  3197. }
  3198. return null;
  3199. }
  3200. releaseContext(context) {
  3201. const canvas = context.canvas;
  3202. if (!canvas[EXPANDO_KEY]) {
  3203. return false;
  3204. }
  3205. const initial = canvas[EXPANDO_KEY].initial;
  3206. ['height', 'width'].forEach((prop) => {
  3207. const value = initial[prop];
  3208. if (isNullOrUndef(value)) {
  3209. canvas.removeAttribute(prop);
  3210. } else {
  3211. canvas.setAttribute(prop, value);
  3212. }
  3213. });
  3214. const style = initial.style || {};
  3215. Object.keys(style).forEach((key) => {
  3216. canvas.style[key] = style[key];
  3217. });
  3218. canvas.width = canvas.width;
  3219. delete canvas[EXPANDO_KEY];
  3220. return true;
  3221. }
  3222. addEventListener(chart, type, listener) {
  3223. this.removeEventListener(chart, type);
  3224. const proxies = chart.$proxies || (chart.$proxies = {});
  3225. const handlers = {
  3226. attach: createAttachObserver,
  3227. detach: createDetachObserver,
  3228. resize: createResizeObserver
  3229. };
  3230. const handler = handlers[type] || createProxyAndListen;
  3231. proxies[type] = handler(chart, type, listener);
  3232. }
  3233. removeEventListener(chart, type) {
  3234. const proxies = chart.$proxies || (chart.$proxies = {});
  3235. const proxy = proxies[type];
  3236. if (!proxy) {
  3237. return;
  3238. }
  3239. const handlers = {
  3240. attach: releaseObserver,
  3241. detach: releaseObserver,
  3242. resize: releaseObserver
  3243. };
  3244. const handler = handlers[type] || removeListener;
  3245. handler(chart, type, proxy);
  3246. proxies[type] = undefined;
  3247. }
  3248. getDevicePixelRatio() {
  3249. return window.devicePixelRatio;
  3250. }
  3251. getMaximumSize(canvas, width, height, aspectRatio) {
  3252. return getMaximumSize(canvas, width, height, aspectRatio);
  3253. }
  3254. isAttached(canvas) {
  3255. const container = _getParentNode(canvas);
  3256. return !!(container && container.isConnected);
  3257. }
  3258. }
  3259. function _detectPlatform(canvas) {
  3260. if (!_isDomSupported() || (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) {
  3261. return BasicPlatform;
  3262. }
  3263. return DomPlatform;
  3264. }
  3265. class Element {
  3266. constructor() {
  3267. this.x = undefined;
  3268. this.y = undefined;
  3269. this.active = false;
  3270. this.options = undefined;
  3271. this.$animations = undefined;
  3272. }
  3273. tooltipPosition(useFinalPosition) {
  3274. const {x, y} = this.getProps(['x', 'y'], useFinalPosition);
  3275. return {x, y};
  3276. }
  3277. hasValue() {
  3278. return isNumber(this.x) && isNumber(this.y);
  3279. }
  3280. getProps(props, final) {
  3281. const anims = this.$animations;
  3282. if (!final || !anims) {
  3283. return this;
  3284. }
  3285. const ret = {};
  3286. props.forEach(prop => {
  3287. ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop];
  3288. });
  3289. return ret;
  3290. }
  3291. }
  3292. Element.defaults = {};
  3293. Element.defaultRoutes = undefined;
  3294. const formatters = {
  3295. values(value) {
  3296. return isArray(value) ? value : '' + value;
  3297. },
  3298. numeric(tickValue, index, ticks) {
  3299. if (tickValue === 0) {
  3300. return '0';
  3301. }
  3302. const locale = this.chart.options.locale;
  3303. let notation;
  3304. let delta = tickValue;
  3305. if (ticks.length > 1) {
  3306. const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));
  3307. if (maxTick < 1e-4 || maxTick > 1e+15) {
  3308. notation = 'scientific';
  3309. }
  3310. delta = calculateDelta(tickValue, ticks);
  3311. }
  3312. const logDelta = log10(Math.abs(delta));
  3313. const numDecimal = Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);
  3314. const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal};
  3315. Object.assign(options, this.options.ticks.format);
  3316. return formatNumber(tickValue, locale, options);
  3317. },
  3318. logarithmic(tickValue, index, ticks) {
  3319. if (tickValue === 0) {
  3320. return '0';
  3321. }
  3322. const remain = tickValue / (Math.pow(10, Math.floor(log10(tickValue))));
  3323. if (remain === 1 || remain === 2 || remain === 5) {
  3324. return formatters.numeric.call(this, tickValue, index, ticks);
  3325. }
  3326. return '';
  3327. }
  3328. };
  3329. function calculateDelta(tickValue, ticks) {
  3330. let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;
  3331. if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) {
  3332. delta = tickValue - Math.floor(tickValue);
  3333. }
  3334. return delta;
  3335. }
  3336. var Ticks = {formatters};
  3337. defaults.set('scale', {
  3338. display: true,
  3339. offset: false,
  3340. reverse: false,
  3341. beginAtZero: false,
  3342. bounds: 'ticks',
  3343. grace: 0,
  3344. grid: {
  3345. display: true,
  3346. lineWidth: 1,
  3347. drawBorder: true,
  3348. drawOnChartArea: true,
  3349. drawTicks: true,
  3350. tickLength: 8,
  3351. tickWidth: (_ctx, options) => options.lineWidth,
  3352. tickColor: (_ctx, options) => options.color,
  3353. offset: false,
  3354. borderDash: [],
  3355. borderDashOffset: 0.0,
  3356. borderWidth: 1
  3357. },
  3358. title: {
  3359. display: false,
  3360. text: '',
  3361. padding: {
  3362. top: 4,
  3363. bottom: 4
  3364. }
  3365. },
  3366. ticks: {
  3367. minRotation: 0,
  3368. maxRotation: 50,
  3369. mirror: false,
  3370. textStrokeWidth: 0,
  3371. textStrokeColor: '',
  3372. padding: 3,
  3373. display: true,
  3374. autoSkip: true,
  3375. autoSkipPadding: 3,
  3376. labelOffset: 0,
  3377. callback: Ticks.formatters.values,
  3378. minor: {},
  3379. major: {},
  3380. align: 'center',
  3381. crossAlign: 'near',
  3382. showLabelBackdrop: false,
  3383. backdropColor: 'rgba(255, 255, 255, 0.75)',
  3384. backdropPadding: 2,
  3385. }
  3386. });
  3387. defaults.route('scale.ticks', 'color', '', 'color');
  3388. defaults.route('scale.grid', 'color', '', 'borderColor');
  3389. defaults.route('scale.grid', 'borderColor', '', 'borderColor');
  3390. defaults.route('scale.title', 'color', '', 'color');
  3391. defaults.describe('scale', {
  3392. _fallback: false,
  3393. _scriptable: (name) => !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser',
  3394. _indexable: (name) => name !== 'borderDash' && name !== 'tickBorderDash',
  3395. });
  3396. defaults.describe('scales', {
  3397. _fallback: 'scale',
  3398. });
  3399. defaults.describe('scale.ticks', {
  3400. _scriptable: (name) => name !== 'backdropPadding' && name !== 'callback',
  3401. _indexable: (name) => name !== 'backdropPadding',
  3402. });
  3403. function autoSkip(scale, ticks) {
  3404. const tickOpts = scale.options.ticks;
  3405. const ticksLimit = tickOpts.maxTicksLimit || determineMaxTicks(scale);
  3406. const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  3407. const numMajorIndices = majorIndices.length;
  3408. const first = majorIndices[0];
  3409. const last = majorIndices[numMajorIndices - 1];
  3410. const newTicks = [];
  3411. if (numMajorIndices > ticksLimit) {
  3412. skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);
  3413. return newTicks;
  3414. }
  3415. const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);
  3416. if (numMajorIndices > 0) {
  3417. let i, ilen;
  3418. const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
  3419. skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  3420. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  3421. skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
  3422. }
  3423. skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  3424. return newTicks;
  3425. }
  3426. skip(ticks, newTicks, spacing);
  3427. return newTicks;
  3428. }
  3429. function determineMaxTicks(scale) {
  3430. const offset = scale.options.offset;
  3431. const tickLength = scale._tickSize();
  3432. const maxScale = scale._length / tickLength + (offset ? 0 : 1);
  3433. const maxChart = scale._maxLength / tickLength;
  3434. return Math.floor(Math.min(maxScale, maxChart));
  3435. }
  3436. function calculateSpacing(majorIndices, ticks, ticksLimit) {
  3437. const evenMajorSpacing = getEvenSpacing(majorIndices);
  3438. const spacing = ticks.length / ticksLimit;
  3439. if (!evenMajorSpacing) {
  3440. return Math.max(spacing, 1);
  3441. }
  3442. const factors = _factorize(evenMajorSpacing);
  3443. for (let i = 0, ilen = factors.length - 1; i < ilen; i++) {
  3444. const factor = factors[i];
  3445. if (factor > spacing) {
  3446. return factor;
  3447. }
  3448. }
  3449. return Math.max(spacing, 1);
  3450. }
  3451. function getMajorIndices(ticks) {
  3452. const result = [];
  3453. let i, ilen;
  3454. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  3455. if (ticks[i].major) {
  3456. result.push(i);
  3457. }
  3458. }
  3459. return result;
  3460. }
  3461. function skipMajors(ticks, newTicks, majorIndices, spacing) {
  3462. let count = 0;
  3463. let next = majorIndices[0];
  3464. let i;
  3465. spacing = Math.ceil(spacing);
  3466. for (i = 0; i < ticks.length; i++) {
  3467. if (i === next) {
  3468. newTicks.push(ticks[i]);
  3469. count++;
  3470. next = majorIndices[count * spacing];
  3471. }
  3472. }
  3473. }
  3474. function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
  3475. const start = valueOrDefault(majorStart, 0);
  3476. const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);
  3477. let count = 0;
  3478. let length, i, next;
  3479. spacing = Math.ceil(spacing);
  3480. if (majorEnd) {
  3481. length = majorEnd - majorStart;
  3482. spacing = length / Math.floor(length / spacing);
  3483. }
  3484. next = start;
  3485. while (next < 0) {
  3486. count++;
  3487. next = Math.round(start + count * spacing);
  3488. }
  3489. for (i = Math.max(start, 0); i < end; i++) {
  3490. if (i === next) {
  3491. newTicks.push(ticks[i]);
  3492. count++;
  3493. next = Math.round(start + count * spacing);
  3494. }
  3495. }
  3496. }
  3497. function getEvenSpacing(arr) {
  3498. const len = arr.length;
  3499. let i, diff;
  3500. if (len < 2) {
  3501. return false;
  3502. }
  3503. for (diff = arr[0], i = 1; i < len; ++i) {
  3504. if (arr[i] - arr[i - 1] !== diff) {
  3505. return false;
  3506. }
  3507. }
  3508. return diff;
  3509. }
  3510. const reverseAlign = (align) => align === 'left' ? 'right' : align === 'right' ? 'left' : align;
  3511. const offsetFromEdge = (scale, edge, offset) => edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;
  3512. function sample(arr, numItems) {
  3513. const result = [];
  3514. const increment = arr.length / numItems;
  3515. const len = arr.length;
  3516. let i = 0;
  3517. for (; i < len; i += increment) {
  3518. result.push(arr[Math.floor(i)]);
  3519. }
  3520. return result;
  3521. }
  3522. function getPixelForGridLine(scale, index, offsetGridLines) {
  3523. const length = scale.ticks.length;
  3524. const validIndex = Math.min(index, length - 1);
  3525. const start = scale._startPixel;
  3526. const end = scale._endPixel;
  3527. const epsilon = 1e-6;
  3528. let lineValue = scale.getPixelForTick(validIndex);
  3529. let offset;
  3530. if (offsetGridLines) {
  3531. if (length === 1) {
  3532. offset = Math.max(lineValue - start, end - lineValue);
  3533. } else if (index === 0) {
  3534. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  3535. } else {
  3536. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  3537. }
  3538. lineValue += validIndex < index ? offset : -offset;
  3539. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  3540. return;
  3541. }
  3542. }
  3543. return lineValue;
  3544. }
  3545. function garbageCollect(caches, length) {
  3546. each(caches, (cache) => {
  3547. const gc = cache.gc;
  3548. const gcLen = gc.length / 2;
  3549. let i;
  3550. if (gcLen > length) {
  3551. for (i = 0; i < gcLen; ++i) {
  3552. delete cache.data[gc[i]];
  3553. }
  3554. gc.splice(0, gcLen);
  3555. }
  3556. });
  3557. }
  3558. function getTickMarkLength(options) {
  3559. return options.drawTicks ? options.tickLength : 0;
  3560. }
  3561. function getTitleHeight(options, fallback) {
  3562. if (!options.display) {
  3563. return 0;
  3564. }
  3565. const font = toFont(options.font, fallback);
  3566. const padding = toPadding(options.padding);
  3567. const lines = isArray(options.text) ? options.text.length : 1;
  3568. return (lines * font.lineHeight) + padding.height;
  3569. }
  3570. function createScaleContext(parent, scale) {
  3571. return createContext(parent, {
  3572. scale,
  3573. type: 'scale'
  3574. });
  3575. }
  3576. function createTickContext(parent, index, tick) {
  3577. return createContext(parent, {
  3578. tick,
  3579. index,
  3580. type: 'tick'
  3581. });
  3582. }
  3583. function titleAlign(align, position, reverse) {
  3584. let ret = _toLeftRightCenter(align);
  3585. if ((reverse && position !== 'right') || (!reverse && position === 'right')) {
  3586. ret = reverseAlign(ret);
  3587. }
  3588. return ret;
  3589. }
  3590. function titleArgs(scale, offset, position, align) {
  3591. const {top, left, bottom, right, chart} = scale;
  3592. const {chartArea, scales} = chart;
  3593. let rotation = 0;
  3594. let maxWidth, titleX, titleY;
  3595. const height = bottom - top;
  3596. const width = right - left;
  3597. if (scale.isHorizontal()) {
  3598. titleX = _alignStartEnd(align, left, right);
  3599. if (isObject(position)) {
  3600. const positionAxisID = Object.keys(position)[0];
  3601. const value = position[positionAxisID];
  3602. titleY = scales[positionAxisID].getPixelForValue(value) + height - offset;
  3603. } else if (position === 'center') {
  3604. titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset;
  3605. } else {
  3606. titleY = offsetFromEdge(scale, position, offset);
  3607. }
  3608. maxWidth = right - left;
  3609. } else {
  3610. if (isObject(position)) {
  3611. const positionAxisID = Object.keys(position)[0];
  3612. const value = position[positionAxisID];
  3613. titleX = scales[positionAxisID].getPixelForValue(value) - width + offset;
  3614. } else if (position === 'center') {
  3615. titleX = (chartArea.left + chartArea.right) / 2 - width + offset;
  3616. } else {
  3617. titleX = offsetFromEdge(scale, position, offset);
  3618. }
  3619. titleY = _alignStartEnd(align, bottom, top);
  3620. rotation = position === 'left' ? -HALF_PI : HALF_PI;
  3621. }
  3622. return {titleX, titleY, maxWidth, rotation};
  3623. }
  3624. class Scale extends Element {
  3625. constructor(cfg) {
  3626. super();
  3627. this.id = cfg.id;
  3628. this.type = cfg.type;
  3629. this.options = undefined;
  3630. this.ctx = cfg.ctx;
  3631. this.chart = cfg.chart;
  3632. this.top = undefined;
  3633. this.bottom = undefined;
  3634. this.left = undefined;
  3635. this.right = undefined;
  3636. this.width = undefined;
  3637. this.height = undefined;
  3638. this._margins = {
  3639. left: 0,
  3640. right: 0,
  3641. top: 0,
  3642. bottom: 0
  3643. };
  3644. this.maxWidth = undefined;
  3645. this.maxHeight = undefined;
  3646. this.paddingTop = undefined;
  3647. this.paddingBottom = undefined;
  3648. this.paddingLeft = undefined;
  3649. this.paddingRight = undefined;
  3650. this.axis = undefined;
  3651. this.labelRotation = undefined;
  3652. this.min = undefined;
  3653. this.max = undefined;
  3654. this._range = undefined;
  3655. this.ticks = [];
  3656. this._gridLineItems = null;
  3657. this._labelItems = null;
  3658. this._labelSizes = null;
  3659. this._length = 0;
  3660. this._maxLength = 0;
  3661. this._longestTextCache = {};
  3662. this._startPixel = undefined;
  3663. this._endPixel = undefined;
  3664. this._reversePixels = false;
  3665. this._userMax = undefined;
  3666. this._userMin = undefined;
  3667. this._suggestedMax = undefined;
  3668. this._suggestedMin = undefined;
  3669. this._ticksLength = 0;
  3670. this._borderValue = 0;
  3671. this._cache = {};
  3672. this._dataLimitsCached = false;
  3673. this.$context = undefined;
  3674. }
  3675. init(options) {
  3676. this.options = options.setContext(this.getContext());
  3677. this.axis = options.axis;
  3678. this._userMin = this.parse(options.min);
  3679. this._userMax = this.parse(options.max);
  3680. this._suggestedMin = this.parse(options.suggestedMin);
  3681. this._suggestedMax = this.parse(options.suggestedMax);
  3682. }
  3683. parse(raw, index) {
  3684. return raw;
  3685. }
  3686. getUserBounds() {
  3687. let {_userMin, _userMax, _suggestedMin, _suggestedMax} = this;
  3688. _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);
  3689. _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);
  3690. _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);
  3691. _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);
  3692. return {
  3693. min: finiteOrDefault(_userMin, _suggestedMin),
  3694. max: finiteOrDefault(_userMax, _suggestedMax),
  3695. minDefined: isNumberFinite(_userMin),
  3696. maxDefined: isNumberFinite(_userMax)
  3697. };
  3698. }
  3699. getMinMax(canStack) {
  3700. let {min, max, minDefined, maxDefined} = this.getUserBounds();
  3701. let range;
  3702. if (minDefined && maxDefined) {
  3703. return {min, max};
  3704. }
  3705. const metas = this.getMatchingVisibleMetas();
  3706. for (let i = 0, ilen = metas.length; i < ilen; ++i) {
  3707. range = metas[i].controller.getMinMax(this, canStack);
  3708. if (!minDefined) {
  3709. min = Math.min(min, range.min);
  3710. }
  3711. if (!maxDefined) {
  3712. max = Math.max(max, range.max);
  3713. }
  3714. }
  3715. min = maxDefined && min > max ? max : min;
  3716. max = minDefined && min > max ? min : max;
  3717. return {
  3718. min: finiteOrDefault(min, finiteOrDefault(max, min)),
  3719. max: finiteOrDefault(max, finiteOrDefault(min, max))
  3720. };
  3721. }
  3722. getPadding() {
  3723. return {
  3724. left: this.paddingLeft || 0,
  3725. top: this.paddingTop || 0,
  3726. right: this.paddingRight || 0,
  3727. bottom: this.paddingBottom || 0
  3728. };
  3729. }
  3730. getTicks() {
  3731. return this.ticks;
  3732. }
  3733. getLabels() {
  3734. const data = this.chart.data;
  3735. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  3736. }
  3737. beforeLayout() {
  3738. this._cache = {};
  3739. this._dataLimitsCached = false;
  3740. }
  3741. beforeUpdate() {
  3742. callback(this.options.beforeUpdate, [this]);
  3743. }
  3744. update(maxWidth, maxHeight, margins) {
  3745. const {beginAtZero, grace, ticks: tickOpts} = this.options;
  3746. const sampleSize = tickOpts.sampleSize;
  3747. this.beforeUpdate();
  3748. this.maxWidth = maxWidth;
  3749. this.maxHeight = maxHeight;
  3750. this._margins = margins = Object.assign({
  3751. left: 0,
  3752. right: 0,
  3753. top: 0,
  3754. bottom: 0
  3755. }, margins);
  3756. this.ticks = null;
  3757. this._labelSizes = null;
  3758. this._gridLineItems = null;
  3759. this._labelItems = null;
  3760. this.beforeSetDimensions();
  3761. this.setDimensions();
  3762. this.afterSetDimensions();
  3763. this._maxLength = this.isHorizontal()
  3764. ? this.width + margins.left + margins.right
  3765. : this.height + margins.top + margins.bottom;
  3766. if (!this._dataLimitsCached) {
  3767. this.beforeDataLimits();
  3768. this.determineDataLimits();
  3769. this.afterDataLimits();
  3770. this._range = _addGrace(this, grace, beginAtZero);
  3771. this._dataLimitsCached = true;
  3772. }
  3773. this.beforeBuildTicks();
  3774. this.ticks = this.buildTicks() || [];
  3775. this.afterBuildTicks();
  3776. const samplingEnabled = sampleSize < this.ticks.length;
  3777. this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks);
  3778. this.configure();
  3779. this.beforeCalculateLabelRotation();
  3780. this.calculateLabelRotation();
  3781. this.afterCalculateLabelRotation();
  3782. if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {
  3783. this.ticks = autoSkip(this, this.ticks);
  3784. this._labelSizes = null;
  3785. }
  3786. if (samplingEnabled) {
  3787. this._convertTicksToLabels(this.ticks);
  3788. }
  3789. this.beforeFit();
  3790. this.fit();
  3791. this.afterFit();
  3792. this.afterUpdate();
  3793. }
  3794. configure() {
  3795. let reversePixels = this.options.reverse;
  3796. let startPixel, endPixel;
  3797. if (this.isHorizontal()) {
  3798. startPixel = this.left;
  3799. endPixel = this.right;
  3800. } else {
  3801. startPixel = this.top;
  3802. endPixel = this.bottom;
  3803. reversePixels = !reversePixels;
  3804. }
  3805. this._startPixel = startPixel;
  3806. this._endPixel = endPixel;
  3807. this._reversePixels = reversePixels;
  3808. this._length = endPixel - startPixel;
  3809. this._alignToPixels = this.options.alignToPixels;
  3810. }
  3811. afterUpdate() {
  3812. callback(this.options.afterUpdate, [this]);
  3813. }
  3814. beforeSetDimensions() {
  3815. callback(this.options.beforeSetDimensions, [this]);
  3816. }
  3817. setDimensions() {
  3818. if (this.isHorizontal()) {
  3819. this.width = this.maxWidth;
  3820. this.left = 0;
  3821. this.right = this.width;
  3822. } else {
  3823. this.height = this.maxHeight;
  3824. this.top = 0;
  3825. this.bottom = this.height;
  3826. }
  3827. this.paddingLeft = 0;
  3828. this.paddingTop = 0;
  3829. this.paddingRight = 0;
  3830. this.paddingBottom = 0;
  3831. }
  3832. afterSetDimensions() {
  3833. callback(this.options.afterSetDimensions, [this]);
  3834. }
  3835. _callHooks(name) {
  3836. this.chart.notifyPlugins(name, this.getContext());
  3837. callback(this.options[name], [this]);
  3838. }
  3839. beforeDataLimits() {
  3840. this._callHooks('beforeDataLimits');
  3841. }
  3842. determineDataLimits() {}
  3843. afterDataLimits() {
  3844. this._callHooks('afterDataLimits');
  3845. }
  3846. beforeBuildTicks() {
  3847. this._callHooks('beforeBuildTicks');
  3848. }
  3849. buildTicks() {
  3850. return [];
  3851. }
  3852. afterBuildTicks() {
  3853. this._callHooks('afterBuildTicks');
  3854. }
  3855. beforeTickToLabelConversion() {
  3856. callback(this.options.beforeTickToLabelConversion, [this]);
  3857. }
  3858. generateTickLabels(ticks) {
  3859. const tickOpts = this.options.ticks;
  3860. let i, ilen, tick;
  3861. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  3862. tick = ticks[i];
  3863. tick.label = callback(tickOpts.callback, [tick.value, i, ticks], this);
  3864. }
  3865. }
  3866. afterTickToLabelConversion() {
  3867. callback(this.options.afterTickToLabelConversion, [this]);
  3868. }
  3869. beforeCalculateLabelRotation() {
  3870. callback(this.options.beforeCalculateLabelRotation, [this]);
  3871. }
  3872. calculateLabelRotation() {
  3873. const options = this.options;
  3874. const tickOpts = options.ticks;
  3875. const numTicks = this.ticks.length;
  3876. const minRotation = tickOpts.minRotation || 0;
  3877. const maxRotation = tickOpts.maxRotation;
  3878. let labelRotation = minRotation;
  3879. let tickWidth, maxHeight, maxLabelDiagonal;
  3880. if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) {
  3881. this.labelRotation = minRotation;
  3882. return;
  3883. }
  3884. const labelSizes = this._getLabelSizes();
  3885. const maxLabelWidth = labelSizes.widest.width;
  3886. const maxLabelHeight = labelSizes.highest.height;
  3887. const maxWidth = _limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth);
  3888. tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1);
  3889. if (maxLabelWidth + 6 > tickWidth) {
  3890. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  3891. maxHeight = this.maxHeight - getTickMarkLength(options.grid)
  3892. - tickOpts.padding - getTitleHeight(options.title, this.chart.options.font);
  3893. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  3894. labelRotation = toDegrees(Math.min(
  3895. Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)),
  3896. Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))
  3897. ));
  3898. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  3899. }
  3900. this.labelRotation = labelRotation;
  3901. }
  3902. afterCalculateLabelRotation() {
  3903. callback(this.options.afterCalculateLabelRotation, [this]);
  3904. }
  3905. beforeFit() {
  3906. callback(this.options.beforeFit, [this]);
  3907. }
  3908. fit() {
  3909. const minSize = {
  3910. width: 0,
  3911. height: 0
  3912. };
  3913. const {chart, options: {ticks: tickOpts, title: titleOpts, grid: gridOpts}} = this;
  3914. const display = this._isVisible();
  3915. const isHorizontal = this.isHorizontal();
  3916. if (display) {
  3917. const titleHeight = getTitleHeight(titleOpts, chart.options.font);
  3918. if (isHorizontal) {
  3919. minSize.width = this.maxWidth;
  3920. minSize.height = getTickMarkLength(gridOpts) + titleHeight;
  3921. } else {
  3922. minSize.height = this.maxHeight;
  3923. minSize.width = getTickMarkLength(gridOpts) + titleHeight;
  3924. }
  3925. if (tickOpts.display && this.ticks.length) {
  3926. const {first, last, widest, highest} = this._getLabelSizes();
  3927. const tickPadding = tickOpts.padding * 2;
  3928. const angleRadians = toRadians(this.labelRotation);
  3929. const cos = Math.cos(angleRadians);
  3930. const sin = Math.sin(angleRadians);
  3931. if (isHorizontal) {
  3932. const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;
  3933. minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding);
  3934. } else {
  3935. const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;
  3936. minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding);
  3937. }
  3938. this._calculatePadding(first, last, sin, cos);
  3939. }
  3940. }
  3941. this._handleMargins();
  3942. if (isHorizontal) {
  3943. this.width = this._length = chart.width - this._margins.left - this._margins.right;
  3944. this.height = minSize.height;
  3945. } else {
  3946. this.width = minSize.width;
  3947. this.height = this._length = chart.height - this._margins.top - this._margins.bottom;
  3948. }
  3949. }
  3950. _calculatePadding(first, last, sin, cos) {
  3951. const {ticks: {align, padding}, position} = this.options;
  3952. const isRotated = this.labelRotation !== 0;
  3953. const labelsBelowTicks = position !== 'top' && this.axis === 'x';
  3954. if (this.isHorizontal()) {
  3955. const offsetLeft = this.getPixelForTick(0) - this.left;
  3956. const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1);
  3957. let paddingLeft = 0;
  3958. let paddingRight = 0;
  3959. if (isRotated) {
  3960. if (labelsBelowTicks) {
  3961. paddingLeft = cos * first.width;
  3962. paddingRight = sin * last.height;
  3963. } else {
  3964. paddingLeft = sin * first.height;
  3965. paddingRight = cos * last.width;
  3966. }
  3967. } else if (align === 'start') {
  3968. paddingRight = last.width;
  3969. } else if (align === 'end') {
  3970. paddingLeft = first.width;
  3971. } else if (align !== 'inner') {
  3972. paddingLeft = first.width / 2;
  3973. paddingRight = last.width / 2;
  3974. }
  3975. this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0);
  3976. this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0);
  3977. } else {
  3978. let paddingTop = last.height / 2;
  3979. let paddingBottom = first.height / 2;
  3980. if (align === 'start') {
  3981. paddingTop = 0;
  3982. paddingBottom = first.height;
  3983. } else if (align === 'end') {
  3984. paddingTop = last.height;
  3985. paddingBottom = 0;
  3986. }
  3987. this.paddingTop = paddingTop + padding;
  3988. this.paddingBottom = paddingBottom + padding;
  3989. }
  3990. }
  3991. _handleMargins() {
  3992. if (this._margins) {
  3993. this._margins.left = Math.max(this.paddingLeft, this._margins.left);
  3994. this._margins.top = Math.max(this.paddingTop, this._margins.top);
  3995. this._margins.right = Math.max(this.paddingRight, this._margins.right);
  3996. this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom);
  3997. }
  3998. }
  3999. afterFit() {
  4000. callback(this.options.afterFit, [this]);
  4001. }
  4002. isHorizontal() {
  4003. const {axis, position} = this.options;
  4004. return position === 'top' || position === 'bottom' || axis === 'x';
  4005. }
  4006. isFullSize() {
  4007. return this.options.fullSize;
  4008. }
  4009. _convertTicksToLabels(ticks) {
  4010. this.beforeTickToLabelConversion();
  4011. this.generateTickLabels(ticks);
  4012. let i, ilen;
  4013. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  4014. if (isNullOrUndef(ticks[i].label)) {
  4015. ticks.splice(i, 1);
  4016. ilen--;
  4017. i--;
  4018. }
  4019. }
  4020. this.afterTickToLabelConversion();
  4021. }
  4022. _getLabelSizes() {
  4023. let labelSizes = this._labelSizes;
  4024. if (!labelSizes) {
  4025. const sampleSize = this.options.ticks.sampleSize;
  4026. let ticks = this.ticks;
  4027. if (sampleSize < ticks.length) {
  4028. ticks = sample(ticks, sampleSize);
  4029. }
  4030. this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length);
  4031. }
  4032. return labelSizes;
  4033. }
  4034. _computeLabelSizes(ticks, length) {
  4035. const {ctx, _longestTextCache: caches} = this;
  4036. const widths = [];
  4037. const heights = [];
  4038. let widestLabelSize = 0;
  4039. let highestLabelSize = 0;
  4040. let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;
  4041. for (i = 0; i < length; ++i) {
  4042. label = ticks[i].label;
  4043. tickFont = this._resolveTickFontOptions(i);
  4044. ctx.font = fontString = tickFont.string;
  4045. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  4046. lineHeight = tickFont.lineHeight;
  4047. width = height = 0;
  4048. if (!isNullOrUndef(label) && !isArray(label)) {
  4049. width = _measureText(ctx, cache.data, cache.gc, width, label);
  4050. height = lineHeight;
  4051. } else if (isArray(label)) {
  4052. for (j = 0, jlen = label.length; j < jlen; ++j) {
  4053. nestedLabel = label[j];
  4054. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  4055. width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  4056. height += lineHeight;
  4057. }
  4058. }
  4059. }
  4060. widths.push(width);
  4061. heights.push(height);
  4062. widestLabelSize = Math.max(width, widestLabelSize);
  4063. highestLabelSize = Math.max(height, highestLabelSize);
  4064. }
  4065. garbageCollect(caches, length);
  4066. const widest = widths.indexOf(widestLabelSize);
  4067. const highest = heights.indexOf(highestLabelSize);
  4068. const valueAt = (idx) => ({width: widths[idx] || 0, height: heights[idx] || 0});
  4069. return {
  4070. first: valueAt(0),
  4071. last: valueAt(length - 1),
  4072. widest: valueAt(widest),
  4073. highest: valueAt(highest),
  4074. widths,
  4075. heights,
  4076. };
  4077. }
  4078. getLabelForValue(value) {
  4079. return value;
  4080. }
  4081. getPixelForValue(value, index) {
  4082. return NaN;
  4083. }
  4084. getValueForPixel(pixel) {}
  4085. getPixelForTick(index) {
  4086. const ticks = this.ticks;
  4087. if (index < 0 || index > ticks.length - 1) {
  4088. return null;
  4089. }
  4090. return this.getPixelForValue(ticks[index].value);
  4091. }
  4092. getPixelForDecimal(decimal) {
  4093. if (this._reversePixels) {
  4094. decimal = 1 - decimal;
  4095. }
  4096. const pixel = this._startPixel + decimal * this._length;
  4097. return _int16Range(this._alignToPixels ? _alignPixel(this.chart, pixel, 0) : pixel);
  4098. }
  4099. getDecimalForPixel(pixel) {
  4100. const decimal = (pixel - this._startPixel) / this._length;
  4101. return this._reversePixels ? 1 - decimal : decimal;
  4102. }
  4103. getBasePixel() {
  4104. return this.getPixelForValue(this.getBaseValue());
  4105. }
  4106. getBaseValue() {
  4107. const {min, max} = this;
  4108. return min < 0 && max < 0 ? max :
  4109. min > 0 && max > 0 ? min :
  4110. 0;
  4111. }
  4112. getContext(index) {
  4113. const ticks = this.ticks || [];
  4114. if (index >= 0 && index < ticks.length) {
  4115. const tick = ticks[index];
  4116. return tick.$context ||
  4117. (tick.$context = createTickContext(this.getContext(), index, tick));
  4118. }
  4119. return this.$context ||
  4120. (this.$context = createScaleContext(this.chart.getContext(), this));
  4121. }
  4122. _tickSize() {
  4123. const optionTicks = this.options.ticks;
  4124. const rot = toRadians(this.labelRotation);
  4125. const cos = Math.abs(Math.cos(rot));
  4126. const sin = Math.abs(Math.sin(rot));
  4127. const labelSizes = this._getLabelSizes();
  4128. const padding = optionTicks.autoSkipPadding || 0;
  4129. const w = labelSizes ? labelSizes.widest.width + padding : 0;
  4130. const h = labelSizes ? labelSizes.highest.height + padding : 0;
  4131. return this.isHorizontal()
  4132. ? h * cos > w * sin ? w / cos : h / sin
  4133. : h * sin < w * cos ? h / cos : w / sin;
  4134. }
  4135. _isVisible() {
  4136. const display = this.options.display;
  4137. if (display !== 'auto') {
  4138. return !!display;
  4139. }
  4140. return this.getMatchingVisibleMetas().length > 0;
  4141. }
  4142. _computeGridLineItems(chartArea) {
  4143. const axis = this.axis;
  4144. const chart = this.chart;
  4145. const options = this.options;
  4146. const {grid, position} = options;
  4147. const offset = grid.offset;
  4148. const isHorizontal = this.isHorizontal();
  4149. const ticks = this.ticks;
  4150. const ticksLength = ticks.length + (offset ? 1 : 0);
  4151. const tl = getTickMarkLength(grid);
  4152. const items = [];
  4153. const borderOpts = grid.setContext(this.getContext());
  4154. const axisWidth = borderOpts.drawBorder ? borderOpts.borderWidth : 0;
  4155. const axisHalfWidth = axisWidth / 2;
  4156. const alignBorderValue = function(pixel) {
  4157. return _alignPixel(chart, pixel, axisWidth);
  4158. };
  4159. let borderValue, i, lineValue, alignedLineValue;
  4160. let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
  4161. if (position === 'top') {
  4162. borderValue = alignBorderValue(this.bottom);
  4163. ty1 = this.bottom - tl;
  4164. ty2 = borderValue - axisHalfWidth;
  4165. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  4166. y2 = chartArea.bottom;
  4167. } else if (position === 'bottom') {
  4168. borderValue = alignBorderValue(this.top);
  4169. y1 = chartArea.top;
  4170. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  4171. ty1 = borderValue + axisHalfWidth;
  4172. ty2 = this.top + tl;
  4173. } else if (position === 'left') {
  4174. borderValue = alignBorderValue(this.right);
  4175. tx1 = this.right - tl;
  4176. tx2 = borderValue - axisHalfWidth;
  4177. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  4178. x2 = chartArea.right;
  4179. } else if (position === 'right') {
  4180. borderValue = alignBorderValue(this.left);
  4181. x1 = chartArea.left;
  4182. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  4183. tx1 = borderValue + axisHalfWidth;
  4184. tx2 = this.left + tl;
  4185. } else if (axis === 'x') {
  4186. if (position === 'center') {
  4187. borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);
  4188. } else if (isObject(position)) {
  4189. const positionAxisID = Object.keys(position)[0];
  4190. const value = position[positionAxisID];
  4191. borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));
  4192. }
  4193. y1 = chartArea.top;
  4194. y2 = chartArea.bottom;
  4195. ty1 = borderValue + axisHalfWidth;
  4196. ty2 = ty1 + tl;
  4197. } else if (axis === 'y') {
  4198. if (position === 'center') {
  4199. borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
  4200. } else if (isObject(position)) {
  4201. const positionAxisID = Object.keys(position)[0];
  4202. const value = position[positionAxisID];
  4203. borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value));
  4204. }
  4205. tx1 = borderValue - axisHalfWidth;
  4206. tx2 = tx1 - tl;
  4207. x1 = chartArea.left;
  4208. x2 = chartArea.right;
  4209. }
  4210. const limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength);
  4211. const step = Math.max(1, Math.ceil(ticksLength / limit));
  4212. for (i = 0; i < ticksLength; i += step) {
  4213. const optsAtIndex = grid.setContext(this.getContext(i));
  4214. const lineWidth = optsAtIndex.lineWidth;
  4215. const lineColor = optsAtIndex.color;
  4216. const borderDash = grid.borderDash || [];
  4217. const borderDashOffset = optsAtIndex.borderDashOffset;
  4218. const tickWidth = optsAtIndex.tickWidth;
  4219. const tickColor = optsAtIndex.tickColor;
  4220. const tickBorderDash = optsAtIndex.tickBorderDash || [];
  4221. const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;
  4222. lineValue = getPixelForGridLine(this, i, offset);
  4223. if (lineValue === undefined) {
  4224. continue;
  4225. }
  4226. alignedLineValue = _alignPixel(chart, lineValue, lineWidth);
  4227. if (isHorizontal) {
  4228. tx1 = tx2 = x1 = x2 = alignedLineValue;
  4229. } else {
  4230. ty1 = ty2 = y1 = y2 = alignedLineValue;
  4231. }
  4232. items.push({
  4233. tx1,
  4234. ty1,
  4235. tx2,
  4236. ty2,
  4237. x1,
  4238. y1,
  4239. x2,
  4240. y2,
  4241. width: lineWidth,
  4242. color: lineColor,
  4243. borderDash,
  4244. borderDashOffset,
  4245. tickWidth,
  4246. tickColor,
  4247. tickBorderDash,
  4248. tickBorderDashOffset,
  4249. });
  4250. }
  4251. this._ticksLength = ticksLength;
  4252. this._borderValue = borderValue;
  4253. return items;
  4254. }
  4255. _computeLabelItems(chartArea) {
  4256. const axis = this.axis;
  4257. const options = this.options;
  4258. const {position, ticks: optionTicks} = options;
  4259. const isHorizontal = this.isHorizontal();
  4260. const ticks = this.ticks;
  4261. const {align, crossAlign, padding, mirror} = optionTicks;
  4262. const tl = getTickMarkLength(options.grid);
  4263. const tickAndPadding = tl + padding;
  4264. const hTickAndPadding = mirror ? -padding : tickAndPadding;
  4265. const rotation = -toRadians(this.labelRotation);
  4266. const items = [];
  4267. let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  4268. let textBaseline = 'middle';
  4269. if (position === 'top') {
  4270. y = this.bottom - hTickAndPadding;
  4271. textAlign = this._getXAxisLabelAlignment();
  4272. } else if (position === 'bottom') {
  4273. y = this.top + hTickAndPadding;
  4274. textAlign = this._getXAxisLabelAlignment();
  4275. } else if (position === 'left') {
  4276. const ret = this._getYAxisLabelAlignment(tl);
  4277. textAlign = ret.textAlign;
  4278. x = ret.x;
  4279. } else if (position === 'right') {
  4280. const ret = this._getYAxisLabelAlignment(tl);
  4281. textAlign = ret.textAlign;
  4282. x = ret.x;
  4283. } else if (axis === 'x') {
  4284. if (position === 'center') {
  4285. y = ((chartArea.top + chartArea.bottom) / 2) + tickAndPadding;
  4286. } else if (isObject(position)) {
  4287. const positionAxisID = Object.keys(position)[0];
  4288. const value = position[positionAxisID];
  4289. y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;
  4290. }
  4291. textAlign = this._getXAxisLabelAlignment();
  4292. } else if (axis === 'y') {
  4293. if (position === 'center') {
  4294. x = ((chartArea.left + chartArea.right) / 2) - tickAndPadding;
  4295. } else if (isObject(position)) {
  4296. const positionAxisID = Object.keys(position)[0];
  4297. const value = position[positionAxisID];
  4298. x = this.chart.scales[positionAxisID].getPixelForValue(value);
  4299. }
  4300. textAlign = this._getYAxisLabelAlignment(tl).textAlign;
  4301. }
  4302. if (axis === 'y') {
  4303. if (align === 'start') {
  4304. textBaseline = 'top';
  4305. } else if (align === 'end') {
  4306. textBaseline = 'bottom';
  4307. }
  4308. }
  4309. const labelSizes = this._getLabelSizes();
  4310. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  4311. tick = ticks[i];
  4312. label = tick.label;
  4313. const optsAtIndex = optionTicks.setContext(this.getContext(i));
  4314. pixel = this.getPixelForTick(i) + optionTicks.labelOffset;
  4315. font = this._resolveTickFontOptions(i);
  4316. lineHeight = font.lineHeight;
  4317. lineCount = isArray(label) ? label.length : 1;
  4318. const halfCount = lineCount / 2;
  4319. const color = optsAtIndex.color;
  4320. const strokeColor = optsAtIndex.textStrokeColor;
  4321. const strokeWidth = optsAtIndex.textStrokeWidth;
  4322. let tickTextAlign = textAlign;
  4323. if (isHorizontal) {
  4324. x = pixel;
  4325. if (textAlign === 'inner') {
  4326. if (i === ilen - 1) {
  4327. tickTextAlign = !this.options.reverse ? 'right' : 'left';
  4328. } else if (i === 0) {
  4329. tickTextAlign = !this.options.reverse ? 'left' : 'right';
  4330. } else {
  4331. tickTextAlign = 'center';
  4332. }
  4333. }
  4334. if (position === 'top') {
  4335. if (crossAlign === 'near' || rotation !== 0) {
  4336. textOffset = -lineCount * lineHeight + lineHeight / 2;
  4337. } else if (crossAlign === 'center') {
  4338. textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;
  4339. } else {
  4340. textOffset = -labelSizes.highest.height + lineHeight / 2;
  4341. }
  4342. } else {
  4343. if (crossAlign === 'near' || rotation !== 0) {
  4344. textOffset = lineHeight / 2;
  4345. } else if (crossAlign === 'center') {
  4346. textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;
  4347. } else {
  4348. textOffset = labelSizes.highest.height - lineCount * lineHeight;
  4349. }
  4350. }
  4351. if (mirror) {
  4352. textOffset *= -1;
  4353. }
  4354. } else {
  4355. y = pixel;
  4356. textOffset = (1 - lineCount) * lineHeight / 2;
  4357. }
  4358. let backdrop;
  4359. if (optsAtIndex.showLabelBackdrop) {
  4360. const labelPadding = toPadding(optsAtIndex.backdropPadding);
  4361. const height = labelSizes.heights[i];
  4362. const width = labelSizes.widths[i];
  4363. let top = y + textOffset - labelPadding.top;
  4364. let left = x - labelPadding.left;
  4365. switch (textBaseline) {
  4366. case 'middle':
  4367. top -= height / 2;
  4368. break;
  4369. case 'bottom':
  4370. top -= height;
  4371. break;
  4372. }
  4373. switch (textAlign) {
  4374. case 'center':
  4375. left -= width / 2;
  4376. break;
  4377. case 'right':
  4378. left -= width;
  4379. break;
  4380. }
  4381. backdrop = {
  4382. left,
  4383. top,
  4384. width: width + labelPadding.width,
  4385. height: height + labelPadding.height,
  4386. color: optsAtIndex.backdropColor,
  4387. };
  4388. }
  4389. items.push({
  4390. rotation,
  4391. label,
  4392. font,
  4393. color,
  4394. strokeColor,
  4395. strokeWidth,
  4396. textOffset,
  4397. textAlign: tickTextAlign,
  4398. textBaseline,
  4399. translation: [x, y],
  4400. backdrop,
  4401. });
  4402. }
  4403. return items;
  4404. }
  4405. _getXAxisLabelAlignment() {
  4406. const {position, ticks} = this.options;
  4407. const rotation = -toRadians(this.labelRotation);
  4408. if (rotation) {
  4409. return position === 'top' ? 'left' : 'right';
  4410. }
  4411. let align = 'center';
  4412. if (ticks.align === 'start') {
  4413. align = 'left';
  4414. } else if (ticks.align === 'end') {
  4415. align = 'right';
  4416. } else if (ticks.align === 'inner') {
  4417. align = 'inner';
  4418. }
  4419. return align;
  4420. }
  4421. _getYAxisLabelAlignment(tl) {
  4422. const {position, ticks: {crossAlign, mirror, padding}} = this.options;
  4423. const labelSizes = this._getLabelSizes();
  4424. const tickAndPadding = tl + padding;
  4425. const widest = labelSizes.widest.width;
  4426. let textAlign;
  4427. let x;
  4428. if (position === 'left') {
  4429. if (mirror) {
  4430. x = this.right + padding;
  4431. if (crossAlign === 'near') {
  4432. textAlign = 'left';
  4433. } else if (crossAlign === 'center') {
  4434. textAlign = 'center';
  4435. x += (widest / 2);
  4436. } else {
  4437. textAlign = 'right';
  4438. x += widest;
  4439. }
  4440. } else {
  4441. x = this.right - tickAndPadding;
  4442. if (crossAlign === 'near') {
  4443. textAlign = 'right';
  4444. } else if (crossAlign === 'center') {
  4445. textAlign = 'center';
  4446. x -= (widest / 2);
  4447. } else {
  4448. textAlign = 'left';
  4449. x = this.left;
  4450. }
  4451. }
  4452. } else if (position === 'right') {
  4453. if (mirror) {
  4454. x = this.left + padding;
  4455. if (crossAlign === 'near') {
  4456. textAlign = 'right';
  4457. } else if (crossAlign === 'center') {
  4458. textAlign = 'center';
  4459. x -= (widest / 2);
  4460. } else {
  4461. textAlign = 'left';
  4462. x -= widest;
  4463. }
  4464. } else {
  4465. x = this.left + tickAndPadding;
  4466. if (crossAlign === 'near') {
  4467. textAlign = 'left';
  4468. } else if (crossAlign === 'center') {
  4469. textAlign = 'center';
  4470. x += widest / 2;
  4471. } else {
  4472. textAlign = 'right';
  4473. x = this.right;
  4474. }
  4475. }
  4476. } else {
  4477. textAlign = 'right';
  4478. }
  4479. return {textAlign, x};
  4480. }
  4481. _computeLabelArea() {
  4482. if (this.options.ticks.mirror) {
  4483. return;
  4484. }
  4485. const chart = this.chart;
  4486. const position = this.options.position;
  4487. if (position === 'left' || position === 'right') {
  4488. return {top: 0, left: this.left, bottom: chart.height, right: this.right};
  4489. } if (position === 'top' || position === 'bottom') {
  4490. return {top: this.top, left: 0, bottom: this.bottom, right: chart.width};
  4491. }
  4492. }
  4493. drawBackground() {
  4494. const {ctx, options: {backgroundColor}, left, top, width, height} = this;
  4495. if (backgroundColor) {
  4496. ctx.save();
  4497. ctx.fillStyle = backgroundColor;
  4498. ctx.fillRect(left, top, width, height);
  4499. ctx.restore();
  4500. }
  4501. }
  4502. getLineWidthForValue(value) {
  4503. const grid = this.options.grid;
  4504. if (!this._isVisible() || !grid.display) {
  4505. return 0;
  4506. }
  4507. const ticks = this.ticks;
  4508. const index = ticks.findIndex(t => t.value === value);
  4509. if (index >= 0) {
  4510. const opts = grid.setContext(this.getContext(index));
  4511. return opts.lineWidth;
  4512. }
  4513. return 0;
  4514. }
  4515. drawGrid(chartArea) {
  4516. const grid = this.options.grid;
  4517. const ctx = this.ctx;
  4518. const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea));
  4519. let i, ilen;
  4520. const drawLine = (p1, p2, style) => {
  4521. if (!style.width || !style.color) {
  4522. return;
  4523. }
  4524. ctx.save();
  4525. ctx.lineWidth = style.width;
  4526. ctx.strokeStyle = style.color;
  4527. ctx.setLineDash(style.borderDash || []);
  4528. ctx.lineDashOffset = style.borderDashOffset;
  4529. ctx.beginPath();
  4530. ctx.moveTo(p1.x, p1.y);
  4531. ctx.lineTo(p2.x, p2.y);
  4532. ctx.stroke();
  4533. ctx.restore();
  4534. };
  4535. if (grid.display) {
  4536. for (i = 0, ilen = items.length; i < ilen; ++i) {
  4537. const item = items[i];
  4538. if (grid.drawOnChartArea) {
  4539. drawLine(
  4540. {x: item.x1, y: item.y1},
  4541. {x: item.x2, y: item.y2},
  4542. item
  4543. );
  4544. }
  4545. if (grid.drawTicks) {
  4546. drawLine(
  4547. {x: item.tx1, y: item.ty1},
  4548. {x: item.tx2, y: item.ty2},
  4549. {
  4550. color: item.tickColor,
  4551. width: item.tickWidth,
  4552. borderDash: item.tickBorderDash,
  4553. borderDashOffset: item.tickBorderDashOffset
  4554. }
  4555. );
  4556. }
  4557. }
  4558. }
  4559. }
  4560. drawBorder() {
  4561. const {chart, ctx, options: {grid}} = this;
  4562. const borderOpts = grid.setContext(this.getContext());
  4563. const axisWidth = grid.drawBorder ? borderOpts.borderWidth : 0;
  4564. if (!axisWidth) {
  4565. return;
  4566. }
  4567. const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth;
  4568. const borderValue = this._borderValue;
  4569. let x1, x2, y1, y2;
  4570. if (this.isHorizontal()) {
  4571. x1 = _alignPixel(chart, this.left, axisWidth) - axisWidth / 2;
  4572. x2 = _alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2;
  4573. y1 = y2 = borderValue;
  4574. } else {
  4575. y1 = _alignPixel(chart, this.top, axisWidth) - axisWidth / 2;
  4576. y2 = _alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2;
  4577. x1 = x2 = borderValue;
  4578. }
  4579. ctx.save();
  4580. ctx.lineWidth = borderOpts.borderWidth;
  4581. ctx.strokeStyle = borderOpts.borderColor;
  4582. ctx.beginPath();
  4583. ctx.moveTo(x1, y1);
  4584. ctx.lineTo(x2, y2);
  4585. ctx.stroke();
  4586. ctx.restore();
  4587. }
  4588. drawLabels(chartArea) {
  4589. const optionTicks = this.options.ticks;
  4590. if (!optionTicks.display) {
  4591. return;
  4592. }
  4593. const ctx = this.ctx;
  4594. const area = this._computeLabelArea();
  4595. if (area) {
  4596. clipArea(ctx, area);
  4597. }
  4598. const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea));
  4599. let i, ilen;
  4600. for (i = 0, ilen = items.length; i < ilen; ++i) {
  4601. const item = items[i];
  4602. const tickFont = item.font;
  4603. const label = item.label;
  4604. if (item.backdrop) {
  4605. ctx.fillStyle = item.backdrop.color;
  4606. ctx.fillRect(item.backdrop.left, item.backdrop.top, item.backdrop.width, item.backdrop.height);
  4607. }
  4608. let y = item.textOffset;
  4609. renderText(ctx, label, 0, y, tickFont, item);
  4610. }
  4611. if (area) {
  4612. unclipArea(ctx);
  4613. }
  4614. }
  4615. drawTitle() {
  4616. const {ctx, options: {position, title, reverse}} = this;
  4617. if (!title.display) {
  4618. return;
  4619. }
  4620. const font = toFont(title.font);
  4621. const padding = toPadding(title.padding);
  4622. const align = title.align;
  4623. let offset = font.lineHeight / 2;
  4624. if (position === 'bottom' || position === 'center' || isObject(position)) {
  4625. offset += padding.bottom;
  4626. if (isArray(title.text)) {
  4627. offset += font.lineHeight * (title.text.length - 1);
  4628. }
  4629. } else {
  4630. offset += padding.top;
  4631. }
  4632. const {titleX, titleY, maxWidth, rotation} = titleArgs(this, offset, position, align);
  4633. renderText(ctx, title.text, 0, 0, font, {
  4634. color: title.color,
  4635. maxWidth,
  4636. rotation,
  4637. textAlign: titleAlign(align, position, reverse),
  4638. textBaseline: 'middle',
  4639. translation: [titleX, titleY],
  4640. });
  4641. }
  4642. draw(chartArea) {
  4643. if (!this._isVisible()) {
  4644. return;
  4645. }
  4646. this.drawBackground();
  4647. this.drawGrid(chartArea);
  4648. this.drawBorder();
  4649. this.drawTitle();
  4650. this.drawLabels(chartArea);
  4651. }
  4652. _layers() {
  4653. const opts = this.options;
  4654. const tz = opts.ticks && opts.ticks.z || 0;
  4655. const gz = valueOrDefault(opts.grid && opts.grid.z, -1);
  4656. if (!this._isVisible() || this.draw !== Scale.prototype.draw) {
  4657. return [{
  4658. z: tz,
  4659. draw: (chartArea) => {
  4660. this.draw(chartArea);
  4661. }
  4662. }];
  4663. }
  4664. return [{
  4665. z: gz,
  4666. draw: (chartArea) => {
  4667. this.drawBackground();
  4668. this.drawGrid(chartArea);
  4669. this.drawTitle();
  4670. }
  4671. }, {
  4672. z: gz + 1,
  4673. draw: () => {
  4674. this.drawBorder();
  4675. }
  4676. }, {
  4677. z: tz,
  4678. draw: (chartArea) => {
  4679. this.drawLabels(chartArea);
  4680. }
  4681. }];
  4682. }
  4683. getMatchingVisibleMetas(type) {
  4684. const metas = this.chart.getSortedVisibleDatasetMetas();
  4685. const axisID = this.axis + 'AxisID';
  4686. const result = [];
  4687. let i, ilen;
  4688. for (i = 0, ilen = metas.length; i < ilen; ++i) {
  4689. const meta = metas[i];
  4690. if (meta[axisID] === this.id && (!type || meta.type === type)) {
  4691. result.push(meta);
  4692. }
  4693. }
  4694. return result;
  4695. }
  4696. _resolveTickFontOptions(index) {
  4697. const opts = this.options.ticks.setContext(this.getContext(index));
  4698. return toFont(opts.font);
  4699. }
  4700. _maxDigits() {
  4701. const fontSize = this._resolveTickFontOptions(0).lineHeight;
  4702. return (this.isHorizontal() ? this.width : this.height) / fontSize;
  4703. }
  4704. }
  4705. class TypedRegistry {
  4706. constructor(type, scope, override) {
  4707. this.type = type;
  4708. this.scope = scope;
  4709. this.override = override;
  4710. this.items = Object.create(null);
  4711. }
  4712. isForType(type) {
  4713. return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);
  4714. }
  4715. register(item) {
  4716. const proto = Object.getPrototypeOf(item);
  4717. let parentScope;
  4718. if (isIChartComponent(proto)) {
  4719. parentScope = this.register(proto);
  4720. }
  4721. const items = this.items;
  4722. const id = item.id;
  4723. const scope = this.scope + '.' + id;
  4724. if (!id) {
  4725. throw new Error('class does not have id: ' + item);
  4726. }
  4727. if (id in items) {
  4728. return scope;
  4729. }
  4730. items[id] = item;
  4731. registerDefaults(item, scope, parentScope);
  4732. if (this.override) {
  4733. defaults.override(item.id, item.overrides);
  4734. }
  4735. return scope;
  4736. }
  4737. get(id) {
  4738. return this.items[id];
  4739. }
  4740. unregister(item) {
  4741. const items = this.items;
  4742. const id = item.id;
  4743. const scope = this.scope;
  4744. if (id in items) {
  4745. delete items[id];
  4746. }
  4747. if (scope && id in defaults[scope]) {
  4748. delete defaults[scope][id];
  4749. if (this.override) {
  4750. delete overrides[id];
  4751. }
  4752. }
  4753. }
  4754. }
  4755. function registerDefaults(item, scope, parentScope) {
  4756. const itemDefaults = merge(Object.create(null), [
  4757. parentScope ? defaults.get(parentScope) : {},
  4758. defaults.get(scope),
  4759. item.defaults
  4760. ]);
  4761. defaults.set(scope, itemDefaults);
  4762. if (item.defaultRoutes) {
  4763. routeDefaults(scope, item.defaultRoutes);
  4764. }
  4765. if (item.descriptors) {
  4766. defaults.describe(scope, item.descriptors);
  4767. }
  4768. }
  4769. function routeDefaults(scope, routes) {
  4770. Object.keys(routes).forEach(property => {
  4771. const propertyParts = property.split('.');
  4772. const sourceName = propertyParts.pop();
  4773. const sourceScope = [scope].concat(propertyParts).join('.');
  4774. const parts = routes[property].split('.');
  4775. const targetName = parts.pop();
  4776. const targetScope = parts.join('.');
  4777. defaults.route(sourceScope, sourceName, targetScope, targetName);
  4778. });
  4779. }
  4780. function isIChartComponent(proto) {
  4781. return 'id' in proto && 'defaults' in proto;
  4782. }
  4783. class Registry {
  4784. constructor() {
  4785. this.controllers = new TypedRegistry(DatasetController, 'datasets', true);
  4786. this.elements = new TypedRegistry(Element, 'elements');
  4787. this.plugins = new TypedRegistry(Object, 'plugins');
  4788. this.scales = new TypedRegistry(Scale, 'scales');
  4789. this._typedRegistries = [this.controllers, this.scales, this.elements];
  4790. }
  4791. add(...args) {
  4792. this._each('register', args);
  4793. }
  4794. remove(...args) {
  4795. this._each('unregister', args);
  4796. }
  4797. addControllers(...args) {
  4798. this._each('register', args, this.controllers);
  4799. }
  4800. addElements(...args) {
  4801. this._each('register', args, this.elements);
  4802. }
  4803. addPlugins(...args) {
  4804. this._each('register', args, this.plugins);
  4805. }
  4806. addScales(...args) {
  4807. this._each('register', args, this.scales);
  4808. }
  4809. getController(id) {
  4810. return this._get(id, this.controllers, 'controller');
  4811. }
  4812. getElement(id) {
  4813. return this._get(id, this.elements, 'element');
  4814. }
  4815. getPlugin(id) {
  4816. return this._get(id, this.plugins, 'plugin');
  4817. }
  4818. getScale(id) {
  4819. return this._get(id, this.scales, 'scale');
  4820. }
  4821. removeControllers(...args) {
  4822. this._each('unregister', args, this.controllers);
  4823. }
  4824. removeElements(...args) {
  4825. this._each('unregister', args, this.elements);
  4826. }
  4827. removePlugins(...args) {
  4828. this._each('unregister', args, this.plugins);
  4829. }
  4830. removeScales(...args) {
  4831. this._each('unregister', args, this.scales);
  4832. }
  4833. _each(method, args, typedRegistry) {
  4834. [...args].forEach(arg => {
  4835. const reg = typedRegistry || this._getRegistryForType(arg);
  4836. if (typedRegistry || reg.isForType(arg) || (reg === this.plugins && arg.id)) {
  4837. this._exec(method, reg, arg);
  4838. } else {
  4839. each(arg, item => {
  4840. const itemReg = typedRegistry || this._getRegistryForType(item);
  4841. this._exec(method, itemReg, item);
  4842. });
  4843. }
  4844. });
  4845. }
  4846. _exec(method, registry, component) {
  4847. const camelMethod = _capitalize(method);
  4848. callback(component['before' + camelMethod], [], component);
  4849. registry[method](component);
  4850. callback(component['after' + camelMethod], [], component);
  4851. }
  4852. _getRegistryForType(type) {
  4853. for (let i = 0; i < this._typedRegistries.length; i++) {
  4854. const reg = this._typedRegistries[i];
  4855. if (reg.isForType(type)) {
  4856. return reg;
  4857. }
  4858. }
  4859. return this.plugins;
  4860. }
  4861. _get(id, typedRegistry, type) {
  4862. const item = typedRegistry.get(id);
  4863. if (item === undefined) {
  4864. throw new Error('"' + id + '" is not a registered ' + type + '.');
  4865. }
  4866. return item;
  4867. }
  4868. }
  4869. var registry = new Registry();
  4870. class PluginService {
  4871. constructor() {
  4872. this._init = [];
  4873. }
  4874. notify(chart, hook, args, filter) {
  4875. if (hook === 'beforeInit') {
  4876. this._init = this._createDescriptors(chart, true);
  4877. this._notify(this._init, chart, 'install');
  4878. }
  4879. const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart);
  4880. const result = this._notify(descriptors, chart, hook, args);
  4881. if (hook === 'afterDestroy') {
  4882. this._notify(descriptors, chart, 'stop');
  4883. this._notify(this._init, chart, 'uninstall');
  4884. }
  4885. return result;
  4886. }
  4887. _notify(descriptors, chart, hook, args) {
  4888. args = args || {};
  4889. for (const descriptor of descriptors) {
  4890. const plugin = descriptor.plugin;
  4891. const method = plugin[hook];
  4892. const params = [chart, args, descriptor.options];
  4893. if (callback(method, params, plugin) === false && args.cancelable) {
  4894. return false;
  4895. }
  4896. }
  4897. return true;
  4898. }
  4899. invalidate() {
  4900. if (!isNullOrUndef(this._cache)) {
  4901. this._oldCache = this._cache;
  4902. this._cache = undefined;
  4903. }
  4904. }
  4905. _descriptors(chart) {
  4906. if (this._cache) {
  4907. return this._cache;
  4908. }
  4909. const descriptors = this._cache = this._createDescriptors(chart);
  4910. this._notifyStateChanges(chart);
  4911. return descriptors;
  4912. }
  4913. _createDescriptors(chart, all) {
  4914. const config = chart && chart.config;
  4915. const options = valueOrDefault(config.options && config.options.plugins, {});
  4916. const plugins = allPlugins(config);
  4917. return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);
  4918. }
  4919. _notifyStateChanges(chart) {
  4920. const previousDescriptors = this._oldCache || [];
  4921. const descriptors = this._cache;
  4922. const diff = (a, b) => a.filter(x => !b.some(y => x.plugin.id === y.plugin.id));
  4923. this._notify(diff(previousDescriptors, descriptors), chart, 'stop');
  4924. this._notify(diff(descriptors, previousDescriptors), chart, 'start');
  4925. }
  4926. }
  4927. function allPlugins(config) {
  4928. const plugins = [];
  4929. const keys = Object.keys(registry.plugins.items);
  4930. for (let i = 0; i < keys.length; i++) {
  4931. plugins.push(registry.getPlugin(keys[i]));
  4932. }
  4933. const local = config.plugins || [];
  4934. for (let i = 0; i < local.length; i++) {
  4935. const plugin = local[i];
  4936. if (plugins.indexOf(plugin) === -1) {
  4937. plugins.push(plugin);
  4938. }
  4939. }
  4940. return plugins;
  4941. }
  4942. function getOpts(options, all) {
  4943. if (!all && options === false) {
  4944. return null;
  4945. }
  4946. if (options === true) {
  4947. return {};
  4948. }
  4949. return options;
  4950. }
  4951. function createDescriptors(chart, plugins, options, all) {
  4952. const result = [];
  4953. const context = chart.getContext();
  4954. for (let i = 0; i < plugins.length; i++) {
  4955. const plugin = plugins[i];
  4956. const id = plugin.id;
  4957. const opts = getOpts(options[id], all);
  4958. if (opts === null) {
  4959. continue;
  4960. }
  4961. result.push({
  4962. plugin,
  4963. options: pluginOpts(chart.config, plugin, opts, context)
  4964. });
  4965. }
  4966. return result;
  4967. }
  4968. function pluginOpts(config, plugin, opts, context) {
  4969. const keys = config.pluginScopeKeys(plugin);
  4970. const scopes = config.getOptionScopes(opts, keys);
  4971. return config.createResolver(scopes, context, [''], {scriptable: false, indexable: false, allKeys: true});
  4972. }
  4973. function getIndexAxis(type, options) {
  4974. const datasetDefaults = defaults.datasets[type] || {};
  4975. const datasetOptions = (options.datasets || {})[type] || {};
  4976. return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';
  4977. }
  4978. function getAxisFromDefaultScaleID(id, indexAxis) {
  4979. let axis = id;
  4980. if (id === '_index_') {
  4981. axis = indexAxis;
  4982. } else if (id === '_value_') {
  4983. axis = indexAxis === 'x' ? 'y' : 'x';
  4984. }
  4985. return axis;
  4986. }
  4987. function getDefaultScaleIDFromAxis(axis, indexAxis) {
  4988. return axis === indexAxis ? '_index_' : '_value_';
  4989. }
  4990. function axisFromPosition(position) {
  4991. if (position === 'top' || position === 'bottom') {
  4992. return 'x';
  4993. }
  4994. if (position === 'left' || position === 'right') {
  4995. return 'y';
  4996. }
  4997. }
  4998. function determineAxis(id, scaleOptions) {
  4999. if (id === 'x' || id === 'y') {
  5000. return id;
  5001. }
  5002. return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id.charAt(0).toLowerCase();
  5003. }
  5004. function mergeScaleConfig(config, options) {
  5005. const chartDefaults = overrides[config.type] || {scales: {}};
  5006. const configScales = options.scales || {};
  5007. const chartIndexAxis = getIndexAxis(config.type, options);
  5008. const firstIDs = Object.create(null);
  5009. const scales = Object.create(null);
  5010. Object.keys(configScales).forEach(id => {
  5011. const scaleConf = configScales[id];
  5012. if (!isObject(scaleConf)) {
  5013. return console.error(`Invalid scale configuration for scale: ${id}`);
  5014. }
  5015. if (scaleConf._proxy) {
  5016. return console.warn(`Ignoring resolver passed as options for scale: ${id}`);
  5017. }
  5018. const axis = determineAxis(id, scaleConf);
  5019. const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
  5020. const defaultScaleOptions = chartDefaults.scales || {};
  5021. firstIDs[axis] = firstIDs[axis] || id;
  5022. scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, defaultScaleOptions[axis], defaultScaleOptions[defaultId]]);
  5023. });
  5024. config.data.datasets.forEach(dataset => {
  5025. const type = dataset.type || config.type;
  5026. const indexAxis = dataset.indexAxis || getIndexAxis(type, options);
  5027. const datasetDefaults = overrides[type] || {};
  5028. const defaultScaleOptions = datasetDefaults.scales || {};
  5029. Object.keys(defaultScaleOptions).forEach(defaultID => {
  5030. const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
  5031. const id = dataset[axis + 'AxisID'] || firstIDs[axis] || axis;
  5032. scales[id] = scales[id] || Object.create(null);
  5033. mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]);
  5034. });
  5035. });
  5036. Object.keys(scales).forEach(key => {
  5037. const scale = scales[key];
  5038. mergeIf(scale, [defaults.scales[scale.type], defaults.scale]);
  5039. });
  5040. return scales;
  5041. }
  5042. function initOptions(config) {
  5043. const options = config.options || (config.options = {});
  5044. options.plugins = valueOrDefault(options.plugins, {});
  5045. options.scales = mergeScaleConfig(config, options);
  5046. }
  5047. function initData(data) {
  5048. data = data || {};
  5049. data.datasets = data.datasets || [];
  5050. data.labels = data.labels || [];
  5051. return data;
  5052. }
  5053. function initConfig(config) {
  5054. config = config || {};
  5055. config.data = initData(config.data);
  5056. initOptions(config);
  5057. return config;
  5058. }
  5059. const keyCache = new Map();
  5060. const keysCached = new Set();
  5061. function cachedKeys(cacheKey, generate) {
  5062. let keys = keyCache.get(cacheKey);
  5063. if (!keys) {
  5064. keys = generate();
  5065. keyCache.set(cacheKey, keys);
  5066. keysCached.add(keys);
  5067. }
  5068. return keys;
  5069. }
  5070. const addIfFound = (set, obj, key) => {
  5071. const opts = resolveObjectKey(obj, key);
  5072. if (opts !== undefined) {
  5073. set.add(opts);
  5074. }
  5075. };
  5076. class Config {
  5077. constructor(config) {
  5078. this._config = initConfig(config);
  5079. this._scopeCache = new Map();
  5080. this._resolverCache = new Map();
  5081. }
  5082. get platform() {
  5083. return this._config.platform;
  5084. }
  5085. get type() {
  5086. return this._config.type;
  5087. }
  5088. set type(type) {
  5089. this._config.type = type;
  5090. }
  5091. get data() {
  5092. return this._config.data;
  5093. }
  5094. set data(data) {
  5095. this._config.data = initData(data);
  5096. }
  5097. get options() {
  5098. return this._config.options;
  5099. }
  5100. set options(options) {
  5101. this._config.options = options;
  5102. }
  5103. get plugins() {
  5104. return this._config.plugins;
  5105. }
  5106. update() {
  5107. const config = this._config;
  5108. this.clearCache();
  5109. initOptions(config);
  5110. }
  5111. clearCache() {
  5112. this._scopeCache.clear();
  5113. this._resolverCache.clear();
  5114. }
  5115. datasetScopeKeys(datasetType) {
  5116. return cachedKeys(datasetType,
  5117. () => [[
  5118. `datasets.${datasetType}`,
  5119. ''
  5120. ]]);
  5121. }
  5122. datasetAnimationScopeKeys(datasetType, transition) {
  5123. return cachedKeys(`${datasetType}.transition.${transition}`,
  5124. () => [
  5125. [
  5126. `datasets.${datasetType}.transitions.${transition}`,
  5127. `transitions.${transition}`,
  5128. ],
  5129. [
  5130. `datasets.${datasetType}`,
  5131. ''
  5132. ]
  5133. ]);
  5134. }
  5135. datasetElementScopeKeys(datasetType, elementType) {
  5136. return cachedKeys(`${datasetType}-${elementType}`,
  5137. () => [[
  5138. `datasets.${datasetType}.elements.${elementType}`,
  5139. `datasets.${datasetType}`,
  5140. `elements.${elementType}`,
  5141. ''
  5142. ]]);
  5143. }
  5144. pluginScopeKeys(plugin) {
  5145. const id = plugin.id;
  5146. const type = this.type;
  5147. return cachedKeys(`${type}-plugin-${id}`,
  5148. () => [[
  5149. `plugins.${id}`,
  5150. ...plugin.additionalOptionScopes || [],
  5151. ]]);
  5152. }
  5153. _cachedScopes(mainScope, resetCache) {
  5154. const _scopeCache = this._scopeCache;
  5155. let cache = _scopeCache.get(mainScope);
  5156. if (!cache || resetCache) {
  5157. cache = new Map();
  5158. _scopeCache.set(mainScope, cache);
  5159. }
  5160. return cache;
  5161. }
  5162. getOptionScopes(mainScope, keyLists, resetCache) {
  5163. const {options, type} = this;
  5164. const cache = this._cachedScopes(mainScope, resetCache);
  5165. const cached = cache.get(keyLists);
  5166. if (cached) {
  5167. return cached;
  5168. }
  5169. const scopes = new Set();
  5170. keyLists.forEach(keys => {
  5171. if (mainScope) {
  5172. scopes.add(mainScope);
  5173. keys.forEach(key => addIfFound(scopes, mainScope, key));
  5174. }
  5175. keys.forEach(key => addIfFound(scopes, options, key));
  5176. keys.forEach(key => addIfFound(scopes, overrides[type] || {}, key));
  5177. keys.forEach(key => addIfFound(scopes, defaults, key));
  5178. keys.forEach(key => addIfFound(scopes, descriptors, key));
  5179. });
  5180. const array = Array.from(scopes);
  5181. if (array.length === 0) {
  5182. array.push(Object.create(null));
  5183. }
  5184. if (keysCached.has(keyLists)) {
  5185. cache.set(keyLists, array);
  5186. }
  5187. return array;
  5188. }
  5189. chartOptionScopes() {
  5190. const {options, type} = this;
  5191. return [
  5192. options,
  5193. overrides[type] || {},
  5194. defaults.datasets[type] || {},
  5195. {type},
  5196. defaults,
  5197. descriptors
  5198. ];
  5199. }
  5200. resolveNamedOptions(scopes, names, context, prefixes = ['']) {
  5201. const result = {$shared: true};
  5202. const {resolver, subPrefixes} = getResolver(this._resolverCache, scopes, prefixes);
  5203. let options = resolver;
  5204. if (needContext(resolver, names)) {
  5205. result.$shared = false;
  5206. context = isFunction(context) ? context() : context;
  5207. const subResolver = this.createResolver(scopes, context, subPrefixes);
  5208. options = _attachContext(resolver, context, subResolver);
  5209. }
  5210. for (const prop of names) {
  5211. result[prop] = options[prop];
  5212. }
  5213. return result;
  5214. }
  5215. createResolver(scopes, context, prefixes = [''], descriptorDefaults) {
  5216. const {resolver} = getResolver(this._resolverCache, scopes, prefixes);
  5217. return isObject(context)
  5218. ? _attachContext(resolver, context, undefined, descriptorDefaults)
  5219. : resolver;
  5220. }
  5221. }
  5222. function getResolver(resolverCache, scopes, prefixes) {
  5223. let cache = resolverCache.get(scopes);
  5224. if (!cache) {
  5225. cache = new Map();
  5226. resolverCache.set(scopes, cache);
  5227. }
  5228. const cacheKey = prefixes.join();
  5229. let cached = cache.get(cacheKey);
  5230. if (!cached) {
  5231. const resolver = _createResolver(scopes, prefixes);
  5232. cached = {
  5233. resolver,
  5234. subPrefixes: prefixes.filter(p => !p.toLowerCase().includes('hover'))
  5235. };
  5236. cache.set(cacheKey, cached);
  5237. }
  5238. return cached;
  5239. }
  5240. const hasFunction = value => isObject(value)
  5241. && Object.getOwnPropertyNames(value).reduce((acc, key) => acc || isFunction(value[key]), false);
  5242. function needContext(proxy, names) {
  5243. const {isScriptable, isIndexable} = _descriptors(proxy);
  5244. for (const prop of names) {
  5245. const scriptable = isScriptable(prop);
  5246. const indexable = isIndexable(prop);
  5247. const value = (indexable || scriptable) && proxy[prop];
  5248. if ((scriptable && (isFunction(value) || hasFunction(value)))
  5249. || (indexable && isArray(value))) {
  5250. return true;
  5251. }
  5252. }
  5253. return false;
  5254. }
  5255. var version = "3.7.1";
  5256. const KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea'];
  5257. function positionIsHorizontal(position, axis) {
  5258. return position === 'top' || position === 'bottom' || (KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x');
  5259. }
  5260. function compare2Level(l1, l2) {
  5261. return function(a, b) {
  5262. return a[l1] === b[l1]
  5263. ? a[l2] - b[l2]
  5264. : a[l1] - b[l1];
  5265. };
  5266. }
  5267. function onAnimationsComplete(context) {
  5268. const chart = context.chart;
  5269. const animationOptions = chart.options.animation;
  5270. chart.notifyPlugins('afterRender');
  5271. callback(animationOptions && animationOptions.onComplete, [context], chart);
  5272. }
  5273. function onAnimationProgress(context) {
  5274. const chart = context.chart;
  5275. const animationOptions = chart.options.animation;
  5276. callback(animationOptions && animationOptions.onProgress, [context], chart);
  5277. }
  5278. function getCanvas(item) {
  5279. if (_isDomSupported() && typeof item === 'string') {
  5280. item = document.getElementById(item);
  5281. } else if (item && item.length) {
  5282. item = item[0];
  5283. }
  5284. if (item && item.canvas) {
  5285. item = item.canvas;
  5286. }
  5287. return item;
  5288. }
  5289. const instances = {};
  5290. const getChart = (key) => {
  5291. const canvas = getCanvas(key);
  5292. return Object.values(instances).filter((c) => c.canvas === canvas).pop();
  5293. };
  5294. function moveNumericKeys(obj, start, move) {
  5295. const keys = Object.keys(obj);
  5296. for (const key of keys) {
  5297. const intKey = +key;
  5298. if (intKey >= start) {
  5299. const value = obj[key];
  5300. delete obj[key];
  5301. if (move > 0 || intKey > start) {
  5302. obj[intKey + move] = value;
  5303. }
  5304. }
  5305. }
  5306. }
  5307. function determineLastEvent(e, lastEvent, inChartArea, isClick) {
  5308. if (!inChartArea || e.type === 'mouseout') {
  5309. return null;
  5310. }
  5311. if (isClick) {
  5312. return lastEvent;
  5313. }
  5314. return e;
  5315. }
  5316. class Chart {
  5317. constructor(item, userConfig) {
  5318. const config = this.config = new Config(userConfig);
  5319. const initialCanvas = getCanvas(item);
  5320. const existingChart = getChart(initialCanvas);
  5321. if (existingChart) {
  5322. throw new Error(
  5323. 'Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' +
  5324. ' must be destroyed before the canvas can be reused.'
  5325. );
  5326. }
  5327. const options = config.createResolver(config.chartOptionScopes(), this.getContext());
  5328. this.platform = new (config.platform || _detectPlatform(initialCanvas))();
  5329. this.platform.updateConfig(config);
  5330. const context = this.platform.acquireContext(initialCanvas, options.aspectRatio);
  5331. const canvas = context && context.canvas;
  5332. const height = canvas && canvas.height;
  5333. const width = canvas && canvas.width;
  5334. this.id = uid();
  5335. this.ctx = context;
  5336. this.canvas = canvas;
  5337. this.width = width;
  5338. this.height = height;
  5339. this._options = options;
  5340. this._aspectRatio = this.aspectRatio;
  5341. this._layers = [];
  5342. this._metasets = [];
  5343. this._stacks = undefined;
  5344. this.boxes = [];
  5345. this.currentDevicePixelRatio = undefined;
  5346. this.chartArea = undefined;
  5347. this._active = [];
  5348. this._lastEvent = undefined;
  5349. this._listeners = {};
  5350. this._responsiveListeners = undefined;
  5351. this._sortedMetasets = [];
  5352. this.scales = {};
  5353. this._plugins = new PluginService();
  5354. this.$proxies = {};
  5355. this._hiddenIndices = {};
  5356. this.attached = false;
  5357. this._animationsDisabled = undefined;
  5358. this.$context = undefined;
  5359. this._doResize = debounce(mode => this.update(mode), options.resizeDelay || 0);
  5360. this._dataChanges = [];
  5361. instances[this.id] = this;
  5362. if (!context || !canvas) {
  5363. console.error("Failed to create chart: can't acquire context from the given item");
  5364. return;
  5365. }
  5366. animator.listen(this, 'complete', onAnimationsComplete);
  5367. animator.listen(this, 'progress', onAnimationProgress);
  5368. this._initialize();
  5369. if (this.attached) {
  5370. this.update();
  5371. }
  5372. }
  5373. get aspectRatio() {
  5374. const {options: {aspectRatio, maintainAspectRatio}, width, height, _aspectRatio} = this;
  5375. if (!isNullOrUndef(aspectRatio)) {
  5376. return aspectRatio;
  5377. }
  5378. if (maintainAspectRatio && _aspectRatio) {
  5379. return _aspectRatio;
  5380. }
  5381. return height ? width / height : null;
  5382. }
  5383. get data() {
  5384. return this.config.data;
  5385. }
  5386. set data(data) {
  5387. this.config.data = data;
  5388. }
  5389. get options() {
  5390. return this._options;
  5391. }
  5392. set options(options) {
  5393. this.config.options = options;
  5394. }
  5395. _initialize() {
  5396. this.notifyPlugins('beforeInit');
  5397. if (this.options.responsive) {
  5398. this.resize();
  5399. } else {
  5400. retinaScale(this, this.options.devicePixelRatio);
  5401. }
  5402. this.bindEvents();
  5403. this.notifyPlugins('afterInit');
  5404. return this;
  5405. }
  5406. clear() {
  5407. clearCanvas(this.canvas, this.ctx);
  5408. return this;
  5409. }
  5410. stop() {
  5411. animator.stop(this);
  5412. return this;
  5413. }
  5414. resize(width, height) {
  5415. if (!animator.running(this)) {
  5416. this._resize(width, height);
  5417. } else {
  5418. this._resizeBeforeDraw = {width, height};
  5419. }
  5420. }
  5421. _resize(width, height) {
  5422. const options = this.options;
  5423. const canvas = this.canvas;
  5424. const aspectRatio = options.maintainAspectRatio && this.aspectRatio;
  5425. const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio);
  5426. const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio();
  5427. const mode = this.width ? 'resize' : 'attach';
  5428. this.width = newSize.width;
  5429. this.height = newSize.height;
  5430. this._aspectRatio = this.aspectRatio;
  5431. if (!retinaScale(this, newRatio, true)) {
  5432. return;
  5433. }
  5434. this.notifyPlugins('resize', {size: newSize});
  5435. callback(options.onResize, [this, newSize], this);
  5436. if (this.attached) {
  5437. if (this._doResize(mode)) {
  5438. this.render();
  5439. }
  5440. }
  5441. }
  5442. ensureScalesHaveIDs() {
  5443. const options = this.options;
  5444. const scalesOptions = options.scales || {};
  5445. each(scalesOptions, (axisOptions, axisID) => {
  5446. axisOptions.id = axisID;
  5447. });
  5448. }
  5449. buildOrUpdateScales() {
  5450. const options = this.options;
  5451. const scaleOpts = options.scales;
  5452. const scales = this.scales;
  5453. const updated = Object.keys(scales).reduce((obj, id) => {
  5454. obj[id] = false;
  5455. return obj;
  5456. }, {});
  5457. let items = [];
  5458. if (scaleOpts) {
  5459. items = items.concat(
  5460. Object.keys(scaleOpts).map((id) => {
  5461. const scaleOptions = scaleOpts[id];
  5462. const axis = determineAxis(id, scaleOptions);
  5463. const isRadial = axis === 'r';
  5464. const isHorizontal = axis === 'x';
  5465. return {
  5466. options: scaleOptions,
  5467. dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',
  5468. dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'
  5469. };
  5470. })
  5471. );
  5472. }
  5473. each(items, (item) => {
  5474. const scaleOptions = item.options;
  5475. const id = scaleOptions.id;
  5476. const axis = determineAxis(id, scaleOptions);
  5477. const scaleType = valueOrDefault(scaleOptions.type, item.dtype);
  5478. if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {
  5479. scaleOptions.position = item.dposition;
  5480. }
  5481. updated[id] = true;
  5482. let scale = null;
  5483. if (id in scales && scales[id].type === scaleType) {
  5484. scale = scales[id];
  5485. } else {
  5486. const scaleClass = registry.getScale(scaleType);
  5487. scale = new scaleClass({
  5488. id,
  5489. type: scaleType,
  5490. ctx: this.ctx,
  5491. chart: this
  5492. });
  5493. scales[scale.id] = scale;
  5494. }
  5495. scale.init(scaleOptions, options);
  5496. });
  5497. each(updated, (hasUpdated, id) => {
  5498. if (!hasUpdated) {
  5499. delete scales[id];
  5500. }
  5501. });
  5502. each(scales, (scale) => {
  5503. layouts.configure(this, scale, scale.options);
  5504. layouts.addBox(this, scale);
  5505. });
  5506. }
  5507. _updateMetasets() {
  5508. const metasets = this._metasets;
  5509. const numData = this.data.datasets.length;
  5510. const numMeta = metasets.length;
  5511. metasets.sort((a, b) => a.index - b.index);
  5512. if (numMeta > numData) {
  5513. for (let i = numData; i < numMeta; ++i) {
  5514. this._destroyDatasetMeta(i);
  5515. }
  5516. metasets.splice(numData, numMeta - numData);
  5517. }
  5518. this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));
  5519. }
  5520. _removeUnreferencedMetasets() {
  5521. const {_metasets: metasets, data: {datasets}} = this;
  5522. if (metasets.length > datasets.length) {
  5523. delete this._stacks;
  5524. }
  5525. metasets.forEach((meta, index) => {
  5526. if (datasets.filter(x => x === meta._dataset).length === 0) {
  5527. this._destroyDatasetMeta(index);
  5528. }
  5529. });
  5530. }
  5531. buildOrUpdateControllers() {
  5532. const newControllers = [];
  5533. const datasets = this.data.datasets;
  5534. let i, ilen;
  5535. this._removeUnreferencedMetasets();
  5536. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  5537. const dataset = datasets[i];
  5538. let meta = this.getDatasetMeta(i);
  5539. const type = dataset.type || this.config.type;
  5540. if (meta.type && meta.type !== type) {
  5541. this._destroyDatasetMeta(i);
  5542. meta = this.getDatasetMeta(i);
  5543. }
  5544. meta.type = type;
  5545. meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options);
  5546. meta.order = dataset.order || 0;
  5547. meta.index = i;
  5548. meta.label = '' + dataset.label;
  5549. meta.visible = this.isDatasetVisible(i);
  5550. if (meta.controller) {
  5551. meta.controller.updateIndex(i);
  5552. meta.controller.linkScales();
  5553. } else {
  5554. const ControllerClass = registry.getController(type);
  5555. const {datasetElementType, dataElementType} = defaults.datasets[type];
  5556. Object.assign(ControllerClass.prototype, {
  5557. dataElementType: registry.getElement(dataElementType),
  5558. datasetElementType: datasetElementType && registry.getElement(datasetElementType)
  5559. });
  5560. meta.controller = new ControllerClass(this, i);
  5561. newControllers.push(meta.controller);
  5562. }
  5563. }
  5564. this._updateMetasets();
  5565. return newControllers;
  5566. }
  5567. _resetElements() {
  5568. each(this.data.datasets, (dataset, datasetIndex) => {
  5569. this.getDatasetMeta(datasetIndex).controller.reset();
  5570. }, this);
  5571. }
  5572. reset() {
  5573. this._resetElements();
  5574. this.notifyPlugins('reset');
  5575. }
  5576. update(mode) {
  5577. const config = this.config;
  5578. config.update();
  5579. const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext());
  5580. const animsDisabled = this._animationsDisabled = !options.animation;
  5581. this._updateScales();
  5582. this._checkEventBindings();
  5583. this._updateHiddenIndices();
  5584. this._plugins.invalidate();
  5585. if (this.notifyPlugins('beforeUpdate', {mode, cancelable: true}) === false) {
  5586. return;
  5587. }
  5588. const newControllers = this.buildOrUpdateControllers();
  5589. this.notifyPlugins('beforeElementsUpdate');
  5590. let minPadding = 0;
  5591. for (let i = 0, ilen = this.data.datasets.length; i < ilen; i++) {
  5592. const {controller} = this.getDatasetMeta(i);
  5593. const reset = !animsDisabled && newControllers.indexOf(controller) === -1;
  5594. controller.buildOrUpdateElements(reset);
  5595. minPadding = Math.max(+controller.getMaxOverflow(), minPadding);
  5596. }
  5597. minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0;
  5598. this._updateLayout(minPadding);
  5599. if (!animsDisabled) {
  5600. each(newControllers, (controller) => {
  5601. controller.reset();
  5602. });
  5603. }
  5604. this._updateDatasets(mode);
  5605. this.notifyPlugins('afterUpdate', {mode});
  5606. this._layers.sort(compare2Level('z', '_idx'));
  5607. const {_active, _lastEvent} = this;
  5608. if (_lastEvent) {
  5609. this._eventHandler(_lastEvent, true);
  5610. } else if (_active.length) {
  5611. this._updateHoverStyles(_active, _active, true);
  5612. }
  5613. this.render();
  5614. }
  5615. _updateScales() {
  5616. each(this.scales, (scale) => {
  5617. layouts.removeBox(this, scale);
  5618. });
  5619. this.ensureScalesHaveIDs();
  5620. this.buildOrUpdateScales();
  5621. }
  5622. _checkEventBindings() {
  5623. const options = this.options;
  5624. const existingEvents = new Set(Object.keys(this._listeners));
  5625. const newEvents = new Set(options.events);
  5626. if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) {
  5627. this.unbindEvents();
  5628. this.bindEvents();
  5629. }
  5630. }
  5631. _updateHiddenIndices() {
  5632. const {_hiddenIndices} = this;
  5633. const changes = this._getUniformDataChanges() || [];
  5634. for (const {method, start, count} of changes) {
  5635. const move = method === '_removeElements' ? -count : count;
  5636. moveNumericKeys(_hiddenIndices, start, move);
  5637. }
  5638. }
  5639. _getUniformDataChanges() {
  5640. const _dataChanges = this._dataChanges;
  5641. if (!_dataChanges || !_dataChanges.length) {
  5642. return;
  5643. }
  5644. this._dataChanges = [];
  5645. const datasetCount = this.data.datasets.length;
  5646. const makeSet = (idx) => new Set(
  5647. _dataChanges
  5648. .filter(c => c[0] === idx)
  5649. .map((c, i) => i + ',' + c.splice(1).join(','))
  5650. );
  5651. const changeSet = makeSet(0);
  5652. for (let i = 1; i < datasetCount; i++) {
  5653. if (!setsEqual(changeSet, makeSet(i))) {
  5654. return;
  5655. }
  5656. }
  5657. return Array.from(changeSet)
  5658. .map(c => c.split(','))
  5659. .map(a => ({method: a[1], start: +a[2], count: +a[3]}));
  5660. }
  5661. _updateLayout(minPadding) {
  5662. if (this.notifyPlugins('beforeLayout', {cancelable: true}) === false) {
  5663. return;
  5664. }
  5665. layouts.update(this, this.width, this.height, minPadding);
  5666. const area = this.chartArea;
  5667. const noArea = area.width <= 0 || area.height <= 0;
  5668. this._layers = [];
  5669. each(this.boxes, (box) => {
  5670. if (noArea && box.position === 'chartArea') {
  5671. return;
  5672. }
  5673. if (box.configure) {
  5674. box.configure();
  5675. }
  5676. this._layers.push(...box._layers());
  5677. }, this);
  5678. this._layers.forEach((item, index) => {
  5679. item._idx = index;
  5680. });
  5681. this.notifyPlugins('afterLayout');
  5682. }
  5683. _updateDatasets(mode) {
  5684. if (this.notifyPlugins('beforeDatasetsUpdate', {mode, cancelable: true}) === false) {
  5685. return;
  5686. }
  5687. for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  5688. this.getDatasetMeta(i).controller.configure();
  5689. }
  5690. for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  5691. this._updateDataset(i, isFunction(mode) ? mode({datasetIndex: i}) : mode);
  5692. }
  5693. this.notifyPlugins('afterDatasetsUpdate', {mode});
  5694. }
  5695. _updateDataset(index, mode) {
  5696. const meta = this.getDatasetMeta(index);
  5697. const args = {meta, index, mode, cancelable: true};
  5698. if (this.notifyPlugins('beforeDatasetUpdate', args) === false) {
  5699. return;
  5700. }
  5701. meta.controller._update(mode);
  5702. args.cancelable = false;
  5703. this.notifyPlugins('afterDatasetUpdate', args);
  5704. }
  5705. render() {
  5706. if (this.notifyPlugins('beforeRender', {cancelable: true}) === false) {
  5707. return;
  5708. }
  5709. if (animator.has(this)) {
  5710. if (this.attached && !animator.running(this)) {
  5711. animator.start(this);
  5712. }
  5713. } else {
  5714. this.draw();
  5715. onAnimationsComplete({chart: this});
  5716. }
  5717. }
  5718. draw() {
  5719. let i;
  5720. if (this._resizeBeforeDraw) {
  5721. const {width, height} = this._resizeBeforeDraw;
  5722. this._resize(width, height);
  5723. this._resizeBeforeDraw = null;
  5724. }
  5725. this.clear();
  5726. if (this.width <= 0 || this.height <= 0) {
  5727. return;
  5728. }
  5729. if (this.notifyPlugins('beforeDraw', {cancelable: true}) === false) {
  5730. return;
  5731. }
  5732. const layers = this._layers;
  5733. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  5734. layers[i].draw(this.chartArea);
  5735. }
  5736. this._drawDatasets();
  5737. for (; i < layers.length; ++i) {
  5738. layers[i].draw(this.chartArea);
  5739. }
  5740. this.notifyPlugins('afterDraw');
  5741. }
  5742. _getSortedDatasetMetas(filterVisible) {
  5743. const metasets = this._sortedMetasets;
  5744. const result = [];
  5745. let i, ilen;
  5746. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  5747. const meta = metasets[i];
  5748. if (!filterVisible || meta.visible) {
  5749. result.push(meta);
  5750. }
  5751. }
  5752. return result;
  5753. }
  5754. getSortedVisibleDatasetMetas() {
  5755. return this._getSortedDatasetMetas(true);
  5756. }
  5757. _drawDatasets() {
  5758. if (this.notifyPlugins('beforeDatasetsDraw', {cancelable: true}) === false) {
  5759. return;
  5760. }
  5761. const metasets = this.getSortedVisibleDatasetMetas();
  5762. for (let i = metasets.length - 1; i >= 0; --i) {
  5763. this._drawDataset(metasets[i]);
  5764. }
  5765. this.notifyPlugins('afterDatasetsDraw');
  5766. }
  5767. _drawDataset(meta) {
  5768. const ctx = this.ctx;
  5769. const clip = meta._clip;
  5770. const useClip = !clip.disabled;
  5771. const area = this.chartArea;
  5772. const args = {
  5773. meta,
  5774. index: meta.index,
  5775. cancelable: true
  5776. };
  5777. if (this.notifyPlugins('beforeDatasetDraw', args) === false) {
  5778. return;
  5779. }
  5780. if (useClip) {
  5781. clipArea(ctx, {
  5782. left: clip.left === false ? 0 : area.left - clip.left,
  5783. right: clip.right === false ? this.width : area.right + clip.right,
  5784. top: clip.top === false ? 0 : area.top - clip.top,
  5785. bottom: clip.bottom === false ? this.height : area.bottom + clip.bottom
  5786. });
  5787. }
  5788. meta.controller.draw();
  5789. if (useClip) {
  5790. unclipArea(ctx);
  5791. }
  5792. args.cancelable = false;
  5793. this.notifyPlugins('afterDatasetDraw', args);
  5794. }
  5795. isPointInArea(point) {
  5796. return _isPointInArea(point, this.chartArea, this._minPadding);
  5797. }
  5798. getElementsAtEventForMode(e, mode, options, useFinalPosition) {
  5799. const method = Interaction.modes[mode];
  5800. if (typeof method === 'function') {
  5801. return method(this, e, options, useFinalPosition);
  5802. }
  5803. return [];
  5804. }
  5805. getDatasetMeta(datasetIndex) {
  5806. const dataset = this.data.datasets[datasetIndex];
  5807. const metasets = this._metasets;
  5808. let meta = metasets.filter(x => x && x._dataset === dataset).pop();
  5809. if (!meta) {
  5810. meta = {
  5811. type: null,
  5812. data: [],
  5813. dataset: null,
  5814. controller: null,
  5815. hidden: null,
  5816. xAxisID: null,
  5817. yAxisID: null,
  5818. order: dataset && dataset.order || 0,
  5819. index: datasetIndex,
  5820. _dataset: dataset,
  5821. _parsed: [],
  5822. _sorted: false
  5823. };
  5824. metasets.push(meta);
  5825. }
  5826. return meta;
  5827. }
  5828. getContext() {
  5829. return this.$context || (this.$context = createContext(null, {chart: this, type: 'chart'}));
  5830. }
  5831. getVisibleDatasetCount() {
  5832. return this.getSortedVisibleDatasetMetas().length;
  5833. }
  5834. isDatasetVisible(datasetIndex) {
  5835. const dataset = this.data.datasets[datasetIndex];
  5836. if (!dataset) {
  5837. return false;
  5838. }
  5839. const meta = this.getDatasetMeta(datasetIndex);
  5840. return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;
  5841. }
  5842. setDatasetVisibility(datasetIndex, visible) {
  5843. const meta = this.getDatasetMeta(datasetIndex);
  5844. meta.hidden = !visible;
  5845. }
  5846. toggleDataVisibility(index) {
  5847. this._hiddenIndices[index] = !this._hiddenIndices[index];
  5848. }
  5849. getDataVisibility(index) {
  5850. return !this._hiddenIndices[index];
  5851. }
  5852. _updateVisibility(datasetIndex, dataIndex, visible) {
  5853. const mode = visible ? 'show' : 'hide';
  5854. const meta = this.getDatasetMeta(datasetIndex);
  5855. const anims = meta.controller._resolveAnimations(undefined, mode);
  5856. if (defined(dataIndex)) {
  5857. meta.data[dataIndex].hidden = !visible;
  5858. this.update();
  5859. } else {
  5860. this.setDatasetVisibility(datasetIndex, visible);
  5861. anims.update(meta, {visible});
  5862. this.update((ctx) => ctx.datasetIndex === datasetIndex ? mode : undefined);
  5863. }
  5864. }
  5865. hide(datasetIndex, dataIndex) {
  5866. this._updateVisibility(datasetIndex, dataIndex, false);
  5867. }
  5868. show(datasetIndex, dataIndex) {
  5869. this._updateVisibility(datasetIndex, dataIndex, true);
  5870. }
  5871. _destroyDatasetMeta(datasetIndex) {
  5872. const meta = this._metasets[datasetIndex];
  5873. if (meta && meta.controller) {
  5874. meta.controller._destroy();
  5875. }
  5876. delete this._metasets[datasetIndex];
  5877. }
  5878. _stop() {
  5879. let i, ilen;
  5880. this.stop();
  5881. animator.remove(this);
  5882. for (i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  5883. this._destroyDatasetMeta(i);
  5884. }
  5885. }
  5886. destroy() {
  5887. this.notifyPlugins('beforeDestroy');
  5888. const {canvas, ctx} = this;
  5889. this._stop();
  5890. this.config.clearCache();
  5891. if (canvas) {
  5892. this.unbindEvents();
  5893. clearCanvas(canvas, ctx);
  5894. this.platform.releaseContext(ctx);
  5895. this.canvas = null;
  5896. this.ctx = null;
  5897. }
  5898. this.notifyPlugins('destroy');
  5899. delete instances[this.id];
  5900. this.notifyPlugins('afterDestroy');
  5901. }
  5902. toBase64Image(...args) {
  5903. return this.canvas.toDataURL(...args);
  5904. }
  5905. bindEvents() {
  5906. this.bindUserEvents();
  5907. if (this.options.responsive) {
  5908. this.bindResponsiveEvents();
  5909. } else {
  5910. this.attached = true;
  5911. }
  5912. }
  5913. bindUserEvents() {
  5914. const listeners = this._listeners;
  5915. const platform = this.platform;
  5916. const _add = (type, listener) => {
  5917. platform.addEventListener(this, type, listener);
  5918. listeners[type] = listener;
  5919. };
  5920. const listener = (e, x, y) => {
  5921. e.offsetX = x;
  5922. e.offsetY = y;
  5923. this._eventHandler(e);
  5924. };
  5925. each(this.options.events, (type) => _add(type, listener));
  5926. }
  5927. bindResponsiveEvents() {
  5928. if (!this._responsiveListeners) {
  5929. this._responsiveListeners = {};
  5930. }
  5931. const listeners = this._responsiveListeners;
  5932. const platform = this.platform;
  5933. const _add = (type, listener) => {
  5934. platform.addEventListener(this, type, listener);
  5935. listeners[type] = listener;
  5936. };
  5937. const _remove = (type, listener) => {
  5938. if (listeners[type]) {
  5939. platform.removeEventListener(this, type, listener);
  5940. delete listeners[type];
  5941. }
  5942. };
  5943. const listener = (width, height) => {
  5944. if (this.canvas) {
  5945. this.resize(width, height);
  5946. }
  5947. };
  5948. let detached;
  5949. const attached = () => {
  5950. _remove('attach', attached);
  5951. this.attached = true;
  5952. this.resize();
  5953. _add('resize', listener);
  5954. _add('detach', detached);
  5955. };
  5956. detached = () => {
  5957. this.attached = false;
  5958. _remove('resize', listener);
  5959. this._stop();
  5960. this._resize(0, 0);
  5961. _add('attach', attached);
  5962. };
  5963. if (platform.isAttached(this.canvas)) {
  5964. attached();
  5965. } else {
  5966. detached();
  5967. }
  5968. }
  5969. unbindEvents() {
  5970. each(this._listeners, (listener, type) => {
  5971. this.platform.removeEventListener(this, type, listener);
  5972. });
  5973. this._listeners = {};
  5974. each(this._responsiveListeners, (listener, type) => {
  5975. this.platform.removeEventListener(this, type, listener);
  5976. });
  5977. this._responsiveListeners = undefined;
  5978. }
  5979. updateHoverStyle(items, mode, enabled) {
  5980. const prefix = enabled ? 'set' : 'remove';
  5981. let meta, item, i, ilen;
  5982. if (mode === 'dataset') {
  5983. meta = this.getDatasetMeta(items[0].datasetIndex);
  5984. meta.controller['_' + prefix + 'DatasetHoverStyle']();
  5985. }
  5986. for (i = 0, ilen = items.length; i < ilen; ++i) {
  5987. item = items[i];
  5988. const controller = item && this.getDatasetMeta(item.datasetIndex).controller;
  5989. if (controller) {
  5990. controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
  5991. }
  5992. }
  5993. }
  5994. getActiveElements() {
  5995. return this._active || [];
  5996. }
  5997. setActiveElements(activeElements) {
  5998. const lastActive = this._active || [];
  5999. const active = activeElements.map(({datasetIndex, index}) => {
  6000. const meta = this.getDatasetMeta(datasetIndex);
  6001. if (!meta) {
  6002. throw new Error('No dataset found at index ' + datasetIndex);
  6003. }
  6004. return {
  6005. datasetIndex,
  6006. element: meta.data[index],
  6007. index,
  6008. };
  6009. });
  6010. const changed = !_elementsEqual(active, lastActive);
  6011. if (changed) {
  6012. this._active = active;
  6013. this._lastEvent = null;
  6014. this._updateHoverStyles(active, lastActive);
  6015. }
  6016. }
  6017. notifyPlugins(hook, args, filter) {
  6018. return this._plugins.notify(this, hook, args, filter);
  6019. }
  6020. _updateHoverStyles(active, lastActive, replay) {
  6021. const hoverOptions = this.options.hover;
  6022. const diff = (a, b) => a.filter(x => !b.some(y => x.datasetIndex === y.datasetIndex && x.index === y.index));
  6023. const deactivated = diff(lastActive, active);
  6024. const activated = replay ? active : diff(active, lastActive);
  6025. if (deactivated.length) {
  6026. this.updateHoverStyle(deactivated, hoverOptions.mode, false);
  6027. }
  6028. if (activated.length && hoverOptions.mode) {
  6029. this.updateHoverStyle(activated, hoverOptions.mode, true);
  6030. }
  6031. }
  6032. _eventHandler(e, replay) {
  6033. const args = {
  6034. event: e,
  6035. replay,
  6036. cancelable: true,
  6037. inChartArea: this.isPointInArea(e)
  6038. };
  6039. const eventFilter = (plugin) => (plugin.options.events || this.options.events).includes(e.native.type);
  6040. if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) {
  6041. return;
  6042. }
  6043. const changed = this._handleEvent(e, replay, args.inChartArea);
  6044. args.cancelable = false;
  6045. this.notifyPlugins('afterEvent', args, eventFilter);
  6046. if (changed || args.changed) {
  6047. this.render();
  6048. }
  6049. return this;
  6050. }
  6051. _handleEvent(e, replay, inChartArea) {
  6052. const {_active: lastActive = [], options} = this;
  6053. const useFinalPosition = replay;
  6054. const active = this._getActiveElements(e, lastActive, inChartArea, useFinalPosition);
  6055. const isClick = _isClickEvent(e);
  6056. const lastEvent = determineLastEvent(e, this._lastEvent, inChartArea, isClick);
  6057. if (inChartArea) {
  6058. this._lastEvent = null;
  6059. callback(options.onHover, [e, active, this], this);
  6060. if (isClick) {
  6061. callback(options.onClick, [e, active, this], this);
  6062. }
  6063. }
  6064. const changed = !_elementsEqual(active, lastActive);
  6065. if (changed || replay) {
  6066. this._active = active;
  6067. this._updateHoverStyles(active, lastActive, replay);
  6068. }
  6069. this._lastEvent = lastEvent;
  6070. return changed;
  6071. }
  6072. _getActiveElements(e, lastActive, inChartArea, useFinalPosition) {
  6073. if (e.type === 'mouseout') {
  6074. return [];
  6075. }
  6076. if (!inChartArea) {
  6077. return lastActive;
  6078. }
  6079. const hoverOptions = this.options.hover;
  6080. return this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);
  6081. }
  6082. }
  6083. const invalidatePlugins = () => each(Chart.instances, (chart) => chart._plugins.invalidate());
  6084. const enumerable = true;
  6085. Object.defineProperties(Chart, {
  6086. defaults: {
  6087. enumerable,
  6088. value: defaults
  6089. },
  6090. instances: {
  6091. enumerable,
  6092. value: instances
  6093. },
  6094. overrides: {
  6095. enumerable,
  6096. value: overrides
  6097. },
  6098. registry: {
  6099. enumerable,
  6100. value: registry
  6101. },
  6102. version: {
  6103. enumerable,
  6104. value: version
  6105. },
  6106. getChart: {
  6107. enumerable,
  6108. value: getChart
  6109. },
  6110. register: {
  6111. enumerable,
  6112. value: (...items) => {
  6113. registry.add(...items);
  6114. invalidatePlugins();
  6115. }
  6116. },
  6117. unregister: {
  6118. enumerable,
  6119. value: (...items) => {
  6120. registry.remove(...items);
  6121. invalidatePlugins();
  6122. }
  6123. }
  6124. });
  6125. function clipArc(ctx, element, endAngle) {
  6126. const {startAngle, pixelMargin, x, y, outerRadius, innerRadius} = element;
  6127. let angleMargin = pixelMargin / outerRadius;
  6128. ctx.beginPath();
  6129. ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  6130. if (innerRadius > pixelMargin) {
  6131. angleMargin = pixelMargin / innerRadius;
  6132. ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);
  6133. } else {
  6134. ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI);
  6135. }
  6136. ctx.closePath();
  6137. ctx.clip();
  6138. }
  6139. function toRadiusCorners(value) {
  6140. return _readValueToProps(value, ['outerStart', 'outerEnd', 'innerStart', 'innerEnd']);
  6141. }
  6142. function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) {
  6143. const o = toRadiusCorners(arc.options.borderRadius);
  6144. const halfThickness = (outerRadius - innerRadius) / 2;
  6145. const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);
  6146. const computeOuterLimit = (val) => {
  6147. const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;
  6148. return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit));
  6149. };
  6150. return {
  6151. outerStart: computeOuterLimit(o.outerStart),
  6152. outerEnd: computeOuterLimit(o.outerEnd),
  6153. innerStart: _limitValue(o.innerStart, 0, innerLimit),
  6154. innerEnd: _limitValue(o.innerEnd, 0, innerLimit),
  6155. };
  6156. }
  6157. function rThetaToXY(r, theta, x, y) {
  6158. return {
  6159. x: x + r * Math.cos(theta),
  6160. y: y + r * Math.sin(theta),
  6161. };
  6162. }
  6163. function pathArc(ctx, element, offset, spacing, end) {
  6164. const {x, y, startAngle: start, pixelMargin, innerRadius: innerR} = element;
  6165. const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0);
  6166. const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0;
  6167. let spacingOffset = 0;
  6168. const alpha = end - start;
  6169. if (spacing) {
  6170. const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;
  6171. const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;
  6172. const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;
  6173. const adjustedAngle = avNogSpacingRadius !== 0 ? (alpha * avNogSpacingRadius) / (avNogSpacingRadius + spacing) : alpha;
  6174. spacingOffset = (alpha - adjustedAngle) / 2;
  6175. }
  6176. const beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius;
  6177. const angleOffset = (alpha - beta) / 2;
  6178. const startAngle = start + angleOffset + spacingOffset;
  6179. const endAngle = end - angleOffset - spacingOffset;
  6180. const {outerStart, outerEnd, innerStart, innerEnd} = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle);
  6181. const outerStartAdjustedRadius = outerRadius - outerStart;
  6182. const outerEndAdjustedRadius = outerRadius - outerEnd;
  6183. const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;
  6184. const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;
  6185. const innerStartAdjustedRadius = innerRadius + innerStart;
  6186. const innerEndAdjustedRadius = innerRadius + innerEnd;
  6187. const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;
  6188. const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;
  6189. ctx.beginPath();
  6190. ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerEndAdjustedAngle);
  6191. if (outerEnd > 0) {
  6192. const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);
  6193. ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);
  6194. }
  6195. const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);
  6196. ctx.lineTo(p4.x, p4.y);
  6197. if (innerEnd > 0) {
  6198. const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);
  6199. ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);
  6200. }
  6201. ctx.arc(x, y, innerRadius, endAngle - (innerEnd / innerRadius), startAngle + (innerStart / innerRadius), true);
  6202. if (innerStart > 0) {
  6203. const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);
  6204. ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);
  6205. }
  6206. const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);
  6207. ctx.lineTo(p8.x, p8.y);
  6208. if (outerStart > 0) {
  6209. const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);
  6210. ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);
  6211. }
  6212. ctx.closePath();
  6213. }
  6214. function drawArc(ctx, element, offset, spacing) {
  6215. const {fullCircles, startAngle, circumference} = element;
  6216. let endAngle = element.endAngle;
  6217. if (fullCircles) {
  6218. pathArc(ctx, element, offset, spacing, startAngle + TAU);
  6219. for (let i = 0; i < fullCircles; ++i) {
  6220. ctx.fill();
  6221. }
  6222. if (!isNaN(circumference)) {
  6223. endAngle = startAngle + circumference % TAU;
  6224. if (circumference % TAU === 0) {
  6225. endAngle += TAU;
  6226. }
  6227. }
  6228. }
  6229. pathArc(ctx, element, offset, spacing, endAngle);
  6230. ctx.fill();
  6231. return endAngle;
  6232. }
  6233. function drawFullCircleBorders(ctx, element, inner) {
  6234. const {x, y, startAngle, pixelMargin, fullCircles} = element;
  6235. const outerRadius = Math.max(element.outerRadius - pixelMargin, 0);
  6236. const innerRadius = element.innerRadius + pixelMargin;
  6237. let i;
  6238. if (inner) {
  6239. clipArc(ctx, element, startAngle + TAU);
  6240. }
  6241. ctx.beginPath();
  6242. ctx.arc(x, y, innerRadius, startAngle + TAU, startAngle, true);
  6243. for (i = 0; i < fullCircles; ++i) {
  6244. ctx.stroke();
  6245. }
  6246. ctx.beginPath();
  6247. ctx.arc(x, y, outerRadius, startAngle, startAngle + TAU);
  6248. for (i = 0; i < fullCircles; ++i) {
  6249. ctx.stroke();
  6250. }
  6251. }
  6252. function drawBorder(ctx, element, offset, spacing, endAngle) {
  6253. const {options} = element;
  6254. const {borderWidth, borderJoinStyle} = options;
  6255. const inner = options.borderAlign === 'inner';
  6256. if (!borderWidth) {
  6257. return;
  6258. }
  6259. if (inner) {
  6260. ctx.lineWidth = borderWidth * 2;
  6261. ctx.lineJoin = borderJoinStyle || 'round';
  6262. } else {
  6263. ctx.lineWidth = borderWidth;
  6264. ctx.lineJoin = borderJoinStyle || 'bevel';
  6265. }
  6266. if (element.fullCircles) {
  6267. drawFullCircleBorders(ctx, element, inner);
  6268. }
  6269. if (inner) {
  6270. clipArc(ctx, element, endAngle);
  6271. }
  6272. pathArc(ctx, element, offset, spacing, endAngle);
  6273. ctx.stroke();
  6274. }
  6275. class ArcElement extends Element {
  6276. constructor(cfg) {
  6277. super();
  6278. this.options = undefined;
  6279. this.circumference = undefined;
  6280. this.startAngle = undefined;
  6281. this.endAngle = undefined;
  6282. this.innerRadius = undefined;
  6283. this.outerRadius = undefined;
  6284. this.pixelMargin = 0;
  6285. this.fullCircles = 0;
  6286. if (cfg) {
  6287. Object.assign(this, cfg);
  6288. }
  6289. }
  6290. inRange(chartX, chartY, useFinalPosition) {
  6291. const point = this.getProps(['x', 'y'], useFinalPosition);
  6292. const {angle, distance} = getAngleFromPoint(point, {x: chartX, y: chartY});
  6293. const {startAngle, endAngle, innerRadius, outerRadius, circumference} = this.getProps([
  6294. 'startAngle',
  6295. 'endAngle',
  6296. 'innerRadius',
  6297. 'outerRadius',
  6298. 'circumference'
  6299. ], useFinalPosition);
  6300. const rAdjust = this.options.spacing / 2;
  6301. const _circumference = valueOrDefault(circumference, endAngle - startAngle);
  6302. const betweenAngles = _circumference >= TAU || _angleBetween(angle, startAngle, endAngle);
  6303. const withinRadius = _isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust);
  6304. return (betweenAngles && withinRadius);
  6305. }
  6306. getCenterPoint(useFinalPosition) {
  6307. const {x, y, startAngle, endAngle, innerRadius, outerRadius} = this.getProps([
  6308. 'x',
  6309. 'y',
  6310. 'startAngle',
  6311. 'endAngle',
  6312. 'innerRadius',
  6313. 'outerRadius',
  6314. 'circumference',
  6315. ], useFinalPosition);
  6316. const {offset, spacing} = this.options;
  6317. const halfAngle = (startAngle + endAngle) / 2;
  6318. const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2;
  6319. return {
  6320. x: x + Math.cos(halfAngle) * halfRadius,
  6321. y: y + Math.sin(halfAngle) * halfRadius
  6322. };
  6323. }
  6324. tooltipPosition(useFinalPosition) {
  6325. return this.getCenterPoint(useFinalPosition);
  6326. }
  6327. draw(ctx) {
  6328. const {options, circumference} = this;
  6329. const offset = (options.offset || 0) / 2;
  6330. const spacing = (options.spacing || 0) / 2;
  6331. this.pixelMargin = (options.borderAlign === 'inner') ? 0.33 : 0;
  6332. this.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0;
  6333. if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) {
  6334. return;
  6335. }
  6336. ctx.save();
  6337. let radiusOffset = 0;
  6338. if (offset) {
  6339. radiusOffset = offset / 2;
  6340. const halfAngle = (this.startAngle + this.endAngle) / 2;
  6341. ctx.translate(Math.cos(halfAngle) * radiusOffset, Math.sin(halfAngle) * radiusOffset);
  6342. if (this.circumference >= PI) {
  6343. radiusOffset = offset;
  6344. }
  6345. }
  6346. ctx.fillStyle = options.backgroundColor;
  6347. ctx.strokeStyle = options.borderColor;
  6348. const endAngle = drawArc(ctx, this, radiusOffset, spacing);
  6349. drawBorder(ctx, this, radiusOffset, spacing, endAngle);
  6350. ctx.restore();
  6351. }
  6352. }
  6353. ArcElement.id = 'arc';
  6354. ArcElement.defaults = {
  6355. borderAlign: 'center',
  6356. borderColor: '#fff',
  6357. borderJoinStyle: undefined,
  6358. borderRadius: 0,
  6359. borderWidth: 2,
  6360. offset: 0,
  6361. spacing: 0,
  6362. angle: undefined,
  6363. };
  6364. ArcElement.defaultRoutes = {
  6365. backgroundColor: 'backgroundColor'
  6366. };
  6367. function setStyle(ctx, options, style = options) {
  6368. ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle);
  6369. ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash));
  6370. ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset);
  6371. ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);
  6372. ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth);
  6373. ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor);
  6374. }
  6375. function lineTo(ctx, previous, target) {
  6376. ctx.lineTo(target.x, target.y);
  6377. }
  6378. function getLineMethod(options) {
  6379. if (options.stepped) {
  6380. return _steppedLineTo;
  6381. }
  6382. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  6383. return _bezierCurveTo;
  6384. }
  6385. return lineTo;
  6386. }
  6387. function pathVars(points, segment, params = {}) {
  6388. const count = points.length;
  6389. const {start: paramsStart = 0, end: paramsEnd = count - 1} = params;
  6390. const {start: segmentStart, end: segmentEnd} = segment;
  6391. const start = Math.max(paramsStart, segmentStart);
  6392. const end = Math.min(paramsEnd, segmentEnd);
  6393. const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;
  6394. return {
  6395. count,
  6396. start,
  6397. loop: segment.loop,
  6398. ilen: end < start && !outside ? count + end - start : end - start
  6399. };
  6400. }
  6401. function pathSegment(ctx, line, segment, params) {
  6402. const {points, options} = line;
  6403. const {count, start, loop, ilen} = pathVars(points, segment, params);
  6404. const lineMethod = getLineMethod(options);
  6405. let {move = true, reverse} = params || {};
  6406. let i, point, prev;
  6407. for (i = 0; i <= ilen; ++i) {
  6408. point = points[(start + (reverse ? ilen - i : i)) % count];
  6409. if (point.skip) {
  6410. continue;
  6411. } else if (move) {
  6412. ctx.moveTo(point.x, point.y);
  6413. move = false;
  6414. } else {
  6415. lineMethod(ctx, prev, point, reverse, options.stepped);
  6416. }
  6417. prev = point;
  6418. }
  6419. if (loop) {
  6420. point = points[(start + (reverse ? ilen : 0)) % count];
  6421. lineMethod(ctx, prev, point, reverse, options.stepped);
  6422. }
  6423. return !!loop;
  6424. }
  6425. function fastPathSegment(ctx, line, segment, params) {
  6426. const points = line.points;
  6427. const {count, start, ilen} = pathVars(points, segment, params);
  6428. const {move = true, reverse} = params || {};
  6429. let avgX = 0;
  6430. let countX = 0;
  6431. let i, point, prevX, minY, maxY, lastY;
  6432. const pointIndex = (index) => (start + (reverse ? ilen - index : index)) % count;
  6433. const drawX = () => {
  6434. if (minY !== maxY) {
  6435. ctx.lineTo(avgX, maxY);
  6436. ctx.lineTo(avgX, minY);
  6437. ctx.lineTo(avgX, lastY);
  6438. }
  6439. };
  6440. if (move) {
  6441. point = points[pointIndex(0)];
  6442. ctx.moveTo(point.x, point.y);
  6443. }
  6444. for (i = 0; i <= ilen; ++i) {
  6445. point = points[pointIndex(i)];
  6446. if (point.skip) {
  6447. continue;
  6448. }
  6449. const x = point.x;
  6450. const y = point.y;
  6451. const truncX = x | 0;
  6452. if (truncX === prevX) {
  6453. if (y < minY) {
  6454. minY = y;
  6455. } else if (y > maxY) {
  6456. maxY = y;
  6457. }
  6458. avgX = (countX * avgX + x) / ++countX;
  6459. } else {
  6460. drawX();
  6461. ctx.lineTo(x, y);
  6462. prevX = truncX;
  6463. countX = 0;
  6464. minY = maxY = y;
  6465. }
  6466. lastY = y;
  6467. }
  6468. drawX();
  6469. }
  6470. function _getSegmentMethod(line) {
  6471. const opts = line.options;
  6472. const borderDash = opts.borderDash && opts.borderDash.length;
  6473. const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;
  6474. return useFastPath ? fastPathSegment : pathSegment;
  6475. }
  6476. function _getInterpolationMethod(options) {
  6477. if (options.stepped) {
  6478. return _steppedInterpolation;
  6479. }
  6480. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  6481. return _bezierInterpolation;
  6482. }
  6483. return _pointInLine;
  6484. }
  6485. function strokePathWithCache(ctx, line, start, count) {
  6486. let path = line._path;
  6487. if (!path) {
  6488. path = line._path = new Path2D();
  6489. if (line.path(path, start, count)) {
  6490. path.closePath();
  6491. }
  6492. }
  6493. setStyle(ctx, line.options);
  6494. ctx.stroke(path);
  6495. }
  6496. function strokePathDirect(ctx, line, start, count) {
  6497. const {segments, options} = line;
  6498. const segmentMethod = _getSegmentMethod(line);
  6499. for (const segment of segments) {
  6500. setStyle(ctx, options, segment.style);
  6501. ctx.beginPath();
  6502. if (segmentMethod(ctx, line, segment, {start, end: start + count - 1})) {
  6503. ctx.closePath();
  6504. }
  6505. ctx.stroke();
  6506. }
  6507. }
  6508. const usePath2D = typeof Path2D === 'function';
  6509. function draw(ctx, line, start, count) {
  6510. if (usePath2D && !line.options.segment) {
  6511. strokePathWithCache(ctx, line, start, count);
  6512. } else {
  6513. strokePathDirect(ctx, line, start, count);
  6514. }
  6515. }
  6516. class LineElement extends Element {
  6517. constructor(cfg) {
  6518. super();
  6519. this.animated = true;
  6520. this.options = undefined;
  6521. this._chart = undefined;
  6522. this._loop = undefined;
  6523. this._fullLoop = undefined;
  6524. this._path = undefined;
  6525. this._points = undefined;
  6526. this._segments = undefined;
  6527. this._decimated = false;
  6528. this._pointsUpdated = false;
  6529. this._datasetIndex = undefined;
  6530. if (cfg) {
  6531. Object.assign(this, cfg);
  6532. }
  6533. }
  6534. updateControlPoints(chartArea, indexAxis) {
  6535. const options = this.options;
  6536. if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) {
  6537. const loop = options.spanGaps ? this._loop : this._fullLoop;
  6538. _updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis);
  6539. this._pointsUpdated = true;
  6540. }
  6541. }
  6542. set points(points) {
  6543. this._points = points;
  6544. delete this._segments;
  6545. delete this._path;
  6546. this._pointsUpdated = false;
  6547. }
  6548. get points() {
  6549. return this._points;
  6550. }
  6551. get segments() {
  6552. return this._segments || (this._segments = _computeSegments(this, this.options.segment));
  6553. }
  6554. first() {
  6555. const segments = this.segments;
  6556. const points = this.points;
  6557. return segments.length && points[segments[0].start];
  6558. }
  6559. last() {
  6560. const segments = this.segments;
  6561. const points = this.points;
  6562. const count = segments.length;
  6563. return count && points[segments[count - 1].end];
  6564. }
  6565. interpolate(point, property) {
  6566. const options = this.options;
  6567. const value = point[property];
  6568. const points = this.points;
  6569. const segments = _boundSegments(this, {property, start: value, end: value});
  6570. if (!segments.length) {
  6571. return;
  6572. }
  6573. const result = [];
  6574. const _interpolate = _getInterpolationMethod(options);
  6575. let i, ilen;
  6576. for (i = 0, ilen = segments.length; i < ilen; ++i) {
  6577. const {start, end} = segments[i];
  6578. const p1 = points[start];
  6579. const p2 = points[end];
  6580. if (p1 === p2) {
  6581. result.push(p1);
  6582. continue;
  6583. }
  6584. const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));
  6585. const interpolated = _interpolate(p1, p2, t, options.stepped);
  6586. interpolated[property] = point[property];
  6587. result.push(interpolated);
  6588. }
  6589. return result.length === 1 ? result[0] : result;
  6590. }
  6591. pathSegment(ctx, segment, params) {
  6592. const segmentMethod = _getSegmentMethod(this);
  6593. return segmentMethod(ctx, this, segment, params);
  6594. }
  6595. path(ctx, start, count) {
  6596. const segments = this.segments;
  6597. const segmentMethod = _getSegmentMethod(this);
  6598. let loop = this._loop;
  6599. start = start || 0;
  6600. count = count || (this.points.length - start);
  6601. for (const segment of segments) {
  6602. loop &= segmentMethod(ctx, this, segment, {start, end: start + count - 1});
  6603. }
  6604. return !!loop;
  6605. }
  6606. draw(ctx, chartArea, start, count) {
  6607. const options = this.options || {};
  6608. const points = this.points || [];
  6609. if (points.length && options.borderWidth) {
  6610. ctx.save();
  6611. draw(ctx, this, start, count);
  6612. ctx.restore();
  6613. }
  6614. if (this.animated) {
  6615. this._pointsUpdated = false;
  6616. this._path = undefined;
  6617. }
  6618. }
  6619. }
  6620. LineElement.id = 'line';
  6621. LineElement.defaults = {
  6622. borderCapStyle: 'butt',
  6623. borderDash: [],
  6624. borderDashOffset: 0,
  6625. borderJoinStyle: 'miter',
  6626. borderWidth: 3,
  6627. capBezierPoints: true,
  6628. cubicInterpolationMode: 'default',
  6629. fill: false,
  6630. spanGaps: false,
  6631. stepped: false,
  6632. tension: 0,
  6633. };
  6634. LineElement.defaultRoutes = {
  6635. backgroundColor: 'backgroundColor',
  6636. borderColor: 'borderColor'
  6637. };
  6638. LineElement.descriptors = {
  6639. _scriptable: true,
  6640. _indexable: (name) => name !== 'borderDash' && name !== 'fill',
  6641. };
  6642. function inRange$1(el, pos, axis, useFinalPosition) {
  6643. const options = el.options;
  6644. const {[axis]: value} = el.getProps([axis], useFinalPosition);
  6645. return (Math.abs(pos - value) < options.radius + options.hitRadius);
  6646. }
  6647. class PointElement extends Element {
  6648. constructor(cfg) {
  6649. super();
  6650. this.options = undefined;
  6651. this.parsed = undefined;
  6652. this.skip = undefined;
  6653. this.stop = undefined;
  6654. if (cfg) {
  6655. Object.assign(this, cfg);
  6656. }
  6657. }
  6658. inRange(mouseX, mouseY, useFinalPosition) {
  6659. const options = this.options;
  6660. const {x, y} = this.getProps(['x', 'y'], useFinalPosition);
  6661. return ((Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2)) < Math.pow(options.hitRadius + options.radius, 2));
  6662. }
  6663. inXRange(mouseX, useFinalPosition) {
  6664. return inRange$1(this, mouseX, 'x', useFinalPosition);
  6665. }
  6666. inYRange(mouseY, useFinalPosition) {
  6667. return inRange$1(this, mouseY, 'y', useFinalPosition);
  6668. }
  6669. getCenterPoint(useFinalPosition) {
  6670. const {x, y} = this.getProps(['x', 'y'], useFinalPosition);
  6671. return {x, y};
  6672. }
  6673. size(options) {
  6674. options = options || this.options || {};
  6675. let radius = options.radius || 0;
  6676. radius = Math.max(radius, radius && options.hoverRadius || 0);
  6677. const borderWidth = radius && options.borderWidth || 0;
  6678. return (radius + borderWidth) * 2;
  6679. }
  6680. draw(ctx, area) {
  6681. const options = this.options;
  6682. if (this.skip || options.radius < 0.1 || !_isPointInArea(this, area, this.size(options) / 2)) {
  6683. return;
  6684. }
  6685. ctx.strokeStyle = options.borderColor;
  6686. ctx.lineWidth = options.borderWidth;
  6687. ctx.fillStyle = options.backgroundColor;
  6688. drawPoint(ctx, options, this.x, this.y);
  6689. }
  6690. getRange() {
  6691. const options = this.options || {};
  6692. return options.radius + options.hitRadius;
  6693. }
  6694. }
  6695. PointElement.id = 'point';
  6696. PointElement.defaults = {
  6697. borderWidth: 1,
  6698. hitRadius: 1,
  6699. hoverBorderWidth: 1,
  6700. hoverRadius: 4,
  6701. pointStyle: 'circle',
  6702. radius: 3,
  6703. rotation: 0
  6704. };
  6705. PointElement.defaultRoutes = {
  6706. backgroundColor: 'backgroundColor',
  6707. borderColor: 'borderColor'
  6708. };
  6709. function getBarBounds(bar, useFinalPosition) {
  6710. const {x, y, base, width, height} = bar.getProps(['x', 'y', 'base', 'width', 'height'], useFinalPosition);
  6711. let left, right, top, bottom, half;
  6712. if (bar.horizontal) {
  6713. half = height / 2;
  6714. left = Math.min(x, base);
  6715. right = Math.max(x, base);
  6716. top = y - half;
  6717. bottom = y + half;
  6718. } else {
  6719. half = width / 2;
  6720. left = x - half;
  6721. right = x + half;
  6722. top = Math.min(y, base);
  6723. bottom = Math.max(y, base);
  6724. }
  6725. return {left, top, right, bottom};
  6726. }
  6727. function skipOrLimit(skip, value, min, max) {
  6728. return skip ? 0 : _limitValue(value, min, max);
  6729. }
  6730. function parseBorderWidth(bar, maxW, maxH) {
  6731. const value = bar.options.borderWidth;
  6732. const skip = bar.borderSkipped;
  6733. const o = toTRBL(value);
  6734. return {
  6735. t: skipOrLimit(skip.top, o.top, 0, maxH),
  6736. r: skipOrLimit(skip.right, o.right, 0, maxW),
  6737. b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),
  6738. l: skipOrLimit(skip.left, o.left, 0, maxW)
  6739. };
  6740. }
  6741. function parseBorderRadius(bar, maxW, maxH) {
  6742. const {enableBorderRadius} = bar.getProps(['enableBorderRadius']);
  6743. const value = bar.options.borderRadius;
  6744. const o = toTRBLCorners(value);
  6745. const maxR = Math.min(maxW, maxH);
  6746. const skip = bar.borderSkipped;
  6747. const enableBorder = enableBorderRadius || isObject(value);
  6748. return {
  6749. topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),
  6750. topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),
  6751. bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),
  6752. bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)
  6753. };
  6754. }
  6755. function boundingRects(bar) {
  6756. const bounds = getBarBounds(bar);
  6757. const width = bounds.right - bounds.left;
  6758. const height = bounds.bottom - bounds.top;
  6759. const border = parseBorderWidth(bar, width / 2, height / 2);
  6760. const radius = parseBorderRadius(bar, width / 2, height / 2);
  6761. return {
  6762. outer: {
  6763. x: bounds.left,
  6764. y: bounds.top,
  6765. w: width,
  6766. h: height,
  6767. radius
  6768. },
  6769. inner: {
  6770. x: bounds.left + border.l,
  6771. y: bounds.top + border.t,
  6772. w: width - border.l - border.r,
  6773. h: height - border.t - border.b,
  6774. radius: {
  6775. topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),
  6776. topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),
  6777. bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),
  6778. bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r)),
  6779. }
  6780. }
  6781. };
  6782. }
  6783. function inRange(bar, x, y, useFinalPosition) {
  6784. const skipX = x === null;
  6785. const skipY = y === null;
  6786. const skipBoth = skipX && skipY;
  6787. const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);
  6788. return bounds
  6789. && (skipX || _isBetween(x, bounds.left, bounds.right))
  6790. && (skipY || _isBetween(y, bounds.top, bounds.bottom));
  6791. }
  6792. function hasRadius(radius) {
  6793. return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;
  6794. }
  6795. function addNormalRectPath(ctx, rect) {
  6796. ctx.rect(rect.x, rect.y, rect.w, rect.h);
  6797. }
  6798. function inflateRect(rect, amount, refRect = {}) {
  6799. const x = rect.x !== refRect.x ? -amount : 0;
  6800. const y = rect.y !== refRect.y ? -amount : 0;
  6801. const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x;
  6802. const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y;
  6803. return {
  6804. x: rect.x + x,
  6805. y: rect.y + y,
  6806. w: rect.w + w,
  6807. h: rect.h + h,
  6808. radius: rect.radius
  6809. };
  6810. }
  6811. class BarElement extends Element {
  6812. constructor(cfg) {
  6813. super();
  6814. this.options = undefined;
  6815. this.horizontal = undefined;
  6816. this.base = undefined;
  6817. this.width = undefined;
  6818. this.height = undefined;
  6819. this.inflateAmount = undefined;
  6820. if (cfg) {
  6821. Object.assign(this, cfg);
  6822. }
  6823. }
  6824. draw(ctx) {
  6825. const {inflateAmount, options: {borderColor, backgroundColor}} = this;
  6826. const {inner, outer} = boundingRects(this);
  6827. const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath;
  6828. ctx.save();
  6829. if (outer.w !== inner.w || outer.h !== inner.h) {
  6830. ctx.beginPath();
  6831. addRectPath(ctx, inflateRect(outer, inflateAmount, inner));
  6832. ctx.clip();
  6833. addRectPath(ctx, inflateRect(inner, -inflateAmount, outer));
  6834. ctx.fillStyle = borderColor;
  6835. ctx.fill('evenodd');
  6836. }
  6837. ctx.beginPath();
  6838. addRectPath(ctx, inflateRect(inner, inflateAmount));
  6839. ctx.fillStyle = backgroundColor;
  6840. ctx.fill();
  6841. ctx.restore();
  6842. }
  6843. inRange(mouseX, mouseY, useFinalPosition) {
  6844. return inRange(this, mouseX, mouseY, useFinalPosition);
  6845. }
  6846. inXRange(mouseX, useFinalPosition) {
  6847. return inRange(this, mouseX, null, useFinalPosition);
  6848. }
  6849. inYRange(mouseY, useFinalPosition) {
  6850. return inRange(this, null, mouseY, useFinalPosition);
  6851. }
  6852. getCenterPoint(useFinalPosition) {
  6853. const {x, y, base, horizontal} = this.getProps(['x', 'y', 'base', 'horizontal'], useFinalPosition);
  6854. return {
  6855. x: horizontal ? (x + base) / 2 : x,
  6856. y: horizontal ? y : (y + base) / 2
  6857. };
  6858. }
  6859. getRange(axis) {
  6860. return axis === 'x' ? this.width / 2 : this.height / 2;
  6861. }
  6862. }
  6863. BarElement.id = 'bar';
  6864. BarElement.defaults = {
  6865. borderSkipped: 'start',
  6866. borderWidth: 0,
  6867. borderRadius: 0,
  6868. inflateAmount: 'auto',
  6869. pointStyle: undefined
  6870. };
  6871. BarElement.defaultRoutes = {
  6872. backgroundColor: 'backgroundColor',
  6873. borderColor: 'borderColor'
  6874. };
  6875. var elements = /*#__PURE__*/Object.freeze({
  6876. __proto__: null,
  6877. ArcElement: ArcElement,
  6878. LineElement: LineElement,
  6879. PointElement: PointElement,
  6880. BarElement: BarElement
  6881. });
  6882. function lttbDecimation(data, start, count, availableWidth, options) {
  6883. const samples = options.samples || availableWidth;
  6884. if (samples >= count) {
  6885. return data.slice(start, start + count);
  6886. }
  6887. const decimated = [];
  6888. const bucketWidth = (count - 2) / (samples - 2);
  6889. let sampledIndex = 0;
  6890. const endIndex = start + count - 1;
  6891. let a = start;
  6892. let i, maxAreaPoint, maxArea, area, nextA;
  6893. decimated[sampledIndex++] = data[a];
  6894. for (i = 0; i < samples - 2; i++) {
  6895. let avgX = 0;
  6896. let avgY = 0;
  6897. let j;
  6898. const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;
  6899. const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;
  6900. const avgRangeLength = avgRangeEnd - avgRangeStart;
  6901. for (j = avgRangeStart; j < avgRangeEnd; j++) {
  6902. avgX += data[j].x;
  6903. avgY += data[j].y;
  6904. }
  6905. avgX /= avgRangeLength;
  6906. avgY /= avgRangeLength;
  6907. const rangeOffs = Math.floor(i * bucketWidth) + 1 + start;
  6908. const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start;
  6909. const {x: pointAx, y: pointAy} = data[a];
  6910. maxArea = area = -1;
  6911. for (j = rangeOffs; j < rangeTo; j++) {
  6912. area = 0.5 * Math.abs(
  6913. (pointAx - avgX) * (data[j].y - pointAy) -
  6914. (pointAx - data[j].x) * (avgY - pointAy)
  6915. );
  6916. if (area > maxArea) {
  6917. maxArea = area;
  6918. maxAreaPoint = data[j];
  6919. nextA = j;
  6920. }
  6921. }
  6922. decimated[sampledIndex++] = maxAreaPoint;
  6923. a = nextA;
  6924. }
  6925. decimated[sampledIndex++] = data[endIndex];
  6926. return decimated;
  6927. }
  6928. function minMaxDecimation(data, start, count, availableWidth) {
  6929. let avgX = 0;
  6930. let countX = 0;
  6931. let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;
  6932. const decimated = [];
  6933. const endIndex = start + count - 1;
  6934. const xMin = data[start].x;
  6935. const xMax = data[endIndex].x;
  6936. const dx = xMax - xMin;
  6937. for (i = start; i < start + count; ++i) {
  6938. point = data[i];
  6939. x = (point.x - xMin) / dx * availableWidth;
  6940. y = point.y;
  6941. const truncX = x | 0;
  6942. if (truncX === prevX) {
  6943. if (y < minY) {
  6944. minY = y;
  6945. minIndex = i;
  6946. } else if (y > maxY) {
  6947. maxY = y;
  6948. maxIndex = i;
  6949. }
  6950. avgX = (countX * avgX + point.x) / ++countX;
  6951. } else {
  6952. const lastIndex = i - 1;
  6953. if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) {
  6954. const intermediateIndex1 = Math.min(minIndex, maxIndex);
  6955. const intermediateIndex2 = Math.max(minIndex, maxIndex);
  6956. if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {
  6957. decimated.push({
  6958. ...data[intermediateIndex1],
  6959. x: avgX,
  6960. });
  6961. }
  6962. if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {
  6963. decimated.push({
  6964. ...data[intermediateIndex2],
  6965. x: avgX
  6966. });
  6967. }
  6968. }
  6969. if (i > 0 && lastIndex !== startIndex) {
  6970. decimated.push(data[lastIndex]);
  6971. }
  6972. decimated.push(point);
  6973. prevX = truncX;
  6974. countX = 0;
  6975. minY = maxY = y;
  6976. minIndex = maxIndex = startIndex = i;
  6977. }
  6978. }
  6979. return decimated;
  6980. }
  6981. function cleanDecimatedDataset(dataset) {
  6982. if (dataset._decimated) {
  6983. const data = dataset._data;
  6984. delete dataset._decimated;
  6985. delete dataset._data;
  6986. Object.defineProperty(dataset, 'data', {value: data});
  6987. }
  6988. }
  6989. function cleanDecimatedData(chart) {
  6990. chart.data.datasets.forEach((dataset) => {
  6991. cleanDecimatedDataset(dataset);
  6992. });
  6993. }
  6994. function getStartAndCountOfVisiblePointsSimplified(meta, points) {
  6995. const pointCount = points.length;
  6996. let start = 0;
  6997. let count;
  6998. const {iScale} = meta;
  6999. const {min, max, minDefined, maxDefined} = iScale.getUserBounds();
  7000. if (minDefined) {
  7001. start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);
  7002. }
  7003. if (maxDefined) {
  7004. count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;
  7005. } else {
  7006. count = pointCount - start;
  7007. }
  7008. return {start, count};
  7009. }
  7010. var plugin_decimation = {
  7011. id: 'decimation',
  7012. defaults: {
  7013. algorithm: 'min-max',
  7014. enabled: false,
  7015. },
  7016. beforeElementsUpdate: (chart, args, options) => {
  7017. if (!options.enabled) {
  7018. cleanDecimatedData(chart);
  7019. return;
  7020. }
  7021. const availableWidth = chart.width;
  7022. chart.data.datasets.forEach((dataset, datasetIndex) => {
  7023. const {_data, indexAxis} = dataset;
  7024. const meta = chart.getDatasetMeta(datasetIndex);
  7025. const data = _data || dataset.data;
  7026. if (resolve([indexAxis, chart.options.indexAxis]) === 'y') {
  7027. return;
  7028. }
  7029. if (!meta.controller.supportsDecimation) {
  7030. return;
  7031. }
  7032. const xAxis = chart.scales[meta.xAxisID];
  7033. if (xAxis.type !== 'linear' && xAxis.type !== 'time') {
  7034. return;
  7035. }
  7036. if (chart.options.parsing) {
  7037. return;
  7038. }
  7039. let {start, count} = getStartAndCountOfVisiblePointsSimplified(meta, data);
  7040. const threshold = options.threshold || 4 * availableWidth;
  7041. if (count <= threshold) {
  7042. cleanDecimatedDataset(dataset);
  7043. return;
  7044. }
  7045. if (isNullOrUndef(_data)) {
  7046. dataset._data = data;
  7047. delete dataset.data;
  7048. Object.defineProperty(dataset, 'data', {
  7049. configurable: true,
  7050. enumerable: true,
  7051. get: function() {
  7052. return this._decimated;
  7053. },
  7054. set: function(d) {
  7055. this._data = d;
  7056. }
  7057. });
  7058. }
  7059. let decimated;
  7060. switch (options.algorithm) {
  7061. case 'lttb':
  7062. decimated = lttbDecimation(data, start, count, availableWidth, options);
  7063. break;
  7064. case 'min-max':
  7065. decimated = minMaxDecimation(data, start, count, availableWidth);
  7066. break;
  7067. default:
  7068. throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);
  7069. }
  7070. dataset._decimated = decimated;
  7071. });
  7072. },
  7073. destroy(chart) {
  7074. cleanDecimatedData(chart);
  7075. }
  7076. };
  7077. function _segments(line, target, property) {
  7078. const segments = line.segments;
  7079. const points = line.points;
  7080. const tpoints = target.points;
  7081. const parts = [];
  7082. for (const segment of segments) {
  7083. let {start, end} = segment;
  7084. end = _findSegmentEnd(start, end, points);
  7085. const bounds = _getBounds(property, points[start], points[end], segment.loop);
  7086. if (!target.segments) {
  7087. parts.push({
  7088. source: segment,
  7089. target: bounds,
  7090. start: points[start],
  7091. end: points[end]
  7092. });
  7093. continue;
  7094. }
  7095. const targetSegments = _boundSegments(target, bounds);
  7096. for (const tgt of targetSegments) {
  7097. const subBounds = _getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);
  7098. const fillSources = _boundSegment(segment, points, subBounds);
  7099. for (const fillSource of fillSources) {
  7100. parts.push({
  7101. source: fillSource,
  7102. target: tgt,
  7103. start: {
  7104. [property]: _getEdge(bounds, subBounds, 'start', Math.max)
  7105. },
  7106. end: {
  7107. [property]: _getEdge(bounds, subBounds, 'end', Math.min)
  7108. }
  7109. });
  7110. }
  7111. }
  7112. }
  7113. return parts;
  7114. }
  7115. function _getBounds(property, first, last, loop) {
  7116. if (loop) {
  7117. return;
  7118. }
  7119. let start = first[property];
  7120. let end = last[property];
  7121. if (property === 'angle') {
  7122. start = _normalizeAngle(start);
  7123. end = _normalizeAngle(end);
  7124. }
  7125. return {property, start, end};
  7126. }
  7127. function _pointsFromSegments(boundary, line) {
  7128. const {x = null, y = null} = boundary || {};
  7129. const linePoints = line.points;
  7130. const points = [];
  7131. line.segments.forEach(({start, end}) => {
  7132. end = _findSegmentEnd(start, end, linePoints);
  7133. const first = linePoints[start];
  7134. const last = linePoints[end];
  7135. if (y !== null) {
  7136. points.push({x: first.x, y});
  7137. points.push({x: last.x, y});
  7138. } else if (x !== null) {
  7139. points.push({x, y: first.y});
  7140. points.push({x, y: last.y});
  7141. }
  7142. });
  7143. return points;
  7144. }
  7145. function _findSegmentEnd(start, end, points) {
  7146. for (;end > start; end--) {
  7147. const point = points[end];
  7148. if (!isNaN(point.x) && !isNaN(point.y)) {
  7149. break;
  7150. }
  7151. }
  7152. return end;
  7153. }
  7154. function _getEdge(a, b, prop, fn) {
  7155. if (a && b) {
  7156. return fn(a[prop], b[prop]);
  7157. }
  7158. return a ? a[prop] : b ? b[prop] : 0;
  7159. }
  7160. function _createBoundaryLine(boundary, line) {
  7161. let points = [];
  7162. let _loop = false;
  7163. if (isArray(boundary)) {
  7164. _loop = true;
  7165. points = boundary;
  7166. } else {
  7167. points = _pointsFromSegments(boundary, line);
  7168. }
  7169. return points.length ? new LineElement({
  7170. points,
  7171. options: {tension: 0},
  7172. _loop,
  7173. _fullLoop: _loop
  7174. }) : null;
  7175. }
  7176. function _resolveTarget(sources, index, propagate) {
  7177. const source = sources[index];
  7178. let fill = source.fill;
  7179. const visited = [index];
  7180. let target;
  7181. if (!propagate) {
  7182. return fill;
  7183. }
  7184. while (fill !== false && visited.indexOf(fill) === -1) {
  7185. if (!isNumberFinite(fill)) {
  7186. return fill;
  7187. }
  7188. target = sources[fill];
  7189. if (!target) {
  7190. return false;
  7191. }
  7192. if (target.visible) {
  7193. return fill;
  7194. }
  7195. visited.push(fill);
  7196. fill = target.fill;
  7197. }
  7198. return false;
  7199. }
  7200. function _decodeFill(line, index, count) {
  7201. const fill = parseFillOption(line);
  7202. if (isObject(fill)) {
  7203. return isNaN(fill.value) ? false : fill;
  7204. }
  7205. let target = parseFloat(fill);
  7206. if (isNumberFinite(target) && Math.floor(target) === target) {
  7207. return decodeTargetIndex(fill[0], index, target, count);
  7208. }
  7209. return ['origin', 'start', 'end', 'stack', 'shape'].indexOf(fill) >= 0 && fill;
  7210. }
  7211. function decodeTargetIndex(firstCh, index, target, count) {
  7212. if (firstCh === '-' || firstCh === '+') {
  7213. target = index + target;
  7214. }
  7215. if (target === index || target < 0 || target >= count) {
  7216. return false;
  7217. }
  7218. return target;
  7219. }
  7220. function _getTargetPixel(fill, scale) {
  7221. let pixel = null;
  7222. if (fill === 'start') {
  7223. pixel = scale.bottom;
  7224. } else if (fill === 'end') {
  7225. pixel = scale.top;
  7226. } else if (isObject(fill)) {
  7227. pixel = scale.getPixelForValue(fill.value);
  7228. } else if (scale.getBasePixel) {
  7229. pixel = scale.getBasePixel();
  7230. }
  7231. return pixel;
  7232. }
  7233. function _getTargetValue(fill, scale, startValue) {
  7234. let value;
  7235. if (fill === 'start') {
  7236. value = startValue;
  7237. } else if (fill === 'end') {
  7238. value = scale.options.reverse ? scale.min : scale.max;
  7239. } else if (isObject(fill)) {
  7240. value = fill.value;
  7241. } else {
  7242. value = scale.getBaseValue();
  7243. }
  7244. return value;
  7245. }
  7246. function parseFillOption(line) {
  7247. const options = line.options;
  7248. const fillOption = options.fill;
  7249. let fill = valueOrDefault(fillOption && fillOption.target, fillOption);
  7250. if (fill === undefined) {
  7251. fill = !!options.backgroundColor;
  7252. }
  7253. if (fill === false || fill === null) {
  7254. return false;
  7255. }
  7256. if (fill === true) {
  7257. return 'origin';
  7258. }
  7259. return fill;
  7260. }
  7261. function _buildStackLine(source) {
  7262. const {scale, index, line} = source;
  7263. const points = [];
  7264. const segments = line.segments;
  7265. const sourcePoints = line.points;
  7266. const linesBelow = getLinesBelow(scale, index);
  7267. linesBelow.push(_createBoundaryLine({x: null, y: scale.bottom}, line));
  7268. for (let i = 0; i < segments.length; i++) {
  7269. const segment = segments[i];
  7270. for (let j = segment.start; j <= segment.end; j++) {
  7271. addPointsBelow(points, sourcePoints[j], linesBelow);
  7272. }
  7273. }
  7274. return new LineElement({points, options: {}});
  7275. }
  7276. function getLinesBelow(scale, index) {
  7277. const below = [];
  7278. const metas = scale.getMatchingVisibleMetas('line');
  7279. for (let i = 0; i < metas.length; i++) {
  7280. const meta = metas[i];
  7281. if (meta.index === index) {
  7282. break;
  7283. }
  7284. if (!meta.hidden) {
  7285. below.unshift(meta.dataset);
  7286. }
  7287. }
  7288. return below;
  7289. }
  7290. function addPointsBelow(points, sourcePoint, linesBelow) {
  7291. const postponed = [];
  7292. for (let j = 0; j < linesBelow.length; j++) {
  7293. const line = linesBelow[j];
  7294. const {first, last, point} = findPoint(line, sourcePoint, 'x');
  7295. if (!point || (first && last)) {
  7296. continue;
  7297. }
  7298. if (first) {
  7299. postponed.unshift(point);
  7300. } else {
  7301. points.push(point);
  7302. if (!last) {
  7303. break;
  7304. }
  7305. }
  7306. }
  7307. points.push(...postponed);
  7308. }
  7309. function findPoint(line, sourcePoint, property) {
  7310. const point = line.interpolate(sourcePoint, property);
  7311. if (!point) {
  7312. return {};
  7313. }
  7314. const pointValue = point[property];
  7315. const segments = line.segments;
  7316. const linePoints = line.points;
  7317. let first = false;
  7318. let last = false;
  7319. for (let i = 0; i < segments.length; i++) {
  7320. const segment = segments[i];
  7321. const firstValue = linePoints[segment.start][property];
  7322. const lastValue = linePoints[segment.end][property];
  7323. if (_isBetween(pointValue, firstValue, lastValue)) {
  7324. first = pointValue === firstValue;
  7325. last = pointValue === lastValue;
  7326. break;
  7327. }
  7328. }
  7329. return {first, last, point};
  7330. }
  7331. class simpleArc {
  7332. constructor(opts) {
  7333. this.x = opts.x;
  7334. this.y = opts.y;
  7335. this.radius = opts.radius;
  7336. }
  7337. pathSegment(ctx, bounds, opts) {
  7338. const {x, y, radius} = this;
  7339. bounds = bounds || {start: 0, end: TAU};
  7340. ctx.arc(x, y, radius, bounds.end, bounds.start, true);
  7341. return !opts.bounds;
  7342. }
  7343. interpolate(point) {
  7344. const {x, y, radius} = this;
  7345. const angle = point.angle;
  7346. return {
  7347. x: x + Math.cos(angle) * radius,
  7348. y: y + Math.sin(angle) * radius,
  7349. angle
  7350. };
  7351. }
  7352. }
  7353. function _getTarget(source) {
  7354. const {chart, fill, line} = source;
  7355. if (isNumberFinite(fill)) {
  7356. return getLineByIndex(chart, fill);
  7357. }
  7358. if (fill === 'stack') {
  7359. return _buildStackLine(source);
  7360. }
  7361. if (fill === 'shape') {
  7362. return true;
  7363. }
  7364. const boundary = computeBoundary(source);
  7365. if (boundary instanceof simpleArc) {
  7366. return boundary;
  7367. }
  7368. return _createBoundaryLine(boundary, line);
  7369. }
  7370. function getLineByIndex(chart, index) {
  7371. const meta = chart.getDatasetMeta(index);
  7372. const visible = meta && chart.isDatasetVisible(index);
  7373. return visible ? meta.dataset : null;
  7374. }
  7375. function computeBoundary(source) {
  7376. const scale = source.scale || {};
  7377. if (scale.getPointPositionForValue) {
  7378. return computeCircularBoundary(source);
  7379. }
  7380. return computeLinearBoundary(source);
  7381. }
  7382. function computeLinearBoundary(source) {
  7383. const {scale = {}, fill} = source;
  7384. const pixel = _getTargetPixel(fill, scale);
  7385. if (isNumberFinite(pixel)) {
  7386. const horizontal = scale.isHorizontal();
  7387. return {
  7388. x: horizontal ? pixel : null,
  7389. y: horizontal ? null : pixel
  7390. };
  7391. }
  7392. return null;
  7393. }
  7394. function computeCircularBoundary(source) {
  7395. const {scale, fill} = source;
  7396. const options = scale.options;
  7397. const length = scale.getLabels().length;
  7398. const start = options.reverse ? scale.max : scale.min;
  7399. const value = _getTargetValue(fill, scale, start);
  7400. const target = [];
  7401. if (options.grid.circular) {
  7402. const center = scale.getPointPositionForValue(0, start);
  7403. return new simpleArc({
  7404. x: center.x,
  7405. y: center.y,
  7406. radius: scale.getDistanceFromCenterForValue(value)
  7407. });
  7408. }
  7409. for (let i = 0; i < length; ++i) {
  7410. target.push(scale.getPointPositionForValue(i, value));
  7411. }
  7412. return target;
  7413. }
  7414. function _drawfill(ctx, source, area) {
  7415. const target = _getTarget(source);
  7416. const {line, scale, axis} = source;
  7417. const lineOpts = line.options;
  7418. const fillOption = lineOpts.fill;
  7419. const color = lineOpts.backgroundColor;
  7420. const {above = color, below = color} = fillOption || {};
  7421. if (target && line.points.length) {
  7422. clipArea(ctx, area);
  7423. doFill(ctx, {line, target, above, below, area, scale, axis});
  7424. unclipArea(ctx);
  7425. }
  7426. }
  7427. function doFill(ctx, cfg) {
  7428. const {line, target, above, below, area, scale} = cfg;
  7429. const property = line._loop ? 'angle' : cfg.axis;
  7430. ctx.save();
  7431. if (property === 'x' && below !== above) {
  7432. clipVertical(ctx, target, area.top);
  7433. fill(ctx, {line, target, color: above, scale, property});
  7434. ctx.restore();
  7435. ctx.save();
  7436. clipVertical(ctx, target, area.bottom);
  7437. }
  7438. fill(ctx, {line, target, color: below, scale, property});
  7439. ctx.restore();
  7440. }
  7441. function clipVertical(ctx, target, clipY) {
  7442. const {segments, points} = target;
  7443. let first = true;
  7444. let lineLoop = false;
  7445. ctx.beginPath();
  7446. for (const segment of segments) {
  7447. const {start, end} = segment;
  7448. const firstPoint = points[start];
  7449. const lastPoint = points[_findSegmentEnd(start, end, points)];
  7450. if (first) {
  7451. ctx.moveTo(firstPoint.x, firstPoint.y);
  7452. first = false;
  7453. } else {
  7454. ctx.lineTo(firstPoint.x, clipY);
  7455. ctx.lineTo(firstPoint.x, firstPoint.y);
  7456. }
  7457. lineLoop = !!target.pathSegment(ctx, segment, {move: lineLoop});
  7458. if (lineLoop) {
  7459. ctx.closePath();
  7460. } else {
  7461. ctx.lineTo(lastPoint.x, clipY);
  7462. }
  7463. }
  7464. ctx.lineTo(target.first().x, clipY);
  7465. ctx.closePath();
  7466. ctx.clip();
  7467. }
  7468. function fill(ctx, cfg) {
  7469. const {line, target, property, color, scale} = cfg;
  7470. const segments = _segments(line, target, property);
  7471. for (const {source: src, target: tgt, start, end} of segments) {
  7472. const {style: {backgroundColor = color} = {}} = src;
  7473. const notShape = target !== true;
  7474. ctx.save();
  7475. ctx.fillStyle = backgroundColor;
  7476. clipBounds(ctx, scale, notShape && _getBounds(property, start, end));
  7477. ctx.beginPath();
  7478. const lineLoop = !!line.pathSegment(ctx, src);
  7479. let loop;
  7480. if (notShape) {
  7481. if (lineLoop) {
  7482. ctx.closePath();
  7483. } else {
  7484. interpolatedLineTo(ctx, target, end, property);
  7485. }
  7486. const targetLoop = !!target.pathSegment(ctx, tgt, {move: lineLoop, reverse: true});
  7487. loop = lineLoop && targetLoop;
  7488. if (!loop) {
  7489. interpolatedLineTo(ctx, target, start, property);
  7490. }
  7491. }
  7492. ctx.closePath();
  7493. ctx.fill(loop ? 'evenodd' : 'nonzero');
  7494. ctx.restore();
  7495. }
  7496. }
  7497. function clipBounds(ctx, scale, bounds) {
  7498. const {top, bottom} = scale.chart.chartArea;
  7499. const {property, start, end} = bounds || {};
  7500. if (property === 'x') {
  7501. ctx.beginPath();
  7502. ctx.rect(start, top, end - start, bottom - top);
  7503. ctx.clip();
  7504. }
  7505. }
  7506. function interpolatedLineTo(ctx, target, point, property) {
  7507. const interpolatedPoint = target.interpolate(point, property);
  7508. if (interpolatedPoint) {
  7509. ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);
  7510. }
  7511. }
  7512. var index = {
  7513. id: 'filler',
  7514. afterDatasetsUpdate(chart, _args, options) {
  7515. const count = (chart.data.datasets || []).length;
  7516. const sources = [];
  7517. let meta, i, line, source;
  7518. for (i = 0; i < count; ++i) {
  7519. meta = chart.getDatasetMeta(i);
  7520. line = meta.dataset;
  7521. source = null;
  7522. if (line && line.options && line instanceof LineElement) {
  7523. source = {
  7524. visible: chart.isDatasetVisible(i),
  7525. index: i,
  7526. fill: _decodeFill(line, i, count),
  7527. chart,
  7528. axis: meta.controller.options.indexAxis,
  7529. scale: meta.vScale,
  7530. line,
  7531. };
  7532. }
  7533. meta.$filler = source;
  7534. sources.push(source);
  7535. }
  7536. for (i = 0; i < count; ++i) {
  7537. source = sources[i];
  7538. if (!source || source.fill === false) {
  7539. continue;
  7540. }
  7541. source.fill = _resolveTarget(sources, i, options.propagate);
  7542. }
  7543. },
  7544. beforeDraw(chart, _args, options) {
  7545. const draw = options.drawTime === 'beforeDraw';
  7546. const metasets = chart.getSortedVisibleDatasetMetas();
  7547. const area = chart.chartArea;
  7548. for (let i = metasets.length - 1; i >= 0; --i) {
  7549. const source = metasets[i].$filler;
  7550. if (!source) {
  7551. continue;
  7552. }
  7553. source.line.updateControlPoints(area, source.axis);
  7554. if (draw) {
  7555. _drawfill(chart.ctx, source, area);
  7556. }
  7557. }
  7558. },
  7559. beforeDatasetsDraw(chart, _args, options) {
  7560. if (options.drawTime !== 'beforeDatasetsDraw') {
  7561. return;
  7562. }
  7563. const metasets = chart.getSortedVisibleDatasetMetas();
  7564. for (let i = metasets.length - 1; i >= 0; --i) {
  7565. const source = metasets[i].$filler;
  7566. if (source) {
  7567. _drawfill(chart.ctx, source, chart.chartArea);
  7568. }
  7569. }
  7570. },
  7571. beforeDatasetDraw(chart, args, options) {
  7572. const source = args.meta.$filler;
  7573. if (!source || source.fill === false || options.drawTime !== 'beforeDatasetDraw') {
  7574. return;
  7575. }
  7576. _drawfill(chart.ctx, source, chart.chartArea);
  7577. },
  7578. defaults: {
  7579. propagate: true,
  7580. drawTime: 'beforeDatasetDraw'
  7581. }
  7582. };
  7583. const getBoxSize = (labelOpts, fontSize) => {
  7584. let {boxHeight = fontSize, boxWidth = fontSize} = labelOpts;
  7585. if (labelOpts.usePointStyle) {
  7586. boxHeight = Math.min(boxHeight, fontSize);
  7587. boxWidth = Math.min(boxWidth, fontSize);
  7588. }
  7589. return {
  7590. boxWidth,
  7591. boxHeight,
  7592. itemHeight: Math.max(fontSize, boxHeight)
  7593. };
  7594. };
  7595. const itemsEqual = (a, b) => a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;
  7596. class Legend extends Element {
  7597. constructor(config) {
  7598. super();
  7599. this._added = false;
  7600. this.legendHitBoxes = [];
  7601. this._hoveredItem = null;
  7602. this.doughnutMode = false;
  7603. this.chart = config.chart;
  7604. this.options = config.options;
  7605. this.ctx = config.ctx;
  7606. this.legendItems = undefined;
  7607. this.columnSizes = undefined;
  7608. this.lineWidths = undefined;
  7609. this.maxHeight = undefined;
  7610. this.maxWidth = undefined;
  7611. this.top = undefined;
  7612. this.bottom = undefined;
  7613. this.left = undefined;
  7614. this.right = undefined;
  7615. this.height = undefined;
  7616. this.width = undefined;
  7617. this._margins = undefined;
  7618. this.position = undefined;
  7619. this.weight = undefined;
  7620. this.fullSize = undefined;
  7621. }
  7622. update(maxWidth, maxHeight, margins) {
  7623. this.maxWidth = maxWidth;
  7624. this.maxHeight = maxHeight;
  7625. this._margins = margins;
  7626. this.setDimensions();
  7627. this.buildLabels();
  7628. this.fit();
  7629. }
  7630. setDimensions() {
  7631. if (this.isHorizontal()) {
  7632. this.width = this.maxWidth;
  7633. this.left = this._margins.left;
  7634. this.right = this.width;
  7635. } else {
  7636. this.height = this.maxHeight;
  7637. this.top = this._margins.top;
  7638. this.bottom = this.height;
  7639. }
  7640. }
  7641. buildLabels() {
  7642. const labelOpts = this.options.labels || {};
  7643. let legendItems = callback(labelOpts.generateLabels, [this.chart], this) || [];
  7644. if (labelOpts.filter) {
  7645. legendItems = legendItems.filter((item) => labelOpts.filter(item, this.chart.data));
  7646. }
  7647. if (labelOpts.sort) {
  7648. legendItems = legendItems.sort((a, b) => labelOpts.sort(a, b, this.chart.data));
  7649. }
  7650. if (this.options.reverse) {
  7651. legendItems.reverse();
  7652. }
  7653. this.legendItems = legendItems;
  7654. }
  7655. fit() {
  7656. const {options, ctx} = this;
  7657. if (!options.display) {
  7658. this.width = this.height = 0;
  7659. return;
  7660. }
  7661. const labelOpts = options.labels;
  7662. const labelFont = toFont(labelOpts.font);
  7663. const fontSize = labelFont.size;
  7664. const titleHeight = this._computeTitleHeight();
  7665. const {boxWidth, itemHeight} = getBoxSize(labelOpts, fontSize);
  7666. let width, height;
  7667. ctx.font = labelFont.string;
  7668. if (this.isHorizontal()) {
  7669. width = this.maxWidth;
  7670. height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;
  7671. } else {
  7672. height = this.maxHeight;
  7673. width = this._fitCols(titleHeight, fontSize, boxWidth, itemHeight) + 10;
  7674. }
  7675. this.width = Math.min(width, options.maxWidth || this.maxWidth);
  7676. this.height = Math.min(height, options.maxHeight || this.maxHeight);
  7677. }
  7678. _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {
  7679. const {ctx, maxWidth, options: {labels: {padding}}} = this;
  7680. const hitboxes = this.legendHitBoxes = [];
  7681. const lineWidths = this.lineWidths = [0];
  7682. const lineHeight = itemHeight + padding;
  7683. let totalHeight = titleHeight;
  7684. ctx.textAlign = 'left';
  7685. ctx.textBaseline = 'middle';
  7686. let row = -1;
  7687. let top = -lineHeight;
  7688. this.legendItems.forEach((legendItem, i) => {
  7689. const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  7690. if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {
  7691. totalHeight += lineHeight;
  7692. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  7693. top += lineHeight;
  7694. row++;
  7695. }
  7696. hitboxes[i] = {left: 0, top, row, width: itemWidth, height: itemHeight};
  7697. lineWidths[lineWidths.length - 1] += itemWidth + padding;
  7698. });
  7699. return totalHeight;
  7700. }
  7701. _fitCols(titleHeight, fontSize, boxWidth, itemHeight) {
  7702. const {ctx, maxHeight, options: {labels: {padding}}} = this;
  7703. const hitboxes = this.legendHitBoxes = [];
  7704. const columnSizes = this.columnSizes = [];
  7705. const heightLimit = maxHeight - titleHeight;
  7706. let totalWidth = padding;
  7707. let currentColWidth = 0;
  7708. let currentColHeight = 0;
  7709. let left = 0;
  7710. let col = 0;
  7711. this.legendItems.forEach((legendItem, i) => {
  7712. const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  7713. if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) {
  7714. totalWidth += currentColWidth + padding;
  7715. columnSizes.push({width: currentColWidth, height: currentColHeight});
  7716. left += currentColWidth + padding;
  7717. col++;
  7718. currentColWidth = currentColHeight = 0;
  7719. }
  7720. hitboxes[i] = {left, top: currentColHeight, col, width: itemWidth, height: itemHeight};
  7721. currentColWidth = Math.max(currentColWidth, itemWidth);
  7722. currentColHeight += itemHeight + padding;
  7723. });
  7724. totalWidth += currentColWidth;
  7725. columnSizes.push({width: currentColWidth, height: currentColHeight});
  7726. return totalWidth;
  7727. }
  7728. adjustHitBoxes() {
  7729. if (!this.options.display) {
  7730. return;
  7731. }
  7732. const titleHeight = this._computeTitleHeight();
  7733. const {legendHitBoxes: hitboxes, options: {align, labels: {padding}, rtl}} = this;
  7734. const rtlHelper = getRtlAdapter(rtl, this.left, this.width);
  7735. if (this.isHorizontal()) {
  7736. let row = 0;
  7737. let left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);
  7738. for (const hitbox of hitboxes) {
  7739. if (row !== hitbox.row) {
  7740. row = hitbox.row;
  7741. left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]);
  7742. }
  7743. hitbox.top += this.top + titleHeight + padding;
  7744. hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width);
  7745. left += hitbox.width + padding;
  7746. }
  7747. } else {
  7748. let col = 0;
  7749. let top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);
  7750. for (const hitbox of hitboxes) {
  7751. if (hitbox.col !== col) {
  7752. col = hitbox.col;
  7753. top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height);
  7754. }
  7755. hitbox.top = top;
  7756. hitbox.left += this.left + padding;
  7757. hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width);
  7758. top += hitbox.height + padding;
  7759. }
  7760. }
  7761. }
  7762. isHorizontal() {
  7763. return this.options.position === 'top' || this.options.position === 'bottom';
  7764. }
  7765. draw() {
  7766. if (this.options.display) {
  7767. const ctx = this.ctx;
  7768. clipArea(ctx, this);
  7769. this._draw();
  7770. unclipArea(ctx);
  7771. }
  7772. }
  7773. _draw() {
  7774. const {options: opts, columnSizes, lineWidths, ctx} = this;
  7775. const {align, labels: labelOpts} = opts;
  7776. const defaultColor = defaults.color;
  7777. const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);
  7778. const labelFont = toFont(labelOpts.font);
  7779. const {color: fontColor, padding} = labelOpts;
  7780. const fontSize = labelFont.size;
  7781. const halfFontSize = fontSize / 2;
  7782. let cursor;
  7783. this.drawTitle();
  7784. ctx.textAlign = rtlHelper.textAlign('left');
  7785. ctx.textBaseline = 'middle';
  7786. ctx.lineWidth = 0.5;
  7787. ctx.font = labelFont.string;
  7788. const {boxWidth, boxHeight, itemHeight} = getBoxSize(labelOpts, fontSize);
  7789. const drawLegendBox = function(x, y, legendItem) {
  7790. if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {
  7791. return;
  7792. }
  7793. ctx.save();
  7794. const lineWidth = valueOrDefault(legendItem.lineWidth, 1);
  7795. ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);
  7796. ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt');
  7797. ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0);
  7798. ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter');
  7799. ctx.lineWidth = lineWidth;
  7800. ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor);
  7801. ctx.setLineDash(valueOrDefault(legendItem.lineDash, []));
  7802. if (labelOpts.usePointStyle) {
  7803. const drawOptions = {
  7804. radius: boxWidth * Math.SQRT2 / 2,
  7805. pointStyle: legendItem.pointStyle,
  7806. rotation: legendItem.rotation,
  7807. borderWidth: lineWidth
  7808. };
  7809. const centerX = rtlHelper.xPlus(x, boxWidth / 2);
  7810. const centerY = y + halfFontSize;
  7811. drawPoint(ctx, drawOptions, centerX, centerY);
  7812. } else {
  7813. const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);
  7814. const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);
  7815. const borderRadius = toTRBLCorners(legendItem.borderRadius);
  7816. ctx.beginPath();
  7817. if (Object.values(borderRadius).some(v => v !== 0)) {
  7818. addRoundedRectPath(ctx, {
  7819. x: xBoxLeft,
  7820. y: yBoxTop,
  7821. w: boxWidth,
  7822. h: boxHeight,
  7823. radius: borderRadius,
  7824. });
  7825. } else {
  7826. ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);
  7827. }
  7828. ctx.fill();
  7829. if (lineWidth !== 0) {
  7830. ctx.stroke();
  7831. }
  7832. }
  7833. ctx.restore();
  7834. };
  7835. const fillText = function(x, y, legendItem) {
  7836. renderText(ctx, legendItem.text, x, y + (itemHeight / 2), labelFont, {
  7837. strikethrough: legendItem.hidden,
  7838. textAlign: rtlHelper.textAlign(legendItem.textAlign)
  7839. });
  7840. };
  7841. const isHorizontal = this.isHorizontal();
  7842. const titleHeight = this._computeTitleHeight();
  7843. if (isHorizontal) {
  7844. cursor = {
  7845. x: _alignStartEnd(align, this.left + padding, this.right - lineWidths[0]),
  7846. y: this.top + padding + titleHeight,
  7847. line: 0
  7848. };
  7849. } else {
  7850. cursor = {
  7851. x: this.left + padding,
  7852. y: _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height),
  7853. line: 0
  7854. };
  7855. }
  7856. overrideTextDirection(this.ctx, opts.textDirection);
  7857. const lineHeight = itemHeight + padding;
  7858. this.legendItems.forEach((legendItem, i) => {
  7859. ctx.strokeStyle = legendItem.fontColor || fontColor;
  7860. ctx.fillStyle = legendItem.fontColor || fontColor;
  7861. const textWidth = ctx.measureText(legendItem.text).width;
  7862. const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));
  7863. const width = boxWidth + halfFontSize + textWidth;
  7864. let x = cursor.x;
  7865. let y = cursor.y;
  7866. rtlHelper.setWidth(this.width);
  7867. if (isHorizontal) {
  7868. if (i > 0 && x + width + padding > this.right) {
  7869. y = cursor.y += lineHeight;
  7870. cursor.line++;
  7871. x = cursor.x = _alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]);
  7872. }
  7873. } else if (i > 0 && y + lineHeight > this.bottom) {
  7874. x = cursor.x = x + columnSizes[cursor.line].width + padding;
  7875. cursor.line++;
  7876. y = cursor.y = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height);
  7877. }
  7878. const realX = rtlHelper.x(x);
  7879. drawLegendBox(realX, y, legendItem);
  7880. x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl);
  7881. fillText(rtlHelper.x(x), y, legendItem);
  7882. if (isHorizontal) {
  7883. cursor.x += width + padding;
  7884. } else {
  7885. cursor.y += lineHeight;
  7886. }
  7887. });
  7888. restoreTextDirection(this.ctx, opts.textDirection);
  7889. }
  7890. drawTitle() {
  7891. const opts = this.options;
  7892. const titleOpts = opts.title;
  7893. const titleFont = toFont(titleOpts.font);
  7894. const titlePadding = toPadding(titleOpts.padding);
  7895. if (!titleOpts.display) {
  7896. return;
  7897. }
  7898. const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width);
  7899. const ctx = this.ctx;
  7900. const position = titleOpts.position;
  7901. const halfFontSize = titleFont.size / 2;
  7902. const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;
  7903. let y;
  7904. let left = this.left;
  7905. let maxWidth = this.width;
  7906. if (this.isHorizontal()) {
  7907. maxWidth = Math.max(...this.lineWidths);
  7908. y = this.top + topPaddingPlusHalfFontSize;
  7909. left = _alignStartEnd(opts.align, left, this.right - maxWidth);
  7910. } else {
  7911. const maxHeight = this.columnSizes.reduce((acc, size) => Math.max(acc, size.height), 0);
  7912. y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight());
  7913. }
  7914. const x = _alignStartEnd(position, left, left + maxWidth);
  7915. ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position));
  7916. ctx.textBaseline = 'middle';
  7917. ctx.strokeStyle = titleOpts.color;
  7918. ctx.fillStyle = titleOpts.color;
  7919. ctx.font = titleFont.string;
  7920. renderText(ctx, titleOpts.text, x, y, titleFont);
  7921. }
  7922. _computeTitleHeight() {
  7923. const titleOpts = this.options.title;
  7924. const titleFont = toFont(titleOpts.font);
  7925. const titlePadding = toPadding(titleOpts.padding);
  7926. return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
  7927. }
  7928. _getLegendItemAt(x, y) {
  7929. let i, hitBox, lh;
  7930. if (_isBetween(x, this.left, this.right)
  7931. && _isBetween(y, this.top, this.bottom)) {
  7932. lh = this.legendHitBoxes;
  7933. for (i = 0; i < lh.length; ++i) {
  7934. hitBox = lh[i];
  7935. if (_isBetween(x, hitBox.left, hitBox.left + hitBox.width)
  7936. && _isBetween(y, hitBox.top, hitBox.top + hitBox.height)) {
  7937. return this.legendItems[i];
  7938. }
  7939. }
  7940. }
  7941. return null;
  7942. }
  7943. handleEvent(e) {
  7944. const opts = this.options;
  7945. if (!isListened(e.type, opts)) {
  7946. return;
  7947. }
  7948. const hoveredItem = this._getLegendItemAt(e.x, e.y);
  7949. if (e.type === 'mousemove') {
  7950. const previous = this._hoveredItem;
  7951. const sameItem = itemsEqual(previous, hoveredItem);
  7952. if (previous && !sameItem) {
  7953. callback(opts.onLeave, [e, previous, this], this);
  7954. }
  7955. this._hoveredItem = hoveredItem;
  7956. if (hoveredItem && !sameItem) {
  7957. callback(opts.onHover, [e, hoveredItem, this], this);
  7958. }
  7959. } else if (hoveredItem) {
  7960. callback(opts.onClick, [e, hoveredItem, this], this);
  7961. }
  7962. }
  7963. }
  7964. function isListened(type, opts) {
  7965. if (type === 'mousemove' && (opts.onHover || opts.onLeave)) {
  7966. return true;
  7967. }
  7968. if (opts.onClick && (type === 'click' || type === 'mouseup')) {
  7969. return true;
  7970. }
  7971. return false;
  7972. }
  7973. var plugin_legend = {
  7974. id: 'legend',
  7975. _element: Legend,
  7976. start(chart, _args, options) {
  7977. const legend = chart.legend = new Legend({ctx: chart.ctx, options, chart});
  7978. layouts.configure(chart, legend, options);
  7979. layouts.addBox(chart, legend);
  7980. },
  7981. stop(chart) {
  7982. layouts.removeBox(chart, chart.legend);
  7983. delete chart.legend;
  7984. },
  7985. beforeUpdate(chart, _args, options) {
  7986. const legend = chart.legend;
  7987. layouts.configure(chart, legend, options);
  7988. legend.options = options;
  7989. },
  7990. afterUpdate(chart) {
  7991. const legend = chart.legend;
  7992. legend.buildLabels();
  7993. legend.adjustHitBoxes();
  7994. },
  7995. afterEvent(chart, args) {
  7996. if (!args.replay) {
  7997. chart.legend.handleEvent(args.event);
  7998. }
  7999. },
  8000. defaults: {
  8001. display: true,
  8002. position: 'top',
  8003. align: 'center',
  8004. fullSize: true,
  8005. reverse: false,
  8006. weight: 1000,
  8007. onClick(e, legendItem, legend) {
  8008. const index = legendItem.datasetIndex;
  8009. const ci = legend.chart;
  8010. if (ci.isDatasetVisible(index)) {
  8011. ci.hide(index);
  8012. legendItem.hidden = true;
  8013. } else {
  8014. ci.show(index);
  8015. legendItem.hidden = false;
  8016. }
  8017. },
  8018. onHover: null,
  8019. onLeave: null,
  8020. labels: {
  8021. color: (ctx) => ctx.chart.options.color,
  8022. boxWidth: 40,
  8023. padding: 10,
  8024. generateLabels(chart) {
  8025. const datasets = chart.data.datasets;
  8026. const {labels: {usePointStyle, pointStyle, textAlign, color}} = chart.legend.options;
  8027. return chart._getSortedDatasetMetas().map((meta) => {
  8028. const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  8029. const borderWidth = toPadding(style.borderWidth);
  8030. return {
  8031. text: datasets[meta.index].label,
  8032. fillStyle: style.backgroundColor,
  8033. fontColor: color,
  8034. hidden: !meta.visible,
  8035. lineCap: style.borderCapStyle,
  8036. lineDash: style.borderDash,
  8037. lineDashOffset: style.borderDashOffset,
  8038. lineJoin: style.borderJoinStyle,
  8039. lineWidth: (borderWidth.width + borderWidth.height) / 4,
  8040. strokeStyle: style.borderColor,
  8041. pointStyle: pointStyle || style.pointStyle,
  8042. rotation: style.rotation,
  8043. textAlign: textAlign || style.textAlign,
  8044. borderRadius: 0,
  8045. datasetIndex: meta.index
  8046. };
  8047. }, this);
  8048. }
  8049. },
  8050. title: {
  8051. color: (ctx) => ctx.chart.options.color,
  8052. display: false,
  8053. position: 'center',
  8054. text: '',
  8055. }
  8056. },
  8057. descriptors: {
  8058. _scriptable: (name) => !name.startsWith('on'),
  8059. labels: {
  8060. _scriptable: (name) => !['generateLabels', 'filter', 'sort'].includes(name),
  8061. }
  8062. },
  8063. };
  8064. class Title extends Element {
  8065. constructor(config) {
  8066. super();
  8067. this.chart = config.chart;
  8068. this.options = config.options;
  8069. this.ctx = config.ctx;
  8070. this._padding = undefined;
  8071. this.top = undefined;
  8072. this.bottom = undefined;
  8073. this.left = undefined;
  8074. this.right = undefined;
  8075. this.width = undefined;
  8076. this.height = undefined;
  8077. this.position = undefined;
  8078. this.weight = undefined;
  8079. this.fullSize = undefined;
  8080. }
  8081. update(maxWidth, maxHeight) {
  8082. const opts = this.options;
  8083. this.left = 0;
  8084. this.top = 0;
  8085. if (!opts.display) {
  8086. this.width = this.height = this.right = this.bottom = 0;
  8087. return;
  8088. }
  8089. this.width = this.right = maxWidth;
  8090. this.height = this.bottom = maxHeight;
  8091. const lineCount = isArray(opts.text) ? opts.text.length : 1;
  8092. this._padding = toPadding(opts.padding);
  8093. const textSize = lineCount * toFont(opts.font).lineHeight + this._padding.height;
  8094. if (this.isHorizontal()) {
  8095. this.height = textSize;
  8096. } else {
  8097. this.width = textSize;
  8098. }
  8099. }
  8100. isHorizontal() {
  8101. const pos = this.options.position;
  8102. return pos === 'top' || pos === 'bottom';
  8103. }
  8104. _drawArgs(offset) {
  8105. const {top, left, bottom, right, options} = this;
  8106. const align = options.align;
  8107. let rotation = 0;
  8108. let maxWidth, titleX, titleY;
  8109. if (this.isHorizontal()) {
  8110. titleX = _alignStartEnd(align, left, right);
  8111. titleY = top + offset;
  8112. maxWidth = right - left;
  8113. } else {
  8114. if (options.position === 'left') {
  8115. titleX = left + offset;
  8116. titleY = _alignStartEnd(align, bottom, top);
  8117. rotation = PI * -0.5;
  8118. } else {
  8119. titleX = right - offset;
  8120. titleY = _alignStartEnd(align, top, bottom);
  8121. rotation = PI * 0.5;
  8122. }
  8123. maxWidth = bottom - top;
  8124. }
  8125. return {titleX, titleY, maxWidth, rotation};
  8126. }
  8127. draw() {
  8128. const ctx = this.ctx;
  8129. const opts = this.options;
  8130. if (!opts.display) {
  8131. return;
  8132. }
  8133. const fontOpts = toFont(opts.font);
  8134. const lineHeight = fontOpts.lineHeight;
  8135. const offset = lineHeight / 2 + this._padding.top;
  8136. const {titleX, titleY, maxWidth, rotation} = this._drawArgs(offset);
  8137. renderText(ctx, opts.text, 0, 0, fontOpts, {
  8138. color: opts.color,
  8139. maxWidth,
  8140. rotation,
  8141. textAlign: _toLeftRightCenter(opts.align),
  8142. textBaseline: 'middle',
  8143. translation: [titleX, titleY],
  8144. });
  8145. }
  8146. }
  8147. function createTitle(chart, titleOpts) {
  8148. const title = new Title({
  8149. ctx: chart.ctx,
  8150. options: titleOpts,
  8151. chart
  8152. });
  8153. layouts.configure(chart, title, titleOpts);
  8154. layouts.addBox(chart, title);
  8155. chart.titleBlock = title;
  8156. }
  8157. var plugin_title = {
  8158. id: 'title',
  8159. _element: Title,
  8160. start(chart, _args, options) {
  8161. createTitle(chart, options);
  8162. },
  8163. stop(chart) {
  8164. const titleBlock = chart.titleBlock;
  8165. layouts.removeBox(chart, titleBlock);
  8166. delete chart.titleBlock;
  8167. },
  8168. beforeUpdate(chart, _args, options) {
  8169. const title = chart.titleBlock;
  8170. layouts.configure(chart, title, options);
  8171. title.options = options;
  8172. },
  8173. defaults: {
  8174. align: 'center',
  8175. display: false,
  8176. font: {
  8177. weight: 'bold',
  8178. },
  8179. fullSize: true,
  8180. padding: 10,
  8181. position: 'top',
  8182. text: '',
  8183. weight: 2000
  8184. },
  8185. defaultRoutes: {
  8186. color: 'color'
  8187. },
  8188. descriptors: {
  8189. _scriptable: true,
  8190. _indexable: false,
  8191. },
  8192. };
  8193. const map = new WeakMap();
  8194. var plugin_subtitle = {
  8195. id: 'subtitle',
  8196. start(chart, _args, options) {
  8197. const title = new Title({
  8198. ctx: chart.ctx,
  8199. options,
  8200. chart
  8201. });
  8202. layouts.configure(chart, title, options);
  8203. layouts.addBox(chart, title);
  8204. map.set(chart, title);
  8205. },
  8206. stop(chart) {
  8207. layouts.removeBox(chart, map.get(chart));
  8208. map.delete(chart);
  8209. },
  8210. beforeUpdate(chart, _args, options) {
  8211. const title = map.get(chart);
  8212. layouts.configure(chart, title, options);
  8213. title.options = options;
  8214. },
  8215. defaults: {
  8216. align: 'center',
  8217. display: false,
  8218. font: {
  8219. weight: 'normal',
  8220. },
  8221. fullSize: true,
  8222. padding: 0,
  8223. position: 'top',
  8224. text: '',
  8225. weight: 1500
  8226. },
  8227. defaultRoutes: {
  8228. color: 'color'
  8229. },
  8230. descriptors: {
  8231. _scriptable: true,
  8232. _indexable: false,
  8233. },
  8234. };
  8235. const positioners = {
  8236. average(items) {
  8237. if (!items.length) {
  8238. return false;
  8239. }
  8240. let i, len;
  8241. let x = 0;
  8242. let y = 0;
  8243. let count = 0;
  8244. for (i = 0, len = items.length; i < len; ++i) {
  8245. const el = items[i].element;
  8246. if (el && el.hasValue()) {
  8247. const pos = el.tooltipPosition();
  8248. x += pos.x;
  8249. y += pos.y;
  8250. ++count;
  8251. }
  8252. }
  8253. return {
  8254. x: x / count,
  8255. y: y / count
  8256. };
  8257. },
  8258. nearest(items, eventPosition) {
  8259. if (!items.length) {
  8260. return false;
  8261. }
  8262. let x = eventPosition.x;
  8263. let y = eventPosition.y;
  8264. let minDistance = Number.POSITIVE_INFINITY;
  8265. let i, len, nearestElement;
  8266. for (i = 0, len = items.length; i < len; ++i) {
  8267. const el = items[i].element;
  8268. if (el && el.hasValue()) {
  8269. const center = el.getCenterPoint();
  8270. const d = distanceBetweenPoints(eventPosition, center);
  8271. if (d < minDistance) {
  8272. minDistance = d;
  8273. nearestElement = el;
  8274. }
  8275. }
  8276. }
  8277. if (nearestElement) {
  8278. const tp = nearestElement.tooltipPosition();
  8279. x = tp.x;
  8280. y = tp.y;
  8281. }
  8282. return {
  8283. x,
  8284. y
  8285. };
  8286. }
  8287. };
  8288. function pushOrConcat(base, toPush) {
  8289. if (toPush) {
  8290. if (isArray(toPush)) {
  8291. Array.prototype.push.apply(base, toPush);
  8292. } else {
  8293. base.push(toPush);
  8294. }
  8295. }
  8296. return base;
  8297. }
  8298. function splitNewlines(str) {
  8299. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  8300. return str.split('\n');
  8301. }
  8302. return str;
  8303. }
  8304. function createTooltipItem(chart, item) {
  8305. const {element, datasetIndex, index} = item;
  8306. const controller = chart.getDatasetMeta(datasetIndex).controller;
  8307. const {label, value} = controller.getLabelAndValue(index);
  8308. return {
  8309. chart,
  8310. label,
  8311. parsed: controller.getParsed(index),
  8312. raw: chart.data.datasets[datasetIndex].data[index],
  8313. formattedValue: value,
  8314. dataset: controller.getDataset(),
  8315. dataIndex: index,
  8316. datasetIndex,
  8317. element
  8318. };
  8319. }
  8320. function getTooltipSize(tooltip, options) {
  8321. const ctx = tooltip.chart.ctx;
  8322. const {body, footer, title} = tooltip;
  8323. const {boxWidth, boxHeight} = options;
  8324. const bodyFont = toFont(options.bodyFont);
  8325. const titleFont = toFont(options.titleFont);
  8326. const footerFont = toFont(options.footerFont);
  8327. const titleLineCount = title.length;
  8328. const footerLineCount = footer.length;
  8329. const bodyLineItemCount = body.length;
  8330. const padding = toPadding(options.padding);
  8331. let height = padding.height;
  8332. let width = 0;
  8333. let combinedBodyLength = body.reduce((count, bodyItem) => count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);
  8334. combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;
  8335. if (titleLineCount) {
  8336. height += titleLineCount * titleFont.lineHeight
  8337. + (titleLineCount - 1) * options.titleSpacing
  8338. + options.titleMarginBottom;
  8339. }
  8340. if (combinedBodyLength) {
  8341. const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;
  8342. height += bodyLineItemCount * bodyLineHeight
  8343. + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight
  8344. + (combinedBodyLength - 1) * options.bodySpacing;
  8345. }
  8346. if (footerLineCount) {
  8347. height += options.footerMarginTop
  8348. + footerLineCount * footerFont.lineHeight
  8349. + (footerLineCount - 1) * options.footerSpacing;
  8350. }
  8351. let widthPadding = 0;
  8352. const maxLineWidth = function(line) {
  8353. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  8354. };
  8355. ctx.save();
  8356. ctx.font = titleFont.string;
  8357. each(tooltip.title, maxLineWidth);
  8358. ctx.font = bodyFont.string;
  8359. each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);
  8360. widthPadding = options.displayColors ? (boxWidth + 2 + options.boxPadding) : 0;
  8361. each(body, (bodyItem) => {
  8362. each(bodyItem.before, maxLineWidth);
  8363. each(bodyItem.lines, maxLineWidth);
  8364. each(bodyItem.after, maxLineWidth);
  8365. });
  8366. widthPadding = 0;
  8367. ctx.font = footerFont.string;
  8368. each(tooltip.footer, maxLineWidth);
  8369. ctx.restore();
  8370. width += padding.width;
  8371. return {width, height};
  8372. }
  8373. function determineYAlign(chart, size) {
  8374. const {y, height} = size;
  8375. if (y < height / 2) {
  8376. return 'top';
  8377. } else if (y > (chart.height - height / 2)) {
  8378. return 'bottom';
  8379. }
  8380. return 'center';
  8381. }
  8382. function doesNotFitWithAlign(xAlign, chart, options, size) {
  8383. const {x, width} = size;
  8384. const caret = options.caretSize + options.caretPadding;
  8385. if (xAlign === 'left' && x + width + caret > chart.width) {
  8386. return true;
  8387. }
  8388. if (xAlign === 'right' && x - width - caret < 0) {
  8389. return true;
  8390. }
  8391. }
  8392. function determineXAlign(chart, options, size, yAlign) {
  8393. const {x, width} = size;
  8394. const {width: chartWidth, chartArea: {left, right}} = chart;
  8395. let xAlign = 'center';
  8396. if (yAlign === 'center') {
  8397. xAlign = x <= (left + right) / 2 ? 'left' : 'right';
  8398. } else if (x <= width / 2) {
  8399. xAlign = 'left';
  8400. } else if (x >= chartWidth - width / 2) {
  8401. xAlign = 'right';
  8402. }
  8403. if (doesNotFitWithAlign(xAlign, chart, options, size)) {
  8404. xAlign = 'center';
  8405. }
  8406. return xAlign;
  8407. }
  8408. function determineAlignment(chart, options, size) {
  8409. const yAlign = size.yAlign || options.yAlign || determineYAlign(chart, size);
  8410. return {
  8411. xAlign: size.xAlign || options.xAlign || determineXAlign(chart, options, size, yAlign),
  8412. yAlign
  8413. };
  8414. }
  8415. function alignX(size, xAlign) {
  8416. let {x, width} = size;
  8417. if (xAlign === 'right') {
  8418. x -= width;
  8419. } else if (xAlign === 'center') {
  8420. x -= (width / 2);
  8421. }
  8422. return x;
  8423. }
  8424. function alignY(size, yAlign, paddingAndSize) {
  8425. let {y, height} = size;
  8426. if (yAlign === 'top') {
  8427. y += paddingAndSize;
  8428. } else if (yAlign === 'bottom') {
  8429. y -= height + paddingAndSize;
  8430. } else {
  8431. y -= (height / 2);
  8432. }
  8433. return y;
  8434. }
  8435. function getBackgroundPoint(options, size, alignment, chart) {
  8436. const {caretSize, caretPadding, cornerRadius} = options;
  8437. const {xAlign, yAlign} = alignment;
  8438. const paddingAndSize = caretSize + caretPadding;
  8439. const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(cornerRadius);
  8440. let x = alignX(size, xAlign);
  8441. const y = alignY(size, yAlign, paddingAndSize);
  8442. if (yAlign === 'center') {
  8443. if (xAlign === 'left') {
  8444. x += paddingAndSize;
  8445. } else if (xAlign === 'right') {
  8446. x -= paddingAndSize;
  8447. }
  8448. } else if (xAlign === 'left') {
  8449. x -= Math.max(topLeft, bottomLeft) + caretSize;
  8450. } else if (xAlign === 'right') {
  8451. x += Math.max(topRight, bottomRight) + caretSize;
  8452. }
  8453. return {
  8454. x: _limitValue(x, 0, chart.width - size.width),
  8455. y: _limitValue(y, 0, chart.height - size.height)
  8456. };
  8457. }
  8458. function getAlignedX(tooltip, align, options) {
  8459. const padding = toPadding(options.padding);
  8460. return align === 'center'
  8461. ? tooltip.x + tooltip.width / 2
  8462. : align === 'right'
  8463. ? tooltip.x + tooltip.width - padding.right
  8464. : tooltip.x + padding.left;
  8465. }
  8466. function getBeforeAfterBodyLines(callback) {
  8467. return pushOrConcat([], splitNewlines(callback));
  8468. }
  8469. function createTooltipContext(parent, tooltip, tooltipItems) {
  8470. return createContext(parent, {
  8471. tooltip,
  8472. tooltipItems,
  8473. type: 'tooltip'
  8474. });
  8475. }
  8476. function overrideCallbacks(callbacks, context) {
  8477. const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;
  8478. return override ? callbacks.override(override) : callbacks;
  8479. }
  8480. class Tooltip extends Element {
  8481. constructor(config) {
  8482. super();
  8483. this.opacity = 0;
  8484. this._active = [];
  8485. this._eventPosition = undefined;
  8486. this._size = undefined;
  8487. this._cachedAnimations = undefined;
  8488. this._tooltipItems = [];
  8489. this.$animations = undefined;
  8490. this.$context = undefined;
  8491. this.chart = config.chart || config._chart;
  8492. this._chart = this.chart;
  8493. this.options = config.options;
  8494. this.dataPoints = undefined;
  8495. this.title = undefined;
  8496. this.beforeBody = undefined;
  8497. this.body = undefined;
  8498. this.afterBody = undefined;
  8499. this.footer = undefined;
  8500. this.xAlign = undefined;
  8501. this.yAlign = undefined;
  8502. this.x = undefined;
  8503. this.y = undefined;
  8504. this.height = undefined;
  8505. this.width = undefined;
  8506. this.caretX = undefined;
  8507. this.caretY = undefined;
  8508. this.labelColors = undefined;
  8509. this.labelPointStyles = undefined;
  8510. this.labelTextColors = undefined;
  8511. }
  8512. initialize(options) {
  8513. this.options = options;
  8514. this._cachedAnimations = undefined;
  8515. this.$context = undefined;
  8516. }
  8517. _resolveAnimations() {
  8518. const cached = this._cachedAnimations;
  8519. if (cached) {
  8520. return cached;
  8521. }
  8522. const chart = this.chart;
  8523. const options = this.options.setContext(this.getContext());
  8524. const opts = options.enabled && chart.options.animation && options.animations;
  8525. const animations = new Animations(this.chart, opts);
  8526. if (opts._cacheable) {
  8527. this._cachedAnimations = Object.freeze(animations);
  8528. }
  8529. return animations;
  8530. }
  8531. getContext() {
  8532. return this.$context ||
  8533. (this.$context = createTooltipContext(this.chart.getContext(), this, this._tooltipItems));
  8534. }
  8535. getTitle(context, options) {
  8536. const {callbacks} = options;
  8537. const beforeTitle = callbacks.beforeTitle.apply(this, [context]);
  8538. const title = callbacks.title.apply(this, [context]);
  8539. const afterTitle = callbacks.afterTitle.apply(this, [context]);
  8540. let lines = [];
  8541. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  8542. lines = pushOrConcat(lines, splitNewlines(title));
  8543. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  8544. return lines;
  8545. }
  8546. getBeforeBody(tooltipItems, options) {
  8547. return getBeforeAfterBodyLines(options.callbacks.beforeBody.apply(this, [tooltipItems]));
  8548. }
  8549. getBody(tooltipItems, options) {
  8550. const {callbacks} = options;
  8551. const bodyItems = [];
  8552. each(tooltipItems, (context) => {
  8553. const bodyItem = {
  8554. before: [],
  8555. lines: [],
  8556. after: []
  8557. };
  8558. const scoped = overrideCallbacks(callbacks, context);
  8559. pushOrConcat(bodyItem.before, splitNewlines(scoped.beforeLabel.call(this, context)));
  8560. pushOrConcat(bodyItem.lines, scoped.label.call(this, context));
  8561. pushOrConcat(bodyItem.after, splitNewlines(scoped.afterLabel.call(this, context)));
  8562. bodyItems.push(bodyItem);
  8563. });
  8564. return bodyItems;
  8565. }
  8566. getAfterBody(tooltipItems, options) {
  8567. return getBeforeAfterBodyLines(options.callbacks.afterBody.apply(this, [tooltipItems]));
  8568. }
  8569. getFooter(tooltipItems, options) {
  8570. const {callbacks} = options;
  8571. const beforeFooter = callbacks.beforeFooter.apply(this, [tooltipItems]);
  8572. const footer = callbacks.footer.apply(this, [tooltipItems]);
  8573. const afterFooter = callbacks.afterFooter.apply(this, [tooltipItems]);
  8574. let lines = [];
  8575. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  8576. lines = pushOrConcat(lines, splitNewlines(footer));
  8577. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  8578. return lines;
  8579. }
  8580. _createItems(options) {
  8581. const active = this._active;
  8582. const data = this.chart.data;
  8583. const labelColors = [];
  8584. const labelPointStyles = [];
  8585. const labelTextColors = [];
  8586. let tooltipItems = [];
  8587. let i, len;
  8588. for (i = 0, len = active.length; i < len; ++i) {
  8589. tooltipItems.push(createTooltipItem(this.chart, active[i]));
  8590. }
  8591. if (options.filter) {
  8592. tooltipItems = tooltipItems.filter((element, index, array) => options.filter(element, index, array, data));
  8593. }
  8594. if (options.itemSort) {
  8595. tooltipItems = tooltipItems.sort((a, b) => options.itemSort(a, b, data));
  8596. }
  8597. each(tooltipItems, (context) => {
  8598. const scoped = overrideCallbacks(options.callbacks, context);
  8599. labelColors.push(scoped.labelColor.call(this, context));
  8600. labelPointStyles.push(scoped.labelPointStyle.call(this, context));
  8601. labelTextColors.push(scoped.labelTextColor.call(this, context));
  8602. });
  8603. this.labelColors = labelColors;
  8604. this.labelPointStyles = labelPointStyles;
  8605. this.labelTextColors = labelTextColors;
  8606. this.dataPoints = tooltipItems;
  8607. return tooltipItems;
  8608. }
  8609. update(changed, replay) {
  8610. const options = this.options.setContext(this.getContext());
  8611. const active = this._active;
  8612. let properties;
  8613. let tooltipItems = [];
  8614. if (!active.length) {
  8615. if (this.opacity !== 0) {
  8616. properties = {
  8617. opacity: 0
  8618. };
  8619. }
  8620. } else {
  8621. const position = positioners[options.position].call(this, active, this._eventPosition);
  8622. tooltipItems = this._createItems(options);
  8623. this.title = this.getTitle(tooltipItems, options);
  8624. this.beforeBody = this.getBeforeBody(tooltipItems, options);
  8625. this.body = this.getBody(tooltipItems, options);
  8626. this.afterBody = this.getAfterBody(tooltipItems, options);
  8627. this.footer = this.getFooter(tooltipItems, options);
  8628. const size = this._size = getTooltipSize(this, options);
  8629. const positionAndSize = Object.assign({}, position, size);
  8630. const alignment = determineAlignment(this.chart, options, positionAndSize);
  8631. const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this.chart);
  8632. this.xAlign = alignment.xAlign;
  8633. this.yAlign = alignment.yAlign;
  8634. properties = {
  8635. opacity: 1,
  8636. x: backgroundPoint.x,
  8637. y: backgroundPoint.y,
  8638. width: size.width,
  8639. height: size.height,
  8640. caretX: position.x,
  8641. caretY: position.y
  8642. };
  8643. }
  8644. this._tooltipItems = tooltipItems;
  8645. this.$context = undefined;
  8646. if (properties) {
  8647. this._resolveAnimations().update(this, properties);
  8648. }
  8649. if (changed && options.external) {
  8650. options.external.call(this, {chart: this.chart, tooltip: this, replay});
  8651. }
  8652. }
  8653. drawCaret(tooltipPoint, ctx, size, options) {
  8654. const caretPosition = this.getCaretPosition(tooltipPoint, size, options);
  8655. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  8656. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  8657. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  8658. }
  8659. getCaretPosition(tooltipPoint, size, options) {
  8660. const {xAlign, yAlign} = this;
  8661. const {caretSize, cornerRadius} = options;
  8662. const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(cornerRadius);
  8663. const {x: ptX, y: ptY} = tooltipPoint;
  8664. const {width, height} = size;
  8665. let x1, x2, x3, y1, y2, y3;
  8666. if (yAlign === 'center') {
  8667. y2 = ptY + (height / 2);
  8668. if (xAlign === 'left') {
  8669. x1 = ptX;
  8670. x2 = x1 - caretSize;
  8671. y1 = y2 + caretSize;
  8672. y3 = y2 - caretSize;
  8673. } else {
  8674. x1 = ptX + width;
  8675. x2 = x1 + caretSize;
  8676. y1 = y2 - caretSize;
  8677. y3 = y2 + caretSize;
  8678. }
  8679. x3 = x1;
  8680. } else {
  8681. if (xAlign === 'left') {
  8682. x2 = ptX + Math.max(topLeft, bottomLeft) + (caretSize);
  8683. } else if (xAlign === 'right') {
  8684. x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize;
  8685. } else {
  8686. x2 = this.caretX;
  8687. }
  8688. if (yAlign === 'top') {
  8689. y1 = ptY;
  8690. y2 = y1 - caretSize;
  8691. x1 = x2 - caretSize;
  8692. x3 = x2 + caretSize;
  8693. } else {
  8694. y1 = ptY + height;
  8695. y2 = y1 + caretSize;
  8696. x1 = x2 + caretSize;
  8697. x3 = x2 - caretSize;
  8698. }
  8699. y3 = y1;
  8700. }
  8701. return {x1, x2, x3, y1, y2, y3};
  8702. }
  8703. drawTitle(pt, ctx, options) {
  8704. const title = this.title;
  8705. const length = title.length;
  8706. let titleFont, titleSpacing, i;
  8707. if (length) {
  8708. const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);
  8709. pt.x = getAlignedX(this, options.titleAlign, options);
  8710. ctx.textAlign = rtlHelper.textAlign(options.titleAlign);
  8711. ctx.textBaseline = 'middle';
  8712. titleFont = toFont(options.titleFont);
  8713. titleSpacing = options.titleSpacing;
  8714. ctx.fillStyle = options.titleColor;
  8715. ctx.font = titleFont.string;
  8716. for (i = 0; i < length; ++i) {
  8717. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);
  8718. pt.y += titleFont.lineHeight + titleSpacing;
  8719. if (i + 1 === length) {
  8720. pt.y += options.titleMarginBottom - titleSpacing;
  8721. }
  8722. }
  8723. }
  8724. }
  8725. _drawColorBox(ctx, pt, i, rtlHelper, options) {
  8726. const labelColors = this.labelColors[i];
  8727. const labelPointStyle = this.labelPointStyles[i];
  8728. const {boxHeight, boxWidth, boxPadding} = options;
  8729. const bodyFont = toFont(options.bodyFont);
  8730. const colorX = getAlignedX(this, 'left', options);
  8731. const rtlColorX = rtlHelper.x(colorX);
  8732. const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;
  8733. const colorY = pt.y + yOffSet;
  8734. if (options.usePointStyle) {
  8735. const drawOptions = {
  8736. radius: Math.min(boxWidth, boxHeight) / 2,
  8737. pointStyle: labelPointStyle.pointStyle,
  8738. rotation: labelPointStyle.rotation,
  8739. borderWidth: 1
  8740. };
  8741. const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;
  8742. const centerY = colorY + boxHeight / 2;
  8743. ctx.strokeStyle = options.multiKeyBackground;
  8744. ctx.fillStyle = options.multiKeyBackground;
  8745. drawPoint(ctx, drawOptions, centerX, centerY);
  8746. ctx.strokeStyle = labelColors.borderColor;
  8747. ctx.fillStyle = labelColors.backgroundColor;
  8748. drawPoint(ctx, drawOptions, centerX, centerY);
  8749. } else {
  8750. ctx.lineWidth = labelColors.borderWidth || 1;
  8751. ctx.strokeStyle = labelColors.borderColor;
  8752. ctx.setLineDash(labelColors.borderDash || []);
  8753. ctx.lineDashOffset = labelColors.borderDashOffset || 0;
  8754. const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth - boxPadding);
  8755. const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - boxPadding - 2);
  8756. const borderRadius = toTRBLCorners(labelColors.borderRadius);
  8757. if (Object.values(borderRadius).some(v => v !== 0)) {
  8758. ctx.beginPath();
  8759. ctx.fillStyle = options.multiKeyBackground;
  8760. addRoundedRectPath(ctx, {
  8761. x: outerX,
  8762. y: colorY,
  8763. w: boxWidth,
  8764. h: boxHeight,
  8765. radius: borderRadius,
  8766. });
  8767. ctx.fill();
  8768. ctx.stroke();
  8769. ctx.fillStyle = labelColors.backgroundColor;
  8770. ctx.beginPath();
  8771. addRoundedRectPath(ctx, {
  8772. x: innerX,
  8773. y: colorY + 1,
  8774. w: boxWidth - 2,
  8775. h: boxHeight - 2,
  8776. radius: borderRadius,
  8777. });
  8778. ctx.fill();
  8779. } else {
  8780. ctx.fillStyle = options.multiKeyBackground;
  8781. ctx.fillRect(outerX, colorY, boxWidth, boxHeight);
  8782. ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);
  8783. ctx.fillStyle = labelColors.backgroundColor;
  8784. ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);
  8785. }
  8786. }
  8787. ctx.fillStyle = this.labelTextColors[i];
  8788. }
  8789. drawBody(pt, ctx, options) {
  8790. const {body} = this;
  8791. const {bodySpacing, bodyAlign, displayColors, boxHeight, boxWidth, boxPadding} = options;
  8792. const bodyFont = toFont(options.bodyFont);
  8793. let bodyLineHeight = bodyFont.lineHeight;
  8794. let xLinePadding = 0;
  8795. const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);
  8796. const fillLineOfText = function(line) {
  8797. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);
  8798. pt.y += bodyLineHeight + bodySpacing;
  8799. };
  8800. const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  8801. let bodyItem, textColor, lines, i, j, ilen, jlen;
  8802. ctx.textAlign = bodyAlign;
  8803. ctx.textBaseline = 'middle';
  8804. ctx.font = bodyFont.string;
  8805. pt.x = getAlignedX(this, bodyAlignForCalculation, options);
  8806. ctx.fillStyle = options.bodyColor;
  8807. each(this.beforeBody, fillLineOfText);
  8808. xLinePadding = displayColors && bodyAlignForCalculation !== 'right'
  8809. ? bodyAlign === 'center' ? (boxWidth / 2 + boxPadding) : (boxWidth + 2 + boxPadding)
  8810. : 0;
  8811. for (i = 0, ilen = body.length; i < ilen; ++i) {
  8812. bodyItem = body[i];
  8813. textColor = this.labelTextColors[i];
  8814. ctx.fillStyle = textColor;
  8815. each(bodyItem.before, fillLineOfText);
  8816. lines = bodyItem.lines;
  8817. if (displayColors && lines.length) {
  8818. this._drawColorBox(ctx, pt, i, rtlHelper, options);
  8819. bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);
  8820. }
  8821. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  8822. fillLineOfText(lines[j]);
  8823. bodyLineHeight = bodyFont.lineHeight;
  8824. }
  8825. each(bodyItem.after, fillLineOfText);
  8826. }
  8827. xLinePadding = 0;
  8828. bodyLineHeight = bodyFont.lineHeight;
  8829. each(this.afterBody, fillLineOfText);
  8830. pt.y -= bodySpacing;
  8831. }
  8832. drawFooter(pt, ctx, options) {
  8833. const footer = this.footer;
  8834. const length = footer.length;
  8835. let footerFont, i;
  8836. if (length) {
  8837. const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width);
  8838. pt.x = getAlignedX(this, options.footerAlign, options);
  8839. pt.y += options.footerMarginTop;
  8840. ctx.textAlign = rtlHelper.textAlign(options.footerAlign);
  8841. ctx.textBaseline = 'middle';
  8842. footerFont = toFont(options.footerFont);
  8843. ctx.fillStyle = options.footerColor;
  8844. ctx.font = footerFont.string;
  8845. for (i = 0; i < length; ++i) {
  8846. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);
  8847. pt.y += footerFont.lineHeight + options.footerSpacing;
  8848. }
  8849. }
  8850. }
  8851. drawBackground(pt, ctx, tooltipSize, options) {
  8852. const {xAlign, yAlign} = this;
  8853. const {x, y} = pt;
  8854. const {width, height} = tooltipSize;
  8855. const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(options.cornerRadius);
  8856. ctx.fillStyle = options.backgroundColor;
  8857. ctx.strokeStyle = options.borderColor;
  8858. ctx.lineWidth = options.borderWidth;
  8859. ctx.beginPath();
  8860. ctx.moveTo(x + topLeft, y);
  8861. if (yAlign === 'top') {
  8862. this.drawCaret(pt, ctx, tooltipSize, options);
  8863. }
  8864. ctx.lineTo(x + width - topRight, y);
  8865. ctx.quadraticCurveTo(x + width, y, x + width, y + topRight);
  8866. if (yAlign === 'center' && xAlign === 'right') {
  8867. this.drawCaret(pt, ctx, tooltipSize, options);
  8868. }
  8869. ctx.lineTo(x + width, y + height - bottomRight);
  8870. ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height);
  8871. if (yAlign === 'bottom') {
  8872. this.drawCaret(pt, ctx, tooltipSize, options);
  8873. }
  8874. ctx.lineTo(x + bottomLeft, y + height);
  8875. ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft);
  8876. if (yAlign === 'center' && xAlign === 'left') {
  8877. this.drawCaret(pt, ctx, tooltipSize, options);
  8878. }
  8879. ctx.lineTo(x, y + topLeft);
  8880. ctx.quadraticCurveTo(x, y, x + topLeft, y);
  8881. ctx.closePath();
  8882. ctx.fill();
  8883. if (options.borderWidth > 0) {
  8884. ctx.stroke();
  8885. }
  8886. }
  8887. _updateAnimationTarget(options) {
  8888. const chart = this.chart;
  8889. const anims = this.$animations;
  8890. const animX = anims && anims.x;
  8891. const animY = anims && anims.y;
  8892. if (animX || animY) {
  8893. const position = positioners[options.position].call(this, this._active, this._eventPosition);
  8894. if (!position) {
  8895. return;
  8896. }
  8897. const size = this._size = getTooltipSize(this, options);
  8898. const positionAndSize = Object.assign({}, position, this._size);
  8899. const alignment = determineAlignment(chart, options, positionAndSize);
  8900. const point = getBackgroundPoint(options, positionAndSize, alignment, chart);
  8901. if (animX._to !== point.x || animY._to !== point.y) {
  8902. this.xAlign = alignment.xAlign;
  8903. this.yAlign = alignment.yAlign;
  8904. this.width = size.width;
  8905. this.height = size.height;
  8906. this.caretX = position.x;
  8907. this.caretY = position.y;
  8908. this._resolveAnimations().update(this, point);
  8909. }
  8910. }
  8911. }
  8912. draw(ctx) {
  8913. const options = this.options.setContext(this.getContext());
  8914. let opacity = this.opacity;
  8915. if (!opacity) {
  8916. return;
  8917. }
  8918. this._updateAnimationTarget(options);
  8919. const tooltipSize = {
  8920. width: this.width,
  8921. height: this.height
  8922. };
  8923. const pt = {
  8924. x: this.x,
  8925. y: this.y
  8926. };
  8927. opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
  8928. const padding = toPadding(options.padding);
  8929. const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length;
  8930. if (options.enabled && hasTooltipContent) {
  8931. ctx.save();
  8932. ctx.globalAlpha = opacity;
  8933. this.drawBackground(pt, ctx, tooltipSize, options);
  8934. overrideTextDirection(ctx, options.textDirection);
  8935. pt.y += padding.top;
  8936. this.drawTitle(pt, ctx, options);
  8937. this.drawBody(pt, ctx, options);
  8938. this.drawFooter(pt, ctx, options);
  8939. restoreTextDirection(ctx, options.textDirection);
  8940. ctx.restore();
  8941. }
  8942. }
  8943. getActiveElements() {
  8944. return this._active || [];
  8945. }
  8946. setActiveElements(activeElements, eventPosition) {
  8947. const lastActive = this._active;
  8948. const active = activeElements.map(({datasetIndex, index}) => {
  8949. const meta = this.chart.getDatasetMeta(datasetIndex);
  8950. if (!meta) {
  8951. throw new Error('Cannot find a dataset at index ' + datasetIndex);
  8952. }
  8953. return {
  8954. datasetIndex,
  8955. element: meta.data[index],
  8956. index,
  8957. };
  8958. });
  8959. const changed = !_elementsEqual(lastActive, active);
  8960. const positionChanged = this._positionChanged(active, eventPosition);
  8961. if (changed || positionChanged) {
  8962. this._active = active;
  8963. this._eventPosition = eventPosition;
  8964. this._ignoreReplayEvents = true;
  8965. this.update(true);
  8966. }
  8967. }
  8968. handleEvent(e, replay, inChartArea = true) {
  8969. if (replay && this._ignoreReplayEvents) {
  8970. return false;
  8971. }
  8972. this._ignoreReplayEvents = false;
  8973. const options = this.options;
  8974. const lastActive = this._active || [];
  8975. const active = this._getActiveElements(e, lastActive, replay, inChartArea);
  8976. const positionChanged = this._positionChanged(active, e);
  8977. const changed = replay || !_elementsEqual(active, lastActive) || positionChanged;
  8978. if (changed) {
  8979. this._active = active;
  8980. if (options.enabled || options.external) {
  8981. this._eventPosition = {
  8982. x: e.x,
  8983. y: e.y
  8984. };
  8985. this.update(true, replay);
  8986. }
  8987. }
  8988. return changed;
  8989. }
  8990. _getActiveElements(e, lastActive, replay, inChartArea) {
  8991. const options = this.options;
  8992. if (e.type === 'mouseout') {
  8993. return [];
  8994. }
  8995. if (!inChartArea) {
  8996. return lastActive;
  8997. }
  8998. const active = this.chart.getElementsAtEventForMode(e, options.mode, options, replay);
  8999. if (options.reverse) {
  9000. active.reverse();
  9001. }
  9002. return active;
  9003. }
  9004. _positionChanged(active, e) {
  9005. const {caretX, caretY, options} = this;
  9006. const position = positioners[options.position].call(this, active, e);
  9007. return position !== false && (caretX !== position.x || caretY !== position.y);
  9008. }
  9009. }
  9010. Tooltip.positioners = positioners;
  9011. var plugin_tooltip = {
  9012. id: 'tooltip',
  9013. _element: Tooltip,
  9014. positioners,
  9015. afterInit(chart, _args, options) {
  9016. if (options) {
  9017. chart.tooltip = new Tooltip({chart, options});
  9018. }
  9019. },
  9020. beforeUpdate(chart, _args, options) {
  9021. if (chart.tooltip) {
  9022. chart.tooltip.initialize(options);
  9023. }
  9024. },
  9025. reset(chart, _args, options) {
  9026. if (chart.tooltip) {
  9027. chart.tooltip.initialize(options);
  9028. }
  9029. },
  9030. afterDraw(chart) {
  9031. const tooltip = chart.tooltip;
  9032. const args = {
  9033. tooltip
  9034. };
  9035. if (chart.notifyPlugins('beforeTooltipDraw', args) === false) {
  9036. return;
  9037. }
  9038. if (tooltip) {
  9039. tooltip.draw(chart.ctx);
  9040. }
  9041. chart.notifyPlugins('afterTooltipDraw', args);
  9042. },
  9043. afterEvent(chart, args) {
  9044. if (chart.tooltip) {
  9045. const useFinalPosition = args.replay;
  9046. if (chart.tooltip.handleEvent(args.event, useFinalPosition, args.inChartArea)) {
  9047. args.changed = true;
  9048. }
  9049. }
  9050. },
  9051. defaults: {
  9052. enabled: true,
  9053. external: null,
  9054. position: 'average',
  9055. backgroundColor: 'rgba(0,0,0,0.8)',
  9056. titleColor: '#fff',
  9057. titleFont: {
  9058. weight: 'bold',
  9059. },
  9060. titleSpacing: 2,
  9061. titleMarginBottom: 6,
  9062. titleAlign: 'left',
  9063. bodyColor: '#fff',
  9064. bodySpacing: 2,
  9065. bodyFont: {
  9066. },
  9067. bodyAlign: 'left',
  9068. footerColor: '#fff',
  9069. footerSpacing: 2,
  9070. footerMarginTop: 6,
  9071. footerFont: {
  9072. weight: 'bold',
  9073. },
  9074. footerAlign: 'left',
  9075. padding: 6,
  9076. caretPadding: 2,
  9077. caretSize: 5,
  9078. cornerRadius: 6,
  9079. boxHeight: (ctx, opts) => opts.bodyFont.size,
  9080. boxWidth: (ctx, opts) => opts.bodyFont.size,
  9081. multiKeyBackground: '#fff',
  9082. displayColors: true,
  9083. boxPadding: 0,
  9084. borderColor: 'rgba(0,0,0,0)',
  9085. borderWidth: 0,
  9086. animation: {
  9087. duration: 400,
  9088. easing: 'easeOutQuart',
  9089. },
  9090. animations: {
  9091. numbers: {
  9092. type: 'number',
  9093. properties: ['x', 'y', 'width', 'height', 'caretX', 'caretY'],
  9094. },
  9095. opacity: {
  9096. easing: 'linear',
  9097. duration: 200
  9098. }
  9099. },
  9100. callbacks: {
  9101. beforeTitle: noop,
  9102. title(tooltipItems) {
  9103. if (tooltipItems.length > 0) {
  9104. const item = tooltipItems[0];
  9105. const labels = item.chart.data.labels;
  9106. const labelCount = labels ? labels.length : 0;
  9107. if (this && this.options && this.options.mode === 'dataset') {
  9108. return item.dataset.label || '';
  9109. } else if (item.label) {
  9110. return item.label;
  9111. } else if (labelCount > 0 && item.dataIndex < labelCount) {
  9112. return labels[item.dataIndex];
  9113. }
  9114. }
  9115. return '';
  9116. },
  9117. afterTitle: noop,
  9118. beforeBody: noop,
  9119. beforeLabel: noop,
  9120. label(tooltipItem) {
  9121. if (this && this.options && this.options.mode === 'dataset') {
  9122. return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;
  9123. }
  9124. let label = tooltipItem.dataset.label || '';
  9125. if (label) {
  9126. label += ': ';
  9127. }
  9128. const value = tooltipItem.formattedValue;
  9129. if (!isNullOrUndef(value)) {
  9130. label += value;
  9131. }
  9132. return label;
  9133. },
  9134. labelColor(tooltipItem) {
  9135. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  9136. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  9137. return {
  9138. borderColor: options.borderColor,
  9139. backgroundColor: options.backgroundColor,
  9140. borderWidth: options.borderWidth,
  9141. borderDash: options.borderDash,
  9142. borderDashOffset: options.borderDashOffset,
  9143. borderRadius: 0,
  9144. };
  9145. },
  9146. labelTextColor() {
  9147. return this.options.bodyColor;
  9148. },
  9149. labelPointStyle(tooltipItem) {
  9150. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  9151. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  9152. return {
  9153. pointStyle: options.pointStyle,
  9154. rotation: options.rotation,
  9155. };
  9156. },
  9157. afterLabel: noop,
  9158. afterBody: noop,
  9159. beforeFooter: noop,
  9160. footer: noop,
  9161. afterFooter: noop
  9162. }
  9163. },
  9164. defaultRoutes: {
  9165. bodyFont: 'font',
  9166. footerFont: 'font',
  9167. titleFont: 'font'
  9168. },
  9169. descriptors: {
  9170. _scriptable: (name) => name !== 'filter' && name !== 'itemSort' && name !== 'external',
  9171. _indexable: false,
  9172. callbacks: {
  9173. _scriptable: false,
  9174. _indexable: false,
  9175. },
  9176. animation: {
  9177. _fallback: false
  9178. },
  9179. animations: {
  9180. _fallback: 'animation'
  9181. }
  9182. },
  9183. additionalOptionScopes: ['interaction']
  9184. };
  9185. var plugins = /*#__PURE__*/Object.freeze({
  9186. __proto__: null,
  9187. Decimation: plugin_decimation,
  9188. Filler: index,
  9189. Legend: plugin_legend,
  9190. SubTitle: plugin_subtitle,
  9191. Title: plugin_title,
  9192. Tooltip: plugin_tooltip
  9193. });
  9194. const addIfString = (labels, raw, index, addedLabels) => {
  9195. if (typeof raw === 'string') {
  9196. index = labels.push(raw) - 1;
  9197. addedLabels.unshift({index, label: raw});
  9198. } else if (isNaN(raw)) {
  9199. index = null;
  9200. }
  9201. return index;
  9202. };
  9203. function findOrAddLabel(labels, raw, index, addedLabels) {
  9204. const first = labels.indexOf(raw);
  9205. if (first === -1) {
  9206. return addIfString(labels, raw, index, addedLabels);
  9207. }
  9208. const last = labels.lastIndexOf(raw);
  9209. return first !== last ? index : first;
  9210. }
  9211. const validIndex = (index, max) => index === null ? null : _limitValue(Math.round(index), 0, max);
  9212. class CategoryScale extends Scale {
  9213. constructor(cfg) {
  9214. super(cfg);
  9215. this._startValue = undefined;
  9216. this._valueRange = 0;
  9217. this._addedLabels = [];
  9218. }
  9219. init(scaleOptions) {
  9220. const added = this._addedLabels;
  9221. if (added.length) {
  9222. const labels = this.getLabels();
  9223. for (const {index, label} of added) {
  9224. if (labels[index] === label) {
  9225. labels.splice(index, 1);
  9226. }
  9227. }
  9228. this._addedLabels = [];
  9229. }
  9230. super.init(scaleOptions);
  9231. }
  9232. parse(raw, index) {
  9233. if (isNullOrUndef(raw)) {
  9234. return null;
  9235. }
  9236. const labels = this.getLabels();
  9237. index = isFinite(index) && labels[index] === raw ? index
  9238. : findOrAddLabel(labels, raw, valueOrDefault(index, raw), this._addedLabels);
  9239. return validIndex(index, labels.length - 1);
  9240. }
  9241. determineDataLimits() {
  9242. const {minDefined, maxDefined} = this.getUserBounds();
  9243. let {min, max} = this.getMinMax(true);
  9244. if (this.options.bounds === 'ticks') {
  9245. if (!minDefined) {
  9246. min = 0;
  9247. }
  9248. if (!maxDefined) {
  9249. max = this.getLabels().length - 1;
  9250. }
  9251. }
  9252. this.min = min;
  9253. this.max = max;
  9254. }
  9255. buildTicks() {
  9256. const min = this.min;
  9257. const max = this.max;
  9258. const offset = this.options.offset;
  9259. const ticks = [];
  9260. let labels = this.getLabels();
  9261. labels = (min === 0 && max === labels.length - 1) ? labels : labels.slice(min, max + 1);
  9262. this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);
  9263. this._startValue = this.min - (offset ? 0.5 : 0);
  9264. for (let value = min; value <= max; value++) {
  9265. ticks.push({value});
  9266. }
  9267. return ticks;
  9268. }
  9269. getLabelForValue(value) {
  9270. const labels = this.getLabels();
  9271. if (value >= 0 && value < labels.length) {
  9272. return labels[value];
  9273. }
  9274. return value;
  9275. }
  9276. configure() {
  9277. super.configure();
  9278. if (!this.isHorizontal()) {
  9279. this._reversePixels = !this._reversePixels;
  9280. }
  9281. }
  9282. getPixelForValue(value) {
  9283. if (typeof value !== 'number') {
  9284. value = this.parse(value);
  9285. }
  9286. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  9287. }
  9288. getPixelForTick(index) {
  9289. const ticks = this.ticks;
  9290. if (index < 0 || index > ticks.length - 1) {
  9291. return null;
  9292. }
  9293. return this.getPixelForValue(ticks[index].value);
  9294. }
  9295. getValueForPixel(pixel) {
  9296. return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange);
  9297. }
  9298. getBasePixel() {
  9299. return this.bottom;
  9300. }
  9301. }
  9302. CategoryScale.id = 'category';
  9303. CategoryScale.defaults = {
  9304. ticks: {
  9305. callback: CategoryScale.prototype.getLabelForValue
  9306. }
  9307. };
  9308. function generateTicks$1(generationOptions, dataRange) {
  9309. const ticks = [];
  9310. const MIN_SPACING = 1e-14;
  9311. const {bounds, step, min, max, precision, count, maxTicks, maxDigits, includeBounds} = generationOptions;
  9312. const unit = step || 1;
  9313. const maxSpaces = maxTicks - 1;
  9314. const {min: rmin, max: rmax} = dataRange;
  9315. const minDefined = !isNullOrUndef(min);
  9316. const maxDefined = !isNullOrUndef(max);
  9317. const countDefined = !isNullOrUndef(count);
  9318. const minSpacing = (rmax - rmin) / (maxDigits + 1);
  9319. let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit;
  9320. let factor, niceMin, niceMax, numSpaces;
  9321. if (spacing < MIN_SPACING && !minDefined && !maxDefined) {
  9322. return [{value: rmin}, {value: rmax}];
  9323. }
  9324. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  9325. if (numSpaces > maxSpaces) {
  9326. spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit;
  9327. }
  9328. if (!isNullOrUndef(precision)) {
  9329. factor = Math.pow(10, precision);
  9330. spacing = Math.ceil(spacing * factor) / factor;
  9331. }
  9332. if (bounds === 'ticks') {
  9333. niceMin = Math.floor(rmin / spacing) * spacing;
  9334. niceMax = Math.ceil(rmax / spacing) * spacing;
  9335. } else {
  9336. niceMin = rmin;
  9337. niceMax = rmax;
  9338. }
  9339. if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) {
  9340. numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks));
  9341. spacing = (max - min) / numSpaces;
  9342. niceMin = min;
  9343. niceMax = max;
  9344. } else if (countDefined) {
  9345. niceMin = minDefined ? min : niceMin;
  9346. niceMax = maxDefined ? max : niceMax;
  9347. numSpaces = count - 1;
  9348. spacing = (niceMax - niceMin) / numSpaces;
  9349. } else {
  9350. numSpaces = (niceMax - niceMin) / spacing;
  9351. if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  9352. numSpaces = Math.round(numSpaces);
  9353. } else {
  9354. numSpaces = Math.ceil(numSpaces);
  9355. }
  9356. }
  9357. const decimalPlaces = Math.max(
  9358. _decimalPlaces(spacing),
  9359. _decimalPlaces(niceMin)
  9360. );
  9361. factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision);
  9362. niceMin = Math.round(niceMin * factor) / factor;
  9363. niceMax = Math.round(niceMax * factor) / factor;
  9364. let j = 0;
  9365. if (minDefined) {
  9366. if (includeBounds && niceMin !== min) {
  9367. ticks.push({value: min});
  9368. if (niceMin < min) {
  9369. j++;
  9370. }
  9371. if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) {
  9372. j++;
  9373. }
  9374. } else if (niceMin < min) {
  9375. j++;
  9376. }
  9377. }
  9378. for (; j < numSpaces; ++j) {
  9379. ticks.push({value: Math.round((niceMin + j * spacing) * factor) / factor});
  9380. }
  9381. if (maxDefined && includeBounds && niceMax !== max) {
  9382. if (ticks.length && almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) {
  9383. ticks[ticks.length - 1].value = max;
  9384. } else {
  9385. ticks.push({value: max});
  9386. }
  9387. } else if (!maxDefined || niceMax === max) {
  9388. ticks.push({value: niceMax});
  9389. }
  9390. return ticks;
  9391. }
  9392. function relativeLabelSize(value, minSpacing, {horizontal, minRotation}) {
  9393. const rad = toRadians(minRotation);
  9394. const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001;
  9395. const length = 0.75 * minSpacing * ('' + value).length;
  9396. return Math.min(minSpacing / ratio, length);
  9397. }
  9398. class LinearScaleBase extends Scale {
  9399. constructor(cfg) {
  9400. super(cfg);
  9401. this.start = undefined;
  9402. this.end = undefined;
  9403. this._startValue = undefined;
  9404. this._endValue = undefined;
  9405. this._valueRange = 0;
  9406. }
  9407. parse(raw, index) {
  9408. if (isNullOrUndef(raw)) {
  9409. return null;
  9410. }
  9411. if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {
  9412. return null;
  9413. }
  9414. return +raw;
  9415. }
  9416. handleTickRangeOptions() {
  9417. const {beginAtZero} = this.options;
  9418. const {minDefined, maxDefined} = this.getUserBounds();
  9419. let {min, max} = this;
  9420. const setMin = v => (min = minDefined ? min : v);
  9421. const setMax = v => (max = maxDefined ? max : v);
  9422. if (beginAtZero) {
  9423. const minSign = sign(min);
  9424. const maxSign = sign(max);
  9425. if (minSign < 0 && maxSign < 0) {
  9426. setMax(0);
  9427. } else if (minSign > 0 && maxSign > 0) {
  9428. setMin(0);
  9429. }
  9430. }
  9431. if (min === max) {
  9432. let offset = 1;
  9433. if (max >= Number.MAX_SAFE_INTEGER || min <= Number.MIN_SAFE_INTEGER) {
  9434. offset = Math.abs(max * 0.05);
  9435. }
  9436. setMax(max + offset);
  9437. if (!beginAtZero) {
  9438. setMin(min - offset);
  9439. }
  9440. }
  9441. this.min = min;
  9442. this.max = max;
  9443. }
  9444. getTickLimit() {
  9445. const tickOpts = this.options.ticks;
  9446. let {maxTicksLimit, stepSize} = tickOpts;
  9447. let maxTicks;
  9448. if (stepSize) {
  9449. maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1;
  9450. if (maxTicks > 1000) {
  9451. console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`);
  9452. maxTicks = 1000;
  9453. }
  9454. } else {
  9455. maxTicks = this.computeTickLimit();
  9456. maxTicksLimit = maxTicksLimit || 11;
  9457. }
  9458. if (maxTicksLimit) {
  9459. maxTicks = Math.min(maxTicksLimit, maxTicks);
  9460. }
  9461. return maxTicks;
  9462. }
  9463. computeTickLimit() {
  9464. return Number.POSITIVE_INFINITY;
  9465. }
  9466. buildTicks() {
  9467. const opts = this.options;
  9468. const tickOpts = opts.ticks;
  9469. let maxTicks = this.getTickLimit();
  9470. maxTicks = Math.max(2, maxTicks);
  9471. const numericGeneratorOptions = {
  9472. maxTicks,
  9473. bounds: opts.bounds,
  9474. min: opts.min,
  9475. max: opts.max,
  9476. precision: tickOpts.precision,
  9477. step: tickOpts.stepSize,
  9478. count: tickOpts.count,
  9479. maxDigits: this._maxDigits(),
  9480. horizontal: this.isHorizontal(),
  9481. minRotation: tickOpts.minRotation || 0,
  9482. includeBounds: tickOpts.includeBounds !== false
  9483. };
  9484. const dataRange = this._range || this;
  9485. const ticks = generateTicks$1(numericGeneratorOptions, dataRange);
  9486. if (opts.bounds === 'ticks') {
  9487. _setMinAndMaxByKey(ticks, this, 'value');
  9488. }
  9489. if (opts.reverse) {
  9490. ticks.reverse();
  9491. this.start = this.max;
  9492. this.end = this.min;
  9493. } else {
  9494. this.start = this.min;
  9495. this.end = this.max;
  9496. }
  9497. return ticks;
  9498. }
  9499. configure() {
  9500. const ticks = this.ticks;
  9501. let start = this.min;
  9502. let end = this.max;
  9503. super.configure();
  9504. if (this.options.offset && ticks.length) {
  9505. const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  9506. start -= offset;
  9507. end += offset;
  9508. }
  9509. this._startValue = start;
  9510. this._endValue = end;
  9511. this._valueRange = end - start;
  9512. }
  9513. getLabelForValue(value) {
  9514. return formatNumber(value, this.chart.options.locale, this.options.ticks.format);
  9515. }
  9516. }
  9517. class LinearScale extends LinearScaleBase {
  9518. determineDataLimits() {
  9519. const {min, max} = this.getMinMax(true);
  9520. this.min = isNumberFinite(min) ? min : 0;
  9521. this.max = isNumberFinite(max) ? max : 1;
  9522. this.handleTickRangeOptions();
  9523. }
  9524. computeTickLimit() {
  9525. const horizontal = this.isHorizontal();
  9526. const length = horizontal ? this.width : this.height;
  9527. const minRotation = toRadians(this.options.ticks.minRotation);
  9528. const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001;
  9529. const tickFont = this._resolveTickFontOptions(0);
  9530. return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio));
  9531. }
  9532. getPixelForValue(value) {
  9533. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  9534. }
  9535. getValueForPixel(pixel) {
  9536. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  9537. }
  9538. }
  9539. LinearScale.id = 'linear';
  9540. LinearScale.defaults = {
  9541. ticks: {
  9542. callback: Ticks.formatters.numeric
  9543. }
  9544. };
  9545. function isMajor(tickVal) {
  9546. const remain = tickVal / (Math.pow(10, Math.floor(log10(tickVal))));
  9547. return remain === 1;
  9548. }
  9549. function generateTicks(generationOptions, dataRange) {
  9550. const endExp = Math.floor(log10(dataRange.max));
  9551. const endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  9552. const ticks = [];
  9553. let tickVal = finiteOrDefault(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  9554. let exp = Math.floor(log10(tickVal));
  9555. let significand = Math.floor(tickVal / Math.pow(10, exp));
  9556. let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  9557. do {
  9558. ticks.push({value: tickVal, major: isMajor(tickVal)});
  9559. ++significand;
  9560. if (significand === 10) {
  9561. significand = 1;
  9562. ++exp;
  9563. precision = exp >= 0 ? 1 : precision;
  9564. }
  9565. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  9566. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  9567. const lastTick = finiteOrDefault(generationOptions.max, tickVal);
  9568. ticks.push({value: lastTick, major: isMajor(tickVal)});
  9569. return ticks;
  9570. }
  9571. class LogarithmicScale extends Scale {
  9572. constructor(cfg) {
  9573. super(cfg);
  9574. this.start = undefined;
  9575. this.end = undefined;
  9576. this._startValue = undefined;
  9577. this._valueRange = 0;
  9578. }
  9579. parse(raw, index) {
  9580. const value = LinearScaleBase.prototype.parse.apply(this, [raw, index]);
  9581. if (value === 0) {
  9582. this._zero = true;
  9583. return undefined;
  9584. }
  9585. return isNumberFinite(value) && value > 0 ? value : null;
  9586. }
  9587. determineDataLimits() {
  9588. const {min, max} = this.getMinMax(true);
  9589. this.min = isNumberFinite(min) ? Math.max(0, min) : null;
  9590. this.max = isNumberFinite(max) ? Math.max(0, max) : null;
  9591. if (this.options.beginAtZero) {
  9592. this._zero = true;
  9593. }
  9594. this.handleTickRangeOptions();
  9595. }
  9596. handleTickRangeOptions() {
  9597. const {minDefined, maxDefined} = this.getUserBounds();
  9598. let min = this.min;
  9599. let max = this.max;
  9600. const setMin = v => (min = minDefined ? min : v);
  9601. const setMax = v => (max = maxDefined ? max : v);
  9602. const exp = (v, m) => Math.pow(10, Math.floor(log10(v)) + m);
  9603. if (min === max) {
  9604. if (min <= 0) {
  9605. setMin(1);
  9606. setMax(10);
  9607. } else {
  9608. setMin(exp(min, -1));
  9609. setMax(exp(max, +1));
  9610. }
  9611. }
  9612. if (min <= 0) {
  9613. setMin(exp(max, -1));
  9614. }
  9615. if (max <= 0) {
  9616. setMax(exp(min, +1));
  9617. }
  9618. if (this._zero && this.min !== this._suggestedMin && min === exp(this.min, 0)) {
  9619. setMin(exp(min, -1));
  9620. }
  9621. this.min = min;
  9622. this.max = max;
  9623. }
  9624. buildTicks() {
  9625. const opts = this.options;
  9626. const generationOptions = {
  9627. min: this._userMin,
  9628. max: this._userMax
  9629. };
  9630. const ticks = generateTicks(generationOptions, this);
  9631. if (opts.bounds === 'ticks') {
  9632. _setMinAndMaxByKey(ticks, this, 'value');
  9633. }
  9634. if (opts.reverse) {
  9635. ticks.reverse();
  9636. this.start = this.max;
  9637. this.end = this.min;
  9638. } else {
  9639. this.start = this.min;
  9640. this.end = this.max;
  9641. }
  9642. return ticks;
  9643. }
  9644. getLabelForValue(value) {
  9645. return value === undefined
  9646. ? '0'
  9647. : formatNumber(value, this.chart.options.locale, this.options.ticks.format);
  9648. }
  9649. configure() {
  9650. const start = this.min;
  9651. super.configure();
  9652. this._startValue = log10(start);
  9653. this._valueRange = log10(this.max) - log10(start);
  9654. }
  9655. getPixelForValue(value) {
  9656. if (value === undefined || value === 0) {
  9657. value = this.min;
  9658. }
  9659. if (value === null || isNaN(value)) {
  9660. return NaN;
  9661. }
  9662. return this.getPixelForDecimal(value === this.min
  9663. ? 0
  9664. : (log10(value) - this._startValue) / this._valueRange);
  9665. }
  9666. getValueForPixel(pixel) {
  9667. const decimal = this.getDecimalForPixel(pixel);
  9668. return Math.pow(10, this._startValue + decimal * this._valueRange);
  9669. }
  9670. }
  9671. LogarithmicScale.id = 'logarithmic';
  9672. LogarithmicScale.defaults = {
  9673. ticks: {
  9674. callback: Ticks.formatters.logarithmic,
  9675. major: {
  9676. enabled: true
  9677. }
  9678. }
  9679. };
  9680. function getTickBackdropHeight(opts) {
  9681. const tickOpts = opts.ticks;
  9682. if (tickOpts.display && opts.display) {
  9683. const padding = toPadding(tickOpts.backdropPadding);
  9684. return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height;
  9685. }
  9686. return 0;
  9687. }
  9688. function measureLabelSize(ctx, font, label) {
  9689. label = isArray(label) ? label : [label];
  9690. return {
  9691. w: _longestText(ctx, font.string, label),
  9692. h: label.length * font.lineHeight
  9693. };
  9694. }
  9695. function determineLimits(angle, pos, size, min, max) {
  9696. if (angle === min || angle === max) {
  9697. return {
  9698. start: pos - (size / 2),
  9699. end: pos + (size / 2)
  9700. };
  9701. } else if (angle < min || angle > max) {
  9702. return {
  9703. start: pos - size,
  9704. end: pos
  9705. };
  9706. }
  9707. return {
  9708. start: pos,
  9709. end: pos + size
  9710. };
  9711. }
  9712. function fitWithPointLabels(scale) {
  9713. const orig = {
  9714. l: scale.left + scale._padding.left,
  9715. r: scale.right - scale._padding.right,
  9716. t: scale.top + scale._padding.top,
  9717. b: scale.bottom - scale._padding.bottom
  9718. };
  9719. const limits = Object.assign({}, orig);
  9720. const labelSizes = [];
  9721. const padding = [];
  9722. const valueCount = scale._pointLabels.length;
  9723. const pointLabelOpts = scale.options.pointLabels;
  9724. const additionalAngle = pointLabelOpts.centerPointLabels ? PI / valueCount : 0;
  9725. for (let i = 0; i < valueCount; i++) {
  9726. const opts = pointLabelOpts.setContext(scale.getPointLabelContext(i));
  9727. padding[i] = opts.padding;
  9728. const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i], additionalAngle);
  9729. const plFont = toFont(opts.font);
  9730. const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]);
  9731. labelSizes[i] = textSize;
  9732. const angleRadians = _normalizeAngle(scale.getIndexAngle(i) + additionalAngle);
  9733. const angle = Math.round(toDegrees(angleRadians));
  9734. const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  9735. const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  9736. updateLimits(limits, orig, angleRadians, hLimits, vLimits);
  9737. }
  9738. scale.setCenterPoint(
  9739. orig.l - limits.l,
  9740. limits.r - orig.r,
  9741. orig.t - limits.t,
  9742. limits.b - orig.b
  9743. );
  9744. scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding);
  9745. }
  9746. function updateLimits(limits, orig, angle, hLimits, vLimits) {
  9747. const sin = Math.abs(Math.sin(angle));
  9748. const cos = Math.abs(Math.cos(angle));
  9749. let x = 0;
  9750. let y = 0;
  9751. if (hLimits.start < orig.l) {
  9752. x = (orig.l - hLimits.start) / sin;
  9753. limits.l = Math.min(limits.l, orig.l - x);
  9754. } else if (hLimits.end > orig.r) {
  9755. x = (hLimits.end - orig.r) / sin;
  9756. limits.r = Math.max(limits.r, orig.r + x);
  9757. }
  9758. if (vLimits.start < orig.t) {
  9759. y = (orig.t - vLimits.start) / cos;
  9760. limits.t = Math.min(limits.t, orig.t - y);
  9761. } else if (vLimits.end > orig.b) {
  9762. y = (vLimits.end - orig.b) / cos;
  9763. limits.b = Math.max(limits.b, orig.b + y);
  9764. }
  9765. }
  9766. function buildPointLabelItems(scale, labelSizes, padding) {
  9767. const items = [];
  9768. const valueCount = scale._pointLabels.length;
  9769. const opts = scale.options;
  9770. const extra = getTickBackdropHeight(opts) / 2;
  9771. const outerDistance = scale.drawingArea;
  9772. const additionalAngle = opts.pointLabels.centerPointLabels ? PI / valueCount : 0;
  9773. for (let i = 0; i < valueCount; i++) {
  9774. const pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + padding[i], additionalAngle);
  9775. const angle = Math.round(toDegrees(_normalizeAngle(pointLabelPosition.angle + HALF_PI)));
  9776. const size = labelSizes[i];
  9777. const y = yForAngle(pointLabelPosition.y, size.h, angle);
  9778. const textAlign = getTextAlignForAngle(angle);
  9779. const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign);
  9780. items.push({
  9781. x: pointLabelPosition.x,
  9782. y,
  9783. textAlign,
  9784. left,
  9785. top: y,
  9786. right: left + size.w,
  9787. bottom: y + size.h
  9788. });
  9789. }
  9790. return items;
  9791. }
  9792. function getTextAlignForAngle(angle) {
  9793. if (angle === 0 || angle === 180) {
  9794. return 'center';
  9795. } else if (angle < 180) {
  9796. return 'left';
  9797. }
  9798. return 'right';
  9799. }
  9800. function leftForTextAlign(x, w, align) {
  9801. if (align === 'right') {
  9802. x -= w;
  9803. } else if (align === 'center') {
  9804. x -= (w / 2);
  9805. }
  9806. return x;
  9807. }
  9808. function yForAngle(y, h, angle) {
  9809. if (angle === 90 || angle === 270) {
  9810. y -= (h / 2);
  9811. } else if (angle > 270 || angle < 90) {
  9812. y -= h;
  9813. }
  9814. return y;
  9815. }
  9816. function drawPointLabels(scale, labelCount) {
  9817. const {ctx, options: {pointLabels}} = scale;
  9818. for (let i = labelCount - 1; i >= 0; i--) {
  9819. const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i));
  9820. const plFont = toFont(optsAtIndex.font);
  9821. const {x, y, textAlign, left, top, right, bottom} = scale._pointLabelItems[i];
  9822. const {backdropColor} = optsAtIndex;
  9823. if (!isNullOrUndef(backdropColor)) {
  9824. const padding = toPadding(optsAtIndex.backdropPadding);
  9825. ctx.fillStyle = backdropColor;
  9826. ctx.fillRect(left - padding.left, top - padding.top, right - left + padding.width, bottom - top + padding.height);
  9827. }
  9828. renderText(
  9829. ctx,
  9830. scale._pointLabels[i],
  9831. x,
  9832. y + (plFont.lineHeight / 2),
  9833. plFont,
  9834. {
  9835. color: optsAtIndex.color,
  9836. textAlign: textAlign,
  9837. textBaseline: 'middle'
  9838. }
  9839. );
  9840. }
  9841. }
  9842. function pathRadiusLine(scale, radius, circular, labelCount) {
  9843. const {ctx} = scale;
  9844. if (circular) {
  9845. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU);
  9846. } else {
  9847. let pointPosition = scale.getPointPosition(0, radius);
  9848. ctx.moveTo(pointPosition.x, pointPosition.y);
  9849. for (let i = 1; i < labelCount; i++) {
  9850. pointPosition = scale.getPointPosition(i, radius);
  9851. ctx.lineTo(pointPosition.x, pointPosition.y);
  9852. }
  9853. }
  9854. }
  9855. function drawRadiusLine(scale, gridLineOpts, radius, labelCount) {
  9856. const ctx = scale.ctx;
  9857. const circular = gridLineOpts.circular;
  9858. const {color, lineWidth} = gridLineOpts;
  9859. if ((!circular && !labelCount) || !color || !lineWidth || radius < 0) {
  9860. return;
  9861. }
  9862. ctx.save();
  9863. ctx.strokeStyle = color;
  9864. ctx.lineWidth = lineWidth;
  9865. ctx.setLineDash(gridLineOpts.borderDash);
  9866. ctx.lineDashOffset = gridLineOpts.borderDashOffset;
  9867. ctx.beginPath();
  9868. pathRadiusLine(scale, radius, circular, labelCount);
  9869. ctx.closePath();
  9870. ctx.stroke();
  9871. ctx.restore();
  9872. }
  9873. function createPointLabelContext(parent, index, label) {
  9874. return createContext(parent, {
  9875. label,
  9876. index,
  9877. type: 'pointLabel'
  9878. });
  9879. }
  9880. class RadialLinearScale extends LinearScaleBase {
  9881. constructor(cfg) {
  9882. super(cfg);
  9883. this.xCenter = undefined;
  9884. this.yCenter = undefined;
  9885. this.drawingArea = undefined;
  9886. this._pointLabels = [];
  9887. this._pointLabelItems = [];
  9888. }
  9889. setDimensions() {
  9890. const padding = this._padding = toPadding(getTickBackdropHeight(this.options) / 2);
  9891. const w = this.width = this.maxWidth - padding.width;
  9892. const h = this.height = this.maxHeight - padding.height;
  9893. this.xCenter = Math.floor(this.left + w / 2 + padding.left);
  9894. this.yCenter = Math.floor(this.top + h / 2 + padding.top);
  9895. this.drawingArea = Math.floor(Math.min(w, h) / 2);
  9896. }
  9897. determineDataLimits() {
  9898. const {min, max} = this.getMinMax(false);
  9899. this.min = isNumberFinite(min) && !isNaN(min) ? min : 0;
  9900. this.max = isNumberFinite(max) && !isNaN(max) ? max : 0;
  9901. this.handleTickRangeOptions();
  9902. }
  9903. computeTickLimit() {
  9904. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  9905. }
  9906. generateTickLabels(ticks) {
  9907. LinearScaleBase.prototype.generateTickLabels.call(this, ticks);
  9908. this._pointLabels = this.getLabels()
  9909. .map((value, index) => {
  9910. const label = callback(this.options.pointLabels.callback, [value, index], this);
  9911. return label || label === 0 ? label : '';
  9912. })
  9913. .filter((v, i) => this.chart.getDataVisibility(i));
  9914. }
  9915. fit() {
  9916. const opts = this.options;
  9917. if (opts.display && opts.pointLabels.display) {
  9918. fitWithPointLabels(this);
  9919. } else {
  9920. this.setCenterPoint(0, 0, 0, 0);
  9921. }
  9922. }
  9923. setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {
  9924. this.xCenter += Math.floor((leftMovement - rightMovement) / 2);
  9925. this.yCenter += Math.floor((topMovement - bottomMovement) / 2);
  9926. this.drawingArea -= Math.min(this.drawingArea / 2, Math.max(leftMovement, rightMovement, topMovement, bottomMovement));
  9927. }
  9928. getIndexAngle(index) {
  9929. const angleMultiplier = TAU / (this._pointLabels.length || 1);
  9930. const startAngle = this.options.startAngle || 0;
  9931. return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));
  9932. }
  9933. getDistanceFromCenterForValue(value) {
  9934. if (isNullOrUndef(value)) {
  9935. return NaN;
  9936. }
  9937. const scalingFactor = this.drawingArea / (this.max - this.min);
  9938. if (this.options.reverse) {
  9939. return (this.max - value) * scalingFactor;
  9940. }
  9941. return (value - this.min) * scalingFactor;
  9942. }
  9943. getValueForDistanceFromCenter(distance) {
  9944. if (isNullOrUndef(distance)) {
  9945. return NaN;
  9946. }
  9947. const scaledDistance = distance / (this.drawingArea / (this.max - this.min));
  9948. return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance;
  9949. }
  9950. getPointLabelContext(index) {
  9951. const pointLabels = this._pointLabels || [];
  9952. if (index >= 0 && index < pointLabels.length) {
  9953. const pointLabel = pointLabels[index];
  9954. return createPointLabelContext(this.getContext(), index, pointLabel);
  9955. }
  9956. }
  9957. getPointPosition(index, distanceFromCenter, additionalAngle = 0) {
  9958. const angle = this.getIndexAngle(index) - HALF_PI + additionalAngle;
  9959. return {
  9960. x: Math.cos(angle) * distanceFromCenter + this.xCenter,
  9961. y: Math.sin(angle) * distanceFromCenter + this.yCenter,
  9962. angle
  9963. };
  9964. }
  9965. getPointPositionForValue(index, value) {
  9966. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  9967. }
  9968. getBasePosition(index) {
  9969. return this.getPointPositionForValue(index || 0, this.getBaseValue());
  9970. }
  9971. getPointLabelPosition(index) {
  9972. const {left, top, right, bottom} = this._pointLabelItems[index];
  9973. return {
  9974. left,
  9975. top,
  9976. right,
  9977. bottom,
  9978. };
  9979. }
  9980. drawBackground() {
  9981. const {backgroundColor, grid: {circular}} = this.options;
  9982. if (backgroundColor) {
  9983. const ctx = this.ctx;
  9984. ctx.save();
  9985. ctx.beginPath();
  9986. pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this._pointLabels.length);
  9987. ctx.closePath();
  9988. ctx.fillStyle = backgroundColor;
  9989. ctx.fill();
  9990. ctx.restore();
  9991. }
  9992. }
  9993. drawGrid() {
  9994. const ctx = this.ctx;
  9995. const opts = this.options;
  9996. const {angleLines, grid} = opts;
  9997. const labelCount = this._pointLabels.length;
  9998. let i, offset, position;
  9999. if (opts.pointLabels.display) {
  10000. drawPointLabels(this, labelCount);
  10001. }
  10002. if (grid.display) {
  10003. this.ticks.forEach((tick, index) => {
  10004. if (index !== 0) {
  10005. offset = this.getDistanceFromCenterForValue(tick.value);
  10006. const optsAtIndex = grid.setContext(this.getContext(index - 1));
  10007. drawRadiusLine(this, optsAtIndex, offset, labelCount);
  10008. }
  10009. });
  10010. }
  10011. if (angleLines.display) {
  10012. ctx.save();
  10013. for (i = labelCount - 1; i >= 0; i--) {
  10014. const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i));
  10015. const {color, lineWidth} = optsAtIndex;
  10016. if (!lineWidth || !color) {
  10017. continue;
  10018. }
  10019. ctx.lineWidth = lineWidth;
  10020. ctx.strokeStyle = color;
  10021. ctx.setLineDash(optsAtIndex.borderDash);
  10022. ctx.lineDashOffset = optsAtIndex.borderDashOffset;
  10023. offset = this.getDistanceFromCenterForValue(opts.ticks.reverse ? this.min : this.max);
  10024. position = this.getPointPosition(i, offset);
  10025. ctx.beginPath();
  10026. ctx.moveTo(this.xCenter, this.yCenter);
  10027. ctx.lineTo(position.x, position.y);
  10028. ctx.stroke();
  10029. }
  10030. ctx.restore();
  10031. }
  10032. }
  10033. drawBorder() {}
  10034. drawLabels() {
  10035. const ctx = this.ctx;
  10036. const opts = this.options;
  10037. const tickOpts = opts.ticks;
  10038. if (!tickOpts.display) {
  10039. return;
  10040. }
  10041. const startAngle = this.getIndexAngle(0);
  10042. let offset, width;
  10043. ctx.save();
  10044. ctx.translate(this.xCenter, this.yCenter);
  10045. ctx.rotate(startAngle);
  10046. ctx.textAlign = 'center';
  10047. ctx.textBaseline = 'middle';
  10048. this.ticks.forEach((tick, index) => {
  10049. if (index === 0 && !opts.reverse) {
  10050. return;
  10051. }
  10052. const optsAtIndex = tickOpts.setContext(this.getContext(index));
  10053. const tickFont = toFont(optsAtIndex.font);
  10054. offset = this.getDistanceFromCenterForValue(this.ticks[index].value);
  10055. if (optsAtIndex.showLabelBackdrop) {
  10056. ctx.font = tickFont.string;
  10057. width = ctx.measureText(tick.label).width;
  10058. ctx.fillStyle = optsAtIndex.backdropColor;
  10059. const padding = toPadding(optsAtIndex.backdropPadding);
  10060. ctx.fillRect(
  10061. -width / 2 - padding.left,
  10062. -offset - tickFont.size / 2 - padding.top,
  10063. width + padding.width,
  10064. tickFont.size + padding.height
  10065. );
  10066. }
  10067. renderText(ctx, tick.label, 0, -offset, tickFont, {
  10068. color: optsAtIndex.color,
  10069. });
  10070. });
  10071. ctx.restore();
  10072. }
  10073. drawTitle() {}
  10074. }
  10075. RadialLinearScale.id = 'radialLinear';
  10076. RadialLinearScale.defaults = {
  10077. display: true,
  10078. animate: true,
  10079. position: 'chartArea',
  10080. angleLines: {
  10081. display: true,
  10082. lineWidth: 1,
  10083. borderDash: [],
  10084. borderDashOffset: 0.0
  10085. },
  10086. grid: {
  10087. circular: false
  10088. },
  10089. startAngle: 0,
  10090. ticks: {
  10091. showLabelBackdrop: true,
  10092. callback: Ticks.formatters.numeric
  10093. },
  10094. pointLabels: {
  10095. backdropColor: undefined,
  10096. backdropPadding: 2,
  10097. display: true,
  10098. font: {
  10099. size: 10
  10100. },
  10101. callback(label) {
  10102. return label;
  10103. },
  10104. padding: 5,
  10105. centerPointLabels: false
  10106. }
  10107. };
  10108. RadialLinearScale.defaultRoutes = {
  10109. 'angleLines.color': 'borderColor',
  10110. 'pointLabels.color': 'color',
  10111. 'ticks.color': 'color'
  10112. };
  10113. RadialLinearScale.descriptors = {
  10114. angleLines: {
  10115. _fallback: 'grid'
  10116. }
  10117. };
  10118. const INTERVALS = {
  10119. millisecond: {common: true, size: 1, steps: 1000},
  10120. second: {common: true, size: 1000, steps: 60},
  10121. minute: {common: true, size: 60000, steps: 60},
  10122. hour: {common: true, size: 3600000, steps: 24},
  10123. day: {common: true, size: 86400000, steps: 30},
  10124. week: {common: false, size: 604800000, steps: 4},
  10125. month: {common: true, size: 2.628e9, steps: 12},
  10126. quarter: {common: false, size: 7.884e9, steps: 4},
  10127. year: {common: true, size: 3.154e10}
  10128. };
  10129. const UNITS = (Object.keys(INTERVALS));
  10130. function sorter(a, b) {
  10131. return a - b;
  10132. }
  10133. function parse(scale, input) {
  10134. if (isNullOrUndef(input)) {
  10135. return null;
  10136. }
  10137. const adapter = scale._adapter;
  10138. const {parser, round, isoWeekday} = scale._parseOpts;
  10139. let value = input;
  10140. if (typeof parser === 'function') {
  10141. value = parser(value);
  10142. }
  10143. if (!isNumberFinite(value)) {
  10144. value = typeof parser === 'string'
  10145. ? adapter.parse(value, parser)
  10146. : adapter.parse(value);
  10147. }
  10148. if (value === null) {
  10149. return null;
  10150. }
  10151. if (round) {
  10152. value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true)
  10153. ? adapter.startOf(value, 'isoWeek', isoWeekday)
  10154. : adapter.startOf(value, round);
  10155. }
  10156. return +value;
  10157. }
  10158. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  10159. const ilen = UNITS.length;
  10160. for (let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  10161. const interval = INTERVALS[UNITS[i]];
  10162. const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;
  10163. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  10164. return UNITS[i];
  10165. }
  10166. }
  10167. return UNITS[ilen - 1];
  10168. }
  10169. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  10170. for (let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  10171. const unit = UNITS[i];
  10172. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  10173. return unit;
  10174. }
  10175. }
  10176. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  10177. }
  10178. function determineMajorUnit(unit) {
  10179. for (let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  10180. if (INTERVALS[UNITS[i]].common) {
  10181. return UNITS[i];
  10182. }
  10183. }
  10184. }
  10185. function addTick(ticks, time, timestamps) {
  10186. if (!timestamps) {
  10187. ticks[time] = true;
  10188. } else if (timestamps.length) {
  10189. const {lo, hi} = _lookup(timestamps, time);
  10190. const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];
  10191. ticks[timestamp] = true;
  10192. }
  10193. }
  10194. function setMajorTicks(scale, ticks, map, majorUnit) {
  10195. const adapter = scale._adapter;
  10196. const first = +adapter.startOf(ticks[0].value, majorUnit);
  10197. const last = ticks[ticks.length - 1].value;
  10198. let major, index;
  10199. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  10200. index = map[major];
  10201. if (index >= 0) {
  10202. ticks[index].major = true;
  10203. }
  10204. }
  10205. return ticks;
  10206. }
  10207. function ticksFromTimestamps(scale, values, majorUnit) {
  10208. const ticks = [];
  10209. const map = {};
  10210. const ilen = values.length;
  10211. let i, value;
  10212. for (i = 0; i < ilen; ++i) {
  10213. value = values[i];
  10214. map[value] = i;
  10215. ticks.push({
  10216. value,
  10217. major: false
  10218. });
  10219. }
  10220. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  10221. }
  10222. class TimeScale extends Scale {
  10223. constructor(props) {
  10224. super(props);
  10225. this._cache = {
  10226. data: [],
  10227. labels: [],
  10228. all: []
  10229. };
  10230. this._unit = 'day';
  10231. this._majorUnit = undefined;
  10232. this._offsets = {};
  10233. this._normalized = false;
  10234. this._parseOpts = undefined;
  10235. }
  10236. init(scaleOpts, opts) {
  10237. const time = scaleOpts.time || (scaleOpts.time = {});
  10238. const adapter = this._adapter = new adapters._date(scaleOpts.adapters.date);
  10239. mergeIf(time.displayFormats, adapter.formats());
  10240. this._parseOpts = {
  10241. parser: time.parser,
  10242. round: time.round,
  10243. isoWeekday: time.isoWeekday
  10244. };
  10245. super.init(scaleOpts);
  10246. this._normalized = opts.normalized;
  10247. }
  10248. parse(raw, index) {
  10249. if (raw === undefined) {
  10250. return null;
  10251. }
  10252. return parse(this, raw);
  10253. }
  10254. beforeLayout() {
  10255. super.beforeLayout();
  10256. this._cache = {
  10257. data: [],
  10258. labels: [],
  10259. all: []
  10260. };
  10261. }
  10262. determineDataLimits() {
  10263. const options = this.options;
  10264. const adapter = this._adapter;
  10265. const unit = options.time.unit || 'day';
  10266. let {min, max, minDefined, maxDefined} = this.getUserBounds();
  10267. function _applyBounds(bounds) {
  10268. if (!minDefined && !isNaN(bounds.min)) {
  10269. min = Math.min(min, bounds.min);
  10270. }
  10271. if (!maxDefined && !isNaN(bounds.max)) {
  10272. max = Math.max(max, bounds.max);
  10273. }
  10274. }
  10275. if (!minDefined || !maxDefined) {
  10276. _applyBounds(this._getLabelBounds());
  10277. if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {
  10278. _applyBounds(this.getMinMax(false));
  10279. }
  10280. }
  10281. min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);
  10282. max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;
  10283. this.min = Math.min(min, max - 1);
  10284. this.max = Math.max(min + 1, max);
  10285. }
  10286. _getLabelBounds() {
  10287. const arr = this.getLabelTimestamps();
  10288. let min = Number.POSITIVE_INFINITY;
  10289. let max = Number.NEGATIVE_INFINITY;
  10290. if (arr.length) {
  10291. min = arr[0];
  10292. max = arr[arr.length - 1];
  10293. }
  10294. return {min, max};
  10295. }
  10296. buildTicks() {
  10297. const options = this.options;
  10298. const timeOpts = options.time;
  10299. const tickOpts = options.ticks;
  10300. const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate();
  10301. if (options.bounds === 'ticks' && timestamps.length) {
  10302. this.min = this._userMin || timestamps[0];
  10303. this.max = this._userMax || timestamps[timestamps.length - 1];
  10304. }
  10305. const min = this.min;
  10306. const max = this.max;
  10307. const ticks = _filterBetween(timestamps, min, max);
  10308. this._unit = timeOpts.unit || (tickOpts.autoSkip
  10309. ? determineUnitForAutoTicks(timeOpts.minUnit, this.min, this.max, this._getLabelCapacity(min))
  10310. : determineUnitForFormatting(this, ticks.length, timeOpts.minUnit, this.min, this.max));
  10311. this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined
  10312. : determineMajorUnit(this._unit);
  10313. this.initOffsets(timestamps);
  10314. if (options.reverse) {
  10315. ticks.reverse();
  10316. }
  10317. return ticksFromTimestamps(this, ticks, this._majorUnit);
  10318. }
  10319. initOffsets(timestamps) {
  10320. let start = 0;
  10321. let end = 0;
  10322. let first, last;
  10323. if (this.options.offset && timestamps.length) {
  10324. first = this.getDecimalForValue(timestamps[0]);
  10325. if (timestamps.length === 1) {
  10326. start = 1 - first;
  10327. } else {
  10328. start = (this.getDecimalForValue(timestamps[1]) - first) / 2;
  10329. }
  10330. last = this.getDecimalForValue(timestamps[timestamps.length - 1]);
  10331. if (timestamps.length === 1) {
  10332. end = last;
  10333. } else {
  10334. end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;
  10335. }
  10336. }
  10337. const limit = timestamps.length < 3 ? 0.5 : 0.25;
  10338. start = _limitValue(start, 0, limit);
  10339. end = _limitValue(end, 0, limit);
  10340. this._offsets = {start, end, factor: 1 / (start + 1 + end)};
  10341. }
  10342. _generate() {
  10343. const adapter = this._adapter;
  10344. const min = this.min;
  10345. const max = this.max;
  10346. const options = this.options;
  10347. const timeOpts = options.time;
  10348. const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min));
  10349. const stepSize = valueOrDefault(timeOpts.stepSize, 1);
  10350. const weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  10351. const hasWeekday = isNumber(weekday) || weekday === true;
  10352. const ticks = {};
  10353. let first = min;
  10354. let time, count;
  10355. if (hasWeekday) {
  10356. first = +adapter.startOf(first, 'isoWeek', weekday);
  10357. }
  10358. first = +adapter.startOf(first, hasWeekday ? 'day' : minor);
  10359. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  10360. throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);
  10361. }
  10362. const timestamps = options.ticks.source === 'data' && this.getDataTimestamps();
  10363. for (time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++) {
  10364. addTick(ticks, time, timestamps);
  10365. }
  10366. if (time === max || options.bounds === 'ticks' || count === 1) {
  10367. addTick(ticks, time, timestamps);
  10368. }
  10369. return Object.keys(ticks).sort((a, b) => a - b).map(x => +x);
  10370. }
  10371. getLabelForValue(value) {
  10372. const adapter = this._adapter;
  10373. const timeOpts = this.options.time;
  10374. if (timeOpts.tooltipFormat) {
  10375. return adapter.format(value, timeOpts.tooltipFormat);
  10376. }
  10377. return adapter.format(value, timeOpts.displayFormats.datetime);
  10378. }
  10379. _tickFormatFunction(time, index, ticks, format) {
  10380. const options = this.options;
  10381. const formats = options.time.displayFormats;
  10382. const unit = this._unit;
  10383. const majorUnit = this._majorUnit;
  10384. const minorFormat = unit && formats[unit];
  10385. const majorFormat = majorUnit && formats[majorUnit];
  10386. const tick = ticks[index];
  10387. const major = majorUnit && majorFormat && tick && tick.major;
  10388. const label = this._adapter.format(time, format || (major ? majorFormat : minorFormat));
  10389. const formatter = options.ticks.callback;
  10390. return formatter ? callback(formatter, [label, index, ticks], this) : label;
  10391. }
  10392. generateTickLabels(ticks) {
  10393. let i, ilen, tick;
  10394. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10395. tick = ticks[i];
  10396. tick.label = this._tickFormatFunction(tick.value, i, ticks);
  10397. }
  10398. }
  10399. getDecimalForValue(value) {
  10400. return value === null ? NaN : (value - this.min) / (this.max - this.min);
  10401. }
  10402. getPixelForValue(value) {
  10403. const offsets = this._offsets;
  10404. const pos = this.getDecimalForValue(value);
  10405. return this.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  10406. }
  10407. getValueForPixel(pixel) {
  10408. const offsets = this._offsets;
  10409. const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  10410. return this.min + pos * (this.max - this.min);
  10411. }
  10412. _getLabelSize(label) {
  10413. const ticksOpts = this.options.ticks;
  10414. const tickLabelWidth = this.ctx.measureText(label).width;
  10415. const angle = toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  10416. const cosRotation = Math.cos(angle);
  10417. const sinRotation = Math.sin(angle);
  10418. const tickFontSize = this._resolveTickFontOptions(0).size;
  10419. return {
  10420. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  10421. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  10422. };
  10423. }
  10424. _getLabelCapacity(exampleTime) {
  10425. const timeOpts = this.options.time;
  10426. const displayFormats = timeOpts.displayFormats;
  10427. const format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  10428. const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [exampleTime], this._majorUnit), format);
  10429. const size = this._getLabelSize(exampleLabel);
  10430. const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1;
  10431. return capacity > 0 ? capacity : 1;
  10432. }
  10433. getDataTimestamps() {
  10434. let timestamps = this._cache.data || [];
  10435. let i, ilen;
  10436. if (timestamps.length) {
  10437. return timestamps;
  10438. }
  10439. const metas = this.getMatchingVisibleMetas();
  10440. if (this._normalized && metas.length) {
  10441. return (this._cache.data = metas[0].controller.getAllParsedValues(this));
  10442. }
  10443. for (i = 0, ilen = metas.length; i < ilen; ++i) {
  10444. timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this));
  10445. }
  10446. return (this._cache.data = this.normalize(timestamps));
  10447. }
  10448. getLabelTimestamps() {
  10449. const timestamps = this._cache.labels || [];
  10450. let i, ilen;
  10451. if (timestamps.length) {
  10452. return timestamps;
  10453. }
  10454. const labels = this.getLabels();
  10455. for (i = 0, ilen = labels.length; i < ilen; ++i) {
  10456. timestamps.push(parse(this, labels[i]));
  10457. }
  10458. return (this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps));
  10459. }
  10460. normalize(values) {
  10461. return _arrayUnique(values.sort(sorter));
  10462. }
  10463. }
  10464. TimeScale.id = 'time';
  10465. TimeScale.defaults = {
  10466. bounds: 'data',
  10467. adapters: {},
  10468. time: {
  10469. parser: false,
  10470. unit: false,
  10471. round: false,
  10472. isoWeekday: false,
  10473. minUnit: 'millisecond',
  10474. displayFormats: {}
  10475. },
  10476. ticks: {
  10477. source: 'auto',
  10478. major: {
  10479. enabled: false
  10480. }
  10481. }
  10482. };
  10483. function interpolate(table, val, reverse) {
  10484. let lo = 0;
  10485. let hi = table.length - 1;
  10486. let prevSource, nextSource, prevTarget, nextTarget;
  10487. if (reverse) {
  10488. if (val >= table[lo].pos && val <= table[hi].pos) {
  10489. ({lo, hi} = _lookupByKey(table, 'pos', val));
  10490. }
  10491. ({pos: prevSource, time: prevTarget} = table[lo]);
  10492. ({pos: nextSource, time: nextTarget} = table[hi]);
  10493. } else {
  10494. if (val >= table[lo].time && val <= table[hi].time) {
  10495. ({lo, hi} = _lookupByKey(table, 'time', val));
  10496. }
  10497. ({time: prevSource, pos: prevTarget} = table[lo]);
  10498. ({time: nextSource, pos: nextTarget} = table[hi]);
  10499. }
  10500. const span = nextSource - prevSource;
  10501. return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;
  10502. }
  10503. class TimeSeriesScale extends TimeScale {
  10504. constructor(props) {
  10505. super(props);
  10506. this._table = [];
  10507. this._minPos = undefined;
  10508. this._tableRange = undefined;
  10509. }
  10510. initOffsets() {
  10511. const timestamps = this._getTimestampsForTable();
  10512. const table = this._table = this.buildLookupTable(timestamps);
  10513. this._minPos = interpolate(table, this.min);
  10514. this._tableRange = interpolate(table, this.max) - this._minPos;
  10515. super.initOffsets(timestamps);
  10516. }
  10517. buildLookupTable(timestamps) {
  10518. const {min, max} = this;
  10519. const items = [];
  10520. const table = [];
  10521. let i, ilen, prev, curr, next;
  10522. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  10523. curr = timestamps[i];
  10524. if (curr >= min && curr <= max) {
  10525. items.push(curr);
  10526. }
  10527. }
  10528. if (items.length < 2) {
  10529. return [
  10530. {time: min, pos: 0},
  10531. {time: max, pos: 1}
  10532. ];
  10533. }
  10534. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10535. next = items[i + 1];
  10536. prev = items[i - 1];
  10537. curr = items[i];
  10538. if (Math.round((next + prev) / 2) !== curr) {
  10539. table.push({time: curr, pos: i / (ilen - 1)});
  10540. }
  10541. }
  10542. return table;
  10543. }
  10544. _getTimestampsForTable() {
  10545. let timestamps = this._cache.all || [];
  10546. if (timestamps.length) {
  10547. return timestamps;
  10548. }
  10549. const data = this.getDataTimestamps();
  10550. const label = this.getLabelTimestamps();
  10551. if (data.length && label.length) {
  10552. timestamps = this.normalize(data.concat(label));
  10553. } else {
  10554. timestamps = data.length ? data : label;
  10555. }
  10556. timestamps = this._cache.all = timestamps;
  10557. return timestamps;
  10558. }
  10559. getDecimalForValue(value) {
  10560. return (interpolate(this._table, value) - this._minPos) / this._tableRange;
  10561. }
  10562. getValueForPixel(pixel) {
  10563. const offsets = this._offsets;
  10564. const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  10565. return interpolate(this._table, decimal * this._tableRange + this._minPos, true);
  10566. }
  10567. }
  10568. TimeSeriesScale.id = 'timeseries';
  10569. TimeSeriesScale.defaults = TimeScale.defaults;
  10570. var scales = /*#__PURE__*/Object.freeze({
  10571. __proto__: null,
  10572. CategoryScale: CategoryScale,
  10573. LinearScale: LinearScale,
  10574. LogarithmicScale: LogarithmicScale,
  10575. RadialLinearScale: RadialLinearScale,
  10576. TimeScale: TimeScale,
  10577. TimeSeriesScale: TimeSeriesScale
  10578. });
  10579. const registerables = [
  10580. controllers,
  10581. elements,
  10582. plugins,
  10583. scales,
  10584. ];
  10585. export { Animation, Animations, ArcElement, BarController, BarElement, BasePlatform, BasicPlatform, BubbleController, CategoryScale, Chart, DatasetController, plugin_decimation as Decimation, DomPlatform, DoughnutController, Element, index as Filler, Interaction, plugin_legend as Legend, LineController, LineElement, LinearScale, LogarithmicScale, PieController, PointElement, PolarAreaController, RadarController, RadialLinearScale, Scale, ScatterController, plugin_subtitle as SubTitle, Ticks, TimeScale, TimeSeriesScale, plugin_title as Title, plugin_tooltip as Tooltip, adapters as _adapters, _detectPlatform, animator, controllers, elements, layouts, plugins, registerables, registry, scales };