chart.js 392 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222
  1. /*!
  2. * Chart.js v3.5.1
  3. * https://www.chartjs.org
  4. * (c) 2021 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  9. typeof define === 'function' && define.amd ? define(factory) :
  10. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Chart = factory());
  11. }(this, (function () { 'use strict';
  12. function fontString(pixelSize, fontStyle, fontFamily) {
  13. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  14. }
  15. const requestAnimFrame = (function() {
  16. if (typeof window === 'undefined') {
  17. return function(callback) {
  18. return callback();
  19. };
  20. }
  21. return window.requestAnimationFrame;
  22. }());
  23. function throttled(fn, thisArg, updateFn) {
  24. const updateArgs = updateFn || ((args) => Array.prototype.slice.call(args));
  25. let ticking = false;
  26. let args = [];
  27. return function(...rest) {
  28. args = updateArgs(rest);
  29. if (!ticking) {
  30. ticking = true;
  31. requestAnimFrame.call(window, () => {
  32. ticking = false;
  33. fn.apply(thisArg, args);
  34. });
  35. }
  36. };
  37. }
  38. function debounce(fn, delay) {
  39. let timeout;
  40. return function() {
  41. if (delay) {
  42. clearTimeout(timeout);
  43. timeout = setTimeout(fn, delay);
  44. } else {
  45. fn();
  46. }
  47. return delay;
  48. };
  49. }
  50. const _toLeftRightCenter = (align) => align === 'start' ? 'left' : align === 'end' ? 'right' : 'center';
  51. const _alignStartEnd = (align, start, end) => align === 'start' ? start : align === 'end' ? end : (start + end) / 2;
  52. const _textX = (align, left, right, rtl) => {
  53. const check = rtl ? 'left' : 'right';
  54. return align === check ? right : align === 'center' ? (left + right) / 2 : left;
  55. };
  56. class Animator {
  57. constructor() {
  58. this._request = null;
  59. this._charts = new Map();
  60. this._running = false;
  61. this._lastDate = undefined;
  62. }
  63. _notify(chart, anims, date, type) {
  64. const callbacks = anims.listeners[type];
  65. const numSteps = anims.duration;
  66. callbacks.forEach(fn => fn({
  67. chart,
  68. initial: anims.initial,
  69. numSteps,
  70. currentStep: Math.min(date - anims.start, numSteps)
  71. }));
  72. }
  73. _refresh() {
  74. const me = this;
  75. if (me._request) {
  76. return;
  77. }
  78. me._running = true;
  79. me._request = requestAnimFrame.call(window, () => {
  80. me._update();
  81. me._request = null;
  82. if (me._running) {
  83. me._refresh();
  84. }
  85. });
  86. }
  87. _update(date = Date.now()) {
  88. const me = this;
  89. let remaining = 0;
  90. me._charts.forEach((anims, chart) => {
  91. if (!anims.running || !anims.items.length) {
  92. return;
  93. }
  94. const items = anims.items;
  95. let i = items.length - 1;
  96. let draw = false;
  97. let item;
  98. for (; i >= 0; --i) {
  99. item = items[i];
  100. if (item._active) {
  101. if (item._total > anims.duration) {
  102. anims.duration = item._total;
  103. }
  104. item.tick(date);
  105. draw = true;
  106. } else {
  107. items[i] = items[items.length - 1];
  108. items.pop();
  109. }
  110. }
  111. if (draw) {
  112. chart.draw();
  113. me._notify(chart, anims, date, 'progress');
  114. }
  115. if (!items.length) {
  116. anims.running = false;
  117. me._notify(chart, anims, date, 'complete');
  118. anims.initial = false;
  119. }
  120. remaining += items.length;
  121. });
  122. me._lastDate = date;
  123. if (remaining === 0) {
  124. me._running = false;
  125. }
  126. }
  127. _getAnims(chart) {
  128. const charts = this._charts;
  129. let anims = charts.get(chart);
  130. if (!anims) {
  131. anims = {
  132. running: false,
  133. initial: true,
  134. items: [],
  135. listeners: {
  136. complete: [],
  137. progress: []
  138. }
  139. };
  140. charts.set(chart, anims);
  141. }
  142. return anims;
  143. }
  144. listen(chart, event, cb) {
  145. this._getAnims(chart).listeners[event].push(cb);
  146. }
  147. add(chart, items) {
  148. if (!items || !items.length) {
  149. return;
  150. }
  151. this._getAnims(chart).items.push(...items);
  152. }
  153. has(chart) {
  154. return this._getAnims(chart).items.length > 0;
  155. }
  156. start(chart) {
  157. const anims = this._charts.get(chart);
  158. if (!anims) {
  159. return;
  160. }
  161. anims.running = true;
  162. anims.start = Date.now();
  163. anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0);
  164. this._refresh();
  165. }
  166. running(chart) {
  167. if (!this._running) {
  168. return false;
  169. }
  170. const anims = this._charts.get(chart);
  171. if (!anims || !anims.running || !anims.items.length) {
  172. return false;
  173. }
  174. return true;
  175. }
  176. stop(chart) {
  177. const anims = this._charts.get(chart);
  178. if (!anims || !anims.items.length) {
  179. return;
  180. }
  181. const items = anims.items;
  182. let i = items.length - 1;
  183. for (; i >= 0; --i) {
  184. items[i].cancel();
  185. }
  186. anims.items = [];
  187. this._notify(chart, anims, Date.now(), 'complete');
  188. }
  189. remove(chart) {
  190. return this._charts.delete(chart);
  191. }
  192. }
  193. var animator = new Animator();
  194. /*!
  195. * @kurkle/color v0.1.9
  196. * https://github.com/kurkle/color#readme
  197. * (c) 2020 Jukka Kurkela
  198. * Released under the MIT License
  199. */
  200. const map$1 = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 10, B: 11, C: 12, D: 13, E: 14, F: 15, a: 10, b: 11, c: 12, d: 13, e: 14, f: 15};
  201. const hex = '0123456789ABCDEF';
  202. const h1 = (b) => hex[b & 0xF];
  203. const h2 = (b) => hex[(b & 0xF0) >> 4] + hex[b & 0xF];
  204. const eq = (b) => (((b & 0xF0) >> 4) === (b & 0xF));
  205. function isShort(v) {
  206. return eq(v.r) && eq(v.g) && eq(v.b) && eq(v.a);
  207. }
  208. function hexParse(str) {
  209. var len = str.length;
  210. var ret;
  211. if (str[0] === '#') {
  212. if (len === 4 || len === 5) {
  213. ret = {
  214. r: 255 & map$1[str[1]] * 17,
  215. g: 255 & map$1[str[2]] * 17,
  216. b: 255 & map$1[str[3]] * 17,
  217. a: len === 5 ? map$1[str[4]] * 17 : 255
  218. };
  219. } else if (len === 7 || len === 9) {
  220. ret = {
  221. r: map$1[str[1]] << 4 | map$1[str[2]],
  222. g: map$1[str[3]] << 4 | map$1[str[4]],
  223. b: map$1[str[5]] << 4 | map$1[str[6]],
  224. a: len === 9 ? (map$1[str[7]] << 4 | map$1[str[8]]) : 255
  225. };
  226. }
  227. }
  228. return ret;
  229. }
  230. function hexString(v) {
  231. var f = isShort(v) ? h1 : h2;
  232. return v
  233. ? '#' + f(v.r) + f(v.g) + f(v.b) + (v.a < 255 ? f(v.a) : '')
  234. : v;
  235. }
  236. function round(v) {
  237. return v + 0.5 | 0;
  238. }
  239. const lim = (v, l, h) => Math.max(Math.min(v, h), l);
  240. function p2b(v) {
  241. return lim(round(v * 2.55), 0, 255);
  242. }
  243. function n2b(v) {
  244. return lim(round(v * 255), 0, 255);
  245. }
  246. function b2n(v) {
  247. return lim(round(v / 2.55) / 100, 0, 1);
  248. }
  249. function n2p(v) {
  250. return lim(round(v * 100), 0, 100);
  251. }
  252. const RGB_RE = /^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;
  253. function rgbParse(str) {
  254. const m = RGB_RE.exec(str);
  255. let a = 255;
  256. let r, g, b;
  257. if (!m) {
  258. return;
  259. }
  260. if (m[7] !== r) {
  261. const v = +m[7];
  262. a = 255 & (m[8] ? p2b(v) : v * 255);
  263. }
  264. r = +m[1];
  265. g = +m[3];
  266. b = +m[5];
  267. r = 255 & (m[2] ? p2b(r) : r);
  268. g = 255 & (m[4] ? p2b(g) : g);
  269. b = 255 & (m[6] ? p2b(b) : b);
  270. return {
  271. r: r,
  272. g: g,
  273. b: b,
  274. a: a
  275. };
  276. }
  277. function rgbString(v) {
  278. return v && (
  279. v.a < 255
  280. ? `rgba(${v.r}, ${v.g}, ${v.b}, ${b2n(v.a)})`
  281. : `rgb(${v.r}, ${v.g}, ${v.b})`
  282. );
  283. }
  284. const HUE_RE = /^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;
  285. function hsl2rgbn(h, s, l) {
  286. const a = s * Math.min(l, 1 - l);
  287. const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
  288. return [f(0), f(8), f(4)];
  289. }
  290. function hsv2rgbn(h, s, v) {
  291. const f = (n, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0);
  292. return [f(5), f(3), f(1)];
  293. }
  294. function hwb2rgbn(h, w, b) {
  295. const rgb = hsl2rgbn(h, 1, 0.5);
  296. let i;
  297. if (w + b > 1) {
  298. i = 1 / (w + b);
  299. w *= i;
  300. b *= i;
  301. }
  302. for (i = 0; i < 3; i++) {
  303. rgb[i] *= 1 - w - b;
  304. rgb[i] += w;
  305. }
  306. return rgb;
  307. }
  308. function rgb2hsl(v) {
  309. const range = 255;
  310. const r = v.r / range;
  311. const g = v.g / range;
  312. const b = v.b / range;
  313. const max = Math.max(r, g, b);
  314. const min = Math.min(r, g, b);
  315. const l = (max + min) / 2;
  316. let h, s, d;
  317. if (max !== min) {
  318. d = max - min;
  319. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  320. h = max === r
  321. ? ((g - b) / d) + (g < b ? 6 : 0)
  322. : max === g
  323. ? (b - r) / d + 2
  324. : (r - g) / d + 4;
  325. h = h * 60 + 0.5;
  326. }
  327. return [h | 0, s || 0, l];
  328. }
  329. function calln(f, a, b, c) {
  330. return (
  331. Array.isArray(a)
  332. ? f(a[0], a[1], a[2])
  333. : f(a, b, c)
  334. ).map(n2b);
  335. }
  336. function hsl2rgb(h, s, l) {
  337. return calln(hsl2rgbn, h, s, l);
  338. }
  339. function hwb2rgb(h, w, b) {
  340. return calln(hwb2rgbn, h, w, b);
  341. }
  342. function hsv2rgb(h, s, v) {
  343. return calln(hsv2rgbn, h, s, v);
  344. }
  345. function hue(h) {
  346. return (h % 360 + 360) % 360;
  347. }
  348. function hueParse(str) {
  349. const m = HUE_RE.exec(str);
  350. let a = 255;
  351. let v;
  352. if (!m) {
  353. return;
  354. }
  355. if (m[5] !== v) {
  356. a = m[6] ? p2b(+m[5]) : n2b(+m[5]);
  357. }
  358. const h = hue(+m[2]);
  359. const p1 = +m[3] / 100;
  360. const p2 = +m[4] / 100;
  361. if (m[1] === 'hwb') {
  362. v = hwb2rgb(h, p1, p2);
  363. } else if (m[1] === 'hsv') {
  364. v = hsv2rgb(h, p1, p2);
  365. } else {
  366. v = hsl2rgb(h, p1, p2);
  367. }
  368. return {
  369. r: v[0],
  370. g: v[1],
  371. b: v[2],
  372. a: a
  373. };
  374. }
  375. function rotate(v, deg) {
  376. var h = rgb2hsl(v);
  377. h[0] = hue(h[0] + deg);
  378. h = hsl2rgb(h);
  379. v.r = h[0];
  380. v.g = h[1];
  381. v.b = h[2];
  382. }
  383. function hslString(v) {
  384. if (!v) {
  385. return;
  386. }
  387. const a = rgb2hsl(v);
  388. const h = a[0];
  389. const s = n2p(a[1]);
  390. const l = n2p(a[2]);
  391. return v.a < 255
  392. ? `hsla(${h}, ${s}%, ${l}%, ${b2n(v.a)})`
  393. : `hsl(${h}, ${s}%, ${l}%)`;
  394. }
  395. const map$1$1 = {
  396. x: 'dark',
  397. Z: 'light',
  398. Y: 're',
  399. X: 'blu',
  400. W: 'gr',
  401. V: 'medium',
  402. U: 'slate',
  403. A: 'ee',
  404. T: 'ol',
  405. S: 'or',
  406. B: 'ra',
  407. C: 'lateg',
  408. D: 'ights',
  409. R: 'in',
  410. Q: 'turquois',
  411. E: 'hi',
  412. P: 'ro',
  413. O: 'al',
  414. N: 'le',
  415. M: 'de',
  416. L: 'yello',
  417. F: 'en',
  418. K: 'ch',
  419. G: 'arks',
  420. H: 'ea',
  421. I: 'ightg',
  422. J: 'wh'
  423. };
  424. const names = {
  425. OiceXe: 'f0f8ff',
  426. antiquewEte: 'faebd7',
  427. aqua: 'ffff',
  428. aquamarRe: '7fffd4',
  429. azuY: 'f0ffff',
  430. beige: 'f5f5dc',
  431. bisque: 'ffe4c4',
  432. black: '0',
  433. blanKedOmond: 'ffebcd',
  434. Xe: 'ff',
  435. XeviTet: '8a2be2',
  436. bPwn: 'a52a2a',
  437. burlywood: 'deb887',
  438. caMtXe: '5f9ea0',
  439. KartYuse: '7fff00',
  440. KocTate: 'd2691e',
  441. cSO: 'ff7f50',
  442. cSnflowerXe: '6495ed',
  443. cSnsilk: 'fff8dc',
  444. crimson: 'dc143c',
  445. cyan: 'ffff',
  446. xXe: '8b',
  447. xcyan: '8b8b',
  448. xgTMnPd: 'b8860b',
  449. xWay: 'a9a9a9',
  450. xgYF: '6400',
  451. xgYy: 'a9a9a9',
  452. xkhaki: 'bdb76b',
  453. xmagFta: '8b008b',
  454. xTivegYF: '556b2f',
  455. xSange: 'ff8c00',
  456. xScEd: '9932cc',
  457. xYd: '8b0000',
  458. xsOmon: 'e9967a',
  459. xsHgYF: '8fbc8f',
  460. xUXe: '483d8b',
  461. xUWay: '2f4f4f',
  462. xUgYy: '2f4f4f',
  463. xQe: 'ced1',
  464. xviTet: '9400d3',
  465. dAppRk: 'ff1493',
  466. dApskyXe: 'bfff',
  467. dimWay: '696969',
  468. dimgYy: '696969',
  469. dodgerXe: '1e90ff',
  470. fiYbrick: 'b22222',
  471. flSOwEte: 'fffaf0',
  472. foYstWAn: '228b22',
  473. fuKsia: 'ff00ff',
  474. gaRsbSo: 'dcdcdc',
  475. ghostwEte: 'f8f8ff',
  476. gTd: 'ffd700',
  477. gTMnPd: 'daa520',
  478. Way: '808080',
  479. gYF: '8000',
  480. gYFLw: 'adff2f',
  481. gYy: '808080',
  482. honeyMw: 'f0fff0',
  483. hotpRk: 'ff69b4',
  484. RdianYd: 'cd5c5c',
  485. Rdigo: '4b0082',
  486. ivSy: 'fffff0',
  487. khaki: 'f0e68c',
  488. lavFMr: 'e6e6fa',
  489. lavFMrXsh: 'fff0f5',
  490. lawngYF: '7cfc00',
  491. NmoncEffon: 'fffacd',
  492. ZXe: 'add8e6',
  493. ZcSO: 'f08080',
  494. Zcyan: 'e0ffff',
  495. ZgTMnPdLw: 'fafad2',
  496. ZWay: 'd3d3d3',
  497. ZgYF: '90ee90',
  498. ZgYy: 'd3d3d3',
  499. ZpRk: 'ffb6c1',
  500. ZsOmon: 'ffa07a',
  501. ZsHgYF: '20b2aa',
  502. ZskyXe: '87cefa',
  503. ZUWay: '778899',
  504. ZUgYy: '778899',
  505. ZstAlXe: 'b0c4de',
  506. ZLw: 'ffffe0',
  507. lime: 'ff00',
  508. limegYF: '32cd32',
  509. lRF: 'faf0e6',
  510. magFta: 'ff00ff',
  511. maPon: '800000',
  512. VaquamarRe: '66cdaa',
  513. VXe: 'cd',
  514. VScEd: 'ba55d3',
  515. VpurpN: '9370db',
  516. VsHgYF: '3cb371',
  517. VUXe: '7b68ee',
  518. VsprRggYF: 'fa9a',
  519. VQe: '48d1cc',
  520. VviTetYd: 'c71585',
  521. midnightXe: '191970',
  522. mRtcYam: 'f5fffa',
  523. mistyPse: 'ffe4e1',
  524. moccasR: 'ffe4b5',
  525. navajowEte: 'ffdead',
  526. navy: '80',
  527. Tdlace: 'fdf5e6',
  528. Tive: '808000',
  529. TivedBb: '6b8e23',
  530. Sange: 'ffa500',
  531. SangeYd: 'ff4500',
  532. ScEd: 'da70d6',
  533. pOegTMnPd: 'eee8aa',
  534. pOegYF: '98fb98',
  535. pOeQe: 'afeeee',
  536. pOeviTetYd: 'db7093',
  537. papayawEp: 'ffefd5',
  538. pHKpuff: 'ffdab9',
  539. peru: 'cd853f',
  540. pRk: 'ffc0cb',
  541. plum: 'dda0dd',
  542. powMrXe: 'b0e0e6',
  543. purpN: '800080',
  544. YbeccapurpN: '663399',
  545. Yd: 'ff0000',
  546. Psybrown: 'bc8f8f',
  547. PyOXe: '4169e1',
  548. saddNbPwn: '8b4513',
  549. sOmon: 'fa8072',
  550. sandybPwn: 'f4a460',
  551. sHgYF: '2e8b57',
  552. sHshell: 'fff5ee',
  553. siFna: 'a0522d',
  554. silver: 'c0c0c0',
  555. skyXe: '87ceeb',
  556. UXe: '6a5acd',
  557. UWay: '708090',
  558. UgYy: '708090',
  559. snow: 'fffafa',
  560. sprRggYF: 'ff7f',
  561. stAlXe: '4682b4',
  562. tan: 'd2b48c',
  563. teO: '8080',
  564. tEstN: 'd8bfd8',
  565. tomato: 'ff6347',
  566. Qe: '40e0d0',
  567. viTet: 'ee82ee',
  568. JHt: 'f5deb3',
  569. wEte: 'ffffff',
  570. wEtesmoke: 'f5f5f5',
  571. Lw: 'ffff00',
  572. LwgYF: '9acd32'
  573. };
  574. function unpack() {
  575. const unpacked = {};
  576. const keys = Object.keys(names);
  577. const tkeys = Object.keys(map$1$1);
  578. let i, j, k, ok, nk;
  579. for (i = 0; i < keys.length; i++) {
  580. ok = nk = keys[i];
  581. for (j = 0; j < tkeys.length; j++) {
  582. k = tkeys[j];
  583. nk = nk.replace(k, map$1$1[k]);
  584. }
  585. k = parseInt(names[ok], 16);
  586. unpacked[nk] = [k >> 16 & 0xFF, k >> 8 & 0xFF, k & 0xFF];
  587. }
  588. return unpacked;
  589. }
  590. let names$1;
  591. function nameParse(str) {
  592. if (!names$1) {
  593. names$1 = unpack();
  594. names$1.transparent = [0, 0, 0, 0];
  595. }
  596. const a = names$1[str.toLowerCase()];
  597. return a && {
  598. r: a[0],
  599. g: a[1],
  600. b: a[2],
  601. a: a.length === 4 ? a[3] : 255
  602. };
  603. }
  604. function modHSL(v, i, ratio) {
  605. if (v) {
  606. let tmp = rgb2hsl(v);
  607. tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1));
  608. tmp = hsl2rgb(tmp);
  609. v.r = tmp[0];
  610. v.g = tmp[1];
  611. v.b = tmp[2];
  612. }
  613. }
  614. function clone$1(v, proto) {
  615. return v ? Object.assign(proto || {}, v) : v;
  616. }
  617. function fromObject(input) {
  618. var v = {r: 0, g: 0, b: 0, a: 255};
  619. if (Array.isArray(input)) {
  620. if (input.length >= 3) {
  621. v = {r: input[0], g: input[1], b: input[2], a: 255};
  622. if (input.length > 3) {
  623. v.a = n2b(input[3]);
  624. }
  625. }
  626. } else {
  627. v = clone$1(input, {r: 0, g: 0, b: 0, a: 1});
  628. v.a = n2b(v.a);
  629. }
  630. return v;
  631. }
  632. function functionParse(str) {
  633. if (str.charAt(0) === 'r') {
  634. return rgbParse(str);
  635. }
  636. return hueParse(str);
  637. }
  638. class Color {
  639. constructor(input) {
  640. if (input instanceof Color) {
  641. return input;
  642. }
  643. const type = typeof input;
  644. let v;
  645. if (type === 'object') {
  646. v = fromObject(input);
  647. } else if (type === 'string') {
  648. v = hexParse(input) || nameParse(input) || functionParse(input);
  649. }
  650. this._rgb = v;
  651. this._valid = !!v;
  652. }
  653. get valid() {
  654. return this._valid;
  655. }
  656. get rgb() {
  657. var v = clone$1(this._rgb);
  658. if (v) {
  659. v.a = b2n(v.a);
  660. }
  661. return v;
  662. }
  663. set rgb(obj) {
  664. this._rgb = fromObject(obj);
  665. }
  666. rgbString() {
  667. return this._valid ? rgbString(this._rgb) : this._rgb;
  668. }
  669. hexString() {
  670. return this._valid ? hexString(this._rgb) : this._rgb;
  671. }
  672. hslString() {
  673. return this._valid ? hslString(this._rgb) : this._rgb;
  674. }
  675. mix(color, weight) {
  676. const me = this;
  677. if (color) {
  678. const c1 = me.rgb;
  679. const c2 = color.rgb;
  680. let w2;
  681. const p = weight === w2 ? 0.5 : weight;
  682. const w = 2 * p - 1;
  683. const a = c1.a - c2.a;
  684. const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  685. w2 = 1 - w1;
  686. c1.r = 0xFF & w1 * c1.r + w2 * c2.r + 0.5;
  687. c1.g = 0xFF & w1 * c1.g + w2 * c2.g + 0.5;
  688. c1.b = 0xFF & w1 * c1.b + w2 * c2.b + 0.5;
  689. c1.a = p * c1.a + (1 - p) * c2.a;
  690. me.rgb = c1;
  691. }
  692. return me;
  693. }
  694. clone() {
  695. return new Color(this.rgb);
  696. }
  697. alpha(a) {
  698. this._rgb.a = n2b(a);
  699. return this;
  700. }
  701. clearer(ratio) {
  702. const rgb = this._rgb;
  703. rgb.a *= 1 - ratio;
  704. return this;
  705. }
  706. greyscale() {
  707. const rgb = this._rgb;
  708. const val = round(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11);
  709. rgb.r = rgb.g = rgb.b = val;
  710. return this;
  711. }
  712. opaquer(ratio) {
  713. const rgb = this._rgb;
  714. rgb.a *= 1 + ratio;
  715. return this;
  716. }
  717. negate() {
  718. const v = this._rgb;
  719. v.r = 255 - v.r;
  720. v.g = 255 - v.g;
  721. v.b = 255 - v.b;
  722. return this;
  723. }
  724. lighten(ratio) {
  725. modHSL(this._rgb, 2, ratio);
  726. return this;
  727. }
  728. darken(ratio) {
  729. modHSL(this._rgb, 2, -ratio);
  730. return this;
  731. }
  732. saturate(ratio) {
  733. modHSL(this._rgb, 1, ratio);
  734. return this;
  735. }
  736. desaturate(ratio) {
  737. modHSL(this._rgb, 1, -ratio);
  738. return this;
  739. }
  740. rotate(deg) {
  741. rotate(this._rgb, deg);
  742. return this;
  743. }
  744. }
  745. function index_esm(input) {
  746. return new Color(input);
  747. }
  748. const isPatternOrGradient = (value) => value instanceof CanvasGradient || value instanceof CanvasPattern;
  749. function color(value) {
  750. return isPatternOrGradient(value) ? value : index_esm(value);
  751. }
  752. function getHoverColor(value) {
  753. return isPatternOrGradient(value)
  754. ? value
  755. : index_esm(value).saturate(0.5).darken(0.1).hexString();
  756. }
  757. function noop() {}
  758. const uid = (function() {
  759. let id = 0;
  760. return function() {
  761. return id++;
  762. };
  763. }());
  764. function isNullOrUndef(value) {
  765. return value === null || typeof value === 'undefined';
  766. }
  767. function isArray(value) {
  768. if (Array.isArray && Array.isArray(value)) {
  769. return true;
  770. }
  771. const type = Object.prototype.toString.call(value);
  772. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  773. return true;
  774. }
  775. return false;
  776. }
  777. function isObject(value) {
  778. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  779. }
  780. const isNumberFinite = (value) => (typeof value === 'number' || value instanceof Number) && isFinite(+value);
  781. function finiteOrDefault(value, defaultValue) {
  782. return isNumberFinite(value) ? value : defaultValue;
  783. }
  784. function valueOrDefault(value, defaultValue) {
  785. return typeof value === 'undefined' ? defaultValue : value;
  786. }
  787. const toPercentage = (value, dimension) =>
  788. typeof value === 'string' && value.endsWith('%') ?
  789. parseFloat(value) / 100
  790. : value / dimension;
  791. const toDimension = (value, dimension) =>
  792. typeof value === 'string' && value.endsWith('%') ?
  793. parseFloat(value) / 100 * dimension
  794. : +value;
  795. function callback(fn, args, thisArg) {
  796. if (fn && typeof fn.call === 'function') {
  797. return fn.apply(thisArg, args);
  798. }
  799. }
  800. function each(loopable, fn, thisArg, reverse) {
  801. let i, len, keys;
  802. if (isArray(loopable)) {
  803. len = loopable.length;
  804. if (reverse) {
  805. for (i = len - 1; i >= 0; i--) {
  806. fn.call(thisArg, loopable[i], i);
  807. }
  808. } else {
  809. for (i = 0; i < len; i++) {
  810. fn.call(thisArg, loopable[i], i);
  811. }
  812. }
  813. } else if (isObject(loopable)) {
  814. keys = Object.keys(loopable);
  815. len = keys.length;
  816. for (i = 0; i < len; i++) {
  817. fn.call(thisArg, loopable[keys[i]], keys[i]);
  818. }
  819. }
  820. }
  821. function _elementsEqual(a0, a1) {
  822. let i, ilen, v0, v1;
  823. if (!a0 || !a1 || a0.length !== a1.length) {
  824. return false;
  825. }
  826. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  827. v0 = a0[i];
  828. v1 = a1[i];
  829. if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) {
  830. return false;
  831. }
  832. }
  833. return true;
  834. }
  835. function clone(source) {
  836. if (isArray(source)) {
  837. return source.map(clone);
  838. }
  839. if (isObject(source)) {
  840. const target = Object.create(null);
  841. const keys = Object.keys(source);
  842. const klen = keys.length;
  843. let k = 0;
  844. for (; k < klen; ++k) {
  845. target[keys[k]] = clone(source[keys[k]]);
  846. }
  847. return target;
  848. }
  849. return source;
  850. }
  851. function isValidKey(key) {
  852. return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;
  853. }
  854. function _merger(key, target, source, options) {
  855. if (!isValidKey(key)) {
  856. return;
  857. }
  858. const tval = target[key];
  859. const sval = source[key];
  860. if (isObject(tval) && isObject(sval)) {
  861. merge(tval, sval, options);
  862. } else {
  863. target[key] = clone(sval);
  864. }
  865. }
  866. function merge(target, source, options) {
  867. const sources = isArray(source) ? source : [source];
  868. const ilen = sources.length;
  869. if (!isObject(target)) {
  870. return target;
  871. }
  872. options = options || {};
  873. const merger = options.merger || _merger;
  874. for (let i = 0; i < ilen; ++i) {
  875. source = sources[i];
  876. if (!isObject(source)) {
  877. continue;
  878. }
  879. const keys = Object.keys(source);
  880. for (let k = 0, klen = keys.length; k < klen; ++k) {
  881. merger(keys[k], target, source, options);
  882. }
  883. }
  884. return target;
  885. }
  886. function mergeIf(target, source) {
  887. return merge(target, source, {merger: _mergerIf});
  888. }
  889. function _mergerIf(key, target, source) {
  890. if (!isValidKey(key)) {
  891. return;
  892. }
  893. const tval = target[key];
  894. const sval = source[key];
  895. if (isObject(tval) && isObject(sval)) {
  896. mergeIf(tval, sval);
  897. } else if (!Object.prototype.hasOwnProperty.call(target, key)) {
  898. target[key] = clone(sval);
  899. }
  900. }
  901. function _deprecated(scope, value, previous, current) {
  902. if (value !== undefined) {
  903. console.warn(scope + ': "' + previous +
  904. '" is deprecated. Please use "' + current + '" instead');
  905. }
  906. }
  907. const emptyString = '';
  908. const dot = '.';
  909. function indexOfDotOrLength(key, start) {
  910. const idx = key.indexOf(dot, start);
  911. return idx === -1 ? key.length : idx;
  912. }
  913. function resolveObjectKey(obj, key) {
  914. if (key === emptyString) {
  915. return obj;
  916. }
  917. let pos = 0;
  918. let idx = indexOfDotOrLength(key, pos);
  919. while (obj && idx > pos) {
  920. obj = obj[key.substr(pos, idx - pos)];
  921. pos = idx + 1;
  922. idx = indexOfDotOrLength(key, pos);
  923. }
  924. return obj;
  925. }
  926. function _capitalize(str) {
  927. return str.charAt(0).toUpperCase() + str.slice(1);
  928. }
  929. const defined = (value) => typeof value !== 'undefined';
  930. const isFunction = (value) => typeof value === 'function';
  931. const setsEqual = (a, b) => {
  932. if (a.size !== b.size) {
  933. return false;
  934. }
  935. for (const item of a) {
  936. if (!b.has(item)) {
  937. return false;
  938. }
  939. }
  940. return true;
  941. };
  942. const overrides = Object.create(null);
  943. const descriptors = Object.create(null);
  944. function getScope$1(node, key) {
  945. if (!key) {
  946. return node;
  947. }
  948. const keys = key.split('.');
  949. for (let i = 0, n = keys.length; i < n; ++i) {
  950. const k = keys[i];
  951. node = node[k] || (node[k] = Object.create(null));
  952. }
  953. return node;
  954. }
  955. function set(root, scope, values) {
  956. if (typeof scope === 'string') {
  957. return merge(getScope$1(root, scope), values);
  958. }
  959. return merge(getScope$1(root, ''), scope);
  960. }
  961. class Defaults {
  962. constructor(_descriptors) {
  963. this.animation = undefined;
  964. this.backgroundColor = 'rgba(0,0,0,0.1)';
  965. this.borderColor = 'rgba(0,0,0,0.1)';
  966. this.color = '#666';
  967. this.datasets = {};
  968. this.devicePixelRatio = (context) => context.chart.platform.getDevicePixelRatio();
  969. this.elements = {};
  970. this.events = [
  971. 'mousemove',
  972. 'mouseout',
  973. 'click',
  974. 'touchstart',
  975. 'touchmove'
  976. ];
  977. this.font = {
  978. family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  979. size: 12,
  980. style: 'normal',
  981. lineHeight: 1.2,
  982. weight: null
  983. };
  984. this.hover = {};
  985. this.hoverBackgroundColor = (ctx, options) => getHoverColor(options.backgroundColor);
  986. this.hoverBorderColor = (ctx, options) => getHoverColor(options.borderColor);
  987. this.hoverColor = (ctx, options) => getHoverColor(options.color);
  988. this.indexAxis = 'x';
  989. this.interaction = {
  990. mode: 'nearest',
  991. intersect: true
  992. };
  993. this.maintainAspectRatio = true;
  994. this.onHover = null;
  995. this.onClick = null;
  996. this.parsing = true;
  997. this.plugins = {};
  998. this.responsive = true;
  999. this.scale = undefined;
  1000. this.scales = {};
  1001. this.showLine = true;
  1002. this.describe(_descriptors);
  1003. }
  1004. set(scope, values) {
  1005. return set(this, scope, values);
  1006. }
  1007. get(scope) {
  1008. return getScope$1(this, scope);
  1009. }
  1010. describe(scope, values) {
  1011. return set(descriptors, scope, values);
  1012. }
  1013. override(scope, values) {
  1014. return set(overrides, scope, values);
  1015. }
  1016. route(scope, name, targetScope, targetName) {
  1017. const scopeObject = getScope$1(this, scope);
  1018. const targetScopeObject = getScope$1(this, targetScope);
  1019. const privateName = '_' + name;
  1020. Object.defineProperties(scopeObject, {
  1021. [privateName]: {
  1022. value: scopeObject[name],
  1023. writable: true
  1024. },
  1025. [name]: {
  1026. enumerable: true,
  1027. get() {
  1028. const local = this[privateName];
  1029. const target = targetScopeObject[targetName];
  1030. if (isObject(local)) {
  1031. return Object.assign({}, target, local);
  1032. }
  1033. return valueOrDefault(local, target);
  1034. },
  1035. set(value) {
  1036. this[privateName] = value;
  1037. }
  1038. }
  1039. });
  1040. }
  1041. }
  1042. var defaults = new Defaults({
  1043. _scriptable: (name) => !name.startsWith('on'),
  1044. _indexable: (name) => name !== 'events',
  1045. hover: {
  1046. _fallback: 'interaction'
  1047. },
  1048. interaction: {
  1049. _scriptable: false,
  1050. _indexable: false,
  1051. }
  1052. });
  1053. const PI = Math.PI;
  1054. const TAU = 2 * PI;
  1055. const PITAU = TAU + PI;
  1056. const INFINITY = Number.POSITIVE_INFINITY;
  1057. const RAD_PER_DEG = PI / 180;
  1058. const HALF_PI = PI / 2;
  1059. const QUARTER_PI = PI / 4;
  1060. const TWO_THIRDS_PI = PI * 2 / 3;
  1061. const log10 = Math.log10;
  1062. const sign = Math.sign;
  1063. function niceNum(range) {
  1064. const roundedRange = Math.round(range);
  1065. range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range;
  1066. const niceRange = Math.pow(10, Math.floor(log10(range)));
  1067. const fraction = range / niceRange;
  1068. const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
  1069. return niceFraction * niceRange;
  1070. }
  1071. function _factorize(value) {
  1072. const result = [];
  1073. const sqrt = Math.sqrt(value);
  1074. let i;
  1075. for (i = 1; i < sqrt; i++) {
  1076. if (value % i === 0) {
  1077. result.push(i);
  1078. result.push(value / i);
  1079. }
  1080. }
  1081. if (sqrt === (sqrt | 0)) {
  1082. result.push(sqrt);
  1083. }
  1084. result.sort((a, b) => a - b).pop();
  1085. return result;
  1086. }
  1087. function isNumber(n) {
  1088. return !isNaN(parseFloat(n)) && isFinite(n);
  1089. }
  1090. function almostEquals(x, y, epsilon) {
  1091. return Math.abs(x - y) < epsilon;
  1092. }
  1093. function almostWhole(x, epsilon) {
  1094. const rounded = Math.round(x);
  1095. return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
  1096. }
  1097. function _setMinAndMaxByKey(array, target, property) {
  1098. let i, ilen, value;
  1099. for (i = 0, ilen = array.length; i < ilen; i++) {
  1100. value = array[i][property];
  1101. if (!isNaN(value)) {
  1102. target.min = Math.min(target.min, value);
  1103. target.max = Math.max(target.max, value);
  1104. }
  1105. }
  1106. }
  1107. function toRadians(degrees) {
  1108. return degrees * (PI / 180);
  1109. }
  1110. function toDegrees(radians) {
  1111. return radians * (180 / PI);
  1112. }
  1113. function _decimalPlaces(x) {
  1114. if (!isNumberFinite(x)) {
  1115. return;
  1116. }
  1117. let e = 1;
  1118. let p = 0;
  1119. while (Math.round(x * e) / e !== x) {
  1120. e *= 10;
  1121. p++;
  1122. }
  1123. return p;
  1124. }
  1125. function getAngleFromPoint(centrePoint, anglePoint) {
  1126. const distanceFromXCenter = anglePoint.x - centrePoint.x;
  1127. const distanceFromYCenter = anglePoint.y - centrePoint.y;
  1128. const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  1129. let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  1130. if (angle < (-0.5 * PI)) {
  1131. angle += TAU;
  1132. }
  1133. return {
  1134. angle,
  1135. distance: radialDistanceFromCenter
  1136. };
  1137. }
  1138. function distanceBetweenPoints(pt1, pt2) {
  1139. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  1140. }
  1141. function _angleDiff(a, b) {
  1142. return (a - b + PITAU) % TAU - PI;
  1143. }
  1144. function _normalizeAngle(a) {
  1145. return (a % TAU + TAU) % TAU;
  1146. }
  1147. function _angleBetween(angle, start, end, sameAngleIsFullCircle) {
  1148. const a = _normalizeAngle(angle);
  1149. const s = _normalizeAngle(start);
  1150. const e = _normalizeAngle(end);
  1151. const angleToStart = _normalizeAngle(s - a);
  1152. const angleToEnd = _normalizeAngle(e - a);
  1153. const startToAngle = _normalizeAngle(a - s);
  1154. const endToAngle = _normalizeAngle(a - e);
  1155. return a === s || a === e || (sameAngleIsFullCircle && s === e)
  1156. || (angleToStart > angleToEnd && startToAngle < endToAngle);
  1157. }
  1158. function _limitValue(value, min, max) {
  1159. return Math.max(min, Math.min(max, value));
  1160. }
  1161. function _int16Range(value) {
  1162. return _limitValue(value, -32768, 32767);
  1163. }
  1164. function toFontString(font) {
  1165. if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) {
  1166. return null;
  1167. }
  1168. return (font.style ? font.style + ' ' : '')
  1169. + (font.weight ? font.weight + ' ' : '')
  1170. + font.size + 'px '
  1171. + font.family;
  1172. }
  1173. function _measureText(ctx, data, gc, longest, string) {
  1174. let textWidth = data[string];
  1175. if (!textWidth) {
  1176. textWidth = data[string] = ctx.measureText(string).width;
  1177. gc.push(string);
  1178. }
  1179. if (textWidth > longest) {
  1180. longest = textWidth;
  1181. }
  1182. return longest;
  1183. }
  1184. function _longestText(ctx, font, arrayOfThings, cache) {
  1185. cache = cache || {};
  1186. let data = cache.data = cache.data || {};
  1187. let gc = cache.garbageCollect = cache.garbageCollect || [];
  1188. if (cache.font !== font) {
  1189. data = cache.data = {};
  1190. gc = cache.garbageCollect = [];
  1191. cache.font = font;
  1192. }
  1193. ctx.save();
  1194. ctx.font = font;
  1195. let longest = 0;
  1196. const ilen = arrayOfThings.length;
  1197. let i, j, jlen, thing, nestedThing;
  1198. for (i = 0; i < ilen; i++) {
  1199. thing = arrayOfThings[i];
  1200. if (thing !== undefined && thing !== null && isArray(thing) !== true) {
  1201. longest = _measureText(ctx, data, gc, longest, thing);
  1202. } else if (isArray(thing)) {
  1203. for (j = 0, jlen = thing.length; j < jlen; j++) {
  1204. nestedThing = thing[j];
  1205. if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) {
  1206. longest = _measureText(ctx, data, gc, longest, nestedThing);
  1207. }
  1208. }
  1209. }
  1210. }
  1211. ctx.restore();
  1212. const gcLen = gc.length / 2;
  1213. if (gcLen > arrayOfThings.length) {
  1214. for (i = 0; i < gcLen; i++) {
  1215. delete data[gc[i]];
  1216. }
  1217. gc.splice(0, gcLen);
  1218. }
  1219. return longest;
  1220. }
  1221. function _alignPixel(chart, pixel, width) {
  1222. const devicePixelRatio = chart.currentDevicePixelRatio;
  1223. const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0;
  1224. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  1225. }
  1226. function clearCanvas(canvas, ctx) {
  1227. ctx = ctx || canvas.getContext('2d');
  1228. ctx.save();
  1229. ctx.resetTransform();
  1230. ctx.clearRect(0, 0, canvas.width, canvas.height);
  1231. ctx.restore();
  1232. }
  1233. function drawPoint(ctx, options, x, y) {
  1234. let type, xOffset, yOffset, size, cornerRadius;
  1235. const style = options.pointStyle;
  1236. const rotation = options.rotation;
  1237. const radius = options.radius;
  1238. let rad = (rotation || 0) * RAD_PER_DEG;
  1239. if (style && typeof style === 'object') {
  1240. type = style.toString();
  1241. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  1242. ctx.save();
  1243. ctx.translate(x, y);
  1244. ctx.rotate(rad);
  1245. ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
  1246. ctx.restore();
  1247. return;
  1248. }
  1249. }
  1250. if (isNaN(radius) || radius <= 0) {
  1251. return;
  1252. }
  1253. ctx.beginPath();
  1254. switch (style) {
  1255. default:
  1256. ctx.arc(x, y, radius, 0, TAU);
  1257. ctx.closePath();
  1258. break;
  1259. case 'triangle':
  1260. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  1261. rad += TWO_THIRDS_PI;
  1262. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  1263. rad += TWO_THIRDS_PI;
  1264. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  1265. ctx.closePath();
  1266. break;
  1267. case 'rectRounded':
  1268. cornerRadius = radius * 0.516;
  1269. size = radius - cornerRadius;
  1270. xOffset = Math.cos(rad + QUARTER_PI) * size;
  1271. yOffset = Math.sin(rad + QUARTER_PI) * size;
  1272. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  1273. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  1274. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  1275. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  1276. ctx.closePath();
  1277. break;
  1278. case 'rect':
  1279. if (!rotation) {
  1280. size = Math.SQRT1_2 * radius;
  1281. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  1282. break;
  1283. }
  1284. rad += QUARTER_PI;
  1285. case 'rectRot':
  1286. xOffset = Math.cos(rad) * radius;
  1287. yOffset = Math.sin(rad) * radius;
  1288. ctx.moveTo(x - xOffset, y - yOffset);
  1289. ctx.lineTo(x + yOffset, y - xOffset);
  1290. ctx.lineTo(x + xOffset, y + yOffset);
  1291. ctx.lineTo(x - yOffset, y + xOffset);
  1292. ctx.closePath();
  1293. break;
  1294. case 'crossRot':
  1295. rad += QUARTER_PI;
  1296. case 'cross':
  1297. xOffset = Math.cos(rad) * radius;
  1298. yOffset = Math.sin(rad) * radius;
  1299. ctx.moveTo(x - xOffset, y - yOffset);
  1300. ctx.lineTo(x + xOffset, y + yOffset);
  1301. ctx.moveTo(x + yOffset, y - xOffset);
  1302. ctx.lineTo(x - yOffset, y + xOffset);
  1303. break;
  1304. case 'star':
  1305. xOffset = Math.cos(rad) * radius;
  1306. yOffset = Math.sin(rad) * radius;
  1307. ctx.moveTo(x - xOffset, y - yOffset);
  1308. ctx.lineTo(x + xOffset, y + yOffset);
  1309. ctx.moveTo(x + yOffset, y - xOffset);
  1310. ctx.lineTo(x - yOffset, y + xOffset);
  1311. rad += QUARTER_PI;
  1312. xOffset = Math.cos(rad) * radius;
  1313. yOffset = Math.sin(rad) * radius;
  1314. ctx.moveTo(x - xOffset, y - yOffset);
  1315. ctx.lineTo(x + xOffset, y + yOffset);
  1316. ctx.moveTo(x + yOffset, y - xOffset);
  1317. ctx.lineTo(x - yOffset, y + xOffset);
  1318. break;
  1319. case 'line':
  1320. xOffset = Math.cos(rad) * radius;
  1321. yOffset = Math.sin(rad) * radius;
  1322. ctx.moveTo(x - xOffset, y - yOffset);
  1323. ctx.lineTo(x + xOffset, y + yOffset);
  1324. break;
  1325. case 'dash':
  1326. ctx.moveTo(x, y);
  1327. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  1328. break;
  1329. }
  1330. ctx.fill();
  1331. if (options.borderWidth > 0) {
  1332. ctx.stroke();
  1333. }
  1334. }
  1335. function _isPointInArea(point, area, margin) {
  1336. margin = margin || 0.5;
  1337. return !area || (point && point.x > area.left - margin && point.x < area.right + margin &&
  1338. point.y > area.top - margin && point.y < area.bottom + margin);
  1339. }
  1340. function clipArea(ctx, area) {
  1341. ctx.save();
  1342. ctx.beginPath();
  1343. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  1344. ctx.clip();
  1345. }
  1346. function unclipArea(ctx) {
  1347. ctx.restore();
  1348. }
  1349. function _steppedLineTo(ctx, previous, target, flip, mode) {
  1350. if (!previous) {
  1351. return ctx.lineTo(target.x, target.y);
  1352. }
  1353. if (mode === 'middle') {
  1354. const midpoint = (previous.x + target.x) / 2.0;
  1355. ctx.lineTo(midpoint, previous.y);
  1356. ctx.lineTo(midpoint, target.y);
  1357. } else if (mode === 'after' !== !!flip) {
  1358. ctx.lineTo(previous.x, target.y);
  1359. } else {
  1360. ctx.lineTo(target.x, previous.y);
  1361. }
  1362. ctx.lineTo(target.x, target.y);
  1363. }
  1364. function _bezierCurveTo(ctx, previous, target, flip) {
  1365. if (!previous) {
  1366. return ctx.lineTo(target.x, target.y);
  1367. }
  1368. ctx.bezierCurveTo(
  1369. flip ? previous.cp1x : previous.cp2x,
  1370. flip ? previous.cp1y : previous.cp2y,
  1371. flip ? target.cp2x : target.cp1x,
  1372. flip ? target.cp2y : target.cp1y,
  1373. target.x,
  1374. target.y);
  1375. }
  1376. function renderText(ctx, text, x, y, font, opts = {}) {
  1377. const lines = isArray(text) ? text : [text];
  1378. const stroke = opts.strokeWidth > 0 && opts.strokeColor !== '';
  1379. let i, line;
  1380. ctx.save();
  1381. ctx.font = font.string;
  1382. setRenderOpts(ctx, opts);
  1383. for (i = 0; i < lines.length; ++i) {
  1384. line = lines[i];
  1385. if (stroke) {
  1386. if (opts.strokeColor) {
  1387. ctx.strokeStyle = opts.strokeColor;
  1388. }
  1389. if (!isNullOrUndef(opts.strokeWidth)) {
  1390. ctx.lineWidth = opts.strokeWidth;
  1391. }
  1392. ctx.strokeText(line, x, y, opts.maxWidth);
  1393. }
  1394. ctx.fillText(line, x, y, opts.maxWidth);
  1395. decorateText(ctx, x, y, line, opts);
  1396. y += font.lineHeight;
  1397. }
  1398. ctx.restore();
  1399. }
  1400. function setRenderOpts(ctx, opts) {
  1401. if (opts.translation) {
  1402. ctx.translate(opts.translation[0], opts.translation[1]);
  1403. }
  1404. if (!isNullOrUndef(opts.rotation)) {
  1405. ctx.rotate(opts.rotation);
  1406. }
  1407. if (opts.color) {
  1408. ctx.fillStyle = opts.color;
  1409. }
  1410. if (opts.textAlign) {
  1411. ctx.textAlign = opts.textAlign;
  1412. }
  1413. if (opts.textBaseline) {
  1414. ctx.textBaseline = opts.textBaseline;
  1415. }
  1416. }
  1417. function decorateText(ctx, x, y, line, opts) {
  1418. if (opts.strikethrough || opts.underline) {
  1419. const metrics = ctx.measureText(line);
  1420. const left = x - metrics.actualBoundingBoxLeft;
  1421. const right = x + metrics.actualBoundingBoxRight;
  1422. const top = y - metrics.actualBoundingBoxAscent;
  1423. const bottom = y + metrics.actualBoundingBoxDescent;
  1424. const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom;
  1425. ctx.strokeStyle = ctx.fillStyle;
  1426. ctx.beginPath();
  1427. ctx.lineWidth = opts.decorationWidth || 2;
  1428. ctx.moveTo(left, yDecoration);
  1429. ctx.lineTo(right, yDecoration);
  1430. ctx.stroke();
  1431. }
  1432. }
  1433. function addRoundedRectPath(ctx, rect) {
  1434. const {x, y, w, h, radius} = rect;
  1435. ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, -HALF_PI, PI, true);
  1436. ctx.lineTo(x, y + h - radius.bottomLeft);
  1437. ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true);
  1438. ctx.lineTo(x + w - radius.bottomRight, y + h);
  1439. ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true);
  1440. ctx.lineTo(x + w, y + radius.topRight);
  1441. ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true);
  1442. ctx.lineTo(x + radius.topLeft, y);
  1443. }
  1444. function _lookup(table, value, cmp) {
  1445. cmp = cmp || ((index) => table[index] < value);
  1446. let hi = table.length - 1;
  1447. let lo = 0;
  1448. let mid;
  1449. while (hi - lo > 1) {
  1450. mid = (lo + hi) >> 1;
  1451. if (cmp(mid)) {
  1452. lo = mid;
  1453. } else {
  1454. hi = mid;
  1455. }
  1456. }
  1457. return {lo, hi};
  1458. }
  1459. const _lookupByKey = (table, key, value) =>
  1460. _lookup(table, value, index => table[index][key] < value);
  1461. const _rlookupByKey = (table, key, value) =>
  1462. _lookup(table, value, index => table[index][key] >= value);
  1463. function _filterBetween(values, min, max) {
  1464. let start = 0;
  1465. let end = values.length;
  1466. while (start < end && values[start] < min) {
  1467. start++;
  1468. }
  1469. while (end > start && values[end - 1] > max) {
  1470. end--;
  1471. }
  1472. return start > 0 || end < values.length
  1473. ? values.slice(start, end)
  1474. : values;
  1475. }
  1476. const arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  1477. function listenArrayEvents(array, listener) {
  1478. if (array._chartjs) {
  1479. array._chartjs.listeners.push(listener);
  1480. return;
  1481. }
  1482. Object.defineProperty(array, '_chartjs', {
  1483. configurable: true,
  1484. enumerable: false,
  1485. value: {
  1486. listeners: [listener]
  1487. }
  1488. });
  1489. arrayEvents.forEach((key) => {
  1490. const method = '_onData' + _capitalize(key);
  1491. const base = array[key];
  1492. Object.defineProperty(array, key, {
  1493. configurable: true,
  1494. enumerable: false,
  1495. value(...args) {
  1496. const res = base.apply(this, args);
  1497. array._chartjs.listeners.forEach((object) => {
  1498. if (typeof object[method] === 'function') {
  1499. object[method](...args);
  1500. }
  1501. });
  1502. return res;
  1503. }
  1504. });
  1505. });
  1506. }
  1507. function unlistenArrayEvents(array, listener) {
  1508. const stub = array._chartjs;
  1509. if (!stub) {
  1510. return;
  1511. }
  1512. const listeners = stub.listeners;
  1513. const index = listeners.indexOf(listener);
  1514. if (index !== -1) {
  1515. listeners.splice(index, 1);
  1516. }
  1517. if (listeners.length > 0) {
  1518. return;
  1519. }
  1520. arrayEvents.forEach((key) => {
  1521. delete array[key];
  1522. });
  1523. delete array._chartjs;
  1524. }
  1525. function _arrayUnique(items) {
  1526. const set = new Set();
  1527. let i, ilen;
  1528. for (i = 0, ilen = items.length; i < ilen; ++i) {
  1529. set.add(items[i]);
  1530. }
  1531. if (set.size === ilen) {
  1532. return items;
  1533. }
  1534. return Array.from(set);
  1535. }
  1536. function _isDomSupported() {
  1537. return typeof window !== 'undefined' && typeof document !== 'undefined';
  1538. }
  1539. function _getParentNode(domNode) {
  1540. let parent = domNode.parentNode;
  1541. if (parent && parent.toString() === '[object ShadowRoot]') {
  1542. parent = parent.host;
  1543. }
  1544. return parent;
  1545. }
  1546. function parseMaxStyle(styleValue, node, parentProperty) {
  1547. let valueInPixels;
  1548. if (typeof styleValue === 'string') {
  1549. valueInPixels = parseInt(styleValue, 10);
  1550. if (styleValue.indexOf('%') !== -1) {
  1551. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  1552. }
  1553. } else {
  1554. valueInPixels = styleValue;
  1555. }
  1556. return valueInPixels;
  1557. }
  1558. const getComputedStyle = (element) => window.getComputedStyle(element, null);
  1559. function getStyle(el, property) {
  1560. return getComputedStyle(el).getPropertyValue(property);
  1561. }
  1562. const positions = ['top', 'right', 'bottom', 'left'];
  1563. function getPositionedStyle(styles, style, suffix) {
  1564. const result = {};
  1565. suffix = suffix ? '-' + suffix : '';
  1566. for (let i = 0; i < 4; i++) {
  1567. const pos = positions[i];
  1568. result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0;
  1569. }
  1570. result.width = result.left + result.right;
  1571. result.height = result.top + result.bottom;
  1572. return result;
  1573. }
  1574. const useOffsetPos = (x, y, target) => (x > 0 || y > 0) && (!target || !target.shadowRoot);
  1575. function getCanvasPosition(evt, canvas) {
  1576. const e = evt.native || evt;
  1577. const touches = e.touches;
  1578. const source = touches && touches.length ? touches[0] : e;
  1579. const {offsetX, offsetY} = source;
  1580. let box = false;
  1581. let x, y;
  1582. if (useOffsetPos(offsetX, offsetY, e.target)) {
  1583. x = offsetX;
  1584. y = offsetY;
  1585. } else {
  1586. const rect = canvas.getBoundingClientRect();
  1587. x = source.clientX - rect.left;
  1588. y = source.clientY - rect.top;
  1589. box = true;
  1590. }
  1591. return {x, y, box};
  1592. }
  1593. function getRelativePosition$1(evt, chart) {
  1594. const {canvas, currentDevicePixelRatio} = chart;
  1595. const style = getComputedStyle(canvas);
  1596. const borderBox = style.boxSizing === 'border-box';
  1597. const paddings = getPositionedStyle(style, 'padding');
  1598. const borders = getPositionedStyle(style, 'border', 'width');
  1599. const {x, y, box} = getCanvasPosition(evt, canvas);
  1600. const xOffset = paddings.left + (box && borders.left);
  1601. const yOffset = paddings.top + (box && borders.top);
  1602. let {width, height} = chart;
  1603. if (borderBox) {
  1604. width -= paddings.width + borders.width;
  1605. height -= paddings.height + borders.height;
  1606. }
  1607. return {
  1608. x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio),
  1609. y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio)
  1610. };
  1611. }
  1612. function getContainerSize(canvas, width, height) {
  1613. let maxWidth, maxHeight;
  1614. if (width === undefined || height === undefined) {
  1615. const container = _getParentNode(canvas);
  1616. if (!container) {
  1617. width = canvas.clientWidth;
  1618. height = canvas.clientHeight;
  1619. } else {
  1620. const rect = container.getBoundingClientRect();
  1621. const containerStyle = getComputedStyle(container);
  1622. const containerBorder = getPositionedStyle(containerStyle, 'border', 'width');
  1623. const containerPadding = getPositionedStyle(containerStyle, 'padding');
  1624. width = rect.width - containerPadding.width - containerBorder.width;
  1625. height = rect.height - containerPadding.height - containerBorder.height;
  1626. maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth');
  1627. maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight');
  1628. }
  1629. }
  1630. return {
  1631. width,
  1632. height,
  1633. maxWidth: maxWidth || INFINITY,
  1634. maxHeight: maxHeight || INFINITY
  1635. };
  1636. }
  1637. const round1 = v => Math.round(v * 10) / 10;
  1638. function getMaximumSize(canvas, bbWidth, bbHeight, aspectRatio) {
  1639. const style = getComputedStyle(canvas);
  1640. const margins = getPositionedStyle(style, 'margin');
  1641. const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY;
  1642. const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY;
  1643. const containerSize = getContainerSize(canvas, bbWidth, bbHeight);
  1644. let {width, height} = containerSize;
  1645. if (style.boxSizing === 'content-box') {
  1646. const borders = getPositionedStyle(style, 'border', 'width');
  1647. const paddings = getPositionedStyle(style, 'padding');
  1648. width -= paddings.width + borders.width;
  1649. height -= paddings.height + borders.height;
  1650. }
  1651. width = Math.max(0, width - margins.width);
  1652. height = Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height - margins.height);
  1653. width = round1(Math.min(width, maxWidth, containerSize.maxWidth));
  1654. height = round1(Math.min(height, maxHeight, containerSize.maxHeight));
  1655. if (width && !height) {
  1656. height = round1(width / 2);
  1657. }
  1658. return {
  1659. width,
  1660. height
  1661. };
  1662. }
  1663. function retinaScale(chart, forceRatio, forceStyle) {
  1664. const pixelRatio = forceRatio || 1;
  1665. const deviceHeight = Math.floor(chart.height * pixelRatio);
  1666. const deviceWidth = Math.floor(chart.width * pixelRatio);
  1667. chart.height = deviceHeight / pixelRatio;
  1668. chart.width = deviceWidth / pixelRatio;
  1669. const canvas = chart.canvas;
  1670. if (canvas.style && (forceStyle || (!canvas.style.height && !canvas.style.width))) {
  1671. canvas.style.height = `${chart.height}px`;
  1672. canvas.style.width = `${chart.width}px`;
  1673. }
  1674. if (chart.currentDevicePixelRatio !== pixelRatio
  1675. || canvas.height !== deviceHeight
  1676. || canvas.width !== deviceWidth) {
  1677. chart.currentDevicePixelRatio = pixelRatio;
  1678. canvas.height = deviceHeight;
  1679. canvas.width = deviceWidth;
  1680. chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
  1681. return true;
  1682. }
  1683. return false;
  1684. }
  1685. const supportsEventListenerOptions = (function() {
  1686. let passiveSupported = false;
  1687. try {
  1688. const options = {
  1689. get passive() {
  1690. passiveSupported = true;
  1691. return false;
  1692. }
  1693. };
  1694. window.addEventListener('test', null, options);
  1695. window.removeEventListener('test', null, options);
  1696. } catch (e) {
  1697. }
  1698. return passiveSupported;
  1699. }());
  1700. function readUsedSize(element, property) {
  1701. const value = getStyle(element, property);
  1702. const matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  1703. return matches ? +matches[1] : undefined;
  1704. }
  1705. function getRelativePosition(e, chart) {
  1706. if ('native' in e) {
  1707. return {
  1708. x: e.x,
  1709. y: e.y
  1710. };
  1711. }
  1712. return getRelativePosition$1(e, chart);
  1713. }
  1714. function evaluateAllVisibleItems(chart, handler) {
  1715. const metasets = chart.getSortedVisibleDatasetMetas();
  1716. let index, data, element;
  1717. for (let i = 0, ilen = metasets.length; i < ilen; ++i) {
  1718. ({index, data} = metasets[i]);
  1719. for (let j = 0, jlen = data.length; j < jlen; ++j) {
  1720. element = data[j];
  1721. if (!element.skip) {
  1722. handler(element, index, j);
  1723. }
  1724. }
  1725. }
  1726. }
  1727. function binarySearch(metaset, axis, value, intersect) {
  1728. const {controller, data, _sorted} = metaset;
  1729. const iScale = controller._cachedMeta.iScale;
  1730. if (iScale && axis === iScale.axis && _sorted && data.length) {
  1731. const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;
  1732. if (!intersect) {
  1733. return lookupMethod(data, axis, value);
  1734. } else if (controller._sharedOptions) {
  1735. const el = data[0];
  1736. const range = typeof el.getRange === 'function' && el.getRange(axis);
  1737. if (range) {
  1738. const start = lookupMethod(data, axis, value - range);
  1739. const end = lookupMethod(data, axis, value + range);
  1740. return {lo: start.lo, hi: end.hi};
  1741. }
  1742. }
  1743. }
  1744. return {lo: 0, hi: data.length - 1};
  1745. }
  1746. function optimizedEvaluateItems(chart, axis, position, handler, intersect) {
  1747. const metasets = chart.getSortedVisibleDatasetMetas();
  1748. const value = position[axis];
  1749. for (let i = 0, ilen = metasets.length; i < ilen; ++i) {
  1750. const {index, data} = metasets[i];
  1751. const {lo, hi} = binarySearch(metasets[i], axis, value, intersect);
  1752. for (let j = lo; j <= hi; ++j) {
  1753. const element = data[j];
  1754. if (!element.skip) {
  1755. handler(element, index, j);
  1756. }
  1757. }
  1758. }
  1759. }
  1760. function getDistanceMetricForAxis(axis) {
  1761. const useX = axis.indexOf('x') !== -1;
  1762. const useY = axis.indexOf('y') !== -1;
  1763. return function(pt1, pt2) {
  1764. const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  1765. const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  1766. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  1767. };
  1768. }
  1769. function getIntersectItems(chart, position, axis, useFinalPosition) {
  1770. const items = [];
  1771. if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) {
  1772. return items;
  1773. }
  1774. const evaluationFunc = function(element, datasetIndex, index) {
  1775. if (element.inRange(position.x, position.y, useFinalPosition)) {
  1776. items.push({element, datasetIndex, index});
  1777. }
  1778. };
  1779. optimizedEvaluateItems(chart, axis, position, evaluationFunc, true);
  1780. return items;
  1781. }
  1782. function getNearestItems(chart, position, axis, intersect, useFinalPosition) {
  1783. const distanceMetric = getDistanceMetricForAxis(axis);
  1784. let minDistance = Number.POSITIVE_INFINITY;
  1785. let items = [];
  1786. if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) {
  1787. return items;
  1788. }
  1789. const evaluationFunc = function(element, datasetIndex, index) {
  1790. if (intersect && !element.inRange(position.x, position.y, useFinalPosition)) {
  1791. return;
  1792. }
  1793. const center = element.getCenterPoint(useFinalPosition);
  1794. if (!_isPointInArea(center, chart.chartArea, chart._minPadding) && !element.inRange(position.x, position.y, useFinalPosition)) {
  1795. return;
  1796. }
  1797. const distance = distanceMetric(position, center);
  1798. if (distance < minDistance) {
  1799. items = [{element, datasetIndex, index}];
  1800. minDistance = distance;
  1801. } else if (distance === minDistance) {
  1802. items.push({element, datasetIndex, index});
  1803. }
  1804. };
  1805. optimizedEvaluateItems(chart, axis, position, evaluationFunc);
  1806. return items;
  1807. }
  1808. function getAxisItems(chart, e, options, useFinalPosition) {
  1809. const position = getRelativePosition(e, chart);
  1810. const items = [];
  1811. const axis = options.axis;
  1812. const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';
  1813. let intersectsItem = false;
  1814. evaluateAllVisibleItems(chart, (element, datasetIndex, index) => {
  1815. if (element[rangeMethod](position[axis], useFinalPosition)) {
  1816. items.push({element, datasetIndex, index});
  1817. }
  1818. if (element.inRange(position.x, position.y, useFinalPosition)) {
  1819. intersectsItem = true;
  1820. }
  1821. });
  1822. if (options.intersect && !intersectsItem) {
  1823. return [];
  1824. }
  1825. return items;
  1826. }
  1827. var Interaction = {
  1828. modes: {
  1829. index(chart, e, options, useFinalPosition) {
  1830. const position = getRelativePosition(e, chart);
  1831. const axis = options.axis || 'x';
  1832. const items = options.intersect
  1833. ? getIntersectItems(chart, position, axis, useFinalPosition)
  1834. : getNearestItems(chart, position, axis, false, useFinalPosition);
  1835. const elements = [];
  1836. if (!items.length) {
  1837. return [];
  1838. }
  1839. chart.getSortedVisibleDatasetMetas().forEach((meta) => {
  1840. const index = items[0].index;
  1841. const element = meta.data[index];
  1842. if (element && !element.skip) {
  1843. elements.push({element, datasetIndex: meta.index, index});
  1844. }
  1845. });
  1846. return elements;
  1847. },
  1848. dataset(chart, e, options, useFinalPosition) {
  1849. const position = getRelativePosition(e, chart);
  1850. const axis = options.axis || 'xy';
  1851. let items = options.intersect
  1852. ? getIntersectItems(chart, position, axis, useFinalPosition) :
  1853. getNearestItems(chart, position, axis, false, useFinalPosition);
  1854. if (items.length > 0) {
  1855. const datasetIndex = items[0].datasetIndex;
  1856. const data = chart.getDatasetMeta(datasetIndex).data;
  1857. items = [];
  1858. for (let i = 0; i < data.length; ++i) {
  1859. items.push({element: data[i], datasetIndex, index: i});
  1860. }
  1861. }
  1862. return items;
  1863. },
  1864. point(chart, e, options, useFinalPosition) {
  1865. const position = getRelativePosition(e, chart);
  1866. const axis = options.axis || 'xy';
  1867. return getIntersectItems(chart, position, axis, useFinalPosition);
  1868. },
  1869. nearest(chart, e, options, useFinalPosition) {
  1870. const position = getRelativePosition(e, chart);
  1871. const axis = options.axis || 'xy';
  1872. return getNearestItems(chart, position, axis, options.intersect, useFinalPosition);
  1873. },
  1874. x(chart, e, options, useFinalPosition) {
  1875. options.axis = 'x';
  1876. return getAxisItems(chart, e, options, useFinalPosition);
  1877. },
  1878. y(chart, e, options, useFinalPosition) {
  1879. options.axis = 'y';
  1880. return getAxisItems(chart, e, options, useFinalPosition);
  1881. }
  1882. }
  1883. };
  1884. const LINE_HEIGHT = new RegExp(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  1885. const FONT_STYLE = new RegExp(/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/);
  1886. function toLineHeight(value, size) {
  1887. const matches = ('' + value).match(LINE_HEIGHT);
  1888. if (!matches || matches[1] === 'normal') {
  1889. return size * 1.2;
  1890. }
  1891. value = +matches[2];
  1892. switch (matches[3]) {
  1893. case 'px':
  1894. return value;
  1895. case '%':
  1896. value /= 100;
  1897. break;
  1898. }
  1899. return size * value;
  1900. }
  1901. const numberOrZero$1 = v => +v || 0;
  1902. function _readValueToProps(value, props) {
  1903. const ret = {};
  1904. const objProps = isObject(props);
  1905. const keys = objProps ? Object.keys(props) : props;
  1906. const read = isObject(value)
  1907. ? objProps
  1908. ? prop => valueOrDefault(value[prop], value[props[prop]])
  1909. : prop => value[prop]
  1910. : () => value;
  1911. for (const prop of keys) {
  1912. ret[prop] = numberOrZero$1(read(prop));
  1913. }
  1914. return ret;
  1915. }
  1916. function toTRBL(value) {
  1917. return _readValueToProps(value, {top: 'y', right: 'x', bottom: 'y', left: 'x'});
  1918. }
  1919. function toTRBLCorners(value) {
  1920. return _readValueToProps(value, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']);
  1921. }
  1922. function toPadding(value) {
  1923. const obj = toTRBL(value);
  1924. obj.width = obj.left + obj.right;
  1925. obj.height = obj.top + obj.bottom;
  1926. return obj;
  1927. }
  1928. function toFont(options, fallback) {
  1929. options = options || {};
  1930. fallback = fallback || defaults.font;
  1931. let size = valueOrDefault(options.size, fallback.size);
  1932. if (typeof size === 'string') {
  1933. size = parseInt(size, 10);
  1934. }
  1935. let style = valueOrDefault(options.style, fallback.style);
  1936. if (style && !('' + style).match(FONT_STYLE)) {
  1937. console.warn('Invalid font style specified: "' + style + '"');
  1938. style = '';
  1939. }
  1940. const font = {
  1941. family: valueOrDefault(options.family, fallback.family),
  1942. lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size),
  1943. size,
  1944. style,
  1945. weight: valueOrDefault(options.weight, fallback.weight),
  1946. string: ''
  1947. };
  1948. font.string = toFontString(font);
  1949. return font;
  1950. }
  1951. function resolve(inputs, context, index, info) {
  1952. let cacheable = true;
  1953. let i, ilen, value;
  1954. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  1955. value = inputs[i];
  1956. if (value === undefined) {
  1957. continue;
  1958. }
  1959. if (context !== undefined && typeof value === 'function') {
  1960. value = value(context);
  1961. cacheable = false;
  1962. }
  1963. if (index !== undefined && isArray(value)) {
  1964. value = value[index % value.length];
  1965. cacheable = false;
  1966. }
  1967. if (value !== undefined) {
  1968. if (info && !cacheable) {
  1969. info.cacheable = false;
  1970. }
  1971. return value;
  1972. }
  1973. }
  1974. }
  1975. function _addGrace(minmax, grace) {
  1976. const {min, max} = minmax;
  1977. return {
  1978. min: min - Math.abs(toDimension(grace, min)),
  1979. max: max + toDimension(grace, max)
  1980. };
  1981. }
  1982. const STATIC_POSITIONS = ['left', 'top', 'right', 'bottom'];
  1983. function filterByPosition(array, position) {
  1984. return array.filter(v => v.pos === position);
  1985. }
  1986. function filterDynamicPositionByAxis(array, axis) {
  1987. return array.filter(v => STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);
  1988. }
  1989. function sortByWeight(array, reverse) {
  1990. return array.sort((a, b) => {
  1991. const v0 = reverse ? b : a;
  1992. const v1 = reverse ? a : b;
  1993. return v0.weight === v1.weight ?
  1994. v0.index - v1.index :
  1995. v0.weight - v1.weight;
  1996. });
  1997. }
  1998. function wrapBoxes(boxes) {
  1999. const layoutBoxes = [];
  2000. let i, ilen, box, pos, stack, stackWeight;
  2001. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  2002. box = boxes[i];
  2003. ({position: pos, options: {stack, stackWeight = 1}} = box);
  2004. layoutBoxes.push({
  2005. index: i,
  2006. box,
  2007. pos,
  2008. horizontal: box.isHorizontal(),
  2009. weight: box.weight,
  2010. stack: stack && (pos + stack),
  2011. stackWeight
  2012. });
  2013. }
  2014. return layoutBoxes;
  2015. }
  2016. function buildStacks(layouts) {
  2017. const stacks = {};
  2018. for (const wrap of layouts) {
  2019. const {stack, pos, stackWeight} = wrap;
  2020. if (!stack || !STATIC_POSITIONS.includes(pos)) {
  2021. continue;
  2022. }
  2023. const _stack = stacks[stack] || (stacks[stack] = {count: 0, placed: 0, weight: 0, size: 0});
  2024. _stack.count++;
  2025. _stack.weight += stackWeight;
  2026. }
  2027. return stacks;
  2028. }
  2029. function setLayoutDims(layouts, params) {
  2030. const stacks = buildStacks(layouts);
  2031. const {vBoxMaxWidth, hBoxMaxHeight} = params;
  2032. let i, ilen, layout;
  2033. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  2034. layout = layouts[i];
  2035. const {fullSize} = layout.box;
  2036. const stack = stacks[layout.stack];
  2037. const factor = stack && layout.stackWeight / stack.weight;
  2038. if (layout.horizontal) {
  2039. layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth;
  2040. layout.height = hBoxMaxHeight;
  2041. } else {
  2042. layout.width = vBoxMaxWidth;
  2043. layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight;
  2044. }
  2045. }
  2046. return stacks;
  2047. }
  2048. function buildLayoutBoxes(boxes) {
  2049. const layoutBoxes = wrapBoxes(boxes);
  2050. const fullSize = sortByWeight(layoutBoxes.filter(wrap => wrap.box.fullSize), true);
  2051. const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  2052. const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  2053. const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  2054. const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  2055. const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');
  2056. const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');
  2057. return {
  2058. fullSize,
  2059. leftAndTop: left.concat(top),
  2060. rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),
  2061. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  2062. vertical: left.concat(right).concat(centerVertical),
  2063. horizontal: top.concat(bottom).concat(centerHorizontal)
  2064. };
  2065. }
  2066. function getCombinedMax(maxPadding, chartArea, a, b) {
  2067. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  2068. }
  2069. function updateMaxPadding(maxPadding, boxPadding) {
  2070. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  2071. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  2072. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  2073. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  2074. }
  2075. function updateDims(chartArea, params, layout, stacks) {
  2076. const {pos, box} = layout;
  2077. const maxPadding = chartArea.maxPadding;
  2078. if (!isObject(pos)) {
  2079. if (layout.size) {
  2080. chartArea[pos] -= layout.size;
  2081. }
  2082. const stack = stacks[layout.stack] || {size: 0, count: 1};
  2083. stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width);
  2084. layout.size = stack.size / stack.count;
  2085. chartArea[pos] += layout.size;
  2086. }
  2087. if (box.getPadding) {
  2088. updateMaxPadding(maxPadding, box.getPadding());
  2089. }
  2090. const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));
  2091. const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));
  2092. const widthChanged = newWidth !== chartArea.w;
  2093. const heightChanged = newHeight !== chartArea.h;
  2094. chartArea.w = newWidth;
  2095. chartArea.h = newHeight;
  2096. return layout.horizontal
  2097. ? {same: widthChanged, other: heightChanged}
  2098. : {same: heightChanged, other: widthChanged};
  2099. }
  2100. function handleMaxPadding(chartArea) {
  2101. const maxPadding = chartArea.maxPadding;
  2102. function updatePos(pos) {
  2103. const change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  2104. chartArea[pos] += change;
  2105. return change;
  2106. }
  2107. chartArea.y += updatePos('top');
  2108. chartArea.x += updatePos('left');
  2109. updatePos('right');
  2110. updatePos('bottom');
  2111. }
  2112. function getMargins(horizontal, chartArea) {
  2113. const maxPadding = chartArea.maxPadding;
  2114. function marginForPositions(positions) {
  2115. const margin = {left: 0, top: 0, right: 0, bottom: 0};
  2116. positions.forEach((pos) => {
  2117. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  2118. });
  2119. return margin;
  2120. }
  2121. return horizontal
  2122. ? marginForPositions(['left', 'right'])
  2123. : marginForPositions(['top', 'bottom']);
  2124. }
  2125. function fitBoxes(boxes, chartArea, params, stacks) {
  2126. const refitBoxes = [];
  2127. let i, ilen, layout, box, refit, changed;
  2128. for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) {
  2129. layout = boxes[i];
  2130. box = layout.box;
  2131. box.update(
  2132. layout.width || chartArea.w,
  2133. layout.height || chartArea.h,
  2134. getMargins(layout.horizontal, chartArea)
  2135. );
  2136. const {same, other} = updateDims(chartArea, params, layout, stacks);
  2137. refit |= same && refitBoxes.length;
  2138. changed = changed || other;
  2139. if (!box.fullSize) {
  2140. refitBoxes.push(layout);
  2141. }
  2142. }
  2143. return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed;
  2144. }
  2145. function setBoxDims(box, left, top, width, height) {
  2146. box.top = top;
  2147. box.left = left;
  2148. box.right = left + width;
  2149. box.bottom = top + height;
  2150. box.width = width;
  2151. box.height = height;
  2152. }
  2153. function placeBoxes(boxes, chartArea, params, stacks) {
  2154. const userPadding = params.padding;
  2155. let {x, y} = chartArea;
  2156. for (const layout of boxes) {
  2157. const box = layout.box;
  2158. const stack = stacks[layout.stack] || {count: 1, placed: 0, weight: 1};
  2159. const weight = (layout.stackWeight / stack.weight) || 1;
  2160. if (layout.horizontal) {
  2161. const width = chartArea.w * weight;
  2162. const height = stack.size || box.height;
  2163. if (defined(stack.start)) {
  2164. y = stack.start;
  2165. }
  2166. if (box.fullSize) {
  2167. setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height);
  2168. } else {
  2169. setBoxDims(box, chartArea.left + stack.placed, y, width, height);
  2170. }
  2171. stack.start = y;
  2172. stack.placed += width;
  2173. y = box.bottom;
  2174. } else {
  2175. const height = chartArea.h * weight;
  2176. const width = stack.size || box.width;
  2177. if (defined(stack.start)) {
  2178. x = stack.start;
  2179. }
  2180. if (box.fullSize) {
  2181. setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top);
  2182. } else {
  2183. setBoxDims(box, x, chartArea.top + stack.placed, width, height);
  2184. }
  2185. stack.start = x;
  2186. stack.placed += height;
  2187. x = box.right;
  2188. }
  2189. }
  2190. chartArea.x = x;
  2191. chartArea.y = y;
  2192. }
  2193. defaults.set('layout', {
  2194. padding: {
  2195. top: 0,
  2196. right: 0,
  2197. bottom: 0,
  2198. left: 0
  2199. }
  2200. });
  2201. var layouts = {
  2202. addBox(chart, item) {
  2203. if (!chart.boxes) {
  2204. chart.boxes = [];
  2205. }
  2206. item.fullSize = item.fullSize || false;
  2207. item.position = item.position || 'top';
  2208. item.weight = item.weight || 0;
  2209. item._layers = item._layers || function() {
  2210. return [{
  2211. z: 0,
  2212. draw(chartArea) {
  2213. item.draw(chartArea);
  2214. }
  2215. }];
  2216. };
  2217. chart.boxes.push(item);
  2218. },
  2219. removeBox(chart, layoutItem) {
  2220. const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  2221. if (index !== -1) {
  2222. chart.boxes.splice(index, 1);
  2223. }
  2224. },
  2225. configure(chart, item, options) {
  2226. item.fullSize = options.fullSize;
  2227. item.position = options.position;
  2228. item.weight = options.weight;
  2229. },
  2230. update(chart, width, height, minPadding) {
  2231. if (!chart) {
  2232. return;
  2233. }
  2234. const padding = toPadding(chart.options.layout.padding);
  2235. const availableWidth = Math.max(width - padding.width, 0);
  2236. const availableHeight = Math.max(height - padding.height, 0);
  2237. const boxes = buildLayoutBoxes(chart.boxes);
  2238. const verticalBoxes = boxes.vertical;
  2239. const horizontalBoxes = boxes.horizontal;
  2240. each(chart.boxes, box => {
  2241. if (typeof box.beforeLayout === 'function') {
  2242. box.beforeLayout();
  2243. }
  2244. });
  2245. const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) =>
  2246. wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;
  2247. const params = Object.freeze({
  2248. outerWidth: width,
  2249. outerHeight: height,
  2250. padding,
  2251. availableWidth,
  2252. availableHeight,
  2253. vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,
  2254. hBoxMaxHeight: availableHeight / 2
  2255. });
  2256. const maxPadding = Object.assign({}, padding);
  2257. updateMaxPadding(maxPadding, toPadding(minPadding));
  2258. const chartArea = Object.assign({
  2259. maxPadding,
  2260. w: availableWidth,
  2261. h: availableHeight,
  2262. x: padding.left,
  2263. y: padding.top
  2264. }, padding);
  2265. const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  2266. fitBoxes(boxes.fullSize, chartArea, params, stacks);
  2267. fitBoxes(verticalBoxes, chartArea, params, stacks);
  2268. if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) {
  2269. fitBoxes(verticalBoxes, chartArea, params, stacks);
  2270. }
  2271. handleMaxPadding(chartArea);
  2272. placeBoxes(boxes.leftAndTop, chartArea, params, stacks);
  2273. chartArea.x += chartArea.w;
  2274. chartArea.y += chartArea.h;
  2275. placeBoxes(boxes.rightAndBottom, chartArea, params, stacks);
  2276. chart.chartArea = {
  2277. left: chartArea.left,
  2278. top: chartArea.top,
  2279. right: chartArea.left + chartArea.w,
  2280. bottom: chartArea.top + chartArea.h,
  2281. height: chartArea.h,
  2282. width: chartArea.w,
  2283. };
  2284. each(boxes.chartArea, (layout) => {
  2285. const box = layout.box;
  2286. Object.assign(box, chart.chartArea);
  2287. box.update(chartArea.w, chartArea.h);
  2288. });
  2289. }
  2290. };
  2291. function _createResolver(scopes, prefixes = [''], rootScopes = scopes, fallback, getTarget = () => scopes[0]) {
  2292. if (!defined(fallback)) {
  2293. fallback = _resolve('_fallback', scopes);
  2294. }
  2295. const cache = {
  2296. [Symbol.toStringTag]: 'Object',
  2297. _cacheable: true,
  2298. _scopes: scopes,
  2299. _rootScopes: rootScopes,
  2300. _fallback: fallback,
  2301. _getTarget: getTarget,
  2302. override: (scope) => _createResolver([scope, ...scopes], prefixes, rootScopes, fallback),
  2303. };
  2304. return new Proxy(cache, {
  2305. deleteProperty(target, prop) {
  2306. delete target[prop];
  2307. delete target._keys;
  2308. delete scopes[0][prop];
  2309. return true;
  2310. },
  2311. get(target, prop) {
  2312. return _cached(target, prop,
  2313. () => _resolveWithPrefixes(prop, prefixes, scopes, target));
  2314. },
  2315. getOwnPropertyDescriptor(target, prop) {
  2316. return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop);
  2317. },
  2318. getPrototypeOf() {
  2319. return Reflect.getPrototypeOf(scopes[0]);
  2320. },
  2321. has(target, prop) {
  2322. return getKeysFromAllScopes(target).includes(prop);
  2323. },
  2324. ownKeys(target) {
  2325. return getKeysFromAllScopes(target);
  2326. },
  2327. set(target, prop, value) {
  2328. const storage = target._storage || (target._storage = getTarget());
  2329. storage[prop] = value;
  2330. delete target[prop];
  2331. delete target._keys;
  2332. return true;
  2333. }
  2334. });
  2335. }
  2336. function _attachContext(proxy, context, subProxy, descriptorDefaults) {
  2337. const cache = {
  2338. _cacheable: false,
  2339. _proxy: proxy,
  2340. _context: context,
  2341. _subProxy: subProxy,
  2342. _stack: new Set(),
  2343. _descriptors: _descriptors(proxy, descriptorDefaults),
  2344. setContext: (ctx) => _attachContext(proxy, ctx, subProxy, descriptorDefaults),
  2345. override: (scope) => _attachContext(proxy.override(scope), context, subProxy, descriptorDefaults)
  2346. };
  2347. return new Proxy(cache, {
  2348. deleteProperty(target, prop) {
  2349. delete target[prop];
  2350. delete proxy[prop];
  2351. return true;
  2352. },
  2353. get(target, prop, receiver) {
  2354. return _cached(target, prop,
  2355. () => _resolveWithContext(target, prop, receiver));
  2356. },
  2357. getOwnPropertyDescriptor(target, prop) {
  2358. return target._descriptors.allKeys
  2359. ? Reflect.has(proxy, prop) ? {enumerable: true, configurable: true} : undefined
  2360. : Reflect.getOwnPropertyDescriptor(proxy, prop);
  2361. },
  2362. getPrototypeOf() {
  2363. return Reflect.getPrototypeOf(proxy);
  2364. },
  2365. has(target, prop) {
  2366. return Reflect.has(proxy, prop);
  2367. },
  2368. ownKeys() {
  2369. return Reflect.ownKeys(proxy);
  2370. },
  2371. set(target, prop, value) {
  2372. proxy[prop] = value;
  2373. delete target[prop];
  2374. return true;
  2375. }
  2376. });
  2377. }
  2378. function _descriptors(proxy, defaults = {scriptable: true, indexable: true}) {
  2379. const {_scriptable = defaults.scriptable, _indexable = defaults.indexable, _allKeys = defaults.allKeys} = proxy;
  2380. return {
  2381. allKeys: _allKeys,
  2382. scriptable: _scriptable,
  2383. indexable: _indexable,
  2384. isScriptable: isFunction(_scriptable) ? _scriptable : () => _scriptable,
  2385. isIndexable: isFunction(_indexable) ? _indexable : () => _indexable
  2386. };
  2387. }
  2388. const readKey = (prefix, name) => prefix ? prefix + _capitalize(name) : name;
  2389. const needsSubResolver = (prop, value) => isObject(value) && prop !== 'adapters';
  2390. function _cached(target, prop, resolve) {
  2391. let value = target[prop];
  2392. if (defined(value)) {
  2393. return value;
  2394. }
  2395. value = resolve();
  2396. if (defined(value)) {
  2397. target[prop] = value;
  2398. }
  2399. return value;
  2400. }
  2401. function _resolveWithContext(target, prop, receiver) {
  2402. const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;
  2403. let value = _proxy[prop];
  2404. if (isFunction(value) && descriptors.isScriptable(prop)) {
  2405. value = _resolveScriptable(prop, value, target, receiver);
  2406. }
  2407. if (isArray(value) && value.length) {
  2408. value = _resolveArray(prop, value, target, descriptors.isIndexable);
  2409. }
  2410. if (needsSubResolver(prop, value)) {
  2411. value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors);
  2412. }
  2413. return value;
  2414. }
  2415. function _resolveScriptable(prop, value, target, receiver) {
  2416. const {_proxy, _context, _subProxy, _stack} = target;
  2417. if (_stack.has(prop)) {
  2418. throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop);
  2419. }
  2420. _stack.add(prop);
  2421. value = value(_context, _subProxy || receiver);
  2422. _stack.delete(prop);
  2423. if (isObject(value)) {
  2424. value = createSubResolver(_proxy._scopes, _proxy, prop, value);
  2425. }
  2426. return value;
  2427. }
  2428. function _resolveArray(prop, value, target, isIndexable) {
  2429. const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;
  2430. if (defined(_context.index) && isIndexable(prop)) {
  2431. value = value[_context.index % value.length];
  2432. } else if (isObject(value[0])) {
  2433. const arr = value;
  2434. const scopes = _proxy._scopes.filter(s => s !== arr);
  2435. value = [];
  2436. for (const item of arr) {
  2437. const resolver = createSubResolver(scopes, _proxy, prop, item);
  2438. value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors));
  2439. }
  2440. }
  2441. return value;
  2442. }
  2443. function resolveFallback(fallback, prop, value) {
  2444. return isFunction(fallback) ? fallback(prop, value) : fallback;
  2445. }
  2446. const getScope = (key, parent) => key === true ? parent
  2447. : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined;
  2448. function addScopes(set, parentScopes, key, parentFallback) {
  2449. for (const parent of parentScopes) {
  2450. const scope = getScope(key, parent);
  2451. if (scope) {
  2452. set.add(scope);
  2453. const fallback = resolveFallback(scope._fallback, key, scope);
  2454. if (defined(fallback) && fallback !== key && fallback !== parentFallback) {
  2455. return fallback;
  2456. }
  2457. } else if (scope === false && defined(parentFallback) && key !== parentFallback) {
  2458. return null;
  2459. }
  2460. }
  2461. return false;
  2462. }
  2463. function createSubResolver(parentScopes, resolver, prop, value) {
  2464. const rootScopes = resolver._rootScopes;
  2465. const fallback = resolveFallback(resolver._fallback, prop, value);
  2466. const allScopes = [...parentScopes, ...rootScopes];
  2467. const set = new Set();
  2468. set.add(value);
  2469. let key = addScopesFromKey(set, allScopes, prop, fallback || prop);
  2470. if (key === null) {
  2471. return false;
  2472. }
  2473. if (defined(fallback) && fallback !== prop) {
  2474. key = addScopesFromKey(set, allScopes, fallback, key);
  2475. if (key === null) {
  2476. return false;
  2477. }
  2478. }
  2479. return _createResolver(Array.from(set), [''], rootScopes, fallback,
  2480. () => subGetTarget(resolver, prop, value));
  2481. }
  2482. function addScopesFromKey(set, allScopes, key, fallback) {
  2483. while (key) {
  2484. key = addScopes(set, allScopes, key, fallback);
  2485. }
  2486. return key;
  2487. }
  2488. function subGetTarget(resolver, prop, value) {
  2489. const parent = resolver._getTarget();
  2490. if (!(prop in parent)) {
  2491. parent[prop] = {};
  2492. }
  2493. const target = parent[prop];
  2494. if (isArray(target) && isObject(value)) {
  2495. return value;
  2496. }
  2497. return target;
  2498. }
  2499. function _resolveWithPrefixes(prop, prefixes, scopes, proxy) {
  2500. let value;
  2501. for (const prefix of prefixes) {
  2502. value = _resolve(readKey(prefix, prop), scopes);
  2503. if (defined(value)) {
  2504. return needsSubResolver(prop, value)
  2505. ? createSubResolver(scopes, proxy, prop, value)
  2506. : value;
  2507. }
  2508. }
  2509. }
  2510. function _resolve(key, scopes) {
  2511. for (const scope of scopes) {
  2512. if (!scope) {
  2513. continue;
  2514. }
  2515. const value = scope[key];
  2516. if (defined(value)) {
  2517. return value;
  2518. }
  2519. }
  2520. }
  2521. function getKeysFromAllScopes(target) {
  2522. let keys = target._keys;
  2523. if (!keys) {
  2524. keys = target._keys = resolveKeysFromAllScopes(target._scopes);
  2525. }
  2526. return keys;
  2527. }
  2528. function resolveKeysFromAllScopes(scopes) {
  2529. const set = new Set();
  2530. for (const scope of scopes) {
  2531. for (const key of Object.keys(scope).filter(k => !k.startsWith('_'))) {
  2532. set.add(key);
  2533. }
  2534. }
  2535. return Array.from(set);
  2536. }
  2537. const EPSILON = Number.EPSILON || 1e-14;
  2538. const getPoint = (points, i) => i < points.length && !points[i].skip && points[i];
  2539. const getValueAxis = (indexAxis) => indexAxis === 'x' ? 'y' : 'x';
  2540. function splineCurve(firstPoint, middlePoint, afterPoint, t) {
  2541. const previous = firstPoint.skip ? middlePoint : firstPoint;
  2542. const current = middlePoint;
  2543. const next = afterPoint.skip ? middlePoint : afterPoint;
  2544. const d01 = distanceBetweenPoints(current, previous);
  2545. const d12 = distanceBetweenPoints(next, current);
  2546. let s01 = d01 / (d01 + d12);
  2547. let s12 = d12 / (d01 + d12);
  2548. s01 = isNaN(s01) ? 0 : s01;
  2549. s12 = isNaN(s12) ? 0 : s12;
  2550. const fa = t * s01;
  2551. const fb = t * s12;
  2552. return {
  2553. previous: {
  2554. x: current.x - fa * (next.x - previous.x),
  2555. y: current.y - fa * (next.y - previous.y)
  2556. },
  2557. next: {
  2558. x: current.x + fb * (next.x - previous.x),
  2559. y: current.y + fb * (next.y - previous.y)
  2560. }
  2561. };
  2562. }
  2563. function monotoneAdjust(points, deltaK, mK) {
  2564. const pointsLen = points.length;
  2565. let alphaK, betaK, tauK, squaredMagnitude, pointCurrent;
  2566. let pointAfter = getPoint(points, 0);
  2567. for (let i = 0; i < pointsLen - 1; ++i) {
  2568. pointCurrent = pointAfter;
  2569. pointAfter = getPoint(points, i + 1);
  2570. if (!pointCurrent || !pointAfter) {
  2571. continue;
  2572. }
  2573. if (almostEquals(deltaK[i], 0, EPSILON)) {
  2574. mK[i] = mK[i + 1] = 0;
  2575. continue;
  2576. }
  2577. alphaK = mK[i] / deltaK[i];
  2578. betaK = mK[i + 1] / deltaK[i];
  2579. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  2580. if (squaredMagnitude <= 9) {
  2581. continue;
  2582. }
  2583. tauK = 3 / Math.sqrt(squaredMagnitude);
  2584. mK[i] = alphaK * tauK * deltaK[i];
  2585. mK[i + 1] = betaK * tauK * deltaK[i];
  2586. }
  2587. }
  2588. function monotoneCompute(points, mK, indexAxis = 'x') {
  2589. const valueAxis = getValueAxis(indexAxis);
  2590. const pointsLen = points.length;
  2591. let delta, pointBefore, pointCurrent;
  2592. let pointAfter = getPoint(points, 0);
  2593. for (let i = 0; i < pointsLen; ++i) {
  2594. pointBefore = pointCurrent;
  2595. pointCurrent = pointAfter;
  2596. pointAfter = getPoint(points, i + 1);
  2597. if (!pointCurrent) {
  2598. continue;
  2599. }
  2600. const iPixel = pointCurrent[indexAxis];
  2601. const vPixel = pointCurrent[valueAxis];
  2602. if (pointBefore) {
  2603. delta = (iPixel - pointBefore[indexAxis]) / 3;
  2604. pointCurrent[`cp1${indexAxis}`] = iPixel - delta;
  2605. pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i];
  2606. }
  2607. if (pointAfter) {
  2608. delta = (pointAfter[indexAxis] - iPixel) / 3;
  2609. pointCurrent[`cp2${indexAxis}`] = iPixel + delta;
  2610. pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i];
  2611. }
  2612. }
  2613. }
  2614. function splineCurveMonotone(points, indexAxis = 'x') {
  2615. const valueAxis = getValueAxis(indexAxis);
  2616. const pointsLen = points.length;
  2617. const deltaK = Array(pointsLen).fill(0);
  2618. const mK = Array(pointsLen);
  2619. let i, pointBefore, pointCurrent;
  2620. let pointAfter = getPoint(points, 0);
  2621. for (i = 0; i < pointsLen; ++i) {
  2622. pointBefore = pointCurrent;
  2623. pointCurrent = pointAfter;
  2624. pointAfter = getPoint(points, i + 1);
  2625. if (!pointCurrent) {
  2626. continue;
  2627. }
  2628. if (pointAfter) {
  2629. const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis];
  2630. deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0;
  2631. }
  2632. mK[i] = !pointBefore ? deltaK[i]
  2633. : !pointAfter ? deltaK[i - 1]
  2634. : (sign(deltaK[i - 1]) !== sign(deltaK[i])) ? 0
  2635. : (deltaK[i - 1] + deltaK[i]) / 2;
  2636. }
  2637. monotoneAdjust(points, deltaK, mK);
  2638. monotoneCompute(points, mK, indexAxis);
  2639. }
  2640. function capControlPoint(pt, min, max) {
  2641. return Math.max(Math.min(pt, max), min);
  2642. }
  2643. function capBezierPoints(points, area) {
  2644. let i, ilen, point, inArea, inAreaPrev;
  2645. let inAreaNext = _isPointInArea(points[0], area);
  2646. for (i = 0, ilen = points.length; i < ilen; ++i) {
  2647. inAreaPrev = inArea;
  2648. inArea = inAreaNext;
  2649. inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area);
  2650. if (!inArea) {
  2651. continue;
  2652. }
  2653. point = points[i];
  2654. if (inAreaPrev) {
  2655. point.cp1x = capControlPoint(point.cp1x, area.left, area.right);
  2656. point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom);
  2657. }
  2658. if (inAreaNext) {
  2659. point.cp2x = capControlPoint(point.cp2x, area.left, area.right);
  2660. point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom);
  2661. }
  2662. }
  2663. }
  2664. function _updateBezierControlPoints(points, options, area, loop, indexAxis) {
  2665. let i, ilen, point, controlPoints;
  2666. if (options.spanGaps) {
  2667. points = points.filter((pt) => !pt.skip);
  2668. }
  2669. if (options.cubicInterpolationMode === 'monotone') {
  2670. splineCurveMonotone(points, indexAxis);
  2671. } else {
  2672. let prev = loop ? points[points.length - 1] : points[0];
  2673. for (i = 0, ilen = points.length; i < ilen; ++i) {
  2674. point = points[i];
  2675. controlPoints = splineCurve(
  2676. prev,
  2677. point,
  2678. points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen],
  2679. options.tension
  2680. );
  2681. point.cp1x = controlPoints.previous.x;
  2682. point.cp1y = controlPoints.previous.y;
  2683. point.cp2x = controlPoints.next.x;
  2684. point.cp2y = controlPoints.next.y;
  2685. prev = point;
  2686. }
  2687. }
  2688. if (options.capBezierPoints) {
  2689. capBezierPoints(points, area);
  2690. }
  2691. }
  2692. const atEdge = (t) => t === 0 || t === 1;
  2693. const elasticIn = (t, s, p) => -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p));
  2694. const elasticOut = (t, s, p) => Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1;
  2695. const effects = {
  2696. linear: t => t,
  2697. easeInQuad: t => t * t,
  2698. easeOutQuad: t => -t * (t - 2),
  2699. easeInOutQuad: t => ((t /= 0.5) < 1)
  2700. ? 0.5 * t * t
  2701. : -0.5 * ((--t) * (t - 2) - 1),
  2702. easeInCubic: t => t * t * t,
  2703. easeOutCubic: t => (t -= 1) * t * t + 1,
  2704. easeInOutCubic: t => ((t /= 0.5) < 1)
  2705. ? 0.5 * t * t * t
  2706. : 0.5 * ((t -= 2) * t * t + 2),
  2707. easeInQuart: t => t * t * t * t,
  2708. easeOutQuart: t => -((t -= 1) * t * t * t - 1),
  2709. easeInOutQuart: t => ((t /= 0.5) < 1)
  2710. ? 0.5 * t * t * t * t
  2711. : -0.5 * ((t -= 2) * t * t * t - 2),
  2712. easeInQuint: t => t * t * t * t * t,
  2713. easeOutQuint: t => (t -= 1) * t * t * t * t + 1,
  2714. easeInOutQuint: t => ((t /= 0.5) < 1)
  2715. ? 0.5 * t * t * t * t * t
  2716. : 0.5 * ((t -= 2) * t * t * t * t + 2),
  2717. easeInSine: t => -Math.cos(t * HALF_PI) + 1,
  2718. easeOutSine: t => Math.sin(t * HALF_PI),
  2719. easeInOutSine: t => -0.5 * (Math.cos(PI * t) - 1),
  2720. easeInExpo: t => (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)),
  2721. easeOutExpo: t => (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1,
  2722. easeInOutExpo: t => atEdge(t) ? t : t < 0.5
  2723. ? 0.5 * Math.pow(2, 10 * (t * 2 - 1))
  2724. : 0.5 * (-Math.pow(2, -10 * (t * 2 - 1)) + 2),
  2725. easeInCirc: t => (t >= 1) ? t : -(Math.sqrt(1 - t * t) - 1),
  2726. easeOutCirc: t => Math.sqrt(1 - (t -= 1) * t),
  2727. easeInOutCirc: t => ((t /= 0.5) < 1)
  2728. ? -0.5 * (Math.sqrt(1 - t * t) - 1)
  2729. : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1),
  2730. easeInElastic: t => atEdge(t) ? t : elasticIn(t, 0.075, 0.3),
  2731. easeOutElastic: t => atEdge(t) ? t : elasticOut(t, 0.075, 0.3),
  2732. easeInOutElastic(t) {
  2733. const s = 0.1125;
  2734. const p = 0.45;
  2735. return atEdge(t) ? t :
  2736. t < 0.5
  2737. ? 0.5 * elasticIn(t * 2, s, p)
  2738. : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p);
  2739. },
  2740. easeInBack(t) {
  2741. const s = 1.70158;
  2742. return t * t * ((s + 1) * t - s);
  2743. },
  2744. easeOutBack(t) {
  2745. const s = 1.70158;
  2746. return (t -= 1) * t * ((s + 1) * t + s) + 1;
  2747. },
  2748. easeInOutBack(t) {
  2749. let s = 1.70158;
  2750. if ((t /= 0.5) < 1) {
  2751. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  2752. }
  2753. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  2754. },
  2755. easeInBounce: t => 1 - effects.easeOutBounce(1 - t),
  2756. easeOutBounce(t) {
  2757. const m = 7.5625;
  2758. const d = 2.75;
  2759. if (t < (1 / d)) {
  2760. return m * t * t;
  2761. }
  2762. if (t < (2 / d)) {
  2763. return m * (t -= (1.5 / d)) * t + 0.75;
  2764. }
  2765. if (t < (2.5 / d)) {
  2766. return m * (t -= (2.25 / d)) * t + 0.9375;
  2767. }
  2768. return m * (t -= (2.625 / d)) * t + 0.984375;
  2769. },
  2770. easeInOutBounce: t => (t < 0.5)
  2771. ? effects.easeInBounce(t * 2) * 0.5
  2772. : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5,
  2773. };
  2774. function _pointInLine(p1, p2, t, mode) {
  2775. return {
  2776. x: p1.x + t * (p2.x - p1.x),
  2777. y: p1.y + t * (p2.y - p1.y)
  2778. };
  2779. }
  2780. function _steppedInterpolation(p1, p2, t, mode) {
  2781. return {
  2782. x: p1.x + t * (p2.x - p1.x),
  2783. y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y
  2784. : mode === 'after' ? t < 1 ? p1.y : p2.y
  2785. : t > 0 ? p2.y : p1.y
  2786. };
  2787. }
  2788. function _bezierInterpolation(p1, p2, t, mode) {
  2789. const cp1 = {x: p1.cp2x, y: p1.cp2y};
  2790. const cp2 = {x: p2.cp1x, y: p2.cp1y};
  2791. const a = _pointInLine(p1, cp1, t);
  2792. const b = _pointInLine(cp1, cp2, t);
  2793. const c = _pointInLine(cp2, p2, t);
  2794. const d = _pointInLine(a, b, t);
  2795. const e = _pointInLine(b, c, t);
  2796. return _pointInLine(d, e, t);
  2797. }
  2798. const intlCache = new Map();
  2799. function getNumberFormat(locale, options) {
  2800. options = options || {};
  2801. const cacheKey = locale + JSON.stringify(options);
  2802. let formatter = intlCache.get(cacheKey);
  2803. if (!formatter) {
  2804. formatter = new Intl.NumberFormat(locale, options);
  2805. intlCache.set(cacheKey, formatter);
  2806. }
  2807. return formatter;
  2808. }
  2809. function formatNumber(num, locale, options) {
  2810. return getNumberFormat(locale, options).format(num);
  2811. }
  2812. const getRightToLeftAdapter = function(rectX, width) {
  2813. return {
  2814. x(x) {
  2815. return rectX + rectX + width - x;
  2816. },
  2817. setWidth(w) {
  2818. width = w;
  2819. },
  2820. textAlign(align) {
  2821. if (align === 'center') {
  2822. return align;
  2823. }
  2824. return align === 'right' ? 'left' : 'right';
  2825. },
  2826. xPlus(x, value) {
  2827. return x - value;
  2828. },
  2829. leftForLtr(x, itemWidth) {
  2830. return x - itemWidth;
  2831. },
  2832. };
  2833. };
  2834. const getLeftToRightAdapter = function() {
  2835. return {
  2836. x(x) {
  2837. return x;
  2838. },
  2839. setWidth(w) {
  2840. },
  2841. textAlign(align) {
  2842. return align;
  2843. },
  2844. xPlus(x, value) {
  2845. return x + value;
  2846. },
  2847. leftForLtr(x, _itemWidth) {
  2848. return x;
  2849. },
  2850. };
  2851. };
  2852. function getRtlAdapter(rtl, rectX, width) {
  2853. return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter();
  2854. }
  2855. function overrideTextDirection(ctx, direction) {
  2856. let style, original;
  2857. if (direction === 'ltr' || direction === 'rtl') {
  2858. style = ctx.canvas.style;
  2859. original = [
  2860. style.getPropertyValue('direction'),
  2861. style.getPropertyPriority('direction'),
  2862. ];
  2863. style.setProperty('direction', direction, 'important');
  2864. ctx.prevTextDirection = original;
  2865. }
  2866. }
  2867. function restoreTextDirection(ctx, original) {
  2868. if (original !== undefined) {
  2869. delete ctx.prevTextDirection;
  2870. ctx.canvas.style.setProperty('direction', original[0], original[1]);
  2871. }
  2872. }
  2873. function propertyFn(property) {
  2874. if (property === 'angle') {
  2875. return {
  2876. between: _angleBetween,
  2877. compare: _angleDiff,
  2878. normalize: _normalizeAngle,
  2879. };
  2880. }
  2881. return {
  2882. between: (n, s, e) => n >= Math.min(s, e) && n <= Math.max(e, s),
  2883. compare: (a, b) => a - b,
  2884. normalize: x => x
  2885. };
  2886. }
  2887. function normalizeSegment({start, end, count, loop, style}) {
  2888. return {
  2889. start: start % count,
  2890. end: end % count,
  2891. loop: loop && (end - start + 1) % count === 0,
  2892. style
  2893. };
  2894. }
  2895. function getSegment(segment, points, bounds) {
  2896. const {property, start: startBound, end: endBound} = bounds;
  2897. const {between, normalize} = propertyFn(property);
  2898. const count = points.length;
  2899. let {start, end, loop} = segment;
  2900. let i, ilen;
  2901. if (loop) {
  2902. start += count;
  2903. end += count;
  2904. for (i = 0, ilen = count; i < ilen; ++i) {
  2905. if (!between(normalize(points[start % count][property]), startBound, endBound)) {
  2906. break;
  2907. }
  2908. start--;
  2909. end--;
  2910. }
  2911. start %= count;
  2912. end %= count;
  2913. }
  2914. if (end < start) {
  2915. end += count;
  2916. }
  2917. return {start, end, loop, style: segment.style};
  2918. }
  2919. function _boundSegment(segment, points, bounds) {
  2920. if (!bounds) {
  2921. return [segment];
  2922. }
  2923. const {property, start: startBound, end: endBound} = bounds;
  2924. const count = points.length;
  2925. const {compare, between, normalize} = propertyFn(property);
  2926. const {start, end, loop, style} = getSegment(segment, points, bounds);
  2927. const result = [];
  2928. let inside = false;
  2929. let subStart = null;
  2930. let value, point, prevValue;
  2931. const startIsBefore = () => between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0;
  2932. const endIsBefore = () => compare(endBound, value) === 0 || between(endBound, prevValue, value);
  2933. const shouldStart = () => inside || startIsBefore();
  2934. const shouldStop = () => !inside || endIsBefore();
  2935. for (let i = start, prev = start; i <= end; ++i) {
  2936. point = points[i % count];
  2937. if (point.skip) {
  2938. continue;
  2939. }
  2940. value = normalize(point[property]);
  2941. if (value === prevValue) {
  2942. continue;
  2943. }
  2944. inside = between(value, startBound, endBound);
  2945. if (subStart === null && shouldStart()) {
  2946. subStart = compare(value, startBound) === 0 ? i : prev;
  2947. }
  2948. if (subStart !== null && shouldStop()) {
  2949. result.push(normalizeSegment({start: subStart, end: i, loop, count, style}));
  2950. subStart = null;
  2951. }
  2952. prev = i;
  2953. prevValue = value;
  2954. }
  2955. if (subStart !== null) {
  2956. result.push(normalizeSegment({start: subStart, end, loop, count, style}));
  2957. }
  2958. return result;
  2959. }
  2960. function _boundSegments(line, bounds) {
  2961. const result = [];
  2962. const segments = line.segments;
  2963. for (let i = 0; i < segments.length; i++) {
  2964. const sub = _boundSegment(segments[i], line.points, bounds);
  2965. if (sub.length) {
  2966. result.push(...sub);
  2967. }
  2968. }
  2969. return result;
  2970. }
  2971. function findStartAndEnd(points, count, loop, spanGaps) {
  2972. let start = 0;
  2973. let end = count - 1;
  2974. if (loop && !spanGaps) {
  2975. while (start < count && !points[start].skip) {
  2976. start++;
  2977. }
  2978. }
  2979. while (start < count && points[start].skip) {
  2980. start++;
  2981. }
  2982. start %= count;
  2983. if (loop) {
  2984. end += start;
  2985. }
  2986. while (end > start && points[end % count].skip) {
  2987. end--;
  2988. }
  2989. end %= count;
  2990. return {start, end};
  2991. }
  2992. function solidSegments(points, start, max, loop) {
  2993. const count = points.length;
  2994. const result = [];
  2995. let last = start;
  2996. let prev = points[start];
  2997. let end;
  2998. for (end = start + 1; end <= max; ++end) {
  2999. const cur = points[end % count];
  3000. if (cur.skip || cur.stop) {
  3001. if (!prev.skip) {
  3002. loop = false;
  3003. result.push({start: start % count, end: (end - 1) % count, loop});
  3004. start = last = cur.stop ? end : null;
  3005. }
  3006. } else {
  3007. last = end;
  3008. if (prev.skip) {
  3009. start = end;
  3010. }
  3011. }
  3012. prev = cur;
  3013. }
  3014. if (last !== null) {
  3015. result.push({start: start % count, end: last % count, loop});
  3016. }
  3017. return result;
  3018. }
  3019. function _computeSegments(line, segmentOptions) {
  3020. const points = line.points;
  3021. const spanGaps = line.options.spanGaps;
  3022. const count = points.length;
  3023. if (!count) {
  3024. return [];
  3025. }
  3026. const loop = !!line._loop;
  3027. const {start, end} = findStartAndEnd(points, count, loop, spanGaps);
  3028. if (spanGaps === true) {
  3029. return splitByStyles(line, [{start, end, loop}], points, segmentOptions);
  3030. }
  3031. const max = end < start ? end + count : end;
  3032. const completeLoop = !!line._fullLoop && start === 0 && end === count - 1;
  3033. return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions);
  3034. }
  3035. function splitByStyles(line, segments, points, segmentOptions) {
  3036. if (!segmentOptions || !segmentOptions.setContext || !points) {
  3037. return segments;
  3038. }
  3039. return doSplitByStyles(line, segments, points, segmentOptions);
  3040. }
  3041. function doSplitByStyles(line, segments, points, segmentOptions) {
  3042. const baseStyle = readStyle(line.options);
  3043. const count = points.length;
  3044. const result = [];
  3045. let start = segments[0].start;
  3046. let i = start;
  3047. for (const segment of segments) {
  3048. let prevStyle = baseStyle;
  3049. let prev = points[start % count];
  3050. let style;
  3051. for (i = start + 1; i <= segment.end; i++) {
  3052. const pt = points[i % count];
  3053. style = readStyle(segmentOptions.setContext({
  3054. type: 'segment',
  3055. p0: prev,
  3056. p1: pt,
  3057. p0DataIndex: (i - 1) % count,
  3058. p1DataIndex: i % count,
  3059. datasetIndex: line._datasetIndex
  3060. }));
  3061. if (styleChanged(style, prevStyle)) {
  3062. result.push({start: start, end: i - 1, loop: segment.loop, style: prevStyle});
  3063. prevStyle = style;
  3064. start = i - 1;
  3065. }
  3066. prev = pt;
  3067. prevStyle = style;
  3068. }
  3069. if (start < i - 1) {
  3070. result.push({start, end: i - 1, loop: segment.loop, style});
  3071. start = i - 1;
  3072. }
  3073. }
  3074. return result;
  3075. }
  3076. function readStyle(options) {
  3077. return {
  3078. backgroundColor: options.backgroundColor,
  3079. borderCapStyle: options.borderCapStyle,
  3080. borderDash: options.borderDash,
  3081. borderDashOffset: options.borderDashOffset,
  3082. borderJoinStyle: options.borderJoinStyle,
  3083. borderWidth: options.borderWidth,
  3084. borderColor: options.borderColor
  3085. };
  3086. }
  3087. function styleChanged(style, prevStyle) {
  3088. return prevStyle && JSON.stringify(style) !== JSON.stringify(prevStyle);
  3089. }
  3090. var helpers = /*#__PURE__*/Object.freeze({
  3091. __proto__: null,
  3092. easingEffects: effects,
  3093. color: color,
  3094. getHoverColor: getHoverColor,
  3095. noop: noop,
  3096. uid: uid,
  3097. isNullOrUndef: isNullOrUndef,
  3098. isArray: isArray,
  3099. isObject: isObject,
  3100. isFinite: isNumberFinite,
  3101. finiteOrDefault: finiteOrDefault,
  3102. valueOrDefault: valueOrDefault,
  3103. toPercentage: toPercentage,
  3104. toDimension: toDimension,
  3105. callback: callback,
  3106. each: each,
  3107. _elementsEqual: _elementsEqual,
  3108. clone: clone,
  3109. _merger: _merger,
  3110. merge: merge,
  3111. mergeIf: mergeIf,
  3112. _mergerIf: _mergerIf,
  3113. _deprecated: _deprecated,
  3114. resolveObjectKey: resolveObjectKey,
  3115. _capitalize: _capitalize,
  3116. defined: defined,
  3117. isFunction: isFunction,
  3118. setsEqual: setsEqual,
  3119. toFontString: toFontString,
  3120. _measureText: _measureText,
  3121. _longestText: _longestText,
  3122. _alignPixel: _alignPixel,
  3123. clearCanvas: clearCanvas,
  3124. drawPoint: drawPoint,
  3125. _isPointInArea: _isPointInArea,
  3126. clipArea: clipArea,
  3127. unclipArea: unclipArea,
  3128. _steppedLineTo: _steppedLineTo,
  3129. _bezierCurveTo: _bezierCurveTo,
  3130. renderText: renderText,
  3131. addRoundedRectPath: addRoundedRectPath,
  3132. _lookup: _lookup,
  3133. _lookupByKey: _lookupByKey,
  3134. _rlookupByKey: _rlookupByKey,
  3135. _filterBetween: _filterBetween,
  3136. listenArrayEvents: listenArrayEvents,
  3137. unlistenArrayEvents: unlistenArrayEvents,
  3138. _arrayUnique: _arrayUnique,
  3139. _createResolver: _createResolver,
  3140. _attachContext: _attachContext,
  3141. _descriptors: _descriptors,
  3142. splineCurve: splineCurve,
  3143. splineCurveMonotone: splineCurveMonotone,
  3144. _updateBezierControlPoints: _updateBezierControlPoints,
  3145. _isDomSupported: _isDomSupported,
  3146. _getParentNode: _getParentNode,
  3147. getStyle: getStyle,
  3148. getRelativePosition: getRelativePosition$1,
  3149. getMaximumSize: getMaximumSize,
  3150. retinaScale: retinaScale,
  3151. supportsEventListenerOptions: supportsEventListenerOptions,
  3152. readUsedSize: readUsedSize,
  3153. fontString: fontString,
  3154. requestAnimFrame: requestAnimFrame,
  3155. throttled: throttled,
  3156. debounce: debounce,
  3157. _toLeftRightCenter: _toLeftRightCenter,
  3158. _alignStartEnd: _alignStartEnd,
  3159. _textX: _textX,
  3160. _pointInLine: _pointInLine,
  3161. _steppedInterpolation: _steppedInterpolation,
  3162. _bezierInterpolation: _bezierInterpolation,
  3163. formatNumber: formatNumber,
  3164. toLineHeight: toLineHeight,
  3165. _readValueToProps: _readValueToProps,
  3166. toTRBL: toTRBL,
  3167. toTRBLCorners: toTRBLCorners,
  3168. toPadding: toPadding,
  3169. toFont: toFont,
  3170. resolve: resolve,
  3171. _addGrace: _addGrace,
  3172. PI: PI,
  3173. TAU: TAU,
  3174. PITAU: PITAU,
  3175. INFINITY: INFINITY,
  3176. RAD_PER_DEG: RAD_PER_DEG,
  3177. HALF_PI: HALF_PI,
  3178. QUARTER_PI: QUARTER_PI,
  3179. TWO_THIRDS_PI: TWO_THIRDS_PI,
  3180. log10: log10,
  3181. sign: sign,
  3182. niceNum: niceNum,
  3183. _factorize: _factorize,
  3184. isNumber: isNumber,
  3185. almostEquals: almostEquals,
  3186. almostWhole: almostWhole,
  3187. _setMinAndMaxByKey: _setMinAndMaxByKey,
  3188. toRadians: toRadians,
  3189. toDegrees: toDegrees,
  3190. _decimalPlaces: _decimalPlaces,
  3191. getAngleFromPoint: getAngleFromPoint,
  3192. distanceBetweenPoints: distanceBetweenPoints,
  3193. _angleDiff: _angleDiff,
  3194. _normalizeAngle: _normalizeAngle,
  3195. _angleBetween: _angleBetween,
  3196. _limitValue: _limitValue,
  3197. _int16Range: _int16Range,
  3198. getRtlAdapter: getRtlAdapter,
  3199. overrideTextDirection: overrideTextDirection,
  3200. restoreTextDirection: restoreTextDirection,
  3201. _boundSegment: _boundSegment,
  3202. _boundSegments: _boundSegments,
  3203. _computeSegments: _computeSegments
  3204. });
  3205. class BasePlatform {
  3206. acquireContext(canvas, aspectRatio) {}
  3207. releaseContext(context) {
  3208. return false;
  3209. }
  3210. addEventListener(chart, type, listener) {}
  3211. removeEventListener(chart, type, listener) {}
  3212. getDevicePixelRatio() {
  3213. return 1;
  3214. }
  3215. getMaximumSize(element, width, height, aspectRatio) {
  3216. width = Math.max(0, width || element.width);
  3217. height = height || element.height;
  3218. return {
  3219. width,
  3220. height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)
  3221. };
  3222. }
  3223. isAttached(canvas) {
  3224. return true;
  3225. }
  3226. }
  3227. class BasicPlatform extends BasePlatform {
  3228. acquireContext(item) {
  3229. return item && item.getContext && item.getContext('2d') || null;
  3230. }
  3231. }
  3232. const EXPANDO_KEY = '$chartjs';
  3233. const EVENT_TYPES = {
  3234. touchstart: 'mousedown',
  3235. touchmove: 'mousemove',
  3236. touchend: 'mouseup',
  3237. pointerenter: 'mouseenter',
  3238. pointerdown: 'mousedown',
  3239. pointermove: 'mousemove',
  3240. pointerup: 'mouseup',
  3241. pointerleave: 'mouseout',
  3242. pointerout: 'mouseout'
  3243. };
  3244. const isNullOrEmpty = value => value === null || value === '';
  3245. function initCanvas(canvas, aspectRatio) {
  3246. const style = canvas.style;
  3247. const renderHeight = canvas.getAttribute('height');
  3248. const renderWidth = canvas.getAttribute('width');
  3249. canvas[EXPANDO_KEY] = {
  3250. initial: {
  3251. height: renderHeight,
  3252. width: renderWidth,
  3253. style: {
  3254. display: style.display,
  3255. height: style.height,
  3256. width: style.width
  3257. }
  3258. }
  3259. };
  3260. style.display = style.display || 'block';
  3261. style.boxSizing = style.boxSizing || 'border-box';
  3262. if (isNullOrEmpty(renderWidth)) {
  3263. const displayWidth = readUsedSize(canvas, 'width');
  3264. if (displayWidth !== undefined) {
  3265. canvas.width = displayWidth;
  3266. }
  3267. }
  3268. if (isNullOrEmpty(renderHeight)) {
  3269. if (canvas.style.height === '') {
  3270. canvas.height = canvas.width / (aspectRatio || 2);
  3271. } else {
  3272. const displayHeight = readUsedSize(canvas, 'height');
  3273. if (displayHeight !== undefined) {
  3274. canvas.height = displayHeight;
  3275. }
  3276. }
  3277. }
  3278. return canvas;
  3279. }
  3280. const eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  3281. function addListener(node, type, listener) {
  3282. node.addEventListener(type, listener, eventListenerOptions);
  3283. }
  3284. function removeListener(chart, type, listener) {
  3285. chart.canvas.removeEventListener(type, listener, eventListenerOptions);
  3286. }
  3287. function fromNativeEvent(event, chart) {
  3288. const type = EVENT_TYPES[event.type] || event.type;
  3289. const {x, y} = getRelativePosition$1(event, chart);
  3290. return {
  3291. type,
  3292. chart,
  3293. native: event,
  3294. x: x !== undefined ? x : null,
  3295. y: y !== undefined ? y : null,
  3296. };
  3297. }
  3298. function createAttachObserver(chart, type, listener) {
  3299. const canvas = chart.canvas;
  3300. const container = canvas && _getParentNode(canvas);
  3301. const element = container || canvas;
  3302. const observer = new MutationObserver(entries => {
  3303. const parent = _getParentNode(element);
  3304. entries.forEach(entry => {
  3305. for (let i = 0; i < entry.addedNodes.length; i++) {
  3306. const added = entry.addedNodes[i];
  3307. if (added === element || added === parent) {
  3308. listener(entry.target);
  3309. }
  3310. }
  3311. });
  3312. });
  3313. observer.observe(document, {childList: true, subtree: true});
  3314. return observer;
  3315. }
  3316. function createDetachObserver(chart, type, listener) {
  3317. const canvas = chart.canvas;
  3318. const container = canvas && _getParentNode(canvas);
  3319. if (!container) {
  3320. return;
  3321. }
  3322. const observer = new MutationObserver(entries => {
  3323. entries.forEach(entry => {
  3324. for (let i = 0; i < entry.removedNodes.length; i++) {
  3325. if (entry.removedNodes[i] === canvas) {
  3326. listener();
  3327. break;
  3328. }
  3329. }
  3330. });
  3331. });
  3332. observer.observe(container, {childList: true});
  3333. return observer;
  3334. }
  3335. const drpListeningCharts = new Map();
  3336. let oldDevicePixelRatio = 0;
  3337. function onWindowResize() {
  3338. const dpr = window.devicePixelRatio;
  3339. if (dpr === oldDevicePixelRatio) {
  3340. return;
  3341. }
  3342. oldDevicePixelRatio = dpr;
  3343. drpListeningCharts.forEach((resize, chart) => {
  3344. if (chart.currentDevicePixelRatio !== dpr) {
  3345. resize();
  3346. }
  3347. });
  3348. }
  3349. function listenDevicePixelRatioChanges(chart, resize) {
  3350. if (!drpListeningCharts.size) {
  3351. window.addEventListener('resize', onWindowResize);
  3352. }
  3353. drpListeningCharts.set(chart, resize);
  3354. }
  3355. function unlistenDevicePixelRatioChanges(chart) {
  3356. drpListeningCharts.delete(chart);
  3357. if (!drpListeningCharts.size) {
  3358. window.removeEventListener('resize', onWindowResize);
  3359. }
  3360. }
  3361. function createResizeObserver(chart, type, listener) {
  3362. const canvas = chart.canvas;
  3363. const container = canvas && _getParentNode(canvas);
  3364. if (!container) {
  3365. return;
  3366. }
  3367. const resize = throttled((width, height) => {
  3368. const w = container.clientWidth;
  3369. listener(width, height);
  3370. if (w < container.clientWidth) {
  3371. listener();
  3372. }
  3373. }, window);
  3374. const observer = new ResizeObserver(entries => {
  3375. const entry = entries[0];
  3376. const width = entry.contentRect.width;
  3377. const height = entry.contentRect.height;
  3378. if (width === 0 && height === 0) {
  3379. return;
  3380. }
  3381. resize(width, height);
  3382. });
  3383. observer.observe(container);
  3384. listenDevicePixelRatioChanges(chart, resize);
  3385. return observer;
  3386. }
  3387. function releaseObserver(chart, type, observer) {
  3388. if (observer) {
  3389. observer.disconnect();
  3390. }
  3391. if (type === 'resize') {
  3392. unlistenDevicePixelRatioChanges(chart);
  3393. }
  3394. }
  3395. function createProxyAndListen(chart, type, listener) {
  3396. const canvas = chart.canvas;
  3397. const proxy = throttled((event) => {
  3398. if (chart.ctx !== null) {
  3399. listener(fromNativeEvent(event, chart));
  3400. }
  3401. }, chart, (args) => {
  3402. const event = args[0];
  3403. return [event, event.offsetX, event.offsetY];
  3404. });
  3405. addListener(canvas, type, proxy);
  3406. return proxy;
  3407. }
  3408. class DomPlatform extends BasePlatform {
  3409. acquireContext(canvas, aspectRatio) {
  3410. const context = canvas && canvas.getContext && canvas.getContext('2d');
  3411. if (context && context.canvas === canvas) {
  3412. initCanvas(canvas, aspectRatio);
  3413. return context;
  3414. }
  3415. return null;
  3416. }
  3417. releaseContext(context) {
  3418. const canvas = context.canvas;
  3419. if (!canvas[EXPANDO_KEY]) {
  3420. return false;
  3421. }
  3422. const initial = canvas[EXPANDO_KEY].initial;
  3423. ['height', 'width'].forEach((prop) => {
  3424. const value = initial[prop];
  3425. if (isNullOrUndef(value)) {
  3426. canvas.removeAttribute(prop);
  3427. } else {
  3428. canvas.setAttribute(prop, value);
  3429. }
  3430. });
  3431. const style = initial.style || {};
  3432. Object.keys(style).forEach((key) => {
  3433. canvas.style[key] = style[key];
  3434. });
  3435. canvas.width = canvas.width;
  3436. delete canvas[EXPANDO_KEY];
  3437. return true;
  3438. }
  3439. addEventListener(chart, type, listener) {
  3440. this.removeEventListener(chart, type);
  3441. const proxies = chart.$proxies || (chart.$proxies = {});
  3442. const handlers = {
  3443. attach: createAttachObserver,
  3444. detach: createDetachObserver,
  3445. resize: createResizeObserver
  3446. };
  3447. const handler = handlers[type] || createProxyAndListen;
  3448. proxies[type] = handler(chart, type, listener);
  3449. }
  3450. removeEventListener(chart, type) {
  3451. const proxies = chart.$proxies || (chart.$proxies = {});
  3452. const proxy = proxies[type];
  3453. if (!proxy) {
  3454. return;
  3455. }
  3456. const handlers = {
  3457. attach: releaseObserver,
  3458. detach: releaseObserver,
  3459. resize: releaseObserver
  3460. };
  3461. const handler = handlers[type] || removeListener;
  3462. handler(chart, type, proxy);
  3463. proxies[type] = undefined;
  3464. }
  3465. getDevicePixelRatio() {
  3466. return window.devicePixelRatio;
  3467. }
  3468. getMaximumSize(canvas, width, height, aspectRatio) {
  3469. return getMaximumSize(canvas, width, height, aspectRatio);
  3470. }
  3471. isAttached(canvas) {
  3472. const container = _getParentNode(canvas);
  3473. return !!(container && container.isConnected);
  3474. }
  3475. }
  3476. function _detectPlatform(canvas) {
  3477. if (!_isDomSupported() || (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) {
  3478. return BasicPlatform;
  3479. }
  3480. return DomPlatform;
  3481. }
  3482. var platforms = /*#__PURE__*/Object.freeze({
  3483. __proto__: null,
  3484. _detectPlatform: _detectPlatform,
  3485. BasePlatform: BasePlatform,
  3486. BasicPlatform: BasicPlatform,
  3487. DomPlatform: DomPlatform
  3488. });
  3489. const transparent = 'transparent';
  3490. const interpolators = {
  3491. boolean(from, to, factor) {
  3492. return factor > 0.5 ? to : from;
  3493. },
  3494. color(from, to, factor) {
  3495. const c0 = color(from || transparent);
  3496. const c1 = c0.valid && color(to || transparent);
  3497. return c1 && c1.valid
  3498. ? c1.mix(c0, factor).hexString()
  3499. : to;
  3500. },
  3501. number(from, to, factor) {
  3502. return from + (to - from) * factor;
  3503. }
  3504. };
  3505. class Animation {
  3506. constructor(cfg, target, prop, to) {
  3507. const currentValue = target[prop];
  3508. to = resolve([cfg.to, to, currentValue, cfg.from]);
  3509. const from = resolve([cfg.from, currentValue, to]);
  3510. this._active = true;
  3511. this._fn = cfg.fn || interpolators[cfg.type || typeof from];
  3512. this._easing = effects[cfg.easing] || effects.linear;
  3513. this._start = Math.floor(Date.now() + (cfg.delay || 0));
  3514. this._duration = this._total = Math.floor(cfg.duration);
  3515. this._loop = !!cfg.loop;
  3516. this._target = target;
  3517. this._prop = prop;
  3518. this._from = from;
  3519. this._to = to;
  3520. this._promises = undefined;
  3521. }
  3522. active() {
  3523. return this._active;
  3524. }
  3525. update(cfg, to, date) {
  3526. const me = this;
  3527. if (me._active) {
  3528. me._notify(false);
  3529. const currentValue = me._target[me._prop];
  3530. const elapsed = date - me._start;
  3531. const remain = me._duration - elapsed;
  3532. me._start = date;
  3533. me._duration = Math.floor(Math.max(remain, cfg.duration));
  3534. me._total += elapsed;
  3535. me._loop = !!cfg.loop;
  3536. me._to = resolve([cfg.to, to, currentValue, cfg.from]);
  3537. me._from = resolve([cfg.from, currentValue, to]);
  3538. }
  3539. }
  3540. cancel() {
  3541. const me = this;
  3542. if (me._active) {
  3543. me.tick(Date.now());
  3544. me._active = false;
  3545. me._notify(false);
  3546. }
  3547. }
  3548. tick(date) {
  3549. const me = this;
  3550. const elapsed = date - me._start;
  3551. const duration = me._duration;
  3552. const prop = me._prop;
  3553. const from = me._from;
  3554. const loop = me._loop;
  3555. const to = me._to;
  3556. let factor;
  3557. me._active = from !== to && (loop || (elapsed < duration));
  3558. if (!me._active) {
  3559. me._target[prop] = to;
  3560. me._notify(true);
  3561. return;
  3562. }
  3563. if (elapsed < 0) {
  3564. me._target[prop] = from;
  3565. return;
  3566. }
  3567. factor = (elapsed / duration) % 2;
  3568. factor = loop && factor > 1 ? 2 - factor : factor;
  3569. factor = me._easing(Math.min(1, Math.max(0, factor)));
  3570. me._target[prop] = me._fn(from, to, factor);
  3571. }
  3572. wait() {
  3573. const promises = this._promises || (this._promises = []);
  3574. return new Promise((res, rej) => {
  3575. promises.push({res, rej});
  3576. });
  3577. }
  3578. _notify(resolved) {
  3579. const method = resolved ? 'res' : 'rej';
  3580. const promises = this._promises || [];
  3581. for (let i = 0; i < promises.length; i++) {
  3582. promises[i][method]();
  3583. }
  3584. }
  3585. }
  3586. const numbers = ['x', 'y', 'borderWidth', 'radius', 'tension'];
  3587. const colors = ['color', 'borderColor', 'backgroundColor'];
  3588. defaults.set('animation', {
  3589. delay: undefined,
  3590. duration: 1000,
  3591. easing: 'easeOutQuart',
  3592. fn: undefined,
  3593. from: undefined,
  3594. loop: undefined,
  3595. to: undefined,
  3596. type: undefined,
  3597. });
  3598. const animationOptions = Object.keys(defaults.animation);
  3599. defaults.describe('animation', {
  3600. _fallback: false,
  3601. _indexable: false,
  3602. _scriptable: (name) => name !== 'onProgress' && name !== 'onComplete' && name !== 'fn',
  3603. });
  3604. defaults.set('animations', {
  3605. colors: {
  3606. type: 'color',
  3607. properties: colors
  3608. },
  3609. numbers: {
  3610. type: 'number',
  3611. properties: numbers
  3612. },
  3613. });
  3614. defaults.describe('animations', {
  3615. _fallback: 'animation',
  3616. });
  3617. defaults.set('transitions', {
  3618. active: {
  3619. animation: {
  3620. duration: 400
  3621. }
  3622. },
  3623. resize: {
  3624. animation: {
  3625. duration: 0
  3626. }
  3627. },
  3628. show: {
  3629. animations: {
  3630. colors: {
  3631. from: 'transparent'
  3632. },
  3633. visible: {
  3634. type: 'boolean',
  3635. duration: 0
  3636. },
  3637. }
  3638. },
  3639. hide: {
  3640. animations: {
  3641. colors: {
  3642. to: 'transparent'
  3643. },
  3644. visible: {
  3645. type: 'boolean',
  3646. easing: 'linear',
  3647. fn: v => v | 0
  3648. },
  3649. }
  3650. }
  3651. });
  3652. class Animations {
  3653. constructor(chart, config) {
  3654. this._chart = chart;
  3655. this._properties = new Map();
  3656. this.configure(config);
  3657. }
  3658. configure(config) {
  3659. if (!isObject(config)) {
  3660. return;
  3661. }
  3662. const animatedProps = this._properties;
  3663. Object.getOwnPropertyNames(config).forEach(key => {
  3664. const cfg = config[key];
  3665. if (!isObject(cfg)) {
  3666. return;
  3667. }
  3668. const resolved = {};
  3669. for (const option of animationOptions) {
  3670. resolved[option] = cfg[option];
  3671. }
  3672. (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => {
  3673. if (prop === key || !animatedProps.has(prop)) {
  3674. animatedProps.set(prop, resolved);
  3675. }
  3676. });
  3677. });
  3678. }
  3679. _animateOptions(target, values) {
  3680. const newOptions = values.options;
  3681. const options = resolveTargetOptions(target, newOptions);
  3682. if (!options) {
  3683. return [];
  3684. }
  3685. const animations = this._createAnimations(options, newOptions);
  3686. if (newOptions.$shared) {
  3687. awaitAll(target.options.$animations, newOptions).then(() => {
  3688. target.options = newOptions;
  3689. }, () => {
  3690. });
  3691. }
  3692. return animations;
  3693. }
  3694. _createAnimations(target, values) {
  3695. const animatedProps = this._properties;
  3696. const animations = [];
  3697. const running = target.$animations || (target.$animations = {});
  3698. const props = Object.keys(values);
  3699. const date = Date.now();
  3700. let i;
  3701. for (i = props.length - 1; i >= 0; --i) {
  3702. const prop = props[i];
  3703. if (prop.charAt(0) === '$') {
  3704. continue;
  3705. }
  3706. if (prop === 'options') {
  3707. animations.push(...this._animateOptions(target, values));
  3708. continue;
  3709. }
  3710. const value = values[prop];
  3711. let animation = running[prop];
  3712. const cfg = animatedProps.get(prop);
  3713. if (animation) {
  3714. if (cfg && animation.active()) {
  3715. animation.update(cfg, value, date);
  3716. continue;
  3717. } else {
  3718. animation.cancel();
  3719. }
  3720. }
  3721. if (!cfg || !cfg.duration) {
  3722. target[prop] = value;
  3723. continue;
  3724. }
  3725. running[prop] = animation = new Animation(cfg, target, prop, value);
  3726. animations.push(animation);
  3727. }
  3728. return animations;
  3729. }
  3730. update(target, values) {
  3731. if (this._properties.size === 0) {
  3732. Object.assign(target, values);
  3733. return;
  3734. }
  3735. const animations = this._createAnimations(target, values);
  3736. if (animations.length) {
  3737. animator.add(this._chart, animations);
  3738. return true;
  3739. }
  3740. }
  3741. }
  3742. function awaitAll(animations, properties) {
  3743. const running = [];
  3744. const keys = Object.keys(properties);
  3745. for (let i = 0; i < keys.length; i++) {
  3746. const anim = animations[keys[i]];
  3747. if (anim && anim.active()) {
  3748. running.push(anim.wait());
  3749. }
  3750. }
  3751. return Promise.all(running);
  3752. }
  3753. function resolveTargetOptions(target, newOptions) {
  3754. if (!newOptions) {
  3755. return;
  3756. }
  3757. let options = target.options;
  3758. if (!options) {
  3759. target.options = newOptions;
  3760. return;
  3761. }
  3762. if (options.$shared) {
  3763. target.options = options = Object.assign({}, options, {$shared: false, $animations: {}});
  3764. }
  3765. return options;
  3766. }
  3767. function scaleClip(scale, allowedOverflow) {
  3768. const opts = scale && scale.options || {};
  3769. const reverse = opts.reverse;
  3770. const min = opts.min === undefined ? allowedOverflow : 0;
  3771. const max = opts.max === undefined ? allowedOverflow : 0;
  3772. return {
  3773. start: reverse ? max : min,
  3774. end: reverse ? min : max
  3775. };
  3776. }
  3777. function defaultClip(xScale, yScale, allowedOverflow) {
  3778. if (allowedOverflow === false) {
  3779. return false;
  3780. }
  3781. const x = scaleClip(xScale, allowedOverflow);
  3782. const y = scaleClip(yScale, allowedOverflow);
  3783. return {
  3784. top: y.end,
  3785. right: x.end,
  3786. bottom: y.start,
  3787. left: x.start
  3788. };
  3789. }
  3790. function toClip(value) {
  3791. let t, r, b, l;
  3792. if (isObject(value)) {
  3793. t = value.top;
  3794. r = value.right;
  3795. b = value.bottom;
  3796. l = value.left;
  3797. } else {
  3798. t = r = b = l = value;
  3799. }
  3800. return {
  3801. top: t,
  3802. right: r,
  3803. bottom: b,
  3804. left: l,
  3805. disabled: value === false
  3806. };
  3807. }
  3808. function getSortedDatasetIndices(chart, filterVisible) {
  3809. const keys = [];
  3810. const metasets = chart._getSortedDatasetMetas(filterVisible);
  3811. let i, ilen;
  3812. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  3813. keys.push(metasets[i].index);
  3814. }
  3815. return keys;
  3816. }
  3817. function applyStack(stack, value, dsIndex, options) {
  3818. const keys = stack.keys;
  3819. const singleMode = options.mode === 'single';
  3820. let i, ilen, datasetIndex, otherValue;
  3821. if (value === null) {
  3822. return;
  3823. }
  3824. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3825. datasetIndex = +keys[i];
  3826. if (datasetIndex === dsIndex) {
  3827. if (options.all) {
  3828. continue;
  3829. }
  3830. break;
  3831. }
  3832. otherValue = stack.values[datasetIndex];
  3833. if (isNumberFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) {
  3834. value += otherValue;
  3835. }
  3836. }
  3837. return value;
  3838. }
  3839. function convertObjectDataToArray(data) {
  3840. const keys = Object.keys(data);
  3841. const adata = new Array(keys.length);
  3842. let i, ilen, key;
  3843. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3844. key = keys[i];
  3845. adata[i] = {
  3846. x: key,
  3847. y: data[key]
  3848. };
  3849. }
  3850. return adata;
  3851. }
  3852. function isStacked(scale, meta) {
  3853. const stacked = scale && scale.options.stacked;
  3854. return stacked || (stacked === undefined && meta.stack !== undefined);
  3855. }
  3856. function getStackKey(indexScale, valueScale, meta) {
  3857. return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;
  3858. }
  3859. function getUserBounds(scale) {
  3860. const {min, max, minDefined, maxDefined} = scale.getUserBounds();
  3861. return {
  3862. min: minDefined ? min : Number.NEGATIVE_INFINITY,
  3863. max: maxDefined ? max : Number.POSITIVE_INFINITY
  3864. };
  3865. }
  3866. function getOrCreateStack(stacks, stackKey, indexValue) {
  3867. const subStack = stacks[stackKey] || (stacks[stackKey] = {});
  3868. return subStack[indexValue] || (subStack[indexValue] = {});
  3869. }
  3870. function getLastIndexInStack(stack, vScale, positive) {
  3871. for (const meta of vScale.getMatchingVisibleMetas('bar').reverse()) {
  3872. const value = stack[meta.index];
  3873. if ((positive && value > 0) || (!positive && value < 0)) {
  3874. return meta.index;
  3875. }
  3876. }
  3877. return null;
  3878. }
  3879. function updateStacks(controller, parsed) {
  3880. const {chart, _cachedMeta: meta} = controller;
  3881. const stacks = chart._stacks || (chart._stacks = {});
  3882. const {iScale, vScale, index: datasetIndex} = meta;
  3883. const iAxis = iScale.axis;
  3884. const vAxis = vScale.axis;
  3885. const key = getStackKey(iScale, vScale, meta);
  3886. const ilen = parsed.length;
  3887. let stack;
  3888. for (let i = 0; i < ilen; ++i) {
  3889. const item = parsed[i];
  3890. const {[iAxis]: index, [vAxis]: value} = item;
  3891. const itemStacks = item._stacks || (item._stacks = {});
  3892. stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);
  3893. stack[datasetIndex] = value;
  3894. stack._top = getLastIndexInStack(stack, vScale, true);
  3895. stack._bottom = getLastIndexInStack(stack, vScale, false);
  3896. }
  3897. }
  3898. function getFirstScaleId(chart, axis) {
  3899. const scales = chart.scales;
  3900. return Object.keys(scales).filter(key => scales[key].axis === axis).shift();
  3901. }
  3902. function createDatasetContext(parent, index) {
  3903. return Object.assign(Object.create(parent),
  3904. {
  3905. active: false,
  3906. dataset: undefined,
  3907. datasetIndex: index,
  3908. index,
  3909. mode: 'default',
  3910. type: 'dataset'
  3911. }
  3912. );
  3913. }
  3914. function createDataContext(parent, index, element) {
  3915. return Object.assign(Object.create(parent), {
  3916. active: false,
  3917. dataIndex: index,
  3918. parsed: undefined,
  3919. raw: undefined,
  3920. element,
  3921. index,
  3922. mode: 'default',
  3923. type: 'data'
  3924. });
  3925. }
  3926. function clearStacks(meta, items) {
  3927. const datasetIndex = meta.controller.index;
  3928. const axis = meta.vScale && meta.vScale.axis;
  3929. if (!axis) {
  3930. return;
  3931. }
  3932. items = items || meta._parsed;
  3933. for (const parsed of items) {
  3934. const stacks = parsed._stacks;
  3935. if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) {
  3936. return;
  3937. }
  3938. delete stacks[axis][datasetIndex];
  3939. }
  3940. }
  3941. const isDirectUpdateMode = (mode) => mode === 'reset' || mode === 'none';
  3942. const cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached);
  3943. class DatasetController {
  3944. constructor(chart, datasetIndex) {
  3945. this.chart = chart;
  3946. this._ctx = chart.ctx;
  3947. this.index = datasetIndex;
  3948. this._cachedDataOpts = {};
  3949. this._cachedMeta = this.getMeta();
  3950. this._type = this._cachedMeta.type;
  3951. this.options = undefined;
  3952. this._parsing = false;
  3953. this._data = undefined;
  3954. this._objectData = undefined;
  3955. this._sharedOptions = undefined;
  3956. this._drawStart = undefined;
  3957. this._drawCount = undefined;
  3958. this.enableOptionSharing = false;
  3959. this.$context = undefined;
  3960. this._syncList = [];
  3961. this.initialize();
  3962. }
  3963. initialize() {
  3964. const me = this;
  3965. const meta = me._cachedMeta;
  3966. me.configure();
  3967. me.linkScales();
  3968. meta._stacked = isStacked(meta.vScale, meta);
  3969. me.addElements();
  3970. }
  3971. updateIndex(datasetIndex) {
  3972. if (this.index !== datasetIndex) {
  3973. clearStacks(this._cachedMeta);
  3974. }
  3975. this.index = datasetIndex;
  3976. }
  3977. linkScales() {
  3978. const me = this;
  3979. const chart = me.chart;
  3980. const meta = me._cachedMeta;
  3981. const dataset = me.getDataset();
  3982. const chooseId = (axis, x, y, r) => axis === 'x' ? x : axis === 'r' ? r : y;
  3983. const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));
  3984. const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));
  3985. const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));
  3986. const indexAxis = meta.indexAxis;
  3987. const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);
  3988. const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);
  3989. meta.xScale = me.getScaleForId(xid);
  3990. meta.yScale = me.getScaleForId(yid);
  3991. meta.rScale = me.getScaleForId(rid);
  3992. meta.iScale = me.getScaleForId(iid);
  3993. meta.vScale = me.getScaleForId(vid);
  3994. }
  3995. getDataset() {
  3996. return this.chart.data.datasets[this.index];
  3997. }
  3998. getMeta() {
  3999. return this.chart.getDatasetMeta(this.index);
  4000. }
  4001. getScaleForId(scaleID) {
  4002. return this.chart.scales[scaleID];
  4003. }
  4004. _getOtherScale(scale) {
  4005. const meta = this._cachedMeta;
  4006. return scale === meta.iScale
  4007. ? meta.vScale
  4008. : meta.iScale;
  4009. }
  4010. reset() {
  4011. this._update('reset');
  4012. }
  4013. _destroy() {
  4014. const meta = this._cachedMeta;
  4015. if (this._data) {
  4016. unlistenArrayEvents(this._data, this);
  4017. }
  4018. if (meta._stacked) {
  4019. clearStacks(meta);
  4020. }
  4021. }
  4022. _dataCheck() {
  4023. const me = this;
  4024. const dataset = me.getDataset();
  4025. const data = dataset.data || (dataset.data = []);
  4026. const _data = me._data;
  4027. if (isObject(data)) {
  4028. me._data = convertObjectDataToArray(data);
  4029. } else if (_data !== data) {
  4030. if (_data) {
  4031. unlistenArrayEvents(_data, me);
  4032. const meta = me._cachedMeta;
  4033. clearStacks(meta);
  4034. meta._parsed = [];
  4035. }
  4036. if (data && Object.isExtensible(data)) {
  4037. listenArrayEvents(data, me);
  4038. }
  4039. me._syncList = [];
  4040. me._data = data;
  4041. }
  4042. }
  4043. addElements() {
  4044. const me = this;
  4045. const meta = me._cachedMeta;
  4046. me._dataCheck();
  4047. if (me.datasetElementType) {
  4048. meta.dataset = new me.datasetElementType();
  4049. }
  4050. }
  4051. buildOrUpdateElements(resetNewElements) {
  4052. const me = this;
  4053. const meta = me._cachedMeta;
  4054. const dataset = me.getDataset();
  4055. let stackChanged = false;
  4056. me._dataCheck();
  4057. const oldStacked = meta._stacked;
  4058. meta._stacked = isStacked(meta.vScale, meta);
  4059. if (meta.stack !== dataset.stack) {
  4060. stackChanged = true;
  4061. clearStacks(meta);
  4062. meta.stack = dataset.stack;
  4063. }
  4064. me._resyncElements(resetNewElements);
  4065. if (stackChanged || oldStacked !== meta._stacked) {
  4066. updateStacks(me, meta._parsed);
  4067. }
  4068. }
  4069. configure() {
  4070. const me = this;
  4071. const config = me.chart.config;
  4072. const scopeKeys = config.datasetScopeKeys(me._type);
  4073. const scopes = config.getOptionScopes(me.getDataset(), scopeKeys, true);
  4074. me.options = config.createResolver(scopes, me.getContext());
  4075. me._parsing = me.options.parsing;
  4076. }
  4077. parse(start, count) {
  4078. const me = this;
  4079. const {_cachedMeta: meta, _data: data} = me;
  4080. const {iScale, _stacked} = meta;
  4081. const iAxis = iScale.axis;
  4082. let sorted = start === 0 && count === data.length ? true : meta._sorted;
  4083. let prev = start > 0 && meta._parsed[start - 1];
  4084. let i, cur, parsed;
  4085. if (me._parsing === false) {
  4086. meta._parsed = data;
  4087. meta._sorted = true;
  4088. parsed = data;
  4089. } else {
  4090. if (isArray(data[start])) {
  4091. parsed = me.parseArrayData(meta, data, start, count);
  4092. } else if (isObject(data[start])) {
  4093. parsed = me.parseObjectData(meta, data, start, count);
  4094. } else {
  4095. parsed = me.parsePrimitiveData(meta, data, start, count);
  4096. }
  4097. const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]);
  4098. for (i = 0; i < count; ++i) {
  4099. meta._parsed[i + start] = cur = parsed[i];
  4100. if (sorted) {
  4101. if (isNotInOrderComparedToPrev()) {
  4102. sorted = false;
  4103. }
  4104. prev = cur;
  4105. }
  4106. }
  4107. meta._sorted = sorted;
  4108. }
  4109. if (_stacked) {
  4110. updateStacks(me, parsed);
  4111. }
  4112. }
  4113. parsePrimitiveData(meta, data, start, count) {
  4114. const {iScale, vScale} = meta;
  4115. const iAxis = iScale.axis;
  4116. const vAxis = vScale.axis;
  4117. const labels = iScale.getLabels();
  4118. const singleScale = iScale === vScale;
  4119. const parsed = new Array(count);
  4120. let i, ilen, index;
  4121. for (i = 0, ilen = count; i < ilen; ++i) {
  4122. index = i + start;
  4123. parsed[i] = {
  4124. [iAxis]: singleScale || iScale.parse(labels[index], index),
  4125. [vAxis]: vScale.parse(data[index], index)
  4126. };
  4127. }
  4128. return parsed;
  4129. }
  4130. parseArrayData(meta, data, start, count) {
  4131. const {xScale, yScale} = meta;
  4132. const parsed = new Array(count);
  4133. let i, ilen, index, item;
  4134. for (i = 0, ilen = count; i < ilen; ++i) {
  4135. index = i + start;
  4136. item = data[index];
  4137. parsed[i] = {
  4138. x: xScale.parse(item[0], index),
  4139. y: yScale.parse(item[1], index)
  4140. };
  4141. }
  4142. return parsed;
  4143. }
  4144. parseObjectData(meta, data, start, count) {
  4145. const {xScale, yScale} = meta;
  4146. const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;
  4147. const parsed = new Array(count);
  4148. let i, ilen, index, item;
  4149. for (i = 0, ilen = count; i < ilen; ++i) {
  4150. index = i + start;
  4151. item = data[index];
  4152. parsed[i] = {
  4153. x: xScale.parse(resolveObjectKey(item, xAxisKey), index),
  4154. y: yScale.parse(resolveObjectKey(item, yAxisKey), index)
  4155. };
  4156. }
  4157. return parsed;
  4158. }
  4159. getParsed(index) {
  4160. return this._cachedMeta._parsed[index];
  4161. }
  4162. getDataElement(index) {
  4163. return this._cachedMeta.data[index];
  4164. }
  4165. applyStack(scale, parsed, mode) {
  4166. const chart = this.chart;
  4167. const meta = this._cachedMeta;
  4168. const value = parsed[scale.axis];
  4169. const stack = {
  4170. keys: getSortedDatasetIndices(chart, true),
  4171. values: parsed._stacks[scale.axis]
  4172. };
  4173. return applyStack(stack, value, meta.index, {mode});
  4174. }
  4175. updateRangeFromParsed(range, scale, parsed, stack) {
  4176. const parsedValue = parsed[scale.axis];
  4177. let value = parsedValue === null ? NaN : parsedValue;
  4178. const values = stack && parsed._stacks[scale.axis];
  4179. if (stack && values) {
  4180. stack.values = values;
  4181. range.min = Math.min(range.min, value);
  4182. range.max = Math.max(range.max, value);
  4183. value = applyStack(stack, parsedValue, this._cachedMeta.index, {all: true});
  4184. }
  4185. range.min = Math.min(range.min, value);
  4186. range.max = Math.max(range.max, value);
  4187. }
  4188. getMinMax(scale, canStack) {
  4189. const me = this;
  4190. const meta = me._cachedMeta;
  4191. const _parsed = meta._parsed;
  4192. const sorted = meta._sorted && scale === meta.iScale;
  4193. const ilen = _parsed.length;
  4194. const otherScale = me._getOtherScale(scale);
  4195. const stack = canStack && meta._stacked && {keys: getSortedDatasetIndices(me.chart, true), values: null};
  4196. const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};
  4197. const {min: otherMin, max: otherMax} = getUserBounds(otherScale);
  4198. let i, value, parsed, otherValue;
  4199. function _skip() {
  4200. parsed = _parsed[i];
  4201. value = parsed[scale.axis];
  4202. otherValue = parsed[otherScale.axis];
  4203. return !isNumberFinite(value) || otherMin > otherValue || otherMax < otherValue;
  4204. }
  4205. for (i = 0; i < ilen; ++i) {
  4206. if (_skip()) {
  4207. continue;
  4208. }
  4209. me.updateRangeFromParsed(range, scale, parsed, stack);
  4210. if (sorted) {
  4211. break;
  4212. }
  4213. }
  4214. if (sorted) {
  4215. for (i = ilen - 1; i >= 0; --i) {
  4216. if (_skip()) {
  4217. continue;
  4218. }
  4219. me.updateRangeFromParsed(range, scale, parsed, stack);
  4220. break;
  4221. }
  4222. }
  4223. return range;
  4224. }
  4225. getAllParsedValues(scale) {
  4226. const parsed = this._cachedMeta._parsed;
  4227. const values = [];
  4228. let i, ilen, value;
  4229. for (i = 0, ilen = parsed.length; i < ilen; ++i) {
  4230. value = parsed[i][scale.axis];
  4231. if (isNumberFinite(value)) {
  4232. values.push(value);
  4233. }
  4234. }
  4235. return values;
  4236. }
  4237. getMaxOverflow() {
  4238. return false;
  4239. }
  4240. getLabelAndValue(index) {
  4241. const me = this;
  4242. const meta = me._cachedMeta;
  4243. const iScale = meta.iScale;
  4244. const vScale = meta.vScale;
  4245. const parsed = me.getParsed(index);
  4246. return {
  4247. label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',
  4248. value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''
  4249. };
  4250. }
  4251. _update(mode) {
  4252. const me = this;
  4253. const meta = me._cachedMeta;
  4254. me.configure();
  4255. me._cachedDataOpts = {};
  4256. me.update(mode || 'default');
  4257. meta._clip = toClip(valueOrDefault(me.options.clip, defaultClip(meta.xScale, meta.yScale, me.getMaxOverflow())));
  4258. }
  4259. update(mode) {}
  4260. draw() {
  4261. const me = this;
  4262. const ctx = me._ctx;
  4263. const chart = me.chart;
  4264. const meta = me._cachedMeta;
  4265. const elements = meta.data || [];
  4266. const area = chart.chartArea;
  4267. const active = [];
  4268. const start = me._drawStart || 0;
  4269. const count = me._drawCount || (elements.length - start);
  4270. let i;
  4271. if (meta.dataset) {
  4272. meta.dataset.draw(ctx, area, start, count);
  4273. }
  4274. for (i = start; i < start + count; ++i) {
  4275. const element = elements[i];
  4276. if (element.hidden) {
  4277. continue;
  4278. }
  4279. if (element.active) {
  4280. active.push(element);
  4281. } else {
  4282. element.draw(ctx, area);
  4283. }
  4284. }
  4285. for (i = 0; i < active.length; ++i) {
  4286. active[i].draw(ctx, area);
  4287. }
  4288. }
  4289. getStyle(index, active) {
  4290. const mode = active ? 'active' : 'default';
  4291. return index === undefined && this._cachedMeta.dataset
  4292. ? this.resolveDatasetElementOptions(mode)
  4293. : this.resolveDataElementOptions(index || 0, mode);
  4294. }
  4295. getContext(index, active, mode) {
  4296. const me = this;
  4297. const dataset = me.getDataset();
  4298. let context;
  4299. if (index >= 0 && index < me._cachedMeta.data.length) {
  4300. const element = me._cachedMeta.data[index];
  4301. context = element.$context ||
  4302. (element.$context = createDataContext(me.getContext(), index, element));
  4303. context.parsed = me.getParsed(index);
  4304. context.raw = dataset.data[index];
  4305. context.index = context.dataIndex = index;
  4306. } else {
  4307. context = me.$context ||
  4308. (me.$context = createDatasetContext(me.chart.getContext(), me.index));
  4309. context.dataset = dataset;
  4310. context.index = context.datasetIndex = me.index;
  4311. }
  4312. context.active = !!active;
  4313. context.mode = mode;
  4314. return context;
  4315. }
  4316. resolveDatasetElementOptions(mode) {
  4317. return this._resolveElementOptions(this.datasetElementType.id, mode);
  4318. }
  4319. resolveDataElementOptions(index, mode) {
  4320. return this._resolveElementOptions(this.dataElementType.id, mode, index);
  4321. }
  4322. _resolveElementOptions(elementType, mode = 'default', index) {
  4323. const me = this;
  4324. const active = mode === 'active';
  4325. const cache = me._cachedDataOpts;
  4326. const cacheKey = elementType + '-' + mode;
  4327. const cached = cache[cacheKey];
  4328. const sharing = me.enableOptionSharing && defined(index);
  4329. if (cached) {
  4330. return cloneIfNotShared(cached, sharing);
  4331. }
  4332. const config = me.chart.config;
  4333. const scopeKeys = config.datasetElementScopeKeys(me._type, elementType);
  4334. const prefixes = active ? [`${elementType}Hover`, 'hover', elementType, ''] : [elementType, ''];
  4335. const scopes = config.getOptionScopes(me.getDataset(), scopeKeys);
  4336. const names = Object.keys(defaults.elements[elementType]);
  4337. const context = () => me.getContext(index, active);
  4338. const values = config.resolveNamedOptions(scopes, names, context, prefixes);
  4339. if (values.$shared) {
  4340. values.$shared = sharing;
  4341. cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));
  4342. }
  4343. return values;
  4344. }
  4345. _resolveAnimations(index, transition, active) {
  4346. const me = this;
  4347. const chart = me.chart;
  4348. const cache = me._cachedDataOpts;
  4349. const cacheKey = `animation-${transition}`;
  4350. const cached = cache[cacheKey];
  4351. if (cached) {
  4352. return cached;
  4353. }
  4354. let options;
  4355. if (chart.options.animation !== false) {
  4356. const config = me.chart.config;
  4357. const scopeKeys = config.datasetAnimationScopeKeys(me._type, transition);
  4358. const scopes = config.getOptionScopes(me.getDataset(), scopeKeys);
  4359. options = config.createResolver(scopes, me.getContext(index, active, transition));
  4360. }
  4361. const animations = new Animations(chart, options && options.animations);
  4362. if (options && options._cacheable) {
  4363. cache[cacheKey] = Object.freeze(animations);
  4364. }
  4365. return animations;
  4366. }
  4367. getSharedOptions(options) {
  4368. if (!options.$shared) {
  4369. return;
  4370. }
  4371. return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));
  4372. }
  4373. includeOptions(mode, sharedOptions) {
  4374. return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;
  4375. }
  4376. updateElement(element, index, properties, mode) {
  4377. if (isDirectUpdateMode(mode)) {
  4378. Object.assign(element, properties);
  4379. } else {
  4380. this._resolveAnimations(index, mode).update(element, properties);
  4381. }
  4382. }
  4383. updateSharedOptions(sharedOptions, mode, newOptions) {
  4384. if (sharedOptions && !isDirectUpdateMode(mode)) {
  4385. this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);
  4386. }
  4387. }
  4388. _setStyle(element, index, mode, active) {
  4389. element.active = active;
  4390. const options = this.getStyle(index, active);
  4391. this._resolveAnimations(index, mode, active).update(element, {
  4392. options: (!active && this.getSharedOptions(options)) || options
  4393. });
  4394. }
  4395. removeHoverStyle(element, datasetIndex, index) {
  4396. this._setStyle(element, index, 'active', false);
  4397. }
  4398. setHoverStyle(element, datasetIndex, index) {
  4399. this._setStyle(element, index, 'active', true);
  4400. }
  4401. _removeDatasetHoverStyle() {
  4402. const element = this._cachedMeta.dataset;
  4403. if (element) {
  4404. this._setStyle(element, undefined, 'active', false);
  4405. }
  4406. }
  4407. _setDatasetHoverStyle() {
  4408. const element = this._cachedMeta.dataset;
  4409. if (element) {
  4410. this._setStyle(element, undefined, 'active', true);
  4411. }
  4412. }
  4413. _resyncElements(resetNewElements) {
  4414. const me = this;
  4415. const data = me._data;
  4416. const elements = me._cachedMeta.data;
  4417. for (const [method, arg1, arg2] of me._syncList) {
  4418. me[method](arg1, arg2);
  4419. }
  4420. me._syncList = [];
  4421. const numMeta = elements.length;
  4422. const numData = data.length;
  4423. const count = Math.min(numData, numMeta);
  4424. if (count) {
  4425. me.parse(0, count);
  4426. }
  4427. if (numData > numMeta) {
  4428. me._insertElements(numMeta, numData - numMeta, resetNewElements);
  4429. } else if (numData < numMeta) {
  4430. me._removeElements(numData, numMeta - numData);
  4431. }
  4432. }
  4433. _insertElements(start, count, resetNewElements = true) {
  4434. const me = this;
  4435. const meta = me._cachedMeta;
  4436. const data = meta.data;
  4437. const end = start + count;
  4438. let i;
  4439. const move = (arr) => {
  4440. arr.length += count;
  4441. for (i = arr.length - 1; i >= end; i--) {
  4442. arr[i] = arr[i - count];
  4443. }
  4444. };
  4445. move(data);
  4446. for (i = start; i < end; ++i) {
  4447. data[i] = new me.dataElementType();
  4448. }
  4449. if (me._parsing) {
  4450. move(meta._parsed);
  4451. }
  4452. me.parse(start, count);
  4453. if (resetNewElements) {
  4454. me.updateElements(data, start, count, 'reset');
  4455. }
  4456. }
  4457. updateElements(element, start, count, mode) {}
  4458. _removeElements(start, count) {
  4459. const me = this;
  4460. const meta = me._cachedMeta;
  4461. if (me._parsing) {
  4462. const removed = meta._parsed.splice(start, count);
  4463. if (meta._stacked) {
  4464. clearStacks(meta, removed);
  4465. }
  4466. }
  4467. meta.data.splice(start, count);
  4468. }
  4469. _sync(args) {
  4470. if (this._parsing) {
  4471. this._syncList.push(args);
  4472. } else {
  4473. const [method, arg1, arg2] = args;
  4474. this[method](arg1, arg2);
  4475. }
  4476. }
  4477. _onDataPush() {
  4478. const count = arguments.length;
  4479. this._sync(['_insertElements', this.getDataset().data.length - count, count]);
  4480. }
  4481. _onDataPop() {
  4482. this._sync(['_removeElements', this._cachedMeta.data.length - 1, 1]);
  4483. }
  4484. _onDataShift() {
  4485. this._sync(['_removeElements', 0, 1]);
  4486. }
  4487. _onDataSplice(start, count) {
  4488. this._sync(['_removeElements', start, count]);
  4489. this._sync(['_insertElements', start, arguments.length - 2]);
  4490. }
  4491. _onDataUnshift() {
  4492. this._sync(['_insertElements', 0, arguments.length]);
  4493. }
  4494. }
  4495. DatasetController.defaults = {};
  4496. DatasetController.prototype.datasetElementType = null;
  4497. DatasetController.prototype.dataElementType = null;
  4498. class Element {
  4499. constructor() {
  4500. this.x = undefined;
  4501. this.y = undefined;
  4502. this.active = false;
  4503. this.options = undefined;
  4504. this.$animations = undefined;
  4505. }
  4506. tooltipPosition(useFinalPosition) {
  4507. const {x, y} = this.getProps(['x', 'y'], useFinalPosition);
  4508. return {x, y};
  4509. }
  4510. hasValue() {
  4511. return isNumber(this.x) && isNumber(this.y);
  4512. }
  4513. getProps(props, final) {
  4514. const me = this;
  4515. const anims = this.$animations;
  4516. if (!final || !anims) {
  4517. return me;
  4518. }
  4519. const ret = {};
  4520. props.forEach(prop => {
  4521. ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : me[prop];
  4522. });
  4523. return ret;
  4524. }
  4525. }
  4526. Element.defaults = {};
  4527. Element.defaultRoutes = undefined;
  4528. const formatters = {
  4529. values(value) {
  4530. return isArray(value) ? value : '' + value;
  4531. },
  4532. numeric(tickValue, index, ticks) {
  4533. if (tickValue === 0) {
  4534. return '0';
  4535. }
  4536. const locale = this.chart.options.locale;
  4537. let notation;
  4538. let delta = tickValue;
  4539. if (ticks.length > 1) {
  4540. const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));
  4541. if (maxTick < 1e-4 || maxTick > 1e+15) {
  4542. notation = 'scientific';
  4543. }
  4544. delta = calculateDelta(tickValue, ticks);
  4545. }
  4546. const logDelta = log10(Math.abs(delta));
  4547. const numDecimal = Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);
  4548. const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal};
  4549. Object.assign(options, this.options.ticks.format);
  4550. return formatNumber(tickValue, locale, options);
  4551. },
  4552. logarithmic(tickValue, index, ticks) {
  4553. if (tickValue === 0) {
  4554. return '0';
  4555. }
  4556. const remain = tickValue / (Math.pow(10, Math.floor(log10(tickValue))));
  4557. if (remain === 1 || remain === 2 || remain === 5) {
  4558. return formatters.numeric.call(this, tickValue, index, ticks);
  4559. }
  4560. return '';
  4561. }
  4562. };
  4563. function calculateDelta(tickValue, ticks) {
  4564. let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;
  4565. if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) {
  4566. delta = tickValue - Math.floor(tickValue);
  4567. }
  4568. return delta;
  4569. }
  4570. var Ticks = {formatters};
  4571. defaults.set('scale', {
  4572. display: true,
  4573. offset: false,
  4574. reverse: false,
  4575. beginAtZero: false,
  4576. bounds: 'ticks',
  4577. grace: 0,
  4578. grid: {
  4579. display: true,
  4580. lineWidth: 1,
  4581. drawBorder: true,
  4582. drawOnChartArea: true,
  4583. drawTicks: true,
  4584. tickLength: 8,
  4585. tickWidth: (_ctx, options) => options.lineWidth,
  4586. tickColor: (_ctx, options) => options.color,
  4587. offset: false,
  4588. borderDash: [],
  4589. borderDashOffset: 0.0,
  4590. borderWidth: 1
  4591. },
  4592. title: {
  4593. display: false,
  4594. text: '',
  4595. padding: {
  4596. top: 4,
  4597. bottom: 4
  4598. }
  4599. },
  4600. ticks: {
  4601. minRotation: 0,
  4602. maxRotation: 50,
  4603. mirror: false,
  4604. textStrokeWidth: 0,
  4605. textStrokeColor: '',
  4606. padding: 3,
  4607. display: true,
  4608. autoSkip: true,
  4609. autoSkipPadding: 3,
  4610. labelOffset: 0,
  4611. callback: Ticks.formatters.values,
  4612. minor: {},
  4613. major: {},
  4614. align: 'center',
  4615. crossAlign: 'near',
  4616. showLabelBackdrop: false,
  4617. backdropColor: 'rgba(255, 255, 255, 0.75)',
  4618. backdropPadding: 2,
  4619. }
  4620. });
  4621. defaults.route('scale.ticks', 'color', '', 'color');
  4622. defaults.route('scale.grid', 'color', '', 'borderColor');
  4623. defaults.route('scale.grid', 'borderColor', '', 'borderColor');
  4624. defaults.route('scale.title', 'color', '', 'color');
  4625. defaults.describe('scale', {
  4626. _fallback: false,
  4627. _scriptable: (name) => !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser',
  4628. _indexable: (name) => name !== 'borderDash' && name !== 'tickBorderDash',
  4629. });
  4630. defaults.describe('scales', {
  4631. _fallback: 'scale',
  4632. });
  4633. defaults.describe('scale.ticks', {
  4634. _scriptable: (name) => name !== 'backdropPadding' && name !== 'callback',
  4635. _indexable: (name) => name !== 'backdropPadding',
  4636. });
  4637. function autoSkip(scale, ticks) {
  4638. const tickOpts = scale.options.ticks;
  4639. const ticksLimit = tickOpts.maxTicksLimit || determineMaxTicks(scale);
  4640. const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  4641. const numMajorIndices = majorIndices.length;
  4642. const first = majorIndices[0];
  4643. const last = majorIndices[numMajorIndices - 1];
  4644. const newTicks = [];
  4645. if (numMajorIndices > ticksLimit) {
  4646. skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);
  4647. return newTicks;
  4648. }
  4649. const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);
  4650. if (numMajorIndices > 0) {
  4651. let i, ilen;
  4652. const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
  4653. skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  4654. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  4655. skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
  4656. }
  4657. skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  4658. return newTicks;
  4659. }
  4660. skip(ticks, newTicks, spacing);
  4661. return newTicks;
  4662. }
  4663. function determineMaxTicks(scale) {
  4664. const offset = scale.options.offset;
  4665. const tickLength = scale._tickSize();
  4666. const maxScale = scale._length / tickLength + (offset ? 0 : 1);
  4667. const maxChart = scale._maxLength / tickLength;
  4668. return Math.floor(Math.min(maxScale, maxChart));
  4669. }
  4670. function calculateSpacing(majorIndices, ticks, ticksLimit) {
  4671. const evenMajorSpacing = getEvenSpacing(majorIndices);
  4672. const spacing = ticks.length / ticksLimit;
  4673. if (!evenMajorSpacing) {
  4674. return Math.max(spacing, 1);
  4675. }
  4676. const factors = _factorize(evenMajorSpacing);
  4677. for (let i = 0, ilen = factors.length - 1; i < ilen; i++) {
  4678. const factor = factors[i];
  4679. if (factor > spacing) {
  4680. return factor;
  4681. }
  4682. }
  4683. return Math.max(spacing, 1);
  4684. }
  4685. function getMajorIndices(ticks) {
  4686. const result = [];
  4687. let i, ilen;
  4688. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  4689. if (ticks[i].major) {
  4690. result.push(i);
  4691. }
  4692. }
  4693. return result;
  4694. }
  4695. function skipMajors(ticks, newTicks, majorIndices, spacing) {
  4696. let count = 0;
  4697. let next = majorIndices[0];
  4698. let i;
  4699. spacing = Math.ceil(spacing);
  4700. for (i = 0; i < ticks.length; i++) {
  4701. if (i === next) {
  4702. newTicks.push(ticks[i]);
  4703. count++;
  4704. next = majorIndices[count * spacing];
  4705. }
  4706. }
  4707. }
  4708. function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
  4709. const start = valueOrDefault(majorStart, 0);
  4710. const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);
  4711. let count = 0;
  4712. let length, i, next;
  4713. spacing = Math.ceil(spacing);
  4714. if (majorEnd) {
  4715. length = majorEnd - majorStart;
  4716. spacing = length / Math.floor(length / spacing);
  4717. }
  4718. next = start;
  4719. while (next < 0) {
  4720. count++;
  4721. next = Math.round(start + count * spacing);
  4722. }
  4723. for (i = Math.max(start, 0); i < end; i++) {
  4724. if (i === next) {
  4725. newTicks.push(ticks[i]);
  4726. count++;
  4727. next = Math.round(start + count * spacing);
  4728. }
  4729. }
  4730. }
  4731. function getEvenSpacing(arr) {
  4732. const len = arr.length;
  4733. let i, diff;
  4734. if (len < 2) {
  4735. return false;
  4736. }
  4737. for (diff = arr[0], i = 1; i < len; ++i) {
  4738. if (arr[i] - arr[i - 1] !== diff) {
  4739. return false;
  4740. }
  4741. }
  4742. return diff;
  4743. }
  4744. const reverseAlign = (align) => align === 'left' ? 'right' : align === 'right' ? 'left' : align;
  4745. const offsetFromEdge = (scale, edge, offset) => edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;
  4746. function sample(arr, numItems) {
  4747. const result = [];
  4748. const increment = arr.length / numItems;
  4749. const len = arr.length;
  4750. let i = 0;
  4751. for (; i < len; i += increment) {
  4752. result.push(arr[Math.floor(i)]);
  4753. }
  4754. return result;
  4755. }
  4756. function getPixelForGridLine(scale, index, offsetGridLines) {
  4757. const length = scale.ticks.length;
  4758. const validIndex = Math.min(index, length - 1);
  4759. const start = scale._startPixel;
  4760. const end = scale._endPixel;
  4761. const epsilon = 1e-6;
  4762. let lineValue = scale.getPixelForTick(validIndex);
  4763. let offset;
  4764. if (offsetGridLines) {
  4765. if (length === 1) {
  4766. offset = Math.max(lineValue - start, end - lineValue);
  4767. } else if (index === 0) {
  4768. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  4769. } else {
  4770. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  4771. }
  4772. lineValue += validIndex < index ? offset : -offset;
  4773. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  4774. return;
  4775. }
  4776. }
  4777. return lineValue;
  4778. }
  4779. function garbageCollect(caches, length) {
  4780. each(caches, (cache) => {
  4781. const gc = cache.gc;
  4782. const gcLen = gc.length / 2;
  4783. let i;
  4784. if (gcLen > length) {
  4785. for (i = 0; i < gcLen; ++i) {
  4786. delete cache.data[gc[i]];
  4787. }
  4788. gc.splice(0, gcLen);
  4789. }
  4790. });
  4791. }
  4792. function getTickMarkLength(options) {
  4793. return options.drawTicks ? options.tickLength : 0;
  4794. }
  4795. function getTitleHeight(options, fallback) {
  4796. if (!options.display) {
  4797. return 0;
  4798. }
  4799. const font = toFont(options.font, fallback);
  4800. const padding = toPadding(options.padding);
  4801. const lines = isArray(options.text) ? options.text.length : 1;
  4802. return (lines * font.lineHeight) + padding.height;
  4803. }
  4804. function createScaleContext(parent, scale) {
  4805. return Object.assign(Object.create(parent), {
  4806. scale,
  4807. type: 'scale'
  4808. });
  4809. }
  4810. function createTickContext(parent, index, tick) {
  4811. return Object.assign(Object.create(parent), {
  4812. tick,
  4813. index,
  4814. type: 'tick'
  4815. });
  4816. }
  4817. function titleAlign(align, position, reverse) {
  4818. let ret = _toLeftRightCenter(align);
  4819. if ((reverse && position !== 'right') || (!reverse && position === 'right')) {
  4820. ret = reverseAlign(ret);
  4821. }
  4822. return ret;
  4823. }
  4824. function titleArgs(scale, offset, position, align) {
  4825. const {top, left, bottom, right, chart} = scale;
  4826. const {chartArea, scales} = chart;
  4827. let rotation = 0;
  4828. let maxWidth, titleX, titleY;
  4829. const height = bottom - top;
  4830. const width = right - left;
  4831. if (scale.isHorizontal()) {
  4832. titleX = _alignStartEnd(align, left, right);
  4833. if (isObject(position)) {
  4834. const positionAxisID = Object.keys(position)[0];
  4835. const value = position[positionAxisID];
  4836. titleY = scales[positionAxisID].getPixelForValue(value) + height - offset;
  4837. } else if (position === 'center') {
  4838. titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset;
  4839. } else {
  4840. titleY = offsetFromEdge(scale, position, offset);
  4841. }
  4842. maxWidth = right - left;
  4843. } else {
  4844. if (isObject(position)) {
  4845. const positionAxisID = Object.keys(position)[0];
  4846. const value = position[positionAxisID];
  4847. titleX = scales[positionAxisID].getPixelForValue(value) - width + offset;
  4848. } else if (position === 'center') {
  4849. titleX = (chartArea.left + chartArea.right) / 2 - width + offset;
  4850. } else {
  4851. titleX = offsetFromEdge(scale, position, offset);
  4852. }
  4853. titleY = _alignStartEnd(align, bottom, top);
  4854. rotation = position === 'left' ? -HALF_PI : HALF_PI;
  4855. }
  4856. return {titleX, titleY, maxWidth, rotation};
  4857. }
  4858. class Scale extends Element {
  4859. constructor(cfg) {
  4860. super();
  4861. this.id = cfg.id;
  4862. this.type = cfg.type;
  4863. this.options = undefined;
  4864. this.ctx = cfg.ctx;
  4865. this.chart = cfg.chart;
  4866. this.top = undefined;
  4867. this.bottom = undefined;
  4868. this.left = undefined;
  4869. this.right = undefined;
  4870. this.width = undefined;
  4871. this.height = undefined;
  4872. this._margins = {
  4873. left: 0,
  4874. right: 0,
  4875. top: 0,
  4876. bottom: 0
  4877. };
  4878. this.maxWidth = undefined;
  4879. this.maxHeight = undefined;
  4880. this.paddingTop = undefined;
  4881. this.paddingBottom = undefined;
  4882. this.paddingLeft = undefined;
  4883. this.paddingRight = undefined;
  4884. this.axis = undefined;
  4885. this.labelRotation = undefined;
  4886. this.min = undefined;
  4887. this.max = undefined;
  4888. this._range = undefined;
  4889. this.ticks = [];
  4890. this._gridLineItems = null;
  4891. this._labelItems = null;
  4892. this._labelSizes = null;
  4893. this._length = 0;
  4894. this._maxLength = 0;
  4895. this._longestTextCache = {};
  4896. this._startPixel = undefined;
  4897. this._endPixel = undefined;
  4898. this._reversePixels = false;
  4899. this._userMax = undefined;
  4900. this._userMin = undefined;
  4901. this._suggestedMax = undefined;
  4902. this._suggestedMin = undefined;
  4903. this._ticksLength = 0;
  4904. this._borderValue = 0;
  4905. this._cache = {};
  4906. this._dataLimitsCached = false;
  4907. this.$context = undefined;
  4908. }
  4909. init(options) {
  4910. const me = this;
  4911. me.options = options.setContext(me.getContext());
  4912. me.axis = options.axis;
  4913. me._userMin = me.parse(options.min);
  4914. me._userMax = me.parse(options.max);
  4915. me._suggestedMin = me.parse(options.suggestedMin);
  4916. me._suggestedMax = me.parse(options.suggestedMax);
  4917. }
  4918. parse(raw, index) {
  4919. return raw;
  4920. }
  4921. getUserBounds() {
  4922. let {_userMin, _userMax, _suggestedMin, _suggestedMax} = this;
  4923. _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);
  4924. _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);
  4925. _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);
  4926. _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);
  4927. return {
  4928. min: finiteOrDefault(_userMin, _suggestedMin),
  4929. max: finiteOrDefault(_userMax, _suggestedMax),
  4930. minDefined: isNumberFinite(_userMin),
  4931. maxDefined: isNumberFinite(_userMax)
  4932. };
  4933. }
  4934. getMinMax(canStack) {
  4935. const me = this;
  4936. let {min, max, minDefined, maxDefined} = me.getUserBounds();
  4937. let range;
  4938. if (minDefined && maxDefined) {
  4939. return {min, max};
  4940. }
  4941. const metas = me.getMatchingVisibleMetas();
  4942. for (let i = 0, ilen = metas.length; i < ilen; ++i) {
  4943. range = metas[i].controller.getMinMax(me, canStack);
  4944. if (!minDefined) {
  4945. min = Math.min(min, range.min);
  4946. }
  4947. if (!maxDefined) {
  4948. max = Math.max(max, range.max);
  4949. }
  4950. }
  4951. return {
  4952. min: finiteOrDefault(min, finiteOrDefault(max, min)),
  4953. max: finiteOrDefault(max, finiteOrDefault(min, max))
  4954. };
  4955. }
  4956. getPadding() {
  4957. const me = this;
  4958. return {
  4959. left: me.paddingLeft || 0,
  4960. top: me.paddingTop || 0,
  4961. right: me.paddingRight || 0,
  4962. bottom: me.paddingBottom || 0
  4963. };
  4964. }
  4965. getTicks() {
  4966. return this.ticks;
  4967. }
  4968. getLabels() {
  4969. const data = this.chart.data;
  4970. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  4971. }
  4972. beforeLayout() {
  4973. this._cache = {};
  4974. this._dataLimitsCached = false;
  4975. }
  4976. beforeUpdate() {
  4977. callback(this.options.beforeUpdate, [this]);
  4978. }
  4979. update(maxWidth, maxHeight, margins) {
  4980. const me = this;
  4981. const tickOpts = me.options.ticks;
  4982. const sampleSize = tickOpts.sampleSize;
  4983. me.beforeUpdate();
  4984. me.maxWidth = maxWidth;
  4985. me.maxHeight = maxHeight;
  4986. me._margins = margins = Object.assign({
  4987. left: 0,
  4988. right: 0,
  4989. top: 0,
  4990. bottom: 0
  4991. }, margins);
  4992. me.ticks = null;
  4993. me._labelSizes = null;
  4994. me._gridLineItems = null;
  4995. me._labelItems = null;
  4996. me.beforeSetDimensions();
  4997. me.setDimensions();
  4998. me.afterSetDimensions();
  4999. me._maxLength = me.isHorizontal()
  5000. ? me.width + margins.left + margins.right
  5001. : me.height + margins.top + margins.bottom;
  5002. if (!me._dataLimitsCached) {
  5003. me.beforeDataLimits();
  5004. me.determineDataLimits();
  5005. me.afterDataLimits();
  5006. me._range = _addGrace(me, me.options.grace);
  5007. me._dataLimitsCached = true;
  5008. }
  5009. me.beforeBuildTicks();
  5010. me.ticks = me.buildTicks() || [];
  5011. me.afterBuildTicks();
  5012. const samplingEnabled = sampleSize < me.ticks.length;
  5013. me._convertTicksToLabels(samplingEnabled ? sample(me.ticks, sampleSize) : me.ticks);
  5014. me.configure();
  5015. me.beforeCalculateLabelRotation();
  5016. me.calculateLabelRotation();
  5017. me.afterCalculateLabelRotation();
  5018. if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {
  5019. me.ticks = autoSkip(me, me.ticks);
  5020. me._labelSizes = null;
  5021. }
  5022. if (samplingEnabled) {
  5023. me._convertTicksToLabels(me.ticks);
  5024. }
  5025. me.beforeFit();
  5026. me.fit();
  5027. me.afterFit();
  5028. me.afterUpdate();
  5029. }
  5030. configure() {
  5031. const me = this;
  5032. let reversePixels = me.options.reverse;
  5033. let startPixel, endPixel;
  5034. if (me.isHorizontal()) {
  5035. startPixel = me.left;
  5036. endPixel = me.right;
  5037. } else {
  5038. startPixel = me.top;
  5039. endPixel = me.bottom;
  5040. reversePixels = !reversePixels;
  5041. }
  5042. me._startPixel = startPixel;
  5043. me._endPixel = endPixel;
  5044. me._reversePixels = reversePixels;
  5045. me._length = endPixel - startPixel;
  5046. me._alignToPixels = me.options.alignToPixels;
  5047. }
  5048. afterUpdate() {
  5049. callback(this.options.afterUpdate, [this]);
  5050. }
  5051. beforeSetDimensions() {
  5052. callback(this.options.beforeSetDimensions, [this]);
  5053. }
  5054. setDimensions() {
  5055. const me = this;
  5056. if (me.isHorizontal()) {
  5057. me.width = me.maxWidth;
  5058. me.left = 0;
  5059. me.right = me.width;
  5060. } else {
  5061. me.height = me.maxHeight;
  5062. me.top = 0;
  5063. me.bottom = me.height;
  5064. }
  5065. me.paddingLeft = 0;
  5066. me.paddingTop = 0;
  5067. me.paddingRight = 0;
  5068. me.paddingBottom = 0;
  5069. }
  5070. afterSetDimensions() {
  5071. callback(this.options.afterSetDimensions, [this]);
  5072. }
  5073. _callHooks(name) {
  5074. const me = this;
  5075. me.chart.notifyPlugins(name, me.getContext());
  5076. callback(me.options[name], [me]);
  5077. }
  5078. beforeDataLimits() {
  5079. this._callHooks('beforeDataLimits');
  5080. }
  5081. determineDataLimits() {}
  5082. afterDataLimits() {
  5083. this._callHooks('afterDataLimits');
  5084. }
  5085. beforeBuildTicks() {
  5086. this._callHooks('beforeBuildTicks');
  5087. }
  5088. buildTicks() {
  5089. return [];
  5090. }
  5091. afterBuildTicks() {
  5092. this._callHooks('afterBuildTicks');
  5093. }
  5094. beforeTickToLabelConversion() {
  5095. callback(this.options.beforeTickToLabelConversion, [this]);
  5096. }
  5097. generateTickLabels(ticks) {
  5098. const me = this;
  5099. const tickOpts = me.options.ticks;
  5100. let i, ilen, tick;
  5101. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  5102. tick = ticks[i];
  5103. tick.label = callback(tickOpts.callback, [tick.value, i, ticks], me);
  5104. }
  5105. }
  5106. afterTickToLabelConversion() {
  5107. callback(this.options.afterTickToLabelConversion, [this]);
  5108. }
  5109. beforeCalculateLabelRotation() {
  5110. callback(this.options.beforeCalculateLabelRotation, [this]);
  5111. }
  5112. calculateLabelRotation() {
  5113. const me = this;
  5114. const options = me.options;
  5115. const tickOpts = options.ticks;
  5116. const numTicks = me.ticks.length;
  5117. const minRotation = tickOpts.minRotation || 0;
  5118. const maxRotation = tickOpts.maxRotation;
  5119. let labelRotation = minRotation;
  5120. let tickWidth, maxHeight, maxLabelDiagonal;
  5121. if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
  5122. me.labelRotation = minRotation;
  5123. return;
  5124. }
  5125. const labelSizes = me._getLabelSizes();
  5126. const maxLabelWidth = labelSizes.widest.width;
  5127. const maxLabelHeight = labelSizes.highest.height;
  5128. const maxWidth = _limitValue(me.chart.width - maxLabelWidth, 0, me.maxWidth);
  5129. tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
  5130. if (maxLabelWidth + 6 > tickWidth) {
  5131. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  5132. maxHeight = me.maxHeight - getTickMarkLength(options.grid)
  5133. - tickOpts.padding - getTitleHeight(options.title, me.chart.options.font);
  5134. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  5135. labelRotation = toDegrees(Math.min(
  5136. Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)),
  5137. Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))
  5138. ));
  5139. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  5140. }
  5141. me.labelRotation = labelRotation;
  5142. }
  5143. afterCalculateLabelRotation() {
  5144. callback(this.options.afterCalculateLabelRotation, [this]);
  5145. }
  5146. beforeFit() {
  5147. callback(this.options.beforeFit, [this]);
  5148. }
  5149. fit() {
  5150. const me = this;
  5151. const minSize = {
  5152. width: 0,
  5153. height: 0
  5154. };
  5155. const {chart, options: {ticks: tickOpts, title: titleOpts, grid: gridOpts}} = me;
  5156. const display = me._isVisible();
  5157. const isHorizontal = me.isHorizontal();
  5158. if (display) {
  5159. const titleHeight = getTitleHeight(titleOpts, chart.options.font);
  5160. if (isHorizontal) {
  5161. minSize.width = me.maxWidth;
  5162. minSize.height = getTickMarkLength(gridOpts) + titleHeight;
  5163. } else {
  5164. minSize.height = me.maxHeight;
  5165. minSize.width = getTickMarkLength(gridOpts) + titleHeight;
  5166. }
  5167. if (tickOpts.display && me.ticks.length) {
  5168. const {first, last, widest, highest} = me._getLabelSizes();
  5169. const tickPadding = tickOpts.padding * 2;
  5170. const angleRadians = toRadians(me.labelRotation);
  5171. const cos = Math.cos(angleRadians);
  5172. const sin = Math.sin(angleRadians);
  5173. if (isHorizontal) {
  5174. const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;
  5175. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  5176. } else {
  5177. const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;
  5178. minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth + tickPadding);
  5179. }
  5180. me._calculatePadding(first, last, sin, cos);
  5181. }
  5182. }
  5183. me._handleMargins();
  5184. if (isHorizontal) {
  5185. me.width = me._length = chart.width - me._margins.left - me._margins.right;
  5186. me.height = minSize.height;
  5187. } else {
  5188. me.width = minSize.width;
  5189. me.height = me._length = chart.height - me._margins.top - me._margins.bottom;
  5190. }
  5191. }
  5192. _calculatePadding(first, last, sin, cos) {
  5193. const me = this;
  5194. const {ticks: {align, padding}, position} = me.options;
  5195. const isRotated = me.labelRotation !== 0;
  5196. const labelsBelowTicks = position !== 'top' && me.axis === 'x';
  5197. if (me.isHorizontal()) {
  5198. const offsetLeft = me.getPixelForTick(0) - me.left;
  5199. const offsetRight = me.right - me.getPixelForTick(me.ticks.length - 1);
  5200. let paddingLeft = 0;
  5201. let paddingRight = 0;
  5202. if (isRotated) {
  5203. if (labelsBelowTicks) {
  5204. paddingLeft = cos * first.width;
  5205. paddingRight = sin * last.height;
  5206. } else {
  5207. paddingLeft = sin * first.height;
  5208. paddingRight = cos * last.width;
  5209. }
  5210. } else if (align === 'start') {
  5211. paddingRight = last.width;
  5212. } else if (align === 'end') {
  5213. paddingLeft = first.width;
  5214. } else {
  5215. paddingLeft = first.width / 2;
  5216. paddingRight = last.width / 2;
  5217. }
  5218. me.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * me.width / (me.width - offsetLeft), 0);
  5219. me.paddingRight = Math.max((paddingRight - offsetRight + padding) * me.width / (me.width - offsetRight), 0);
  5220. } else {
  5221. let paddingTop = last.height / 2;
  5222. let paddingBottom = first.height / 2;
  5223. if (align === 'start') {
  5224. paddingTop = 0;
  5225. paddingBottom = first.height;
  5226. } else if (align === 'end') {
  5227. paddingTop = last.height;
  5228. paddingBottom = 0;
  5229. }
  5230. me.paddingTop = paddingTop + padding;
  5231. me.paddingBottom = paddingBottom + padding;
  5232. }
  5233. }
  5234. _handleMargins() {
  5235. const me = this;
  5236. if (me._margins) {
  5237. me._margins.left = Math.max(me.paddingLeft, me._margins.left);
  5238. me._margins.top = Math.max(me.paddingTop, me._margins.top);
  5239. me._margins.right = Math.max(me.paddingRight, me._margins.right);
  5240. me._margins.bottom = Math.max(me.paddingBottom, me._margins.bottom);
  5241. }
  5242. }
  5243. afterFit() {
  5244. callback(this.options.afterFit, [this]);
  5245. }
  5246. isHorizontal() {
  5247. const {axis, position} = this.options;
  5248. return position === 'top' || position === 'bottom' || axis === 'x';
  5249. }
  5250. isFullSize() {
  5251. return this.options.fullSize;
  5252. }
  5253. _convertTicksToLabels(ticks) {
  5254. const me = this;
  5255. me.beforeTickToLabelConversion();
  5256. me.generateTickLabels(ticks);
  5257. let i, ilen;
  5258. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  5259. if (isNullOrUndef(ticks[i].label)) {
  5260. ticks.splice(i, 1);
  5261. ilen--;
  5262. i--;
  5263. }
  5264. }
  5265. me.afterTickToLabelConversion();
  5266. }
  5267. _getLabelSizes() {
  5268. const me = this;
  5269. let labelSizes = me._labelSizes;
  5270. if (!labelSizes) {
  5271. const sampleSize = me.options.ticks.sampleSize;
  5272. let ticks = me.ticks;
  5273. if (sampleSize < ticks.length) {
  5274. ticks = sample(ticks, sampleSize);
  5275. }
  5276. me._labelSizes = labelSizes = me._computeLabelSizes(ticks, ticks.length);
  5277. }
  5278. return labelSizes;
  5279. }
  5280. _computeLabelSizes(ticks, length) {
  5281. const {ctx, _longestTextCache: caches} = this;
  5282. const widths = [];
  5283. const heights = [];
  5284. let widestLabelSize = 0;
  5285. let highestLabelSize = 0;
  5286. let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;
  5287. for (i = 0; i < length; ++i) {
  5288. label = ticks[i].label;
  5289. tickFont = this._resolveTickFontOptions(i);
  5290. ctx.font = fontString = tickFont.string;
  5291. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  5292. lineHeight = tickFont.lineHeight;
  5293. width = height = 0;
  5294. if (!isNullOrUndef(label) && !isArray(label)) {
  5295. width = _measureText(ctx, cache.data, cache.gc, width, label);
  5296. height = lineHeight;
  5297. } else if (isArray(label)) {
  5298. for (j = 0, jlen = label.length; j < jlen; ++j) {
  5299. nestedLabel = label[j];
  5300. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  5301. width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  5302. height += lineHeight;
  5303. }
  5304. }
  5305. }
  5306. widths.push(width);
  5307. heights.push(height);
  5308. widestLabelSize = Math.max(width, widestLabelSize);
  5309. highestLabelSize = Math.max(height, highestLabelSize);
  5310. }
  5311. garbageCollect(caches, length);
  5312. const widest = widths.indexOf(widestLabelSize);
  5313. const highest = heights.indexOf(highestLabelSize);
  5314. const valueAt = (idx) => ({width: widths[idx] || 0, height: heights[idx] || 0});
  5315. return {
  5316. first: valueAt(0),
  5317. last: valueAt(length - 1),
  5318. widest: valueAt(widest),
  5319. highest: valueAt(highest),
  5320. widths,
  5321. heights,
  5322. };
  5323. }
  5324. getLabelForValue(value) {
  5325. return value;
  5326. }
  5327. getPixelForValue(value, index) {
  5328. return NaN;
  5329. }
  5330. getValueForPixel(pixel) {}
  5331. getPixelForTick(index) {
  5332. const ticks = this.ticks;
  5333. if (index < 0 || index > ticks.length - 1) {
  5334. return null;
  5335. }
  5336. return this.getPixelForValue(ticks[index].value);
  5337. }
  5338. getPixelForDecimal(decimal) {
  5339. const me = this;
  5340. if (me._reversePixels) {
  5341. decimal = 1 - decimal;
  5342. }
  5343. const pixel = me._startPixel + decimal * me._length;
  5344. return _int16Range(me._alignToPixels ? _alignPixel(me.chart, pixel, 0) : pixel);
  5345. }
  5346. getDecimalForPixel(pixel) {
  5347. const decimal = (pixel - this._startPixel) / this._length;
  5348. return this._reversePixels ? 1 - decimal : decimal;
  5349. }
  5350. getBasePixel() {
  5351. return this.getPixelForValue(this.getBaseValue());
  5352. }
  5353. getBaseValue() {
  5354. const {min, max} = this;
  5355. return min < 0 && max < 0 ? max :
  5356. min > 0 && max > 0 ? min :
  5357. 0;
  5358. }
  5359. getContext(index) {
  5360. const me = this;
  5361. const ticks = me.ticks || [];
  5362. if (index >= 0 && index < ticks.length) {
  5363. const tick = ticks[index];
  5364. return tick.$context ||
  5365. (tick.$context = createTickContext(me.getContext(), index, tick));
  5366. }
  5367. return me.$context ||
  5368. (me.$context = createScaleContext(me.chart.getContext(), me));
  5369. }
  5370. _tickSize() {
  5371. const me = this;
  5372. const optionTicks = me.options.ticks;
  5373. const rot = toRadians(me.labelRotation);
  5374. const cos = Math.abs(Math.cos(rot));
  5375. const sin = Math.abs(Math.sin(rot));
  5376. const labelSizes = me._getLabelSizes();
  5377. const padding = optionTicks.autoSkipPadding || 0;
  5378. const w = labelSizes ? labelSizes.widest.width + padding : 0;
  5379. const h = labelSizes ? labelSizes.highest.height + padding : 0;
  5380. return me.isHorizontal()
  5381. ? h * cos > w * sin ? w / cos : h / sin
  5382. : h * sin < w * cos ? h / cos : w / sin;
  5383. }
  5384. _isVisible() {
  5385. const display = this.options.display;
  5386. if (display !== 'auto') {
  5387. return !!display;
  5388. }
  5389. return this.getMatchingVisibleMetas().length > 0;
  5390. }
  5391. _computeGridLineItems(chartArea) {
  5392. const me = this;
  5393. const axis = me.axis;
  5394. const chart = me.chart;
  5395. const options = me.options;
  5396. const {grid, position} = options;
  5397. const offset = grid.offset;
  5398. const isHorizontal = me.isHorizontal();
  5399. const ticks = me.ticks;
  5400. const ticksLength = ticks.length + (offset ? 1 : 0);
  5401. const tl = getTickMarkLength(grid);
  5402. const items = [];
  5403. const borderOpts = grid.setContext(me.getContext());
  5404. const axisWidth = borderOpts.drawBorder ? borderOpts.borderWidth : 0;
  5405. const axisHalfWidth = axisWidth / 2;
  5406. const alignBorderValue = function(pixel) {
  5407. return _alignPixel(chart, pixel, axisWidth);
  5408. };
  5409. let borderValue, i, lineValue, alignedLineValue;
  5410. let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
  5411. if (position === 'top') {
  5412. borderValue = alignBorderValue(me.bottom);
  5413. ty1 = me.bottom - tl;
  5414. ty2 = borderValue - axisHalfWidth;
  5415. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  5416. y2 = chartArea.bottom;
  5417. } else if (position === 'bottom') {
  5418. borderValue = alignBorderValue(me.top);
  5419. y1 = chartArea.top;
  5420. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  5421. ty1 = borderValue + axisHalfWidth;
  5422. ty2 = me.top + tl;
  5423. } else if (position === 'left') {
  5424. borderValue = alignBorderValue(me.right);
  5425. tx1 = me.right - tl;
  5426. tx2 = borderValue - axisHalfWidth;
  5427. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  5428. x2 = chartArea.right;
  5429. } else if (position === 'right') {
  5430. borderValue = alignBorderValue(me.left);
  5431. x1 = chartArea.left;
  5432. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  5433. tx1 = borderValue + axisHalfWidth;
  5434. tx2 = me.left + tl;
  5435. } else if (axis === 'x') {
  5436. if (position === 'center') {
  5437. borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);
  5438. } else if (isObject(position)) {
  5439. const positionAxisID = Object.keys(position)[0];
  5440. const value = position[positionAxisID];
  5441. borderValue = alignBorderValue(me.chart.scales[positionAxisID].getPixelForValue(value));
  5442. }
  5443. y1 = chartArea.top;
  5444. y2 = chartArea.bottom;
  5445. ty1 = borderValue + axisHalfWidth;
  5446. ty2 = ty1 + tl;
  5447. } else if (axis === 'y') {
  5448. if (position === 'center') {
  5449. borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
  5450. } else if (isObject(position)) {
  5451. const positionAxisID = Object.keys(position)[0];
  5452. const value = position[positionAxisID];
  5453. borderValue = alignBorderValue(me.chart.scales[positionAxisID].getPixelForValue(value));
  5454. }
  5455. tx1 = borderValue - axisHalfWidth;
  5456. tx2 = tx1 - tl;
  5457. x1 = chartArea.left;
  5458. x2 = chartArea.right;
  5459. }
  5460. const limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength);
  5461. const step = Math.max(1, Math.ceil(ticksLength / limit));
  5462. for (i = 0; i < ticksLength; i += step) {
  5463. const optsAtIndex = grid.setContext(me.getContext(i));
  5464. const lineWidth = optsAtIndex.lineWidth;
  5465. const lineColor = optsAtIndex.color;
  5466. const borderDash = grid.borderDash || [];
  5467. const borderDashOffset = optsAtIndex.borderDashOffset;
  5468. const tickWidth = optsAtIndex.tickWidth;
  5469. const tickColor = optsAtIndex.tickColor;
  5470. const tickBorderDash = optsAtIndex.tickBorderDash || [];
  5471. const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;
  5472. lineValue = getPixelForGridLine(me, i, offset);
  5473. if (lineValue === undefined) {
  5474. continue;
  5475. }
  5476. alignedLineValue = _alignPixel(chart, lineValue, lineWidth);
  5477. if (isHorizontal) {
  5478. tx1 = tx2 = x1 = x2 = alignedLineValue;
  5479. } else {
  5480. ty1 = ty2 = y1 = y2 = alignedLineValue;
  5481. }
  5482. items.push({
  5483. tx1,
  5484. ty1,
  5485. tx2,
  5486. ty2,
  5487. x1,
  5488. y1,
  5489. x2,
  5490. y2,
  5491. width: lineWidth,
  5492. color: lineColor,
  5493. borderDash,
  5494. borderDashOffset,
  5495. tickWidth,
  5496. tickColor,
  5497. tickBorderDash,
  5498. tickBorderDashOffset,
  5499. });
  5500. }
  5501. me._ticksLength = ticksLength;
  5502. me._borderValue = borderValue;
  5503. return items;
  5504. }
  5505. _computeLabelItems(chartArea) {
  5506. const me = this;
  5507. const axis = me.axis;
  5508. const options = me.options;
  5509. const {position, ticks: optionTicks} = options;
  5510. const isHorizontal = me.isHorizontal();
  5511. const ticks = me.ticks;
  5512. const {align, crossAlign, padding, mirror} = optionTicks;
  5513. const tl = getTickMarkLength(options.grid);
  5514. const tickAndPadding = tl + padding;
  5515. const hTickAndPadding = mirror ? -padding : tickAndPadding;
  5516. const rotation = -toRadians(me.labelRotation);
  5517. const items = [];
  5518. let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  5519. let textBaseline = 'middle';
  5520. if (position === 'top') {
  5521. y = me.bottom - hTickAndPadding;
  5522. textAlign = me._getXAxisLabelAlignment();
  5523. } else if (position === 'bottom') {
  5524. y = me.top + hTickAndPadding;
  5525. textAlign = me._getXAxisLabelAlignment();
  5526. } else if (position === 'left') {
  5527. const ret = me._getYAxisLabelAlignment(tl);
  5528. textAlign = ret.textAlign;
  5529. x = ret.x;
  5530. } else if (position === 'right') {
  5531. const ret = me._getYAxisLabelAlignment(tl);
  5532. textAlign = ret.textAlign;
  5533. x = ret.x;
  5534. } else if (axis === 'x') {
  5535. if (position === 'center') {
  5536. y = ((chartArea.top + chartArea.bottom) / 2) + tickAndPadding;
  5537. } else if (isObject(position)) {
  5538. const positionAxisID = Object.keys(position)[0];
  5539. const value = position[positionAxisID];
  5540. y = me.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;
  5541. }
  5542. textAlign = me._getXAxisLabelAlignment();
  5543. } else if (axis === 'y') {
  5544. if (position === 'center') {
  5545. x = ((chartArea.left + chartArea.right) / 2) - tickAndPadding;
  5546. } else if (isObject(position)) {
  5547. const positionAxisID = Object.keys(position)[0];
  5548. const value = position[positionAxisID];
  5549. x = me.chart.scales[positionAxisID].getPixelForValue(value);
  5550. }
  5551. textAlign = me._getYAxisLabelAlignment(tl).textAlign;
  5552. }
  5553. if (axis === 'y') {
  5554. if (align === 'start') {
  5555. textBaseline = 'top';
  5556. } else if (align === 'end') {
  5557. textBaseline = 'bottom';
  5558. }
  5559. }
  5560. const labelSizes = me._getLabelSizes();
  5561. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  5562. tick = ticks[i];
  5563. label = tick.label;
  5564. const optsAtIndex = optionTicks.setContext(me.getContext(i));
  5565. pixel = me.getPixelForTick(i) + optionTicks.labelOffset;
  5566. font = me._resolveTickFontOptions(i);
  5567. lineHeight = font.lineHeight;
  5568. lineCount = isArray(label) ? label.length : 1;
  5569. const halfCount = lineCount / 2;
  5570. const color = optsAtIndex.color;
  5571. const strokeColor = optsAtIndex.textStrokeColor;
  5572. const strokeWidth = optsAtIndex.textStrokeWidth;
  5573. if (isHorizontal) {
  5574. x = pixel;
  5575. if (position === 'top') {
  5576. if (crossAlign === 'near' || rotation !== 0) {
  5577. textOffset = -lineCount * lineHeight + lineHeight / 2;
  5578. } else if (crossAlign === 'center') {
  5579. textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;
  5580. } else {
  5581. textOffset = -labelSizes.highest.height + lineHeight / 2;
  5582. }
  5583. } else {
  5584. if (crossAlign === 'near' || rotation !== 0) {
  5585. textOffset = lineHeight / 2;
  5586. } else if (crossAlign === 'center') {
  5587. textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;
  5588. } else {
  5589. textOffset = labelSizes.highest.height - lineCount * lineHeight;
  5590. }
  5591. }
  5592. if (mirror) {
  5593. textOffset *= -1;
  5594. }
  5595. } else {
  5596. y = pixel;
  5597. textOffset = (1 - lineCount) * lineHeight / 2;
  5598. }
  5599. let backdrop;
  5600. if (optsAtIndex.showLabelBackdrop) {
  5601. const labelPadding = toPadding(optsAtIndex.backdropPadding);
  5602. const height = labelSizes.heights[i];
  5603. const width = labelSizes.widths[i];
  5604. let top = y + textOffset - labelPadding.top;
  5605. let left = x - labelPadding.left;
  5606. switch (textBaseline) {
  5607. case 'middle':
  5608. top -= height / 2;
  5609. break;
  5610. case 'bottom':
  5611. top -= height;
  5612. break;
  5613. }
  5614. switch (textAlign) {
  5615. case 'center':
  5616. left -= width / 2;
  5617. break;
  5618. case 'right':
  5619. left -= width;
  5620. break;
  5621. }
  5622. backdrop = {
  5623. left,
  5624. top,
  5625. width: width + labelPadding.width,
  5626. height: height + labelPadding.height,
  5627. color: optsAtIndex.backdropColor,
  5628. };
  5629. }
  5630. items.push({
  5631. rotation,
  5632. label,
  5633. font,
  5634. color,
  5635. strokeColor,
  5636. strokeWidth,
  5637. textOffset,
  5638. textAlign,
  5639. textBaseline,
  5640. translation: [x, y],
  5641. backdrop,
  5642. });
  5643. }
  5644. return items;
  5645. }
  5646. _getXAxisLabelAlignment() {
  5647. const me = this;
  5648. const {position, ticks} = me.options;
  5649. const rotation = -toRadians(me.labelRotation);
  5650. if (rotation) {
  5651. return position === 'top' ? 'left' : 'right';
  5652. }
  5653. let align = 'center';
  5654. if (ticks.align === 'start') {
  5655. align = 'left';
  5656. } else if (ticks.align === 'end') {
  5657. align = 'right';
  5658. }
  5659. return align;
  5660. }
  5661. _getYAxisLabelAlignment(tl) {
  5662. const me = this;
  5663. const {position, ticks: {crossAlign, mirror, padding}} = me.options;
  5664. const labelSizes = me._getLabelSizes();
  5665. const tickAndPadding = tl + padding;
  5666. const widest = labelSizes.widest.width;
  5667. let textAlign;
  5668. let x;
  5669. if (position === 'left') {
  5670. if (mirror) {
  5671. x = me.right + padding;
  5672. if (crossAlign === 'near') {
  5673. textAlign = 'left';
  5674. } else if (crossAlign === 'center') {
  5675. textAlign = 'center';
  5676. x += (widest / 2);
  5677. } else {
  5678. textAlign = 'right';
  5679. x += widest;
  5680. }
  5681. } else {
  5682. x = me.right - tickAndPadding;
  5683. if (crossAlign === 'near') {
  5684. textAlign = 'right';
  5685. } else if (crossAlign === 'center') {
  5686. textAlign = 'center';
  5687. x -= (widest / 2);
  5688. } else {
  5689. textAlign = 'left';
  5690. x = me.left;
  5691. }
  5692. }
  5693. } else if (position === 'right') {
  5694. if (mirror) {
  5695. x = me.left + padding;
  5696. if (crossAlign === 'near') {
  5697. textAlign = 'right';
  5698. } else if (crossAlign === 'center') {
  5699. textAlign = 'center';
  5700. x -= (widest / 2);
  5701. } else {
  5702. textAlign = 'left';
  5703. x -= widest;
  5704. }
  5705. } else {
  5706. x = me.left + tickAndPadding;
  5707. if (crossAlign === 'near') {
  5708. textAlign = 'left';
  5709. } else if (crossAlign === 'center') {
  5710. textAlign = 'center';
  5711. x += widest / 2;
  5712. } else {
  5713. textAlign = 'right';
  5714. x = me.right;
  5715. }
  5716. }
  5717. } else {
  5718. textAlign = 'right';
  5719. }
  5720. return {textAlign, x};
  5721. }
  5722. _computeLabelArea() {
  5723. const me = this;
  5724. if (me.options.ticks.mirror) {
  5725. return;
  5726. }
  5727. const chart = me.chart;
  5728. const position = me.options.position;
  5729. if (position === 'left' || position === 'right') {
  5730. return {top: 0, left: me.left, bottom: chart.height, right: me.right};
  5731. } if (position === 'top' || position === 'bottom') {
  5732. return {top: me.top, left: 0, bottom: me.bottom, right: chart.width};
  5733. }
  5734. }
  5735. drawBackground() {
  5736. const {ctx, options: {backgroundColor}, left, top, width, height} = this;
  5737. if (backgroundColor) {
  5738. ctx.save();
  5739. ctx.fillStyle = backgroundColor;
  5740. ctx.fillRect(left, top, width, height);
  5741. ctx.restore();
  5742. }
  5743. }
  5744. getLineWidthForValue(value) {
  5745. const me = this;
  5746. const grid = me.options.grid;
  5747. if (!me._isVisible() || !grid.display) {
  5748. return 0;
  5749. }
  5750. const ticks = me.ticks;
  5751. const index = ticks.findIndex(t => t.value === value);
  5752. if (index >= 0) {
  5753. const opts = grid.setContext(me.getContext(index));
  5754. return opts.lineWidth;
  5755. }
  5756. return 0;
  5757. }
  5758. drawGrid(chartArea) {
  5759. const me = this;
  5760. const grid = me.options.grid;
  5761. const ctx = me.ctx;
  5762. const items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
  5763. let i, ilen;
  5764. const drawLine = (p1, p2, style) => {
  5765. if (!style.width || !style.color) {
  5766. return;
  5767. }
  5768. ctx.save();
  5769. ctx.lineWidth = style.width;
  5770. ctx.strokeStyle = style.color;
  5771. ctx.setLineDash(style.borderDash || []);
  5772. ctx.lineDashOffset = style.borderDashOffset;
  5773. ctx.beginPath();
  5774. ctx.moveTo(p1.x, p1.y);
  5775. ctx.lineTo(p2.x, p2.y);
  5776. ctx.stroke();
  5777. ctx.restore();
  5778. };
  5779. if (grid.display) {
  5780. for (i = 0, ilen = items.length; i < ilen; ++i) {
  5781. const item = items[i];
  5782. if (grid.drawOnChartArea) {
  5783. drawLine(
  5784. {x: item.x1, y: item.y1},
  5785. {x: item.x2, y: item.y2},
  5786. item
  5787. );
  5788. }
  5789. if (grid.drawTicks) {
  5790. drawLine(
  5791. {x: item.tx1, y: item.ty1},
  5792. {x: item.tx2, y: item.ty2},
  5793. {
  5794. color: item.tickColor,
  5795. width: item.tickWidth,
  5796. borderDash: item.tickBorderDash,
  5797. borderDashOffset: item.tickBorderDashOffset
  5798. }
  5799. );
  5800. }
  5801. }
  5802. }
  5803. }
  5804. drawBorder() {
  5805. const me = this;
  5806. const {chart, ctx, options: {grid}} = me;
  5807. const borderOpts = grid.setContext(me.getContext());
  5808. const axisWidth = grid.drawBorder ? borderOpts.borderWidth : 0;
  5809. if (!axisWidth) {
  5810. return;
  5811. }
  5812. const lastLineWidth = grid.setContext(me.getContext(0)).lineWidth;
  5813. const borderValue = me._borderValue;
  5814. let x1, x2, y1, y2;
  5815. if (me.isHorizontal()) {
  5816. x1 = _alignPixel(chart, me.left, axisWidth) - axisWidth / 2;
  5817. x2 = _alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  5818. y1 = y2 = borderValue;
  5819. } else {
  5820. y1 = _alignPixel(chart, me.top, axisWidth) - axisWidth / 2;
  5821. y2 = _alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  5822. x1 = x2 = borderValue;
  5823. }
  5824. ctx.save();
  5825. ctx.lineWidth = borderOpts.borderWidth;
  5826. ctx.strokeStyle = borderOpts.borderColor;
  5827. ctx.beginPath();
  5828. ctx.moveTo(x1, y1);
  5829. ctx.lineTo(x2, y2);
  5830. ctx.stroke();
  5831. ctx.restore();
  5832. }
  5833. drawLabels(chartArea) {
  5834. const me = this;
  5835. const optionTicks = me.options.ticks;
  5836. if (!optionTicks.display) {
  5837. return;
  5838. }
  5839. const ctx = me.ctx;
  5840. const area = me._computeLabelArea();
  5841. if (area) {
  5842. clipArea(ctx, area);
  5843. }
  5844. const items = me._labelItems || (me._labelItems = me._computeLabelItems(chartArea));
  5845. let i, ilen;
  5846. for (i = 0, ilen = items.length; i < ilen; ++i) {
  5847. const item = items[i];
  5848. const tickFont = item.font;
  5849. const label = item.label;
  5850. if (item.backdrop) {
  5851. ctx.fillStyle = item.backdrop.color;
  5852. ctx.fillRect(item.backdrop.left, item.backdrop.top, item.backdrop.width, item.backdrop.height);
  5853. }
  5854. let y = item.textOffset;
  5855. renderText(ctx, label, 0, y, tickFont, item);
  5856. }
  5857. if (area) {
  5858. unclipArea(ctx);
  5859. }
  5860. }
  5861. drawTitle() {
  5862. const {ctx, options: {position, title, reverse}} = this;
  5863. if (!title.display) {
  5864. return;
  5865. }
  5866. const font = toFont(title.font);
  5867. const padding = toPadding(title.padding);
  5868. const align = title.align;
  5869. let offset = font.lineHeight / 2;
  5870. if (position === 'bottom' || position === 'center' || isObject(position)) {
  5871. offset += padding.bottom;
  5872. if (isArray(title.text)) {
  5873. offset += font.lineHeight * (title.text.length - 1);
  5874. }
  5875. } else {
  5876. offset += padding.top;
  5877. }
  5878. const {titleX, titleY, maxWidth, rotation} = titleArgs(this, offset, position, align);
  5879. renderText(ctx, title.text, 0, 0, font, {
  5880. color: title.color,
  5881. maxWidth,
  5882. rotation,
  5883. textAlign: titleAlign(align, position, reverse),
  5884. textBaseline: 'middle',
  5885. translation: [titleX, titleY],
  5886. });
  5887. }
  5888. draw(chartArea) {
  5889. const me = this;
  5890. if (!me._isVisible()) {
  5891. return;
  5892. }
  5893. me.drawBackground();
  5894. me.drawGrid(chartArea);
  5895. me.drawBorder();
  5896. me.drawTitle();
  5897. me.drawLabels(chartArea);
  5898. }
  5899. _layers() {
  5900. const me = this;
  5901. const opts = me.options;
  5902. const tz = opts.ticks && opts.ticks.z || 0;
  5903. const gz = valueOrDefault(opts.grid && opts.grid.z, -1);
  5904. if (!me._isVisible() || me.draw !== Scale.prototype.draw) {
  5905. return [{
  5906. z: tz,
  5907. draw(chartArea) {
  5908. me.draw(chartArea);
  5909. }
  5910. }];
  5911. }
  5912. return [{
  5913. z: gz,
  5914. draw(chartArea) {
  5915. me.drawBackground();
  5916. me.drawGrid(chartArea);
  5917. me.drawTitle();
  5918. }
  5919. }, {
  5920. z: gz + 1,
  5921. draw() {
  5922. me.drawBorder();
  5923. }
  5924. }, {
  5925. z: tz,
  5926. draw(chartArea) {
  5927. me.drawLabels(chartArea);
  5928. }
  5929. }];
  5930. }
  5931. getMatchingVisibleMetas(type) {
  5932. const me = this;
  5933. const metas = me.chart.getSortedVisibleDatasetMetas();
  5934. const axisID = me.axis + 'AxisID';
  5935. const result = [];
  5936. let i, ilen;
  5937. for (i = 0, ilen = metas.length; i < ilen; ++i) {
  5938. const meta = metas[i];
  5939. if (meta[axisID] === me.id && (!type || meta.type === type)) {
  5940. result.push(meta);
  5941. }
  5942. }
  5943. return result;
  5944. }
  5945. _resolveTickFontOptions(index) {
  5946. const opts = this.options.ticks.setContext(this.getContext(index));
  5947. return toFont(opts.font);
  5948. }
  5949. _maxDigits() {
  5950. const me = this;
  5951. const fontSize = me._resolveTickFontOptions(0).lineHeight;
  5952. return (me.isHorizontal() ? me.width : me.height) / fontSize;
  5953. }
  5954. }
  5955. class TypedRegistry {
  5956. constructor(type, scope, override) {
  5957. this.type = type;
  5958. this.scope = scope;
  5959. this.override = override;
  5960. this.items = Object.create(null);
  5961. }
  5962. isForType(type) {
  5963. return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);
  5964. }
  5965. register(item) {
  5966. const me = this;
  5967. const proto = Object.getPrototypeOf(item);
  5968. let parentScope;
  5969. if (isIChartComponent(proto)) {
  5970. parentScope = me.register(proto);
  5971. }
  5972. const items = me.items;
  5973. const id = item.id;
  5974. const scope = me.scope + '.' + id;
  5975. if (!id) {
  5976. throw new Error('class does not have id: ' + item);
  5977. }
  5978. if (id in items) {
  5979. return scope;
  5980. }
  5981. items[id] = item;
  5982. registerDefaults(item, scope, parentScope);
  5983. if (me.override) {
  5984. defaults.override(item.id, item.overrides);
  5985. }
  5986. return scope;
  5987. }
  5988. get(id) {
  5989. return this.items[id];
  5990. }
  5991. unregister(item) {
  5992. const items = this.items;
  5993. const id = item.id;
  5994. const scope = this.scope;
  5995. if (id in items) {
  5996. delete items[id];
  5997. }
  5998. if (scope && id in defaults[scope]) {
  5999. delete defaults[scope][id];
  6000. if (this.override) {
  6001. delete overrides[id];
  6002. }
  6003. }
  6004. }
  6005. }
  6006. function registerDefaults(item, scope, parentScope) {
  6007. const itemDefaults = merge(Object.create(null), [
  6008. parentScope ? defaults.get(parentScope) : {},
  6009. defaults.get(scope),
  6010. item.defaults
  6011. ]);
  6012. defaults.set(scope, itemDefaults);
  6013. if (item.defaultRoutes) {
  6014. routeDefaults(scope, item.defaultRoutes);
  6015. }
  6016. if (item.descriptors) {
  6017. defaults.describe(scope, item.descriptors);
  6018. }
  6019. }
  6020. function routeDefaults(scope, routes) {
  6021. Object.keys(routes).forEach(property => {
  6022. const propertyParts = property.split('.');
  6023. const sourceName = propertyParts.pop();
  6024. const sourceScope = [scope].concat(propertyParts).join('.');
  6025. const parts = routes[property].split('.');
  6026. const targetName = parts.pop();
  6027. const targetScope = parts.join('.');
  6028. defaults.route(sourceScope, sourceName, targetScope, targetName);
  6029. });
  6030. }
  6031. function isIChartComponent(proto) {
  6032. return 'id' in proto && 'defaults' in proto;
  6033. }
  6034. class Registry {
  6035. constructor() {
  6036. this.controllers = new TypedRegistry(DatasetController, 'datasets', true);
  6037. this.elements = new TypedRegistry(Element, 'elements');
  6038. this.plugins = new TypedRegistry(Object, 'plugins');
  6039. this.scales = new TypedRegistry(Scale, 'scales');
  6040. this._typedRegistries = [this.controllers, this.scales, this.elements];
  6041. }
  6042. add(...args) {
  6043. this._each('register', args);
  6044. }
  6045. remove(...args) {
  6046. this._each('unregister', args);
  6047. }
  6048. addControllers(...args) {
  6049. this._each('register', args, this.controllers);
  6050. }
  6051. addElements(...args) {
  6052. this._each('register', args, this.elements);
  6053. }
  6054. addPlugins(...args) {
  6055. this._each('register', args, this.plugins);
  6056. }
  6057. addScales(...args) {
  6058. this._each('register', args, this.scales);
  6059. }
  6060. getController(id) {
  6061. return this._get(id, this.controllers, 'controller');
  6062. }
  6063. getElement(id) {
  6064. return this._get(id, this.elements, 'element');
  6065. }
  6066. getPlugin(id) {
  6067. return this._get(id, this.plugins, 'plugin');
  6068. }
  6069. getScale(id) {
  6070. return this._get(id, this.scales, 'scale');
  6071. }
  6072. removeControllers(...args) {
  6073. this._each('unregister', args, this.controllers);
  6074. }
  6075. removeElements(...args) {
  6076. this._each('unregister', args, this.elements);
  6077. }
  6078. removePlugins(...args) {
  6079. this._each('unregister', args, this.plugins);
  6080. }
  6081. removeScales(...args) {
  6082. this._each('unregister', args, this.scales);
  6083. }
  6084. _each(method, args, typedRegistry) {
  6085. const me = this;
  6086. [...args].forEach(arg => {
  6087. const reg = typedRegistry || me._getRegistryForType(arg);
  6088. if (typedRegistry || reg.isForType(arg) || (reg === me.plugins && arg.id)) {
  6089. me._exec(method, reg, arg);
  6090. } else {
  6091. each(arg, item => {
  6092. const itemReg = typedRegistry || me._getRegistryForType(item);
  6093. me._exec(method, itemReg, item);
  6094. });
  6095. }
  6096. });
  6097. }
  6098. _exec(method, registry, component) {
  6099. const camelMethod = _capitalize(method);
  6100. callback(component['before' + camelMethod], [], component);
  6101. registry[method](component);
  6102. callback(component['after' + camelMethod], [], component);
  6103. }
  6104. _getRegistryForType(type) {
  6105. for (let i = 0; i < this._typedRegistries.length; i++) {
  6106. const reg = this._typedRegistries[i];
  6107. if (reg.isForType(type)) {
  6108. return reg;
  6109. }
  6110. }
  6111. return this.plugins;
  6112. }
  6113. _get(id, typedRegistry, type) {
  6114. const item = typedRegistry.get(id);
  6115. if (item === undefined) {
  6116. throw new Error('"' + id + '" is not a registered ' + type + '.');
  6117. }
  6118. return item;
  6119. }
  6120. }
  6121. var registry = new Registry();
  6122. class PluginService {
  6123. constructor() {
  6124. this._init = [];
  6125. }
  6126. notify(chart, hook, args, filter) {
  6127. const me = this;
  6128. if (hook === 'beforeInit') {
  6129. me._init = me._createDescriptors(chart, true);
  6130. me._notify(me._init, chart, 'install');
  6131. }
  6132. const descriptors = filter ? me._descriptors(chart).filter(filter) : me._descriptors(chart);
  6133. const result = me._notify(descriptors, chart, hook, args);
  6134. if (hook === 'destroy') {
  6135. me._notify(descriptors, chart, 'stop');
  6136. me._notify(me._init, chart, 'uninstall');
  6137. }
  6138. return result;
  6139. }
  6140. _notify(descriptors, chart, hook, args) {
  6141. args = args || {};
  6142. for (const descriptor of descriptors) {
  6143. const plugin = descriptor.plugin;
  6144. const method = plugin[hook];
  6145. const params = [chart, args, descriptor.options];
  6146. if (callback(method, params, plugin) === false && args.cancelable) {
  6147. return false;
  6148. }
  6149. }
  6150. return true;
  6151. }
  6152. invalidate() {
  6153. if (!isNullOrUndef(this._cache)) {
  6154. this._oldCache = this._cache;
  6155. this._cache = undefined;
  6156. }
  6157. }
  6158. _descriptors(chart) {
  6159. if (this._cache) {
  6160. return this._cache;
  6161. }
  6162. const descriptors = this._cache = this._createDescriptors(chart);
  6163. this._notifyStateChanges(chart);
  6164. return descriptors;
  6165. }
  6166. _createDescriptors(chart, all) {
  6167. const config = chart && chart.config;
  6168. const options = valueOrDefault(config.options && config.options.plugins, {});
  6169. const plugins = allPlugins(config);
  6170. return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);
  6171. }
  6172. _notifyStateChanges(chart) {
  6173. const previousDescriptors = this._oldCache || [];
  6174. const descriptors = this._cache;
  6175. const diff = (a, b) => a.filter(x => !b.some(y => x.plugin.id === y.plugin.id));
  6176. this._notify(diff(previousDescriptors, descriptors), chart, 'stop');
  6177. this._notify(diff(descriptors, previousDescriptors), chart, 'start');
  6178. }
  6179. }
  6180. function allPlugins(config) {
  6181. const plugins = [];
  6182. const keys = Object.keys(registry.plugins.items);
  6183. for (let i = 0; i < keys.length; i++) {
  6184. plugins.push(registry.getPlugin(keys[i]));
  6185. }
  6186. const local = config.plugins || [];
  6187. for (let i = 0; i < local.length; i++) {
  6188. const plugin = local[i];
  6189. if (plugins.indexOf(plugin) === -1) {
  6190. plugins.push(plugin);
  6191. }
  6192. }
  6193. return plugins;
  6194. }
  6195. function getOpts(options, all) {
  6196. if (!all && options === false) {
  6197. return null;
  6198. }
  6199. if (options === true) {
  6200. return {};
  6201. }
  6202. return options;
  6203. }
  6204. function createDescriptors(chart, plugins, options, all) {
  6205. const result = [];
  6206. const context = chart.getContext();
  6207. for (let i = 0; i < plugins.length; i++) {
  6208. const plugin = plugins[i];
  6209. const id = plugin.id;
  6210. const opts = getOpts(options[id], all);
  6211. if (opts === null) {
  6212. continue;
  6213. }
  6214. result.push({
  6215. plugin,
  6216. options: pluginOpts(chart.config, plugin, opts, context)
  6217. });
  6218. }
  6219. return result;
  6220. }
  6221. function pluginOpts(config, plugin, opts, context) {
  6222. const keys = config.pluginScopeKeys(plugin);
  6223. const scopes = config.getOptionScopes(opts, keys);
  6224. return config.createResolver(scopes, context, [''], {scriptable: false, indexable: false, allKeys: true});
  6225. }
  6226. function getIndexAxis(type, options) {
  6227. const datasetDefaults = defaults.datasets[type] || {};
  6228. const datasetOptions = (options.datasets || {})[type] || {};
  6229. return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';
  6230. }
  6231. function getAxisFromDefaultScaleID(id, indexAxis) {
  6232. let axis = id;
  6233. if (id === '_index_') {
  6234. axis = indexAxis;
  6235. } else if (id === '_value_') {
  6236. axis = indexAxis === 'x' ? 'y' : 'x';
  6237. }
  6238. return axis;
  6239. }
  6240. function getDefaultScaleIDFromAxis(axis, indexAxis) {
  6241. return axis === indexAxis ? '_index_' : '_value_';
  6242. }
  6243. function axisFromPosition(position) {
  6244. if (position === 'top' || position === 'bottom') {
  6245. return 'x';
  6246. }
  6247. if (position === 'left' || position === 'right') {
  6248. return 'y';
  6249. }
  6250. }
  6251. function determineAxis(id, scaleOptions) {
  6252. if (id === 'x' || id === 'y') {
  6253. return id;
  6254. }
  6255. return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id.charAt(0).toLowerCase();
  6256. }
  6257. function mergeScaleConfig(config, options) {
  6258. const chartDefaults = overrides[config.type] || {scales: {}};
  6259. const configScales = options.scales || {};
  6260. const chartIndexAxis = getIndexAxis(config.type, options);
  6261. const firstIDs = Object.create(null);
  6262. const scales = Object.create(null);
  6263. Object.keys(configScales).forEach(id => {
  6264. const scaleConf = configScales[id];
  6265. const axis = determineAxis(id, scaleConf);
  6266. const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
  6267. const defaultScaleOptions = chartDefaults.scales || {};
  6268. firstIDs[axis] = firstIDs[axis] || id;
  6269. scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, defaultScaleOptions[axis], defaultScaleOptions[defaultId]]);
  6270. });
  6271. config.data.datasets.forEach(dataset => {
  6272. const type = dataset.type || config.type;
  6273. const indexAxis = dataset.indexAxis || getIndexAxis(type, options);
  6274. const datasetDefaults = overrides[type] || {};
  6275. const defaultScaleOptions = datasetDefaults.scales || {};
  6276. Object.keys(defaultScaleOptions).forEach(defaultID => {
  6277. const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
  6278. const id = dataset[axis + 'AxisID'] || firstIDs[axis] || axis;
  6279. scales[id] = scales[id] || Object.create(null);
  6280. mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]);
  6281. });
  6282. });
  6283. Object.keys(scales).forEach(key => {
  6284. const scale = scales[key];
  6285. mergeIf(scale, [defaults.scales[scale.type], defaults.scale]);
  6286. });
  6287. return scales;
  6288. }
  6289. function initOptions(config) {
  6290. const options = config.options || (config.options = {});
  6291. options.plugins = valueOrDefault(options.plugins, {});
  6292. options.scales = mergeScaleConfig(config, options);
  6293. }
  6294. function initData(data) {
  6295. data = data || {};
  6296. data.datasets = data.datasets || [];
  6297. data.labels = data.labels || [];
  6298. return data;
  6299. }
  6300. function initConfig(config) {
  6301. config = config || {};
  6302. config.data = initData(config.data);
  6303. initOptions(config);
  6304. return config;
  6305. }
  6306. const keyCache = new Map();
  6307. const keysCached = new Set();
  6308. function cachedKeys(cacheKey, generate) {
  6309. let keys = keyCache.get(cacheKey);
  6310. if (!keys) {
  6311. keys = generate();
  6312. keyCache.set(cacheKey, keys);
  6313. keysCached.add(keys);
  6314. }
  6315. return keys;
  6316. }
  6317. const addIfFound = (set, obj, key) => {
  6318. const opts = resolveObjectKey(obj, key);
  6319. if (opts !== undefined) {
  6320. set.add(opts);
  6321. }
  6322. };
  6323. class Config {
  6324. constructor(config) {
  6325. this._config = initConfig(config);
  6326. this._scopeCache = new Map();
  6327. this._resolverCache = new Map();
  6328. }
  6329. get platform() {
  6330. return this._config.platform;
  6331. }
  6332. get type() {
  6333. return this._config.type;
  6334. }
  6335. set type(type) {
  6336. this._config.type = type;
  6337. }
  6338. get data() {
  6339. return this._config.data;
  6340. }
  6341. set data(data) {
  6342. this._config.data = initData(data);
  6343. }
  6344. get options() {
  6345. return this._config.options;
  6346. }
  6347. set options(options) {
  6348. this._config.options = options;
  6349. }
  6350. get plugins() {
  6351. return this._config.plugins;
  6352. }
  6353. update() {
  6354. const config = this._config;
  6355. this.clearCache();
  6356. initOptions(config);
  6357. }
  6358. clearCache() {
  6359. this._scopeCache.clear();
  6360. this._resolverCache.clear();
  6361. }
  6362. datasetScopeKeys(datasetType) {
  6363. return cachedKeys(datasetType,
  6364. () => [[
  6365. `datasets.${datasetType}`,
  6366. ''
  6367. ]]);
  6368. }
  6369. datasetAnimationScopeKeys(datasetType, transition) {
  6370. return cachedKeys(`${datasetType}.transition.${transition}`,
  6371. () => [
  6372. [
  6373. `datasets.${datasetType}.transitions.${transition}`,
  6374. `transitions.${transition}`,
  6375. ],
  6376. [
  6377. `datasets.${datasetType}`,
  6378. ''
  6379. ]
  6380. ]);
  6381. }
  6382. datasetElementScopeKeys(datasetType, elementType) {
  6383. return cachedKeys(`${datasetType}-${elementType}`,
  6384. () => [[
  6385. `datasets.${datasetType}.elements.${elementType}`,
  6386. `datasets.${datasetType}`,
  6387. `elements.${elementType}`,
  6388. ''
  6389. ]]);
  6390. }
  6391. pluginScopeKeys(plugin) {
  6392. const id = plugin.id;
  6393. const type = this.type;
  6394. return cachedKeys(`${type}-plugin-${id}`,
  6395. () => [[
  6396. `plugins.${id}`,
  6397. ...plugin.additionalOptionScopes || [],
  6398. ]]);
  6399. }
  6400. _cachedScopes(mainScope, resetCache) {
  6401. const _scopeCache = this._scopeCache;
  6402. let cache = _scopeCache.get(mainScope);
  6403. if (!cache || resetCache) {
  6404. cache = new Map();
  6405. _scopeCache.set(mainScope, cache);
  6406. }
  6407. return cache;
  6408. }
  6409. getOptionScopes(mainScope, keyLists, resetCache) {
  6410. const {options, type} = this;
  6411. const cache = this._cachedScopes(mainScope, resetCache);
  6412. const cached = cache.get(keyLists);
  6413. if (cached) {
  6414. return cached;
  6415. }
  6416. const scopes = new Set();
  6417. keyLists.forEach(keys => {
  6418. if (mainScope) {
  6419. scopes.add(mainScope);
  6420. keys.forEach(key => addIfFound(scopes, mainScope, key));
  6421. }
  6422. keys.forEach(key => addIfFound(scopes, options, key));
  6423. keys.forEach(key => addIfFound(scopes, overrides[type] || {}, key));
  6424. keys.forEach(key => addIfFound(scopes, defaults, key));
  6425. keys.forEach(key => addIfFound(scopes, descriptors, key));
  6426. });
  6427. const array = Array.from(scopes);
  6428. if (array.length === 0) {
  6429. array.push(Object.create(null));
  6430. }
  6431. if (keysCached.has(keyLists)) {
  6432. cache.set(keyLists, array);
  6433. }
  6434. return array;
  6435. }
  6436. chartOptionScopes() {
  6437. const {options, type} = this;
  6438. return [
  6439. options,
  6440. overrides[type] || {},
  6441. defaults.datasets[type] || {},
  6442. {type},
  6443. defaults,
  6444. descriptors
  6445. ];
  6446. }
  6447. resolveNamedOptions(scopes, names, context, prefixes = ['']) {
  6448. const result = {$shared: true};
  6449. const {resolver, subPrefixes} = getResolver(this._resolverCache, scopes, prefixes);
  6450. let options = resolver;
  6451. if (needContext(resolver, names)) {
  6452. result.$shared = false;
  6453. context = isFunction(context) ? context() : context;
  6454. const subResolver = this.createResolver(scopes, context, subPrefixes);
  6455. options = _attachContext(resolver, context, subResolver);
  6456. }
  6457. for (const prop of names) {
  6458. result[prop] = options[prop];
  6459. }
  6460. return result;
  6461. }
  6462. createResolver(scopes, context, prefixes = [''], descriptorDefaults) {
  6463. const {resolver} = getResolver(this._resolverCache, scopes, prefixes);
  6464. return isObject(context)
  6465. ? _attachContext(resolver, context, undefined, descriptorDefaults)
  6466. : resolver;
  6467. }
  6468. }
  6469. function getResolver(resolverCache, scopes, prefixes) {
  6470. let cache = resolverCache.get(scopes);
  6471. if (!cache) {
  6472. cache = new Map();
  6473. resolverCache.set(scopes, cache);
  6474. }
  6475. const cacheKey = prefixes.join();
  6476. let cached = cache.get(cacheKey);
  6477. if (!cached) {
  6478. const resolver = _createResolver(scopes, prefixes);
  6479. cached = {
  6480. resolver,
  6481. subPrefixes: prefixes.filter(p => !p.toLowerCase().includes('hover'))
  6482. };
  6483. cache.set(cacheKey, cached);
  6484. }
  6485. return cached;
  6486. }
  6487. function needContext(proxy, names) {
  6488. const {isScriptable, isIndexable} = _descriptors(proxy);
  6489. for (const prop of names) {
  6490. if ((isScriptable(prop) && isFunction(proxy[prop]))
  6491. || (isIndexable(prop) && isArray(proxy[prop]))) {
  6492. return true;
  6493. }
  6494. }
  6495. return false;
  6496. }
  6497. var version = "3.5.1";
  6498. const KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea'];
  6499. function positionIsHorizontal(position, axis) {
  6500. return position === 'top' || position === 'bottom' || (KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x');
  6501. }
  6502. function compare2Level(l1, l2) {
  6503. return function(a, b) {
  6504. return a[l1] === b[l1]
  6505. ? a[l2] - b[l2]
  6506. : a[l1] - b[l1];
  6507. };
  6508. }
  6509. function onAnimationsComplete(context) {
  6510. const chart = context.chart;
  6511. const animationOptions = chart.options.animation;
  6512. chart.notifyPlugins('afterRender');
  6513. callback(animationOptions && animationOptions.onComplete, [context], chart);
  6514. }
  6515. function onAnimationProgress(context) {
  6516. const chart = context.chart;
  6517. const animationOptions = chart.options.animation;
  6518. callback(animationOptions && animationOptions.onProgress, [context], chart);
  6519. }
  6520. function getCanvas(item) {
  6521. if (_isDomSupported() && typeof item === 'string') {
  6522. item = document.getElementById(item);
  6523. } else if (item && item.length) {
  6524. item = item[0];
  6525. }
  6526. if (item && item.canvas) {
  6527. item = item.canvas;
  6528. }
  6529. return item;
  6530. }
  6531. const instances = {};
  6532. const getChart = (key) => {
  6533. const canvas = getCanvas(key);
  6534. return Object.values(instances).filter((c) => c.canvas === canvas).pop();
  6535. };
  6536. class Chart {
  6537. constructor(item, userConfig) {
  6538. const me = this;
  6539. const config = this.config = new Config(userConfig);
  6540. const initialCanvas = getCanvas(item);
  6541. const existingChart = getChart(initialCanvas);
  6542. if (existingChart) {
  6543. throw new Error(
  6544. 'Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' +
  6545. ' must be destroyed before the canvas can be reused.'
  6546. );
  6547. }
  6548. const options = config.createResolver(config.chartOptionScopes(), me.getContext());
  6549. this.platform = new (config.platform || _detectPlatform(initialCanvas))();
  6550. const context = me.platform.acquireContext(initialCanvas, options.aspectRatio);
  6551. const canvas = context && context.canvas;
  6552. const height = canvas && canvas.height;
  6553. const width = canvas && canvas.width;
  6554. this.id = uid();
  6555. this.ctx = context;
  6556. this.canvas = canvas;
  6557. this.width = width;
  6558. this.height = height;
  6559. this._options = options;
  6560. this._aspectRatio = this.aspectRatio;
  6561. this._layers = [];
  6562. this._metasets = [];
  6563. this._stacks = undefined;
  6564. this.boxes = [];
  6565. this.currentDevicePixelRatio = undefined;
  6566. this.chartArea = undefined;
  6567. this._active = [];
  6568. this._lastEvent = undefined;
  6569. this._listeners = {};
  6570. this._responsiveListeners = undefined;
  6571. this._sortedMetasets = [];
  6572. this.scales = {};
  6573. this._plugins = new PluginService();
  6574. this.$proxies = {};
  6575. this._hiddenIndices = {};
  6576. this.attached = false;
  6577. this._animationsDisabled = undefined;
  6578. this.$context = undefined;
  6579. this._doResize = debounce(() => this.update('resize'), options.resizeDelay || 0);
  6580. instances[me.id] = me;
  6581. if (!context || !canvas) {
  6582. console.error("Failed to create chart: can't acquire context from the given item");
  6583. return;
  6584. }
  6585. animator.listen(me, 'complete', onAnimationsComplete);
  6586. animator.listen(me, 'progress', onAnimationProgress);
  6587. me._initialize();
  6588. if (me.attached) {
  6589. me.update();
  6590. }
  6591. }
  6592. get aspectRatio() {
  6593. const {options: {aspectRatio, maintainAspectRatio}, width, height, _aspectRatio} = this;
  6594. if (!isNullOrUndef(aspectRatio)) {
  6595. return aspectRatio;
  6596. }
  6597. if (maintainAspectRatio && _aspectRatio) {
  6598. return _aspectRatio;
  6599. }
  6600. return height ? width / height : null;
  6601. }
  6602. get data() {
  6603. return this.config.data;
  6604. }
  6605. set data(data) {
  6606. this.config.data = data;
  6607. }
  6608. get options() {
  6609. return this._options;
  6610. }
  6611. set options(options) {
  6612. this.config.options = options;
  6613. }
  6614. _initialize() {
  6615. const me = this;
  6616. me.notifyPlugins('beforeInit');
  6617. if (me.options.responsive) {
  6618. me.resize();
  6619. } else {
  6620. retinaScale(me, me.options.devicePixelRatio);
  6621. }
  6622. me.bindEvents();
  6623. me.notifyPlugins('afterInit');
  6624. return me;
  6625. }
  6626. clear() {
  6627. clearCanvas(this.canvas, this.ctx);
  6628. return this;
  6629. }
  6630. stop() {
  6631. animator.stop(this);
  6632. return this;
  6633. }
  6634. resize(width, height) {
  6635. if (!animator.running(this)) {
  6636. this._resize(width, height);
  6637. } else {
  6638. this._resizeBeforeDraw = {width, height};
  6639. }
  6640. }
  6641. _resize(width, height) {
  6642. const me = this;
  6643. const options = me.options;
  6644. const canvas = me.canvas;
  6645. const aspectRatio = options.maintainAspectRatio && me.aspectRatio;
  6646. const newSize = me.platform.getMaximumSize(canvas, width, height, aspectRatio);
  6647. const newRatio = options.devicePixelRatio || me.platform.getDevicePixelRatio();
  6648. me.width = newSize.width;
  6649. me.height = newSize.height;
  6650. me._aspectRatio = me.aspectRatio;
  6651. if (!retinaScale(me, newRatio, true)) {
  6652. return;
  6653. }
  6654. me.notifyPlugins('resize', {size: newSize});
  6655. callback(options.onResize, [me, newSize], me);
  6656. if (me.attached) {
  6657. if (me._doResize()) {
  6658. me.render();
  6659. }
  6660. }
  6661. }
  6662. ensureScalesHaveIDs() {
  6663. const options = this.options;
  6664. const scalesOptions = options.scales || {};
  6665. each(scalesOptions, (axisOptions, axisID) => {
  6666. axisOptions.id = axisID;
  6667. });
  6668. }
  6669. buildOrUpdateScales() {
  6670. const me = this;
  6671. const options = me.options;
  6672. const scaleOpts = options.scales;
  6673. const scales = me.scales;
  6674. const updated = Object.keys(scales).reduce((obj, id) => {
  6675. obj[id] = false;
  6676. return obj;
  6677. }, {});
  6678. let items = [];
  6679. if (scaleOpts) {
  6680. items = items.concat(
  6681. Object.keys(scaleOpts).map((id) => {
  6682. const scaleOptions = scaleOpts[id];
  6683. const axis = determineAxis(id, scaleOptions);
  6684. const isRadial = axis === 'r';
  6685. const isHorizontal = axis === 'x';
  6686. return {
  6687. options: scaleOptions,
  6688. dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',
  6689. dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'
  6690. };
  6691. })
  6692. );
  6693. }
  6694. each(items, (item) => {
  6695. const scaleOptions = item.options;
  6696. const id = scaleOptions.id;
  6697. const axis = determineAxis(id, scaleOptions);
  6698. const scaleType = valueOrDefault(scaleOptions.type, item.dtype);
  6699. if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {
  6700. scaleOptions.position = item.dposition;
  6701. }
  6702. updated[id] = true;
  6703. let scale = null;
  6704. if (id in scales && scales[id].type === scaleType) {
  6705. scale = scales[id];
  6706. } else {
  6707. const scaleClass = registry.getScale(scaleType);
  6708. scale = new scaleClass({
  6709. id,
  6710. type: scaleType,
  6711. ctx: me.ctx,
  6712. chart: me
  6713. });
  6714. scales[scale.id] = scale;
  6715. }
  6716. scale.init(scaleOptions, options);
  6717. });
  6718. each(updated, (hasUpdated, id) => {
  6719. if (!hasUpdated) {
  6720. delete scales[id];
  6721. }
  6722. });
  6723. each(scales, (scale) => {
  6724. layouts.configure(me, scale, scale.options);
  6725. layouts.addBox(me, scale);
  6726. });
  6727. }
  6728. _updateMetasets() {
  6729. const me = this;
  6730. const metasets = me._metasets;
  6731. const numData = me.data.datasets.length;
  6732. const numMeta = metasets.length;
  6733. metasets.sort((a, b) => a.index - b.index);
  6734. if (numMeta > numData) {
  6735. for (let i = numData; i < numMeta; ++i) {
  6736. me._destroyDatasetMeta(i);
  6737. }
  6738. metasets.splice(numData, numMeta - numData);
  6739. }
  6740. me._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));
  6741. }
  6742. _removeUnreferencedMetasets() {
  6743. const me = this;
  6744. const {_metasets: metasets, data: {datasets}} = me;
  6745. if (metasets.length > datasets.length) {
  6746. delete me._stacks;
  6747. }
  6748. metasets.forEach((meta, index) => {
  6749. if (datasets.filter(x => x === meta._dataset).length === 0) {
  6750. me._destroyDatasetMeta(index);
  6751. }
  6752. });
  6753. }
  6754. buildOrUpdateControllers() {
  6755. const me = this;
  6756. const newControllers = [];
  6757. const datasets = me.data.datasets;
  6758. let i, ilen;
  6759. me._removeUnreferencedMetasets();
  6760. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  6761. const dataset = datasets[i];
  6762. let meta = me.getDatasetMeta(i);
  6763. const type = dataset.type || me.config.type;
  6764. if (meta.type && meta.type !== type) {
  6765. me._destroyDatasetMeta(i);
  6766. meta = me.getDatasetMeta(i);
  6767. }
  6768. meta.type = type;
  6769. meta.indexAxis = dataset.indexAxis || getIndexAxis(type, me.options);
  6770. meta.order = dataset.order || 0;
  6771. meta.index = i;
  6772. meta.label = '' + dataset.label;
  6773. meta.visible = me.isDatasetVisible(i);
  6774. if (meta.controller) {
  6775. meta.controller.updateIndex(i);
  6776. meta.controller.linkScales();
  6777. } else {
  6778. const ControllerClass = registry.getController(type);
  6779. const {datasetElementType, dataElementType} = defaults.datasets[type];
  6780. Object.assign(ControllerClass.prototype, {
  6781. dataElementType: registry.getElement(dataElementType),
  6782. datasetElementType: datasetElementType && registry.getElement(datasetElementType)
  6783. });
  6784. meta.controller = new ControllerClass(me, i);
  6785. newControllers.push(meta.controller);
  6786. }
  6787. }
  6788. me._updateMetasets();
  6789. return newControllers;
  6790. }
  6791. _resetElements() {
  6792. const me = this;
  6793. each(me.data.datasets, (dataset, datasetIndex) => {
  6794. me.getDatasetMeta(datasetIndex).controller.reset();
  6795. }, me);
  6796. }
  6797. reset() {
  6798. this._resetElements();
  6799. this.notifyPlugins('reset');
  6800. }
  6801. update(mode) {
  6802. const me = this;
  6803. const config = me.config;
  6804. config.update();
  6805. me._options = config.createResolver(config.chartOptionScopes(), me.getContext());
  6806. each(me.scales, (scale) => {
  6807. layouts.removeBox(me, scale);
  6808. });
  6809. const animsDisabled = me._animationsDisabled = !me.options.animation;
  6810. me.ensureScalesHaveIDs();
  6811. me.buildOrUpdateScales();
  6812. const existingEvents = new Set(Object.keys(me._listeners));
  6813. const newEvents = new Set(me.options.events);
  6814. if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== me.options.responsive) {
  6815. me.unbindEvents();
  6816. me.bindEvents();
  6817. }
  6818. me._plugins.invalidate();
  6819. if (me.notifyPlugins('beforeUpdate', {mode, cancelable: true}) === false) {
  6820. return;
  6821. }
  6822. const newControllers = me.buildOrUpdateControllers();
  6823. me.notifyPlugins('beforeElementsUpdate');
  6824. let minPadding = 0;
  6825. for (let i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
  6826. const {controller} = me.getDatasetMeta(i);
  6827. const reset = !animsDisabled && newControllers.indexOf(controller) === -1;
  6828. controller.buildOrUpdateElements(reset);
  6829. minPadding = Math.max(+controller.getMaxOverflow(), minPadding);
  6830. }
  6831. me._minPadding = minPadding;
  6832. me._updateLayout(minPadding);
  6833. if (!animsDisabled) {
  6834. each(newControllers, (controller) => {
  6835. controller.reset();
  6836. });
  6837. }
  6838. me._updateDatasets(mode);
  6839. me.notifyPlugins('afterUpdate', {mode});
  6840. me._layers.sort(compare2Level('z', '_idx'));
  6841. if (me._lastEvent) {
  6842. me._eventHandler(me._lastEvent, true);
  6843. }
  6844. me.render();
  6845. }
  6846. _updateLayout(minPadding) {
  6847. const me = this;
  6848. if (me.notifyPlugins('beforeLayout', {cancelable: true}) === false) {
  6849. return;
  6850. }
  6851. layouts.update(me, me.width, me.height, minPadding);
  6852. const area = me.chartArea;
  6853. const noArea = area.width <= 0 || area.height <= 0;
  6854. me._layers = [];
  6855. each(me.boxes, (box) => {
  6856. if (noArea && box.position === 'chartArea') {
  6857. return;
  6858. }
  6859. if (box.configure) {
  6860. box.configure();
  6861. }
  6862. me._layers.push(...box._layers());
  6863. }, me);
  6864. me._layers.forEach((item, index) => {
  6865. item._idx = index;
  6866. });
  6867. me.notifyPlugins('afterLayout');
  6868. }
  6869. _updateDatasets(mode) {
  6870. const me = this;
  6871. const isFunction = typeof mode === 'function';
  6872. if (me.notifyPlugins('beforeDatasetsUpdate', {mode, cancelable: true}) === false) {
  6873. return;
  6874. }
  6875. for (let i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  6876. me._updateDataset(i, isFunction ? mode({datasetIndex: i}) : mode);
  6877. }
  6878. me.notifyPlugins('afterDatasetsUpdate', {mode});
  6879. }
  6880. _updateDataset(index, mode) {
  6881. const me = this;
  6882. const meta = me.getDatasetMeta(index);
  6883. const args = {meta, index, mode, cancelable: true};
  6884. if (me.notifyPlugins('beforeDatasetUpdate', args) === false) {
  6885. return;
  6886. }
  6887. meta.controller._update(mode);
  6888. args.cancelable = false;
  6889. me.notifyPlugins('afterDatasetUpdate', args);
  6890. }
  6891. render() {
  6892. const me = this;
  6893. if (me.notifyPlugins('beforeRender', {cancelable: true}) === false) {
  6894. return;
  6895. }
  6896. if (animator.has(me)) {
  6897. if (me.attached && !animator.running(me)) {
  6898. animator.start(me);
  6899. }
  6900. } else {
  6901. me.draw();
  6902. onAnimationsComplete({chart: me});
  6903. }
  6904. }
  6905. draw() {
  6906. const me = this;
  6907. let i;
  6908. if (me._resizeBeforeDraw) {
  6909. const {width, height} = me._resizeBeforeDraw;
  6910. me._resize(width, height);
  6911. me._resizeBeforeDraw = null;
  6912. }
  6913. me.clear();
  6914. if (me.width <= 0 || me.height <= 0) {
  6915. return;
  6916. }
  6917. if (me.notifyPlugins('beforeDraw', {cancelable: true}) === false) {
  6918. return;
  6919. }
  6920. const layers = me._layers;
  6921. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  6922. layers[i].draw(me.chartArea);
  6923. }
  6924. me._drawDatasets();
  6925. for (; i < layers.length; ++i) {
  6926. layers[i].draw(me.chartArea);
  6927. }
  6928. me.notifyPlugins('afterDraw');
  6929. }
  6930. _getSortedDatasetMetas(filterVisible) {
  6931. const me = this;
  6932. const metasets = me._sortedMetasets;
  6933. const result = [];
  6934. let i, ilen;
  6935. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  6936. const meta = metasets[i];
  6937. if (!filterVisible || meta.visible) {
  6938. result.push(meta);
  6939. }
  6940. }
  6941. return result;
  6942. }
  6943. getSortedVisibleDatasetMetas() {
  6944. return this._getSortedDatasetMetas(true);
  6945. }
  6946. _drawDatasets() {
  6947. const me = this;
  6948. if (me.notifyPlugins('beforeDatasetsDraw', {cancelable: true}) === false) {
  6949. return;
  6950. }
  6951. const metasets = me.getSortedVisibleDatasetMetas();
  6952. for (let i = metasets.length - 1; i >= 0; --i) {
  6953. me._drawDataset(metasets[i]);
  6954. }
  6955. me.notifyPlugins('afterDatasetsDraw');
  6956. }
  6957. _drawDataset(meta) {
  6958. const me = this;
  6959. const ctx = me.ctx;
  6960. const clip = meta._clip;
  6961. const useClip = !clip.disabled;
  6962. const area = me.chartArea;
  6963. const args = {
  6964. meta,
  6965. index: meta.index,
  6966. cancelable: true
  6967. };
  6968. if (me.notifyPlugins('beforeDatasetDraw', args) === false) {
  6969. return;
  6970. }
  6971. if (useClip) {
  6972. clipArea(ctx, {
  6973. left: clip.left === false ? 0 : area.left - clip.left,
  6974. right: clip.right === false ? me.width : area.right + clip.right,
  6975. top: clip.top === false ? 0 : area.top - clip.top,
  6976. bottom: clip.bottom === false ? me.height : area.bottom + clip.bottom
  6977. });
  6978. }
  6979. meta.controller.draw();
  6980. if (useClip) {
  6981. unclipArea(ctx);
  6982. }
  6983. args.cancelable = false;
  6984. me.notifyPlugins('afterDatasetDraw', args);
  6985. }
  6986. getElementsAtEventForMode(e, mode, options, useFinalPosition) {
  6987. const method = Interaction.modes[mode];
  6988. if (typeof method === 'function') {
  6989. return method(this, e, options, useFinalPosition);
  6990. }
  6991. return [];
  6992. }
  6993. getDatasetMeta(datasetIndex) {
  6994. const me = this;
  6995. const dataset = me.data.datasets[datasetIndex];
  6996. const metasets = me._metasets;
  6997. let meta = metasets.filter(x => x && x._dataset === dataset).pop();
  6998. if (!meta) {
  6999. meta = {
  7000. type: null,
  7001. data: [],
  7002. dataset: null,
  7003. controller: null,
  7004. hidden: null,
  7005. xAxisID: null,
  7006. yAxisID: null,
  7007. order: dataset && dataset.order || 0,
  7008. index: datasetIndex,
  7009. _dataset: dataset,
  7010. _parsed: [],
  7011. _sorted: false
  7012. };
  7013. metasets.push(meta);
  7014. }
  7015. return meta;
  7016. }
  7017. getContext() {
  7018. return this.$context || (this.$context = {chart: this, type: 'chart'});
  7019. }
  7020. getVisibleDatasetCount() {
  7021. return this.getSortedVisibleDatasetMetas().length;
  7022. }
  7023. isDatasetVisible(datasetIndex) {
  7024. const dataset = this.data.datasets[datasetIndex];
  7025. if (!dataset) {
  7026. return false;
  7027. }
  7028. const meta = this.getDatasetMeta(datasetIndex);
  7029. return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;
  7030. }
  7031. setDatasetVisibility(datasetIndex, visible) {
  7032. const meta = this.getDatasetMeta(datasetIndex);
  7033. meta.hidden = !visible;
  7034. }
  7035. toggleDataVisibility(index) {
  7036. this._hiddenIndices[index] = !this._hiddenIndices[index];
  7037. }
  7038. getDataVisibility(index) {
  7039. return !this._hiddenIndices[index];
  7040. }
  7041. _updateVisibility(datasetIndex, dataIndex, visible) {
  7042. const me = this;
  7043. const mode = visible ? 'show' : 'hide';
  7044. const meta = me.getDatasetMeta(datasetIndex);
  7045. const anims = meta.controller._resolveAnimations(undefined, mode);
  7046. if (defined(dataIndex)) {
  7047. meta.data[dataIndex].hidden = !visible;
  7048. me.update();
  7049. } else {
  7050. me.setDatasetVisibility(datasetIndex, visible);
  7051. anims.update(meta, {visible});
  7052. me.update((ctx) => ctx.datasetIndex === datasetIndex ? mode : undefined);
  7053. }
  7054. }
  7055. hide(datasetIndex, dataIndex) {
  7056. this._updateVisibility(datasetIndex, dataIndex, false);
  7057. }
  7058. show(datasetIndex, dataIndex) {
  7059. this._updateVisibility(datasetIndex, dataIndex, true);
  7060. }
  7061. _destroyDatasetMeta(datasetIndex) {
  7062. const me = this;
  7063. const meta = me._metasets && me._metasets[datasetIndex];
  7064. if (meta && meta.controller) {
  7065. meta.controller._destroy();
  7066. delete me._metasets[datasetIndex];
  7067. }
  7068. }
  7069. destroy() {
  7070. const me = this;
  7071. const {canvas, ctx} = me;
  7072. let i, ilen;
  7073. me.stop();
  7074. animator.remove(me);
  7075. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  7076. me._destroyDatasetMeta(i);
  7077. }
  7078. me.config.clearCache();
  7079. if (canvas) {
  7080. me.unbindEvents();
  7081. clearCanvas(canvas, ctx);
  7082. me.platform.releaseContext(ctx);
  7083. me.canvas = null;
  7084. me.ctx = null;
  7085. }
  7086. me.notifyPlugins('destroy');
  7087. delete instances[me.id];
  7088. }
  7089. toBase64Image(...args) {
  7090. return this.canvas.toDataURL(...args);
  7091. }
  7092. bindEvents() {
  7093. this.bindUserEvents();
  7094. if (this.options.responsive) {
  7095. this.bindResponsiveEvents();
  7096. } else {
  7097. this.attached = true;
  7098. }
  7099. }
  7100. bindUserEvents() {
  7101. const me = this;
  7102. const listeners = me._listeners;
  7103. const platform = me.platform;
  7104. const _add = (type, listener) => {
  7105. platform.addEventListener(me, type, listener);
  7106. listeners[type] = listener;
  7107. };
  7108. const listener = function(e, x, y) {
  7109. e.offsetX = x;
  7110. e.offsetY = y;
  7111. me._eventHandler(e);
  7112. };
  7113. each(me.options.events, (type) => _add(type, listener));
  7114. }
  7115. bindResponsiveEvents() {
  7116. const me = this;
  7117. if (!me._responsiveListeners) {
  7118. me._responsiveListeners = {};
  7119. }
  7120. const listeners = me._responsiveListeners;
  7121. const platform = me.platform;
  7122. const _add = (type, listener) => {
  7123. platform.addEventListener(me, type, listener);
  7124. listeners[type] = listener;
  7125. };
  7126. const _remove = (type, listener) => {
  7127. if (listeners[type]) {
  7128. platform.removeEventListener(me, type, listener);
  7129. delete listeners[type];
  7130. }
  7131. };
  7132. const listener = (width, height) => {
  7133. if (me.canvas) {
  7134. me.resize(width, height);
  7135. }
  7136. };
  7137. let detached;
  7138. const attached = () => {
  7139. _remove('attach', attached);
  7140. me.attached = true;
  7141. me.resize();
  7142. _add('resize', listener);
  7143. _add('detach', detached);
  7144. };
  7145. detached = () => {
  7146. me.attached = false;
  7147. _remove('resize', listener);
  7148. _add('attach', attached);
  7149. };
  7150. if (platform.isAttached(me.canvas)) {
  7151. attached();
  7152. } else {
  7153. detached();
  7154. }
  7155. }
  7156. unbindEvents() {
  7157. const me = this;
  7158. each(me._listeners, (listener, type) => {
  7159. me.platform.removeEventListener(me, type, listener);
  7160. });
  7161. me._listeners = {};
  7162. each(me._responsiveListeners, (listener, type) => {
  7163. me.platform.removeEventListener(me, type, listener);
  7164. });
  7165. me._responsiveListeners = undefined;
  7166. }
  7167. updateHoverStyle(items, mode, enabled) {
  7168. const prefix = enabled ? 'set' : 'remove';
  7169. let meta, item, i, ilen;
  7170. if (mode === 'dataset') {
  7171. meta = this.getDatasetMeta(items[0].datasetIndex);
  7172. meta.controller['_' + prefix + 'DatasetHoverStyle']();
  7173. }
  7174. for (i = 0, ilen = items.length; i < ilen; ++i) {
  7175. item = items[i];
  7176. const controller = item && this.getDatasetMeta(item.datasetIndex).controller;
  7177. if (controller) {
  7178. controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
  7179. }
  7180. }
  7181. }
  7182. getActiveElements() {
  7183. return this._active || [];
  7184. }
  7185. setActiveElements(activeElements) {
  7186. const me = this;
  7187. const lastActive = me._active || [];
  7188. const active = activeElements.map(({datasetIndex, index}) => {
  7189. const meta = me.getDatasetMeta(datasetIndex);
  7190. if (!meta) {
  7191. throw new Error('No dataset found at index ' + datasetIndex);
  7192. }
  7193. return {
  7194. datasetIndex,
  7195. element: meta.data[index],
  7196. index,
  7197. };
  7198. });
  7199. const changed = !_elementsEqual(active, lastActive);
  7200. if (changed) {
  7201. me._active = active;
  7202. me._updateHoverStyles(active, lastActive);
  7203. }
  7204. }
  7205. notifyPlugins(hook, args, filter) {
  7206. return this._plugins.notify(this, hook, args, filter);
  7207. }
  7208. _updateHoverStyles(active, lastActive, replay) {
  7209. const me = this;
  7210. const hoverOptions = me.options.hover;
  7211. const diff = (a, b) => a.filter(x => !b.some(y => x.datasetIndex === y.datasetIndex && x.index === y.index));
  7212. const deactivated = diff(lastActive, active);
  7213. const activated = replay ? active : diff(active, lastActive);
  7214. if (deactivated.length) {
  7215. me.updateHoverStyle(deactivated, hoverOptions.mode, false);
  7216. }
  7217. if (activated.length && hoverOptions.mode) {
  7218. me.updateHoverStyle(activated, hoverOptions.mode, true);
  7219. }
  7220. }
  7221. _eventHandler(e, replay) {
  7222. const me = this;
  7223. const args = {event: e, replay, cancelable: true};
  7224. const eventFilter = (plugin) => (plugin.options.events || this.options.events).includes(e.type);
  7225. if (me.notifyPlugins('beforeEvent', args, eventFilter) === false) {
  7226. return;
  7227. }
  7228. const changed = me._handleEvent(e, replay);
  7229. args.cancelable = false;
  7230. me.notifyPlugins('afterEvent', args, eventFilter);
  7231. if (changed || args.changed) {
  7232. me.render();
  7233. }
  7234. return me;
  7235. }
  7236. _handleEvent(e, replay) {
  7237. const me = this;
  7238. const {_active: lastActive = [], options} = me;
  7239. const hoverOptions = options.hover;
  7240. const useFinalPosition = replay;
  7241. let active = [];
  7242. let changed = false;
  7243. let lastEvent = null;
  7244. if (e.type !== 'mouseout') {
  7245. active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);
  7246. lastEvent = e.type === 'click' ? me._lastEvent : e;
  7247. }
  7248. me._lastEvent = null;
  7249. if (_isPointInArea(e, me.chartArea, me._minPadding)) {
  7250. callback(options.onHover, [e, active, me], me);
  7251. if (e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu') {
  7252. callback(options.onClick, [e, active, me], me);
  7253. }
  7254. }
  7255. changed = !_elementsEqual(active, lastActive);
  7256. if (changed || replay) {
  7257. me._active = active;
  7258. me._updateHoverStyles(active, lastActive, replay);
  7259. }
  7260. me._lastEvent = lastEvent;
  7261. return changed;
  7262. }
  7263. }
  7264. const invalidatePlugins = () => each(Chart.instances, (chart) => chart._plugins.invalidate());
  7265. const enumerable = true;
  7266. Object.defineProperties(Chart, {
  7267. defaults: {
  7268. enumerable,
  7269. value: defaults
  7270. },
  7271. instances: {
  7272. enumerable,
  7273. value: instances
  7274. },
  7275. overrides: {
  7276. enumerable,
  7277. value: overrides
  7278. },
  7279. registry: {
  7280. enumerable,
  7281. value: registry
  7282. },
  7283. version: {
  7284. enumerable,
  7285. value: version
  7286. },
  7287. getChart: {
  7288. enumerable,
  7289. value: getChart
  7290. },
  7291. register: {
  7292. enumerable,
  7293. value: (...items) => {
  7294. registry.add(...items);
  7295. invalidatePlugins();
  7296. }
  7297. },
  7298. unregister: {
  7299. enumerable,
  7300. value: (...items) => {
  7301. registry.remove(...items);
  7302. invalidatePlugins();
  7303. }
  7304. }
  7305. });
  7306. function abstract() {
  7307. throw new Error('This method is not implemented: Check that a complete date adapter is provided.');
  7308. }
  7309. class DateAdapter {
  7310. constructor(options) {
  7311. this.options = options || {};
  7312. }
  7313. formats() {
  7314. return abstract();
  7315. }
  7316. parse(value, format) {
  7317. return abstract();
  7318. }
  7319. format(timestamp, format) {
  7320. return abstract();
  7321. }
  7322. add(timestamp, amount, unit) {
  7323. return abstract();
  7324. }
  7325. diff(a, b, unit) {
  7326. return abstract();
  7327. }
  7328. startOf(timestamp, unit, weekday) {
  7329. return abstract();
  7330. }
  7331. endOf(timestamp, unit) {
  7332. return abstract();
  7333. }
  7334. }
  7335. DateAdapter.override = function(members) {
  7336. Object.assign(DateAdapter.prototype, members);
  7337. };
  7338. var _adapters = {
  7339. _date: DateAdapter
  7340. };
  7341. function getAllScaleValues(scale) {
  7342. if (!scale._cache.$bar) {
  7343. const metas = scale.getMatchingVisibleMetas('bar');
  7344. let values = [];
  7345. for (let i = 0, ilen = metas.length; i < ilen; i++) {
  7346. values = values.concat(metas[i].controller.getAllParsedValues(scale));
  7347. }
  7348. scale._cache.$bar = _arrayUnique(values.sort((a, b) => a - b));
  7349. }
  7350. return scale._cache.$bar;
  7351. }
  7352. function computeMinSampleSize(scale) {
  7353. const values = getAllScaleValues(scale);
  7354. let min = scale._length;
  7355. let i, ilen, curr, prev;
  7356. const updateMinAndPrev = () => {
  7357. if (curr === 32767 || curr === -32768) {
  7358. return;
  7359. }
  7360. if (defined(prev)) {
  7361. min = Math.min(min, Math.abs(curr - prev) || min);
  7362. }
  7363. prev = curr;
  7364. };
  7365. for (i = 0, ilen = values.length; i < ilen; ++i) {
  7366. curr = scale.getPixelForValue(values[i]);
  7367. updateMinAndPrev();
  7368. }
  7369. prev = undefined;
  7370. for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {
  7371. curr = scale.getPixelForTick(i);
  7372. updateMinAndPrev();
  7373. }
  7374. return min;
  7375. }
  7376. function computeFitCategoryTraits(index, ruler, options, stackCount) {
  7377. const thickness = options.barThickness;
  7378. let size, ratio;
  7379. if (isNullOrUndef(thickness)) {
  7380. size = ruler.min * options.categoryPercentage;
  7381. ratio = options.barPercentage;
  7382. } else {
  7383. size = thickness * stackCount;
  7384. ratio = 1;
  7385. }
  7386. return {
  7387. chunk: size / stackCount,
  7388. ratio,
  7389. start: ruler.pixels[index] - (size / 2)
  7390. };
  7391. }
  7392. function computeFlexCategoryTraits(index, ruler, options, stackCount) {
  7393. const pixels = ruler.pixels;
  7394. const curr = pixels[index];
  7395. let prev = index > 0 ? pixels[index - 1] : null;
  7396. let next = index < pixels.length - 1 ? pixels[index + 1] : null;
  7397. const percent = options.categoryPercentage;
  7398. if (prev === null) {
  7399. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  7400. }
  7401. if (next === null) {
  7402. next = curr + curr - prev;
  7403. }
  7404. const start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  7405. const size = Math.abs(next - prev) / 2 * percent;
  7406. return {
  7407. chunk: size / stackCount,
  7408. ratio: options.barPercentage,
  7409. start
  7410. };
  7411. }
  7412. function parseFloatBar(entry, item, vScale, i) {
  7413. const startValue = vScale.parse(entry[0], i);
  7414. const endValue = vScale.parse(entry[1], i);
  7415. const min = Math.min(startValue, endValue);
  7416. const max = Math.max(startValue, endValue);
  7417. let barStart = min;
  7418. let barEnd = max;
  7419. if (Math.abs(min) > Math.abs(max)) {
  7420. barStart = max;
  7421. barEnd = min;
  7422. }
  7423. item[vScale.axis] = barEnd;
  7424. item._custom = {
  7425. barStart,
  7426. barEnd,
  7427. start: startValue,
  7428. end: endValue,
  7429. min,
  7430. max
  7431. };
  7432. }
  7433. function parseValue(entry, item, vScale, i) {
  7434. if (isArray(entry)) {
  7435. parseFloatBar(entry, item, vScale, i);
  7436. } else {
  7437. item[vScale.axis] = vScale.parse(entry, i);
  7438. }
  7439. return item;
  7440. }
  7441. function parseArrayOrPrimitive(meta, data, start, count) {
  7442. const iScale = meta.iScale;
  7443. const vScale = meta.vScale;
  7444. const labels = iScale.getLabels();
  7445. const singleScale = iScale === vScale;
  7446. const parsed = [];
  7447. let i, ilen, item, entry;
  7448. for (i = start, ilen = start + count; i < ilen; ++i) {
  7449. entry = data[i];
  7450. item = {};
  7451. item[iScale.axis] = singleScale || iScale.parse(labels[i], i);
  7452. parsed.push(parseValue(entry, item, vScale, i));
  7453. }
  7454. return parsed;
  7455. }
  7456. function isFloatBar(custom) {
  7457. return custom && custom.barStart !== undefined && custom.barEnd !== undefined;
  7458. }
  7459. function barSign(size, vScale, actualBase) {
  7460. if (size !== 0) {
  7461. return sign(size);
  7462. }
  7463. return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1);
  7464. }
  7465. function borderProps(properties) {
  7466. let reverse, start, end, top, bottom;
  7467. if (properties.horizontal) {
  7468. reverse = properties.base > properties.x;
  7469. start = 'left';
  7470. end = 'right';
  7471. } else {
  7472. reverse = properties.base < properties.y;
  7473. start = 'bottom';
  7474. end = 'top';
  7475. }
  7476. if (reverse) {
  7477. top = 'end';
  7478. bottom = 'start';
  7479. } else {
  7480. top = 'start';
  7481. bottom = 'end';
  7482. }
  7483. return {start, end, reverse, top, bottom};
  7484. }
  7485. function setBorderSkipped(properties, options, stack, index) {
  7486. let edge = options.borderSkipped;
  7487. const res = {};
  7488. if (!edge) {
  7489. properties.borderSkipped = res;
  7490. return;
  7491. }
  7492. const {start, end, reverse, top, bottom} = borderProps(properties);
  7493. if (edge === 'middle' && stack) {
  7494. properties.enableBorderRadius = true;
  7495. if ((stack._top || 0) === index) {
  7496. edge = top;
  7497. } else if ((stack._bottom || 0) === index) {
  7498. edge = bottom;
  7499. } else {
  7500. res[parseEdge(bottom, start, end, reverse)] = true;
  7501. edge = top;
  7502. }
  7503. }
  7504. res[parseEdge(edge, start, end, reverse)] = true;
  7505. properties.borderSkipped = res;
  7506. }
  7507. function parseEdge(edge, a, b, reverse) {
  7508. if (reverse) {
  7509. edge = swap(edge, a, b);
  7510. edge = startEnd(edge, b, a);
  7511. } else {
  7512. edge = startEnd(edge, a, b);
  7513. }
  7514. return edge;
  7515. }
  7516. function swap(orig, v1, v2) {
  7517. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  7518. }
  7519. function startEnd(v, start, end) {
  7520. return v === 'start' ? start : v === 'end' ? end : v;
  7521. }
  7522. class BarController extends DatasetController {
  7523. parsePrimitiveData(meta, data, start, count) {
  7524. return parseArrayOrPrimitive(meta, data, start, count);
  7525. }
  7526. parseArrayData(meta, data, start, count) {
  7527. return parseArrayOrPrimitive(meta, data, start, count);
  7528. }
  7529. parseObjectData(meta, data, start, count) {
  7530. const {iScale, vScale} = meta;
  7531. const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;
  7532. const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;
  7533. const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;
  7534. const parsed = [];
  7535. let i, ilen, item, obj;
  7536. for (i = start, ilen = start + count; i < ilen; ++i) {
  7537. obj = data[i];
  7538. item = {};
  7539. item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);
  7540. parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));
  7541. }
  7542. return parsed;
  7543. }
  7544. updateRangeFromParsed(range, scale, parsed, stack) {
  7545. super.updateRangeFromParsed(range, scale, parsed, stack);
  7546. const custom = parsed._custom;
  7547. if (custom && scale === this._cachedMeta.vScale) {
  7548. range.min = Math.min(range.min, custom.min);
  7549. range.max = Math.max(range.max, custom.max);
  7550. }
  7551. }
  7552. getMaxOverflow() {
  7553. return 0;
  7554. }
  7555. getLabelAndValue(index) {
  7556. const me = this;
  7557. const meta = me._cachedMeta;
  7558. const {iScale, vScale} = meta;
  7559. const parsed = me.getParsed(index);
  7560. const custom = parsed._custom;
  7561. const value = isFloatBar(custom)
  7562. ? '[' + custom.start + ', ' + custom.end + ']'
  7563. : '' + vScale.getLabelForValue(parsed[vScale.axis]);
  7564. return {
  7565. label: '' + iScale.getLabelForValue(parsed[iScale.axis]),
  7566. value
  7567. };
  7568. }
  7569. initialize() {
  7570. const me = this;
  7571. me.enableOptionSharing = true;
  7572. super.initialize();
  7573. const meta = me._cachedMeta;
  7574. meta.stack = me.getDataset().stack;
  7575. }
  7576. update(mode) {
  7577. const me = this;
  7578. const meta = me._cachedMeta;
  7579. me.updateElements(meta.data, 0, meta.data.length, mode);
  7580. }
  7581. updateElements(bars, start, count, mode) {
  7582. const me = this;
  7583. const reset = mode === 'reset';
  7584. const {index, _cachedMeta: {vScale}} = me;
  7585. const base = vScale.getBasePixel();
  7586. const horizontal = vScale.isHorizontal();
  7587. const ruler = me._getRuler();
  7588. const firstOpts = me.resolveDataElementOptions(start, mode);
  7589. const sharedOptions = me.getSharedOptions(firstOpts);
  7590. const includeOptions = me.includeOptions(mode, sharedOptions);
  7591. me.updateSharedOptions(sharedOptions, mode, firstOpts);
  7592. for (let i = start; i < start + count; i++) {
  7593. const parsed = me.getParsed(i);
  7594. const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {base, head: base} : me._calculateBarValuePixels(i);
  7595. const ipixels = me._calculateBarIndexPixels(i, ruler);
  7596. const stack = (parsed._stacks || {})[vScale.axis];
  7597. const properties = {
  7598. horizontal,
  7599. base: vpixels.base,
  7600. enableBorderRadius: !stack || isFloatBar(parsed._custom) || (index === stack._top || index === stack._bottom),
  7601. x: horizontal ? vpixels.head : ipixels.center,
  7602. y: horizontal ? ipixels.center : vpixels.head,
  7603. height: horizontal ? ipixels.size : Math.abs(vpixels.size),
  7604. width: horizontal ? Math.abs(vpixels.size) : ipixels.size
  7605. };
  7606. if (includeOptions) {
  7607. properties.options = sharedOptions || me.resolveDataElementOptions(i, bars[i].active ? 'active' : mode);
  7608. }
  7609. setBorderSkipped(properties, properties.options || bars[i].options, stack, index);
  7610. me.updateElement(bars[i], i, properties, mode);
  7611. }
  7612. }
  7613. _getStacks(last, dataIndex) {
  7614. const me = this;
  7615. const meta = me._cachedMeta;
  7616. const iScale = meta.iScale;
  7617. const metasets = iScale.getMatchingVisibleMetas(me._type);
  7618. const stacked = iScale.options.stacked;
  7619. const ilen = metasets.length;
  7620. const stacks = [];
  7621. let i, item;
  7622. for (i = 0; i < ilen; ++i) {
  7623. item = metasets[i];
  7624. if (!item.controller.options.grouped) {
  7625. continue;
  7626. }
  7627. if (typeof dataIndex !== 'undefined') {
  7628. const val = item.controller.getParsed(dataIndex)[
  7629. item.controller._cachedMeta.vScale.axis
  7630. ];
  7631. if (isNullOrUndef(val) || isNaN(val)) {
  7632. continue;
  7633. }
  7634. }
  7635. if (stacked === false || stacks.indexOf(item.stack) === -1 ||
  7636. (stacked === undefined && item.stack === undefined)) {
  7637. stacks.push(item.stack);
  7638. }
  7639. if (item.index === last) {
  7640. break;
  7641. }
  7642. }
  7643. if (!stacks.length) {
  7644. stacks.push(undefined);
  7645. }
  7646. return stacks;
  7647. }
  7648. _getStackCount(index) {
  7649. return this._getStacks(undefined, index).length;
  7650. }
  7651. _getStackIndex(datasetIndex, name, dataIndex) {
  7652. const stacks = this._getStacks(datasetIndex, dataIndex);
  7653. const index = (name !== undefined)
  7654. ? stacks.indexOf(name)
  7655. : -1;
  7656. return (index === -1)
  7657. ? stacks.length - 1
  7658. : index;
  7659. }
  7660. _getRuler() {
  7661. const me = this;
  7662. const opts = me.options;
  7663. const meta = me._cachedMeta;
  7664. const iScale = meta.iScale;
  7665. const pixels = [];
  7666. let i, ilen;
  7667. for (i = 0, ilen = meta.data.length; i < ilen; ++i) {
  7668. pixels.push(iScale.getPixelForValue(me.getParsed(i)[iScale.axis], i));
  7669. }
  7670. const barThickness = opts.barThickness;
  7671. const min = barThickness || computeMinSampleSize(iScale);
  7672. return {
  7673. min,
  7674. pixels,
  7675. start: iScale._startPixel,
  7676. end: iScale._endPixel,
  7677. stackCount: me._getStackCount(),
  7678. scale: iScale,
  7679. grouped: opts.grouped,
  7680. ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage
  7681. };
  7682. }
  7683. _calculateBarValuePixels(index) {
  7684. const me = this;
  7685. const {_cachedMeta: {vScale, _stacked}, options: {base: baseValue, minBarLength}} = me;
  7686. const actualBase = baseValue || 0;
  7687. const parsed = me.getParsed(index);
  7688. const custom = parsed._custom;
  7689. const floating = isFloatBar(custom);
  7690. let value = parsed[vScale.axis];
  7691. let start = 0;
  7692. let length = _stacked ? me.applyStack(vScale, parsed, _stacked) : value;
  7693. let head, size;
  7694. if (length !== value) {
  7695. start = length - value;
  7696. length = value;
  7697. }
  7698. if (floating) {
  7699. value = custom.barStart;
  7700. length = custom.barEnd - custom.barStart;
  7701. if (value !== 0 && sign(value) !== sign(custom.barEnd)) {
  7702. start = 0;
  7703. }
  7704. start += value;
  7705. }
  7706. const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;
  7707. let base = vScale.getPixelForValue(startValue);
  7708. if (me.chart.getDataVisibility(index)) {
  7709. head = vScale.getPixelForValue(start + length);
  7710. } else {
  7711. head = base;
  7712. }
  7713. size = head - base;
  7714. if (Math.abs(size) < minBarLength) {
  7715. size = barSign(size, vScale, actualBase) * minBarLength;
  7716. if (value === actualBase) {
  7717. base -= size / 2;
  7718. }
  7719. head = base + size;
  7720. }
  7721. if (base === vScale.getPixelForValue(actualBase)) {
  7722. const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2;
  7723. base += halfGrid;
  7724. size -= halfGrid;
  7725. }
  7726. return {
  7727. size,
  7728. base,
  7729. head,
  7730. center: head + size / 2
  7731. };
  7732. }
  7733. _calculateBarIndexPixels(index, ruler) {
  7734. const me = this;
  7735. const scale = ruler.scale;
  7736. const options = me.options;
  7737. const skipNull = options.skipNull;
  7738. const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);
  7739. let center, size;
  7740. if (ruler.grouped) {
  7741. const stackCount = skipNull ? me._getStackCount(index) : ruler.stackCount;
  7742. const range = options.barThickness === 'flex'
  7743. ? computeFlexCategoryTraits(index, ruler, options, stackCount)
  7744. : computeFitCategoryTraits(index, ruler, options, stackCount);
  7745. const stackIndex = me._getStackIndex(me.index, me._cachedMeta.stack, skipNull ? index : undefined);
  7746. center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  7747. size = Math.min(maxBarThickness, range.chunk * range.ratio);
  7748. } else {
  7749. center = scale.getPixelForValue(me.getParsed(index)[scale.axis], index);
  7750. size = Math.min(maxBarThickness, ruler.min * ruler.ratio);
  7751. }
  7752. return {
  7753. base: center - size / 2,
  7754. head: center + size / 2,
  7755. center,
  7756. size
  7757. };
  7758. }
  7759. draw() {
  7760. const me = this;
  7761. const meta = me._cachedMeta;
  7762. const vScale = meta.vScale;
  7763. const rects = meta.data;
  7764. const ilen = rects.length;
  7765. let i = 0;
  7766. for (; i < ilen; ++i) {
  7767. if (me.getParsed(i)[vScale.axis] !== null) {
  7768. rects[i].draw(me._ctx);
  7769. }
  7770. }
  7771. }
  7772. }
  7773. BarController.id = 'bar';
  7774. BarController.defaults = {
  7775. datasetElementType: false,
  7776. dataElementType: 'bar',
  7777. categoryPercentage: 0.8,
  7778. barPercentage: 0.9,
  7779. grouped: true,
  7780. animations: {
  7781. numbers: {
  7782. type: 'number',
  7783. properties: ['x', 'y', 'base', 'width', 'height']
  7784. }
  7785. }
  7786. };
  7787. BarController.overrides = {
  7788. scales: {
  7789. _index_: {
  7790. type: 'category',
  7791. offset: true,
  7792. grid: {
  7793. offset: true
  7794. }
  7795. },
  7796. _value_: {
  7797. type: 'linear',
  7798. beginAtZero: true,
  7799. }
  7800. }
  7801. };
  7802. class BubbleController extends DatasetController {
  7803. initialize() {
  7804. this.enableOptionSharing = true;
  7805. super.initialize();
  7806. }
  7807. parseObjectData(meta, data, start, count) {
  7808. const {xScale, yScale} = meta;
  7809. const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;
  7810. const parsed = [];
  7811. let i, ilen, item;
  7812. for (i = start, ilen = start + count; i < ilen; ++i) {
  7813. item = data[i];
  7814. parsed.push({
  7815. x: xScale.parse(resolveObjectKey(item, xAxisKey), i),
  7816. y: yScale.parse(resolveObjectKey(item, yAxisKey), i),
  7817. _custom: item && item.r && +item.r
  7818. });
  7819. }
  7820. return parsed;
  7821. }
  7822. getMaxOverflow() {
  7823. const {data, _parsed} = this._cachedMeta;
  7824. let max = 0;
  7825. for (let i = data.length - 1; i >= 0; --i) {
  7826. max = Math.max(max, data[i].size() / 2, _parsed[i]._custom);
  7827. }
  7828. return max > 0 && max;
  7829. }
  7830. getLabelAndValue(index) {
  7831. const me = this;
  7832. const meta = me._cachedMeta;
  7833. const {xScale, yScale} = meta;
  7834. const parsed = me.getParsed(index);
  7835. const x = xScale.getLabelForValue(parsed.x);
  7836. const y = yScale.getLabelForValue(parsed.y);
  7837. const r = parsed._custom;
  7838. return {
  7839. label: meta.label,
  7840. value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'
  7841. };
  7842. }
  7843. update(mode) {
  7844. const me = this;
  7845. const points = me._cachedMeta.data;
  7846. me.updateElements(points, 0, points.length, mode);
  7847. }
  7848. updateElements(points, start, count, mode) {
  7849. const me = this;
  7850. const reset = mode === 'reset';
  7851. const {iScale, vScale} = me._cachedMeta;
  7852. const firstOpts = me.resolveDataElementOptions(start, mode);
  7853. const sharedOptions = me.getSharedOptions(firstOpts);
  7854. const includeOptions = me.includeOptions(mode, sharedOptions);
  7855. const iAxis = iScale.axis;
  7856. const vAxis = vScale.axis;
  7857. for (let i = start; i < start + count; i++) {
  7858. const point = points[i];
  7859. const parsed = !reset && me.getParsed(i);
  7860. const properties = {};
  7861. const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]);
  7862. const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]);
  7863. properties.skip = isNaN(iPixel) || isNaN(vPixel);
  7864. if (includeOptions) {
  7865. properties.options = me.resolveDataElementOptions(i, point.active ? 'active' : mode);
  7866. if (reset) {
  7867. properties.options.radius = 0;
  7868. }
  7869. }
  7870. me.updateElement(point, i, properties, mode);
  7871. }
  7872. me.updateSharedOptions(sharedOptions, mode, firstOpts);
  7873. }
  7874. resolveDataElementOptions(index, mode) {
  7875. const parsed = this.getParsed(index);
  7876. let values = super.resolveDataElementOptions(index, mode);
  7877. if (values.$shared) {
  7878. values = Object.assign({}, values, {$shared: false});
  7879. }
  7880. const radius = values.radius;
  7881. if (mode !== 'active') {
  7882. values.radius = 0;
  7883. }
  7884. values.radius += valueOrDefault(parsed && parsed._custom, radius);
  7885. return values;
  7886. }
  7887. }
  7888. BubbleController.id = 'bubble';
  7889. BubbleController.defaults = {
  7890. datasetElementType: false,
  7891. dataElementType: 'point',
  7892. animations: {
  7893. numbers: {
  7894. type: 'number',
  7895. properties: ['x', 'y', 'borderWidth', 'radius']
  7896. }
  7897. }
  7898. };
  7899. BubbleController.overrides = {
  7900. scales: {
  7901. x: {
  7902. type: 'linear'
  7903. },
  7904. y: {
  7905. type: 'linear'
  7906. }
  7907. },
  7908. plugins: {
  7909. tooltip: {
  7910. callbacks: {
  7911. title() {
  7912. return '';
  7913. }
  7914. }
  7915. }
  7916. }
  7917. };
  7918. function getRatioAndOffset(rotation, circumference, cutout) {
  7919. let ratioX = 1;
  7920. let ratioY = 1;
  7921. let offsetX = 0;
  7922. let offsetY = 0;
  7923. if (circumference < TAU) {
  7924. const startAngle = rotation;
  7925. const endAngle = startAngle + circumference;
  7926. const startX = Math.cos(startAngle);
  7927. const startY = Math.sin(startAngle);
  7928. const endX = Math.cos(endAngle);
  7929. const endY = Math.sin(endAngle);
  7930. const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout);
  7931. const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout);
  7932. const maxX = calcMax(0, startX, endX);
  7933. const maxY = calcMax(HALF_PI, startY, endY);
  7934. const minX = calcMin(PI, startX, endX);
  7935. const minY = calcMin(PI + HALF_PI, startY, endY);
  7936. ratioX = (maxX - minX) / 2;
  7937. ratioY = (maxY - minY) / 2;
  7938. offsetX = -(maxX + minX) / 2;
  7939. offsetY = -(maxY + minY) / 2;
  7940. }
  7941. return {ratioX, ratioY, offsetX, offsetY};
  7942. }
  7943. class DoughnutController extends DatasetController {
  7944. constructor(chart, datasetIndex) {
  7945. super(chart, datasetIndex);
  7946. this.enableOptionSharing = true;
  7947. this.innerRadius = undefined;
  7948. this.outerRadius = undefined;
  7949. this.offsetX = undefined;
  7950. this.offsetY = undefined;
  7951. }
  7952. linkScales() {}
  7953. parse(start, count) {
  7954. const data = this.getDataset().data;
  7955. const meta = this._cachedMeta;
  7956. let i, ilen;
  7957. for (i = start, ilen = start + count; i < ilen; ++i) {
  7958. meta._parsed[i] = +data[i];
  7959. }
  7960. }
  7961. _getRotation() {
  7962. return toRadians(this.options.rotation - 90);
  7963. }
  7964. _getCircumference() {
  7965. return toRadians(this.options.circumference);
  7966. }
  7967. _getRotationExtents() {
  7968. let min = TAU;
  7969. let max = -TAU;
  7970. const me = this;
  7971. for (let i = 0; i < me.chart.data.datasets.length; ++i) {
  7972. if (me.chart.isDatasetVisible(i)) {
  7973. const controller = me.chart.getDatasetMeta(i).controller;
  7974. const rotation = controller._getRotation();
  7975. const circumference = controller._getCircumference();
  7976. min = Math.min(min, rotation);
  7977. max = Math.max(max, rotation + circumference);
  7978. }
  7979. }
  7980. return {
  7981. rotation: min,
  7982. circumference: max - min,
  7983. };
  7984. }
  7985. update(mode) {
  7986. const me = this;
  7987. const chart = me.chart;
  7988. const {chartArea} = chart;
  7989. const meta = me._cachedMeta;
  7990. const arcs = meta.data;
  7991. const spacing = me.getMaxBorderWidth() + me.getMaxOffset(arcs) + me.options.spacing;
  7992. const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);
  7993. const cutout = Math.min(toPercentage(me.options.cutout, maxSize), 1);
  7994. const chartWeight = me._getRingWeight(me.index);
  7995. const {circumference, rotation} = me._getRotationExtents();
  7996. const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout);
  7997. const maxWidth = (chartArea.width - spacing) / ratioX;
  7998. const maxHeight = (chartArea.height - spacing) / ratioY;
  7999. const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  8000. const outerRadius = toDimension(me.options.radius, maxRadius);
  8001. const innerRadius = Math.max(outerRadius * cutout, 0);
  8002. const radiusLength = (outerRadius - innerRadius) / me._getVisibleDatasetWeightTotal();
  8003. me.offsetX = offsetX * outerRadius;
  8004. me.offsetY = offsetY * outerRadius;
  8005. meta.total = me.calculateTotal();
  8006. me.outerRadius = outerRadius - radiusLength * me._getRingWeightOffset(me.index);
  8007. me.innerRadius = Math.max(me.outerRadius - radiusLength * chartWeight, 0);
  8008. me.updateElements(arcs, 0, arcs.length, mode);
  8009. }
  8010. _circumference(i, reset) {
  8011. const me = this;
  8012. const opts = me.options;
  8013. const meta = me._cachedMeta;
  8014. const circumference = me._getCircumference();
  8015. if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) {
  8016. return 0;
  8017. }
  8018. return me.calculateCircumference(meta._parsed[i] * circumference / TAU);
  8019. }
  8020. updateElements(arcs, start, count, mode) {
  8021. const me = this;
  8022. const reset = mode === 'reset';
  8023. const chart = me.chart;
  8024. const chartArea = chart.chartArea;
  8025. const opts = chart.options;
  8026. const animationOpts = opts.animation;
  8027. const centerX = (chartArea.left + chartArea.right) / 2;
  8028. const centerY = (chartArea.top + chartArea.bottom) / 2;
  8029. const animateScale = reset && animationOpts.animateScale;
  8030. const innerRadius = animateScale ? 0 : me.innerRadius;
  8031. const outerRadius = animateScale ? 0 : me.outerRadius;
  8032. const firstOpts = me.resolveDataElementOptions(start, mode);
  8033. const sharedOptions = me.getSharedOptions(firstOpts);
  8034. const includeOptions = me.includeOptions(mode, sharedOptions);
  8035. let startAngle = me._getRotation();
  8036. let i;
  8037. for (i = 0; i < start; ++i) {
  8038. startAngle += me._circumference(i, reset);
  8039. }
  8040. for (i = start; i < start + count; ++i) {
  8041. const circumference = me._circumference(i, reset);
  8042. const arc = arcs[i];
  8043. const properties = {
  8044. x: centerX + me.offsetX,
  8045. y: centerY + me.offsetY,
  8046. startAngle,
  8047. endAngle: startAngle + circumference,
  8048. circumference,
  8049. outerRadius,
  8050. innerRadius
  8051. };
  8052. if (includeOptions) {
  8053. properties.options = sharedOptions || me.resolveDataElementOptions(i, arc.active ? 'active' : mode);
  8054. }
  8055. startAngle += circumference;
  8056. me.updateElement(arc, i, properties, mode);
  8057. }
  8058. me.updateSharedOptions(sharedOptions, mode, firstOpts);
  8059. }
  8060. calculateTotal() {
  8061. const meta = this._cachedMeta;
  8062. const metaData = meta.data;
  8063. let total = 0;
  8064. let i;
  8065. for (i = 0; i < metaData.length; i++) {
  8066. const value = meta._parsed[i];
  8067. if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) {
  8068. total += Math.abs(value);
  8069. }
  8070. }
  8071. return total;
  8072. }
  8073. calculateCircumference(value) {
  8074. const total = this._cachedMeta.total;
  8075. if (total > 0 && !isNaN(value)) {
  8076. return TAU * (Math.abs(value) / total);
  8077. }
  8078. return 0;
  8079. }
  8080. getLabelAndValue(index) {
  8081. const me = this;
  8082. const meta = me._cachedMeta;
  8083. const chart = me.chart;
  8084. const labels = chart.data.labels || [];
  8085. const value = formatNumber(meta._parsed[index], chart.options.locale);
  8086. return {
  8087. label: labels[index] || '',
  8088. value,
  8089. };
  8090. }
  8091. getMaxBorderWidth(arcs) {
  8092. const me = this;
  8093. let max = 0;
  8094. const chart = me.chart;
  8095. let i, ilen, meta, controller, options;
  8096. if (!arcs) {
  8097. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  8098. if (chart.isDatasetVisible(i)) {
  8099. meta = chart.getDatasetMeta(i);
  8100. arcs = meta.data;
  8101. controller = meta.controller;
  8102. if (controller !== me) {
  8103. controller.configure();
  8104. }
  8105. break;
  8106. }
  8107. }
  8108. }
  8109. if (!arcs) {
  8110. return 0;
  8111. }
  8112. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  8113. options = controller.resolveDataElementOptions(i);
  8114. if (options.borderAlign !== 'inner') {
  8115. max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);
  8116. }
  8117. }
  8118. return max;
  8119. }
  8120. getMaxOffset(arcs) {
  8121. let max = 0;
  8122. for (let i = 0, ilen = arcs.length; i < ilen; ++i) {
  8123. const options = this.resolveDataElementOptions(i);
  8124. max = Math.max(max, options.offset || 0, options.hoverOffset || 0);
  8125. }
  8126. return max;
  8127. }
  8128. _getRingWeightOffset(datasetIndex) {
  8129. let ringWeightOffset = 0;
  8130. for (let i = 0; i < datasetIndex; ++i) {
  8131. if (this.chart.isDatasetVisible(i)) {
  8132. ringWeightOffset += this._getRingWeight(i);
  8133. }
  8134. }
  8135. return ringWeightOffset;
  8136. }
  8137. _getRingWeight(datasetIndex) {
  8138. return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);
  8139. }
  8140. _getVisibleDatasetWeightTotal() {
  8141. return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;
  8142. }
  8143. }
  8144. DoughnutController.id = 'doughnut';
  8145. DoughnutController.defaults = {
  8146. datasetElementType: false,
  8147. dataElementType: 'arc',
  8148. animation: {
  8149. animateRotate: true,
  8150. animateScale: false
  8151. },
  8152. animations: {
  8153. numbers: {
  8154. type: 'number',
  8155. properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing']
  8156. },
  8157. },
  8158. cutout: '50%',
  8159. rotation: 0,
  8160. circumference: 360,
  8161. radius: '100%',
  8162. spacing: 0,
  8163. indexAxis: 'r',
  8164. };
  8165. DoughnutController.descriptors = {
  8166. _scriptable: (name) => name !== 'spacing',
  8167. _indexable: (name) => name !== 'spacing',
  8168. };
  8169. DoughnutController.overrides = {
  8170. aspectRatio: 1,
  8171. plugins: {
  8172. legend: {
  8173. labels: {
  8174. generateLabels(chart) {
  8175. const data = chart.data;
  8176. if (data.labels.length && data.datasets.length) {
  8177. const {labels: {pointStyle}} = chart.legend.options;
  8178. return data.labels.map((label, i) => {
  8179. const meta = chart.getDatasetMeta(0);
  8180. const style = meta.controller.getStyle(i);
  8181. return {
  8182. text: label,
  8183. fillStyle: style.backgroundColor,
  8184. strokeStyle: style.borderColor,
  8185. lineWidth: style.borderWidth,
  8186. pointStyle: pointStyle,
  8187. hidden: !chart.getDataVisibility(i),
  8188. index: i
  8189. };
  8190. });
  8191. }
  8192. return [];
  8193. }
  8194. },
  8195. onClick(e, legendItem, legend) {
  8196. legend.chart.toggleDataVisibility(legendItem.index);
  8197. legend.chart.update();
  8198. }
  8199. },
  8200. tooltip: {
  8201. callbacks: {
  8202. title() {
  8203. return '';
  8204. },
  8205. label(tooltipItem) {
  8206. let dataLabel = tooltipItem.label;
  8207. const value = ': ' + tooltipItem.formattedValue;
  8208. if (isArray(dataLabel)) {
  8209. dataLabel = dataLabel.slice();
  8210. dataLabel[0] += value;
  8211. } else {
  8212. dataLabel += value;
  8213. }
  8214. return dataLabel;
  8215. }
  8216. }
  8217. }
  8218. }
  8219. };
  8220. class LineController extends DatasetController {
  8221. initialize() {
  8222. this.enableOptionSharing = true;
  8223. super.initialize();
  8224. }
  8225. update(mode) {
  8226. const me = this;
  8227. const meta = me._cachedMeta;
  8228. const {dataset: line, data: points = [], _dataset} = meta;
  8229. const animationsDisabled = me.chart._animationsDisabled;
  8230. let {start, count} = getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
  8231. me._drawStart = start;
  8232. me._drawCount = count;
  8233. if (scaleRangesChanged(meta)) {
  8234. start = 0;
  8235. count = points.length;
  8236. }
  8237. line._datasetIndex = me.index;
  8238. line._decimated = !!_dataset._decimated;
  8239. line.points = points;
  8240. const options = me.resolveDatasetElementOptions(mode);
  8241. if (!me.options.showLine) {
  8242. options.borderWidth = 0;
  8243. }
  8244. options.segment = me.options.segment;
  8245. me.updateElement(line, undefined, {
  8246. animated: !animationsDisabled,
  8247. options
  8248. }, mode);
  8249. me.updateElements(points, start, count, mode);
  8250. }
  8251. updateElements(points, start, count, mode) {
  8252. const me = this;
  8253. const reset = mode === 'reset';
  8254. const {iScale, vScale, _stacked} = me._cachedMeta;
  8255. const firstOpts = me.resolveDataElementOptions(start, mode);
  8256. const sharedOptions = me.getSharedOptions(firstOpts);
  8257. const includeOptions = me.includeOptions(mode, sharedOptions);
  8258. const iAxis = iScale.axis;
  8259. const vAxis = vScale.axis;
  8260. const spanGaps = me.options.spanGaps;
  8261. const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
  8262. const directUpdate = me.chart._animationsDisabled || reset || mode === 'none';
  8263. let prevParsed = start > 0 && me.getParsed(start - 1);
  8264. for (let i = start; i < start + count; ++i) {
  8265. const point = points[i];
  8266. const parsed = me.getParsed(i);
  8267. const properties = directUpdate ? point : {};
  8268. const nullData = isNullOrUndef(parsed[vAxis]);
  8269. const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i);
  8270. const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? me.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i);
  8271. properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData;
  8272. properties.stop = i > 0 && (parsed[iAxis] - prevParsed[iAxis]) > maxGapLength;
  8273. properties.parsed = parsed;
  8274. if (includeOptions) {
  8275. properties.options = sharedOptions || me.resolveDataElementOptions(i, point.active ? 'active' : mode);
  8276. }
  8277. if (!directUpdate) {
  8278. me.updateElement(point, i, properties, mode);
  8279. }
  8280. prevParsed = parsed;
  8281. }
  8282. me.updateSharedOptions(sharedOptions, mode, firstOpts);
  8283. }
  8284. getMaxOverflow() {
  8285. const me = this;
  8286. const meta = me._cachedMeta;
  8287. const dataset = meta.dataset;
  8288. const border = dataset.options && dataset.options.borderWidth || 0;
  8289. const data = meta.data || [];
  8290. if (!data.length) {
  8291. return border;
  8292. }
  8293. const firstPoint = data[0].size(me.resolveDataElementOptions(0));
  8294. const lastPoint = data[data.length - 1].size(me.resolveDataElementOptions(data.length - 1));
  8295. return Math.max(border, firstPoint, lastPoint) / 2;
  8296. }
  8297. draw() {
  8298. const meta = this._cachedMeta;
  8299. meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis);
  8300. super.draw();
  8301. }
  8302. }
  8303. LineController.id = 'line';
  8304. LineController.defaults = {
  8305. datasetElementType: 'line',
  8306. dataElementType: 'point',
  8307. showLine: true,
  8308. spanGaps: false,
  8309. };
  8310. LineController.overrides = {
  8311. scales: {
  8312. _index_: {
  8313. type: 'category',
  8314. },
  8315. _value_: {
  8316. type: 'linear',
  8317. },
  8318. }
  8319. };
  8320. function getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) {
  8321. const pointCount = points.length;
  8322. let start = 0;
  8323. let count = pointCount;
  8324. if (meta._sorted) {
  8325. const {iScale, _parsed} = meta;
  8326. const axis = iScale.axis;
  8327. const {min, max, minDefined, maxDefined} = iScale.getUserBounds();
  8328. if (minDefined) {
  8329. start = _limitValue(Math.min(
  8330. _lookupByKey(_parsed, iScale.axis, min).lo,
  8331. animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo),
  8332. 0, pointCount - 1);
  8333. }
  8334. if (maxDefined) {
  8335. count = _limitValue(Math.max(
  8336. _lookupByKey(_parsed, iScale.axis, max).hi + 1,
  8337. animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max)).hi + 1),
  8338. start, pointCount) - start;
  8339. } else {
  8340. count = pointCount - start;
  8341. }
  8342. }
  8343. return {start, count};
  8344. }
  8345. function scaleRangesChanged(meta) {
  8346. const {xScale, yScale, _scaleRanges} = meta;
  8347. const newRanges = {
  8348. xmin: xScale.min,
  8349. xmax: xScale.max,
  8350. ymin: yScale.min,
  8351. ymax: yScale.max
  8352. };
  8353. if (!_scaleRanges) {
  8354. meta._scaleRanges = newRanges;
  8355. return true;
  8356. }
  8357. const changed = _scaleRanges.xmin !== xScale.min
  8358. || _scaleRanges.xmax !== xScale.max
  8359. || _scaleRanges.ymin !== yScale.min
  8360. || _scaleRanges.ymax !== yScale.max;
  8361. Object.assign(_scaleRanges, newRanges);
  8362. return changed;
  8363. }
  8364. class PolarAreaController extends DatasetController {
  8365. constructor(chart, datasetIndex) {
  8366. super(chart, datasetIndex);
  8367. this.innerRadius = undefined;
  8368. this.outerRadius = undefined;
  8369. }
  8370. getLabelAndValue(index) {
  8371. const me = this;
  8372. const meta = me._cachedMeta;
  8373. const chart = me.chart;
  8374. const labels = chart.data.labels || [];
  8375. const value = formatNumber(meta._parsed[index].r, chart.options.locale);
  8376. return {
  8377. label: labels[index] || '',
  8378. value,
  8379. };
  8380. }
  8381. update(mode) {
  8382. const arcs = this._cachedMeta.data;
  8383. this._updateRadius();
  8384. this.updateElements(arcs, 0, arcs.length, mode);
  8385. }
  8386. _updateRadius() {
  8387. const me = this;
  8388. const chart = me.chart;
  8389. const chartArea = chart.chartArea;
  8390. const opts = chart.options;
  8391. const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  8392. const outerRadius = Math.max(minSize / 2, 0);
  8393. const innerRadius = Math.max(opts.cutoutPercentage ? (outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  8394. const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();
  8395. me.outerRadius = outerRadius - (radiusLength * me.index);
  8396. me.innerRadius = me.outerRadius - radiusLength;
  8397. }
  8398. updateElements(arcs, start, count, mode) {
  8399. const me = this;
  8400. const reset = mode === 'reset';
  8401. const chart = me.chart;
  8402. const dataset = me.getDataset();
  8403. const opts = chart.options;
  8404. const animationOpts = opts.animation;
  8405. const scale = me._cachedMeta.rScale;
  8406. const centerX = scale.xCenter;
  8407. const centerY = scale.yCenter;
  8408. const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;
  8409. let angle = datasetStartAngle;
  8410. let i;
  8411. const defaultAngle = 360 / me.countVisibleElements();
  8412. for (i = 0; i < start; ++i) {
  8413. angle += me._computeAngle(i, mode, defaultAngle);
  8414. }
  8415. for (i = start; i < start + count; i++) {
  8416. const arc = arcs[i];
  8417. let startAngle = angle;
  8418. let endAngle = angle + me._computeAngle(i, mode, defaultAngle);
  8419. let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(dataset.data[i]) : 0;
  8420. angle = endAngle;
  8421. if (reset) {
  8422. if (animationOpts.animateScale) {
  8423. outerRadius = 0;
  8424. }
  8425. if (animationOpts.animateRotate) {
  8426. startAngle = endAngle = datasetStartAngle;
  8427. }
  8428. }
  8429. const properties = {
  8430. x: centerX,
  8431. y: centerY,
  8432. innerRadius: 0,
  8433. outerRadius,
  8434. startAngle,
  8435. endAngle,
  8436. options: me.resolveDataElementOptions(i, arc.active ? 'active' : mode)
  8437. };
  8438. me.updateElement(arc, i, properties, mode);
  8439. }
  8440. }
  8441. countVisibleElements() {
  8442. const dataset = this.getDataset();
  8443. const meta = this._cachedMeta;
  8444. let count = 0;
  8445. meta.data.forEach((element, index) => {
  8446. if (!isNaN(dataset.data[index]) && this.chart.getDataVisibility(index)) {
  8447. count++;
  8448. }
  8449. });
  8450. return count;
  8451. }
  8452. _computeAngle(index, mode, defaultAngle) {
  8453. return this.chart.getDataVisibility(index)
  8454. ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle)
  8455. : 0;
  8456. }
  8457. }
  8458. PolarAreaController.id = 'polarArea';
  8459. PolarAreaController.defaults = {
  8460. dataElementType: 'arc',
  8461. animation: {
  8462. animateRotate: true,
  8463. animateScale: true
  8464. },
  8465. animations: {
  8466. numbers: {
  8467. type: 'number',
  8468. properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius']
  8469. },
  8470. },
  8471. indexAxis: 'r',
  8472. startAngle: 0,
  8473. };
  8474. PolarAreaController.overrides = {
  8475. aspectRatio: 1,
  8476. plugins: {
  8477. legend: {
  8478. labels: {
  8479. generateLabels(chart) {
  8480. const data = chart.data;
  8481. if (data.labels.length && data.datasets.length) {
  8482. const {labels: {pointStyle}} = chart.legend.options;
  8483. return data.labels.map((label, i) => {
  8484. const meta = chart.getDatasetMeta(0);
  8485. const style = meta.controller.getStyle(i);
  8486. return {
  8487. text: label,
  8488. fillStyle: style.backgroundColor,
  8489. strokeStyle: style.borderColor,
  8490. lineWidth: style.borderWidth,
  8491. pointStyle: pointStyle,
  8492. hidden: !chart.getDataVisibility(i),
  8493. index: i
  8494. };
  8495. });
  8496. }
  8497. return [];
  8498. }
  8499. },
  8500. onClick(e, legendItem, legend) {
  8501. legend.chart.toggleDataVisibility(legendItem.index);
  8502. legend.chart.update();
  8503. }
  8504. },
  8505. tooltip: {
  8506. callbacks: {
  8507. title() {
  8508. return '';
  8509. },
  8510. label(context) {
  8511. return context.chart.data.labels[context.dataIndex] + ': ' + context.formattedValue;
  8512. }
  8513. }
  8514. }
  8515. },
  8516. scales: {
  8517. r: {
  8518. type: 'radialLinear',
  8519. angleLines: {
  8520. display: false
  8521. },
  8522. beginAtZero: true,
  8523. grid: {
  8524. circular: true
  8525. },
  8526. pointLabels: {
  8527. display: false
  8528. },
  8529. startAngle: 0
  8530. }
  8531. }
  8532. };
  8533. class PieController extends DoughnutController {
  8534. }
  8535. PieController.id = 'pie';
  8536. PieController.defaults = {
  8537. cutout: 0,
  8538. rotation: 0,
  8539. circumference: 360,
  8540. radius: '100%'
  8541. };
  8542. class RadarController extends DatasetController {
  8543. getLabelAndValue(index) {
  8544. const me = this;
  8545. const vScale = me._cachedMeta.vScale;
  8546. const parsed = me.getParsed(index);
  8547. return {
  8548. label: vScale.getLabels()[index],
  8549. value: '' + vScale.getLabelForValue(parsed[vScale.axis])
  8550. };
  8551. }
  8552. update(mode) {
  8553. const me = this;
  8554. const meta = me._cachedMeta;
  8555. const line = meta.dataset;
  8556. const points = meta.data || [];
  8557. const labels = meta.iScale.getLabels();
  8558. line.points = points;
  8559. if (mode !== 'resize') {
  8560. const options = me.resolveDatasetElementOptions(mode);
  8561. if (!me.options.showLine) {
  8562. options.borderWidth = 0;
  8563. }
  8564. const properties = {
  8565. _loop: true,
  8566. _fullLoop: labels.length === points.length,
  8567. options
  8568. };
  8569. me.updateElement(line, undefined, properties, mode);
  8570. }
  8571. me.updateElements(points, 0, points.length, mode);
  8572. }
  8573. updateElements(points, start, count, mode) {
  8574. const me = this;
  8575. const dataset = me.getDataset();
  8576. const scale = me._cachedMeta.rScale;
  8577. const reset = mode === 'reset';
  8578. for (let i = start; i < start + count; i++) {
  8579. const point = points[i];
  8580. const options = me.resolveDataElementOptions(i, point.active ? 'active' : mode);
  8581. const pointPosition = scale.getPointPositionForValue(i, dataset.data[i]);
  8582. const x = reset ? scale.xCenter : pointPosition.x;
  8583. const y = reset ? scale.yCenter : pointPosition.y;
  8584. const properties = {
  8585. x,
  8586. y,
  8587. angle: pointPosition.angle,
  8588. skip: isNaN(x) || isNaN(y),
  8589. options
  8590. };
  8591. me.updateElement(point, i, properties, mode);
  8592. }
  8593. }
  8594. }
  8595. RadarController.id = 'radar';
  8596. RadarController.defaults = {
  8597. datasetElementType: 'line',
  8598. dataElementType: 'point',
  8599. indexAxis: 'r',
  8600. showLine: true,
  8601. elements: {
  8602. line: {
  8603. fill: 'start'
  8604. }
  8605. },
  8606. };
  8607. RadarController.overrides = {
  8608. aspectRatio: 1,
  8609. scales: {
  8610. r: {
  8611. type: 'radialLinear',
  8612. }
  8613. }
  8614. };
  8615. class ScatterController extends LineController {
  8616. }
  8617. ScatterController.id = 'scatter';
  8618. ScatterController.defaults = {
  8619. showLine: false,
  8620. fill: false
  8621. };
  8622. ScatterController.overrides = {
  8623. interaction: {
  8624. mode: 'point'
  8625. },
  8626. plugins: {
  8627. tooltip: {
  8628. callbacks: {
  8629. title() {
  8630. return '';
  8631. },
  8632. label(item) {
  8633. return '(' + item.label + ', ' + item.formattedValue + ')';
  8634. }
  8635. }
  8636. }
  8637. },
  8638. scales: {
  8639. x: {
  8640. type: 'linear'
  8641. },
  8642. y: {
  8643. type: 'linear'
  8644. }
  8645. }
  8646. };
  8647. var controllers = /*#__PURE__*/Object.freeze({
  8648. __proto__: null,
  8649. BarController: BarController,
  8650. BubbleController: BubbleController,
  8651. DoughnutController: DoughnutController,
  8652. LineController: LineController,
  8653. PolarAreaController: PolarAreaController,
  8654. PieController: PieController,
  8655. RadarController: RadarController,
  8656. ScatterController: ScatterController
  8657. });
  8658. function clipArc(ctx, element, endAngle) {
  8659. const {startAngle, pixelMargin, x, y, outerRadius, innerRadius} = element;
  8660. let angleMargin = pixelMargin / outerRadius;
  8661. ctx.beginPath();
  8662. ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  8663. if (innerRadius > pixelMargin) {
  8664. angleMargin = pixelMargin / innerRadius;
  8665. ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);
  8666. } else {
  8667. ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI);
  8668. }
  8669. ctx.closePath();
  8670. ctx.clip();
  8671. }
  8672. function toRadiusCorners(value) {
  8673. return _readValueToProps(value, ['outerStart', 'outerEnd', 'innerStart', 'innerEnd']);
  8674. }
  8675. function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) {
  8676. const o = toRadiusCorners(arc.options.borderRadius);
  8677. const halfThickness = (outerRadius - innerRadius) / 2;
  8678. const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);
  8679. const computeOuterLimit = (val) => {
  8680. const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;
  8681. return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit));
  8682. };
  8683. return {
  8684. outerStart: computeOuterLimit(o.outerStart),
  8685. outerEnd: computeOuterLimit(o.outerEnd),
  8686. innerStart: _limitValue(o.innerStart, 0, innerLimit),
  8687. innerEnd: _limitValue(o.innerEnd, 0, innerLimit),
  8688. };
  8689. }
  8690. function rThetaToXY(r, theta, x, y) {
  8691. return {
  8692. x: x + r * Math.cos(theta),
  8693. y: y + r * Math.sin(theta),
  8694. };
  8695. }
  8696. function pathArc(ctx, element, offset, spacing, end) {
  8697. const {x, y, startAngle: start, pixelMargin, innerRadius: innerR} = element;
  8698. const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0);
  8699. const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0;
  8700. let spacingOffset = 0;
  8701. const alpha = end - start;
  8702. if (spacing) {
  8703. const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0;
  8704. const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0;
  8705. const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2;
  8706. const adjustedAngle = avNogSpacingRadius !== 0 ? (alpha * avNogSpacingRadius) / (avNogSpacingRadius + spacing) : alpha;
  8707. spacingOffset = (alpha - adjustedAngle) / 2;
  8708. }
  8709. const beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius;
  8710. const angleOffset = (alpha - beta) / 2;
  8711. const startAngle = start + angleOffset + spacingOffset;
  8712. const endAngle = end - angleOffset - spacingOffset;
  8713. const {outerStart, outerEnd, innerStart, innerEnd} = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle);
  8714. const outerStartAdjustedRadius = outerRadius - outerStart;
  8715. const outerEndAdjustedRadius = outerRadius - outerEnd;
  8716. const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;
  8717. const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;
  8718. const innerStartAdjustedRadius = innerRadius + innerStart;
  8719. const innerEndAdjustedRadius = innerRadius + innerEnd;
  8720. const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;
  8721. const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;
  8722. ctx.beginPath();
  8723. ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerEndAdjustedAngle);
  8724. if (outerEnd > 0) {
  8725. const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);
  8726. ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);
  8727. }
  8728. const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);
  8729. ctx.lineTo(p4.x, p4.y);
  8730. if (innerEnd > 0) {
  8731. const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);
  8732. ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);
  8733. }
  8734. ctx.arc(x, y, innerRadius, endAngle - (innerEnd / innerRadius), startAngle + (innerStart / innerRadius), true);
  8735. if (innerStart > 0) {
  8736. const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);
  8737. ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);
  8738. }
  8739. const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);
  8740. ctx.lineTo(p8.x, p8.y);
  8741. if (outerStart > 0) {
  8742. const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);
  8743. ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);
  8744. }
  8745. ctx.closePath();
  8746. }
  8747. function drawArc(ctx, element, offset, spacing) {
  8748. const {fullCircles, startAngle, circumference} = element;
  8749. let endAngle = element.endAngle;
  8750. if (fullCircles) {
  8751. pathArc(ctx, element, offset, spacing, startAngle + TAU);
  8752. for (let i = 0; i < fullCircles; ++i) {
  8753. ctx.fill();
  8754. }
  8755. if (!isNaN(circumference)) {
  8756. endAngle = startAngle + circumference % TAU;
  8757. if (circumference % TAU === 0) {
  8758. endAngle += TAU;
  8759. }
  8760. }
  8761. }
  8762. pathArc(ctx, element, offset, spacing, endAngle);
  8763. ctx.fill();
  8764. return endAngle;
  8765. }
  8766. function drawFullCircleBorders(ctx, element, inner) {
  8767. const {x, y, startAngle, pixelMargin, fullCircles} = element;
  8768. const outerRadius = Math.max(element.outerRadius - pixelMargin, 0);
  8769. const innerRadius = element.innerRadius + pixelMargin;
  8770. let i;
  8771. if (inner) {
  8772. clipArc(ctx, element, startAngle + TAU);
  8773. }
  8774. ctx.beginPath();
  8775. ctx.arc(x, y, innerRadius, startAngle + TAU, startAngle, true);
  8776. for (i = 0; i < fullCircles; ++i) {
  8777. ctx.stroke();
  8778. }
  8779. ctx.beginPath();
  8780. ctx.arc(x, y, outerRadius, startAngle, startAngle + TAU);
  8781. for (i = 0; i < fullCircles; ++i) {
  8782. ctx.stroke();
  8783. }
  8784. }
  8785. function drawBorder(ctx, element, offset, spacing, endAngle) {
  8786. const {options} = element;
  8787. const inner = options.borderAlign === 'inner';
  8788. if (!options.borderWidth) {
  8789. return;
  8790. }
  8791. if (inner) {
  8792. ctx.lineWidth = options.borderWidth * 2;
  8793. ctx.lineJoin = 'round';
  8794. } else {
  8795. ctx.lineWidth = options.borderWidth;
  8796. ctx.lineJoin = 'bevel';
  8797. }
  8798. if (element.fullCircles) {
  8799. drawFullCircleBorders(ctx, element, inner);
  8800. }
  8801. if (inner) {
  8802. clipArc(ctx, element, endAngle);
  8803. }
  8804. pathArc(ctx, element, offset, spacing, endAngle);
  8805. ctx.stroke();
  8806. }
  8807. class ArcElement extends Element {
  8808. constructor(cfg) {
  8809. super();
  8810. this.options = undefined;
  8811. this.circumference = undefined;
  8812. this.startAngle = undefined;
  8813. this.endAngle = undefined;
  8814. this.innerRadius = undefined;
  8815. this.outerRadius = undefined;
  8816. this.pixelMargin = 0;
  8817. this.fullCircles = 0;
  8818. if (cfg) {
  8819. Object.assign(this, cfg);
  8820. }
  8821. }
  8822. inRange(chartX, chartY, useFinalPosition) {
  8823. const point = this.getProps(['x', 'y'], useFinalPosition);
  8824. const {angle, distance} = getAngleFromPoint(point, {x: chartX, y: chartY});
  8825. const {startAngle, endAngle, innerRadius, outerRadius, circumference} = this.getProps([
  8826. 'startAngle',
  8827. 'endAngle',
  8828. 'innerRadius',
  8829. 'outerRadius',
  8830. 'circumference'
  8831. ], useFinalPosition);
  8832. const rAdjust = this.options.spacing / 2;
  8833. const betweenAngles = circumference >= TAU || _angleBetween(angle, startAngle, endAngle);
  8834. const withinRadius = (distance >= innerRadius + rAdjust && distance <= outerRadius + rAdjust);
  8835. return (betweenAngles && withinRadius);
  8836. }
  8837. getCenterPoint(useFinalPosition) {
  8838. const {x, y, startAngle, endAngle, innerRadius, outerRadius} = this.getProps([
  8839. 'x',
  8840. 'y',
  8841. 'startAngle',
  8842. 'endAngle',
  8843. 'innerRadius',
  8844. 'outerRadius',
  8845. 'circumference',
  8846. ], useFinalPosition);
  8847. const {offset, spacing} = this.options;
  8848. const halfAngle = (startAngle + endAngle) / 2;
  8849. const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2;
  8850. return {
  8851. x: x + Math.cos(halfAngle) * halfRadius,
  8852. y: y + Math.sin(halfAngle) * halfRadius
  8853. };
  8854. }
  8855. tooltipPosition(useFinalPosition) {
  8856. return this.getCenterPoint(useFinalPosition);
  8857. }
  8858. draw(ctx) {
  8859. const me = this;
  8860. const {options, circumference} = me;
  8861. const offset = (options.offset || 0) / 2;
  8862. const spacing = (options.spacing || 0) / 2;
  8863. me.pixelMargin = (options.borderAlign === 'inner') ? 0.33 : 0;
  8864. me.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0;
  8865. if (circumference === 0 || me.innerRadius < 0 || me.outerRadius < 0) {
  8866. return;
  8867. }
  8868. ctx.save();
  8869. let radiusOffset = 0;
  8870. if (offset) {
  8871. radiusOffset = offset / 2;
  8872. const halfAngle = (me.startAngle + me.endAngle) / 2;
  8873. ctx.translate(Math.cos(halfAngle) * radiusOffset, Math.sin(halfAngle) * radiusOffset);
  8874. if (me.circumference >= PI) {
  8875. radiusOffset = offset;
  8876. }
  8877. }
  8878. ctx.fillStyle = options.backgroundColor;
  8879. ctx.strokeStyle = options.borderColor;
  8880. const endAngle = drawArc(ctx, me, radiusOffset, spacing);
  8881. drawBorder(ctx, me, radiusOffset, spacing, endAngle);
  8882. ctx.restore();
  8883. }
  8884. }
  8885. ArcElement.id = 'arc';
  8886. ArcElement.defaults = {
  8887. borderAlign: 'center',
  8888. borderColor: '#fff',
  8889. borderRadius: 0,
  8890. borderWidth: 2,
  8891. offset: 0,
  8892. spacing: 0,
  8893. angle: undefined,
  8894. };
  8895. ArcElement.defaultRoutes = {
  8896. backgroundColor: 'backgroundColor'
  8897. };
  8898. function setStyle(ctx, options, style = options) {
  8899. ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle);
  8900. ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash));
  8901. ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset);
  8902. ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);
  8903. ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth);
  8904. ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor);
  8905. }
  8906. function lineTo(ctx, previous, target) {
  8907. ctx.lineTo(target.x, target.y);
  8908. }
  8909. function getLineMethod(options) {
  8910. if (options.stepped) {
  8911. return _steppedLineTo;
  8912. }
  8913. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  8914. return _bezierCurveTo;
  8915. }
  8916. return lineTo;
  8917. }
  8918. function pathVars(points, segment, params = {}) {
  8919. const count = points.length;
  8920. const {start: paramsStart = 0, end: paramsEnd = count - 1} = params;
  8921. const {start: segmentStart, end: segmentEnd} = segment;
  8922. const start = Math.max(paramsStart, segmentStart);
  8923. const end = Math.min(paramsEnd, segmentEnd);
  8924. const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;
  8925. return {
  8926. count,
  8927. start,
  8928. loop: segment.loop,
  8929. ilen: end < start && !outside ? count + end - start : end - start
  8930. };
  8931. }
  8932. function pathSegment(ctx, line, segment, params) {
  8933. const {points, options} = line;
  8934. const {count, start, loop, ilen} = pathVars(points, segment, params);
  8935. const lineMethod = getLineMethod(options);
  8936. let {move = true, reverse} = params || {};
  8937. let i, point, prev;
  8938. for (i = 0; i <= ilen; ++i) {
  8939. point = points[(start + (reverse ? ilen - i : i)) % count];
  8940. if (point.skip) {
  8941. continue;
  8942. } else if (move) {
  8943. ctx.moveTo(point.x, point.y);
  8944. move = false;
  8945. } else {
  8946. lineMethod(ctx, prev, point, reverse, options.stepped);
  8947. }
  8948. prev = point;
  8949. }
  8950. if (loop) {
  8951. point = points[(start + (reverse ? ilen : 0)) % count];
  8952. lineMethod(ctx, prev, point, reverse, options.stepped);
  8953. }
  8954. return !!loop;
  8955. }
  8956. function fastPathSegment(ctx, line, segment, params) {
  8957. const points = line.points;
  8958. const {count, start, ilen} = pathVars(points, segment, params);
  8959. const {move = true, reverse} = params || {};
  8960. let avgX = 0;
  8961. let countX = 0;
  8962. let i, point, prevX, minY, maxY, lastY;
  8963. const pointIndex = (index) => (start + (reverse ? ilen - index : index)) % count;
  8964. const drawX = () => {
  8965. if (minY !== maxY) {
  8966. ctx.lineTo(avgX, maxY);
  8967. ctx.lineTo(avgX, minY);
  8968. ctx.lineTo(avgX, lastY);
  8969. }
  8970. };
  8971. if (move) {
  8972. point = points[pointIndex(0)];
  8973. ctx.moveTo(point.x, point.y);
  8974. }
  8975. for (i = 0; i <= ilen; ++i) {
  8976. point = points[pointIndex(i)];
  8977. if (point.skip) {
  8978. continue;
  8979. }
  8980. const x = point.x;
  8981. const y = point.y;
  8982. const truncX = x | 0;
  8983. if (truncX === prevX) {
  8984. if (y < minY) {
  8985. minY = y;
  8986. } else if (y > maxY) {
  8987. maxY = y;
  8988. }
  8989. avgX = (countX * avgX + x) / ++countX;
  8990. } else {
  8991. drawX();
  8992. ctx.lineTo(x, y);
  8993. prevX = truncX;
  8994. countX = 0;
  8995. minY = maxY = y;
  8996. }
  8997. lastY = y;
  8998. }
  8999. drawX();
  9000. }
  9001. function _getSegmentMethod(line) {
  9002. const opts = line.options;
  9003. const borderDash = opts.borderDash && opts.borderDash.length;
  9004. const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;
  9005. return useFastPath ? fastPathSegment : pathSegment;
  9006. }
  9007. function _getInterpolationMethod(options) {
  9008. if (options.stepped) {
  9009. return _steppedInterpolation;
  9010. }
  9011. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  9012. return _bezierInterpolation;
  9013. }
  9014. return _pointInLine;
  9015. }
  9016. function strokePathWithCache(ctx, line, start, count) {
  9017. let path = line._path;
  9018. if (!path) {
  9019. path = line._path = new Path2D();
  9020. if (line.path(path, start, count)) {
  9021. path.closePath();
  9022. }
  9023. }
  9024. setStyle(ctx, line.options);
  9025. ctx.stroke(path);
  9026. }
  9027. function strokePathDirect(ctx, line, start, count) {
  9028. const {segments, options} = line;
  9029. const segmentMethod = _getSegmentMethod(line);
  9030. for (const segment of segments) {
  9031. setStyle(ctx, options, segment.style);
  9032. ctx.beginPath();
  9033. if (segmentMethod(ctx, line, segment, {start, end: start + count - 1})) {
  9034. ctx.closePath();
  9035. }
  9036. ctx.stroke();
  9037. }
  9038. }
  9039. const usePath2D = typeof Path2D === 'function';
  9040. function draw(ctx, line, start, count) {
  9041. if (usePath2D && line.segments.length === 1) {
  9042. strokePathWithCache(ctx, line, start, count);
  9043. } else {
  9044. strokePathDirect(ctx, line, start, count);
  9045. }
  9046. }
  9047. class LineElement extends Element {
  9048. constructor(cfg) {
  9049. super();
  9050. this.animated = true;
  9051. this.options = undefined;
  9052. this._loop = undefined;
  9053. this._fullLoop = undefined;
  9054. this._path = undefined;
  9055. this._points = undefined;
  9056. this._segments = undefined;
  9057. this._decimated = false;
  9058. this._pointsUpdated = false;
  9059. this._datasetIndex = undefined;
  9060. if (cfg) {
  9061. Object.assign(this, cfg);
  9062. }
  9063. }
  9064. updateControlPoints(chartArea, indexAxis) {
  9065. const me = this;
  9066. const options = me.options;
  9067. if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !me._pointsUpdated) {
  9068. const loop = options.spanGaps ? me._loop : me._fullLoop;
  9069. _updateBezierControlPoints(me._points, options, chartArea, loop, indexAxis);
  9070. me._pointsUpdated = true;
  9071. }
  9072. }
  9073. set points(points) {
  9074. const me = this;
  9075. me._points = points;
  9076. delete me._segments;
  9077. delete me._path;
  9078. me._pointsUpdated = false;
  9079. }
  9080. get points() {
  9081. return this._points;
  9082. }
  9083. get segments() {
  9084. return this._segments || (this._segments = _computeSegments(this, this.options.segment));
  9085. }
  9086. first() {
  9087. const segments = this.segments;
  9088. const points = this.points;
  9089. return segments.length && points[segments[0].start];
  9090. }
  9091. last() {
  9092. const segments = this.segments;
  9093. const points = this.points;
  9094. const count = segments.length;
  9095. return count && points[segments[count - 1].end];
  9096. }
  9097. interpolate(point, property) {
  9098. const me = this;
  9099. const options = me.options;
  9100. const value = point[property];
  9101. const points = me.points;
  9102. const segments = _boundSegments(me, {property, start: value, end: value});
  9103. if (!segments.length) {
  9104. return;
  9105. }
  9106. const result = [];
  9107. const _interpolate = _getInterpolationMethod(options);
  9108. let i, ilen;
  9109. for (i = 0, ilen = segments.length; i < ilen; ++i) {
  9110. const {start, end} = segments[i];
  9111. const p1 = points[start];
  9112. const p2 = points[end];
  9113. if (p1 === p2) {
  9114. result.push(p1);
  9115. continue;
  9116. }
  9117. const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));
  9118. const interpolated = _interpolate(p1, p2, t, options.stepped);
  9119. interpolated[property] = point[property];
  9120. result.push(interpolated);
  9121. }
  9122. return result.length === 1 ? result[0] : result;
  9123. }
  9124. pathSegment(ctx, segment, params) {
  9125. const segmentMethod = _getSegmentMethod(this);
  9126. return segmentMethod(ctx, this, segment, params);
  9127. }
  9128. path(ctx, start, count) {
  9129. const me = this;
  9130. const segments = me.segments;
  9131. const segmentMethod = _getSegmentMethod(me);
  9132. let loop = me._loop;
  9133. start = start || 0;
  9134. count = count || (me.points.length - start);
  9135. for (const segment of segments) {
  9136. loop &= segmentMethod(ctx, me, segment, {start, end: start + count - 1});
  9137. }
  9138. return !!loop;
  9139. }
  9140. draw(ctx, chartArea, start, count) {
  9141. const me = this;
  9142. const options = me.options || {};
  9143. const points = me.points || [];
  9144. if (!points.length || !options.borderWidth) {
  9145. return;
  9146. }
  9147. ctx.save();
  9148. draw(ctx, me, start, count);
  9149. ctx.restore();
  9150. if (me.animated) {
  9151. me._pointsUpdated = false;
  9152. me._path = undefined;
  9153. }
  9154. }
  9155. }
  9156. LineElement.id = 'line';
  9157. LineElement.defaults = {
  9158. borderCapStyle: 'butt',
  9159. borderDash: [],
  9160. borderDashOffset: 0,
  9161. borderJoinStyle: 'miter',
  9162. borderWidth: 3,
  9163. capBezierPoints: true,
  9164. cubicInterpolationMode: 'default',
  9165. fill: false,
  9166. spanGaps: false,
  9167. stepped: false,
  9168. tension: 0,
  9169. };
  9170. LineElement.defaultRoutes = {
  9171. backgroundColor: 'backgroundColor',
  9172. borderColor: 'borderColor'
  9173. };
  9174. LineElement.descriptors = {
  9175. _scriptable: true,
  9176. _indexable: (name) => name !== 'borderDash' && name !== 'fill',
  9177. };
  9178. function inRange$1(el, pos, axis, useFinalPosition) {
  9179. const options = el.options;
  9180. const {[axis]: value} = el.getProps([axis], useFinalPosition);
  9181. return (Math.abs(pos - value) < options.radius + options.hitRadius);
  9182. }
  9183. class PointElement extends Element {
  9184. constructor(cfg) {
  9185. super();
  9186. this.options = undefined;
  9187. this.parsed = undefined;
  9188. this.skip = undefined;
  9189. this.stop = undefined;
  9190. if (cfg) {
  9191. Object.assign(this, cfg);
  9192. }
  9193. }
  9194. inRange(mouseX, mouseY, useFinalPosition) {
  9195. const options = this.options;
  9196. const {x, y} = this.getProps(['x', 'y'], useFinalPosition);
  9197. return ((Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2)) < Math.pow(options.hitRadius + options.radius, 2));
  9198. }
  9199. inXRange(mouseX, useFinalPosition) {
  9200. return inRange$1(this, mouseX, 'x', useFinalPosition);
  9201. }
  9202. inYRange(mouseY, useFinalPosition) {
  9203. return inRange$1(this, mouseY, 'y', useFinalPosition);
  9204. }
  9205. getCenterPoint(useFinalPosition) {
  9206. const {x, y} = this.getProps(['x', 'y'], useFinalPosition);
  9207. return {x, y};
  9208. }
  9209. size(options) {
  9210. options = options || this.options || {};
  9211. let radius = options.radius || 0;
  9212. radius = Math.max(radius, radius && options.hoverRadius || 0);
  9213. const borderWidth = radius && options.borderWidth || 0;
  9214. return (radius + borderWidth) * 2;
  9215. }
  9216. draw(ctx, area) {
  9217. const me = this;
  9218. const options = me.options;
  9219. if (me.skip || options.radius < 0.1 || !_isPointInArea(me, area, me.size(options) / 2)) {
  9220. return;
  9221. }
  9222. ctx.strokeStyle = options.borderColor;
  9223. ctx.lineWidth = options.borderWidth;
  9224. ctx.fillStyle = options.backgroundColor;
  9225. drawPoint(ctx, options, me.x, me.y);
  9226. }
  9227. getRange() {
  9228. const options = this.options || {};
  9229. return options.radius + options.hitRadius;
  9230. }
  9231. }
  9232. PointElement.id = 'point';
  9233. PointElement.defaults = {
  9234. borderWidth: 1,
  9235. hitRadius: 1,
  9236. hoverBorderWidth: 1,
  9237. hoverRadius: 4,
  9238. pointStyle: 'circle',
  9239. radius: 3,
  9240. rotation: 0
  9241. };
  9242. PointElement.defaultRoutes = {
  9243. backgroundColor: 'backgroundColor',
  9244. borderColor: 'borderColor'
  9245. };
  9246. function getBarBounds(bar, useFinalPosition) {
  9247. const {x, y, base, width, height} = bar.getProps(['x', 'y', 'base', 'width', 'height'], useFinalPosition);
  9248. let left, right, top, bottom, half;
  9249. if (bar.horizontal) {
  9250. half = height / 2;
  9251. left = Math.min(x, base);
  9252. right = Math.max(x, base);
  9253. top = y - half;
  9254. bottom = y + half;
  9255. } else {
  9256. half = width / 2;
  9257. left = x - half;
  9258. right = x + half;
  9259. top = Math.min(y, base);
  9260. bottom = Math.max(y, base);
  9261. }
  9262. return {left, top, right, bottom};
  9263. }
  9264. function skipOrLimit(skip, value, min, max) {
  9265. return skip ? 0 : _limitValue(value, min, max);
  9266. }
  9267. function parseBorderWidth(bar, maxW, maxH) {
  9268. const value = bar.options.borderWidth;
  9269. const skip = bar.borderSkipped;
  9270. const o = toTRBL(value);
  9271. return {
  9272. t: skipOrLimit(skip.top, o.top, 0, maxH),
  9273. r: skipOrLimit(skip.right, o.right, 0, maxW),
  9274. b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),
  9275. l: skipOrLimit(skip.left, o.left, 0, maxW)
  9276. };
  9277. }
  9278. function parseBorderRadius(bar, maxW, maxH) {
  9279. const {enableBorderRadius} = bar.getProps(['enableBorderRadius']);
  9280. const value = bar.options.borderRadius;
  9281. const o = toTRBLCorners(value);
  9282. const maxR = Math.min(maxW, maxH);
  9283. const skip = bar.borderSkipped;
  9284. const enableBorder = enableBorderRadius || isObject(value);
  9285. return {
  9286. topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),
  9287. topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),
  9288. bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),
  9289. bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)
  9290. };
  9291. }
  9292. function boundingRects(bar) {
  9293. const bounds = getBarBounds(bar);
  9294. const width = bounds.right - bounds.left;
  9295. const height = bounds.bottom - bounds.top;
  9296. const border = parseBorderWidth(bar, width / 2, height / 2);
  9297. const radius = parseBorderRadius(bar, width / 2, height / 2);
  9298. return {
  9299. outer: {
  9300. x: bounds.left,
  9301. y: bounds.top,
  9302. w: width,
  9303. h: height,
  9304. radius
  9305. },
  9306. inner: {
  9307. x: bounds.left + border.l,
  9308. y: bounds.top + border.t,
  9309. w: width - border.l - border.r,
  9310. h: height - border.t - border.b,
  9311. radius: {
  9312. topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),
  9313. topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),
  9314. bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),
  9315. bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r)),
  9316. }
  9317. }
  9318. };
  9319. }
  9320. function inRange(bar, x, y, useFinalPosition) {
  9321. const skipX = x === null;
  9322. const skipY = y === null;
  9323. const skipBoth = skipX && skipY;
  9324. const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);
  9325. return bounds
  9326. && (skipX || x >= bounds.left && x <= bounds.right)
  9327. && (skipY || y >= bounds.top && y <= bounds.bottom);
  9328. }
  9329. function hasRadius(radius) {
  9330. return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;
  9331. }
  9332. function addNormalRectPath(ctx, rect) {
  9333. ctx.rect(rect.x, rect.y, rect.w, rect.h);
  9334. }
  9335. function inflateRect(rect, amount, refRect = {}) {
  9336. const x = rect.x !== refRect.x ? -amount : 0;
  9337. const y = rect.y !== refRect.y ? -amount : 0;
  9338. const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x;
  9339. const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y;
  9340. return {
  9341. x: rect.x + x,
  9342. y: rect.y + y,
  9343. w: rect.w + w,
  9344. h: rect.h + h,
  9345. radius: rect.radius
  9346. };
  9347. }
  9348. class BarElement extends Element {
  9349. constructor(cfg) {
  9350. super();
  9351. this.options = undefined;
  9352. this.horizontal = undefined;
  9353. this.base = undefined;
  9354. this.width = undefined;
  9355. this.height = undefined;
  9356. if (cfg) {
  9357. Object.assign(this, cfg);
  9358. }
  9359. }
  9360. draw(ctx) {
  9361. const options = this.options;
  9362. const {inner, outer} = boundingRects(this);
  9363. const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath;
  9364. const inflateAmount = 0.33;
  9365. ctx.save();
  9366. if (outer.w !== inner.w || outer.h !== inner.h) {
  9367. ctx.beginPath();
  9368. addRectPath(ctx, inflateRect(outer, inflateAmount, inner));
  9369. ctx.clip();
  9370. addRectPath(ctx, inflateRect(inner, -inflateAmount, outer));
  9371. ctx.fillStyle = options.borderColor;
  9372. ctx.fill('evenodd');
  9373. }
  9374. ctx.beginPath();
  9375. addRectPath(ctx, inflateRect(inner, inflateAmount, outer));
  9376. ctx.fillStyle = options.backgroundColor;
  9377. ctx.fill();
  9378. ctx.restore();
  9379. }
  9380. inRange(mouseX, mouseY, useFinalPosition) {
  9381. return inRange(this, mouseX, mouseY, useFinalPosition);
  9382. }
  9383. inXRange(mouseX, useFinalPosition) {
  9384. return inRange(this, mouseX, null, useFinalPosition);
  9385. }
  9386. inYRange(mouseY, useFinalPosition) {
  9387. return inRange(this, null, mouseY, useFinalPosition);
  9388. }
  9389. getCenterPoint(useFinalPosition) {
  9390. const {x, y, base, horizontal} = this.getProps(['x', 'y', 'base', 'horizontal'], useFinalPosition);
  9391. return {
  9392. x: horizontal ? (x + base) / 2 : x,
  9393. y: horizontal ? y : (y + base) / 2
  9394. };
  9395. }
  9396. getRange(axis) {
  9397. return axis === 'x' ? this.width / 2 : this.height / 2;
  9398. }
  9399. }
  9400. BarElement.id = 'bar';
  9401. BarElement.defaults = {
  9402. borderSkipped: 'start',
  9403. borderWidth: 0,
  9404. borderRadius: 0,
  9405. enableBorderRadius: true,
  9406. pointStyle: undefined
  9407. };
  9408. BarElement.defaultRoutes = {
  9409. backgroundColor: 'backgroundColor',
  9410. borderColor: 'borderColor'
  9411. };
  9412. var elements = /*#__PURE__*/Object.freeze({
  9413. __proto__: null,
  9414. ArcElement: ArcElement,
  9415. LineElement: LineElement,
  9416. PointElement: PointElement,
  9417. BarElement: BarElement
  9418. });
  9419. function lttbDecimation(data, start, count, availableWidth, options) {
  9420. const samples = options.samples || availableWidth;
  9421. if (samples >= count) {
  9422. return data.slice(start, start + count);
  9423. }
  9424. const decimated = [];
  9425. const bucketWidth = (count - 2) / (samples - 2);
  9426. let sampledIndex = 0;
  9427. const endIndex = start + count - 1;
  9428. let a = start;
  9429. let i, maxAreaPoint, maxArea, area, nextA;
  9430. decimated[sampledIndex++] = data[a];
  9431. for (i = 0; i < samples - 2; i++) {
  9432. let avgX = 0;
  9433. let avgY = 0;
  9434. let j;
  9435. const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;
  9436. const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;
  9437. const avgRangeLength = avgRangeEnd - avgRangeStart;
  9438. for (j = avgRangeStart; j < avgRangeEnd; j++) {
  9439. avgX += data[j].x;
  9440. avgY += data[j].y;
  9441. }
  9442. avgX /= avgRangeLength;
  9443. avgY /= avgRangeLength;
  9444. const rangeOffs = Math.floor(i * bucketWidth) + 1 + start;
  9445. const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start;
  9446. const {x: pointAx, y: pointAy} = data[a];
  9447. maxArea = area = -1;
  9448. for (j = rangeOffs; j < rangeTo; j++) {
  9449. area = 0.5 * Math.abs(
  9450. (pointAx - avgX) * (data[j].y - pointAy) -
  9451. (pointAx - data[j].x) * (avgY - pointAy)
  9452. );
  9453. if (area > maxArea) {
  9454. maxArea = area;
  9455. maxAreaPoint = data[j];
  9456. nextA = j;
  9457. }
  9458. }
  9459. decimated[sampledIndex++] = maxAreaPoint;
  9460. a = nextA;
  9461. }
  9462. decimated[sampledIndex++] = data[endIndex];
  9463. return decimated;
  9464. }
  9465. function minMaxDecimation(data, start, count, availableWidth) {
  9466. let avgX = 0;
  9467. let countX = 0;
  9468. let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;
  9469. const decimated = [];
  9470. const endIndex = start + count - 1;
  9471. const xMin = data[start].x;
  9472. const xMax = data[endIndex].x;
  9473. const dx = xMax - xMin;
  9474. for (i = start; i < start + count; ++i) {
  9475. point = data[i];
  9476. x = (point.x - xMin) / dx * availableWidth;
  9477. y = point.y;
  9478. const truncX = x | 0;
  9479. if (truncX === prevX) {
  9480. if (y < minY) {
  9481. minY = y;
  9482. minIndex = i;
  9483. } else if (y > maxY) {
  9484. maxY = y;
  9485. maxIndex = i;
  9486. }
  9487. avgX = (countX * avgX + point.x) / ++countX;
  9488. } else {
  9489. const lastIndex = i - 1;
  9490. if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) {
  9491. const intermediateIndex1 = Math.min(minIndex, maxIndex);
  9492. const intermediateIndex2 = Math.max(minIndex, maxIndex);
  9493. if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {
  9494. decimated.push({
  9495. ...data[intermediateIndex1],
  9496. x: avgX,
  9497. });
  9498. }
  9499. if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {
  9500. decimated.push({
  9501. ...data[intermediateIndex2],
  9502. x: avgX
  9503. });
  9504. }
  9505. }
  9506. if (i > 0 && lastIndex !== startIndex) {
  9507. decimated.push(data[lastIndex]);
  9508. }
  9509. decimated.push(point);
  9510. prevX = truncX;
  9511. countX = 0;
  9512. minY = maxY = y;
  9513. minIndex = maxIndex = startIndex = i;
  9514. }
  9515. }
  9516. return decimated;
  9517. }
  9518. function cleanDecimatedDataset(dataset) {
  9519. if (dataset._decimated) {
  9520. const data = dataset._data;
  9521. delete dataset._decimated;
  9522. delete dataset._data;
  9523. Object.defineProperty(dataset, 'data', {value: data});
  9524. }
  9525. }
  9526. function cleanDecimatedData(chart) {
  9527. chart.data.datasets.forEach((dataset) => {
  9528. cleanDecimatedDataset(dataset);
  9529. });
  9530. }
  9531. function getStartAndCountOfVisiblePointsSimplified(meta, points) {
  9532. const pointCount = points.length;
  9533. let start = 0;
  9534. let count;
  9535. const {iScale} = meta;
  9536. const {min, max, minDefined, maxDefined} = iScale.getUserBounds();
  9537. if (minDefined) {
  9538. start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);
  9539. }
  9540. if (maxDefined) {
  9541. count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;
  9542. } else {
  9543. count = pointCount - start;
  9544. }
  9545. return {start, count};
  9546. }
  9547. var plugin_decimation = {
  9548. id: 'decimation',
  9549. defaults: {
  9550. algorithm: 'min-max',
  9551. enabled: false,
  9552. },
  9553. beforeElementsUpdate: (chart, args, options) => {
  9554. if (!options.enabled) {
  9555. cleanDecimatedData(chart);
  9556. return;
  9557. }
  9558. const availableWidth = chart.width;
  9559. chart.data.datasets.forEach((dataset, datasetIndex) => {
  9560. const {_data, indexAxis} = dataset;
  9561. const meta = chart.getDatasetMeta(datasetIndex);
  9562. const data = _data || dataset.data;
  9563. if (resolve([indexAxis, chart.options.indexAxis]) === 'y') {
  9564. return;
  9565. }
  9566. if (meta.type !== 'line') {
  9567. return;
  9568. }
  9569. const xAxis = chart.scales[meta.xAxisID];
  9570. if (xAxis.type !== 'linear' && xAxis.type !== 'time') {
  9571. return;
  9572. }
  9573. if (chart.options.parsing) {
  9574. return;
  9575. }
  9576. let {start, count} = getStartAndCountOfVisiblePointsSimplified(meta, data);
  9577. const threshold = options.threshold || 4 * availableWidth;
  9578. if (count <= threshold) {
  9579. cleanDecimatedDataset(dataset);
  9580. return;
  9581. }
  9582. if (isNullOrUndef(_data)) {
  9583. dataset._data = data;
  9584. delete dataset.data;
  9585. Object.defineProperty(dataset, 'data', {
  9586. configurable: true,
  9587. enumerable: true,
  9588. get: function() {
  9589. return this._decimated;
  9590. },
  9591. set: function(d) {
  9592. this._data = d;
  9593. }
  9594. });
  9595. }
  9596. let decimated;
  9597. switch (options.algorithm) {
  9598. case 'lttb':
  9599. decimated = lttbDecimation(data, start, count, availableWidth, options);
  9600. break;
  9601. case 'min-max':
  9602. decimated = minMaxDecimation(data, start, count, availableWidth);
  9603. break;
  9604. default:
  9605. throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);
  9606. }
  9607. dataset._decimated = decimated;
  9608. });
  9609. },
  9610. destroy(chart) {
  9611. cleanDecimatedData(chart);
  9612. }
  9613. };
  9614. function getLineByIndex(chart, index) {
  9615. const meta = chart.getDatasetMeta(index);
  9616. const visible = meta && chart.isDatasetVisible(index);
  9617. return visible ? meta.dataset : null;
  9618. }
  9619. function parseFillOption(line) {
  9620. const options = line.options;
  9621. const fillOption = options.fill;
  9622. let fill = valueOrDefault(fillOption && fillOption.target, fillOption);
  9623. if (fill === undefined) {
  9624. fill = !!options.backgroundColor;
  9625. }
  9626. if (fill === false || fill === null) {
  9627. return false;
  9628. }
  9629. if (fill === true) {
  9630. return 'origin';
  9631. }
  9632. return fill;
  9633. }
  9634. function decodeFill(line, index, count) {
  9635. const fill = parseFillOption(line);
  9636. if (isObject(fill)) {
  9637. return isNaN(fill.value) ? false : fill;
  9638. }
  9639. let target = parseFloat(fill);
  9640. if (isNumberFinite(target) && Math.floor(target) === target) {
  9641. if (fill[0] === '-' || fill[0] === '+') {
  9642. target = index + target;
  9643. }
  9644. if (target === index || target < 0 || target >= count) {
  9645. return false;
  9646. }
  9647. return target;
  9648. }
  9649. return ['origin', 'start', 'end', 'stack', 'shape'].indexOf(fill) >= 0 && fill;
  9650. }
  9651. function computeLinearBoundary(source) {
  9652. const {scale = {}, fill} = source;
  9653. let target = null;
  9654. let horizontal;
  9655. if (fill === 'start') {
  9656. target = scale.bottom;
  9657. } else if (fill === 'end') {
  9658. target = scale.top;
  9659. } else if (isObject(fill)) {
  9660. target = scale.getPixelForValue(fill.value);
  9661. } else if (scale.getBasePixel) {
  9662. target = scale.getBasePixel();
  9663. }
  9664. if (isNumberFinite(target)) {
  9665. horizontal = scale.isHorizontal();
  9666. return {
  9667. x: horizontal ? target : null,
  9668. y: horizontal ? null : target
  9669. };
  9670. }
  9671. return null;
  9672. }
  9673. class simpleArc {
  9674. constructor(opts) {
  9675. this.x = opts.x;
  9676. this.y = opts.y;
  9677. this.radius = opts.radius;
  9678. }
  9679. pathSegment(ctx, bounds, opts) {
  9680. const {x, y, radius} = this;
  9681. bounds = bounds || {start: 0, end: TAU};
  9682. ctx.arc(x, y, radius, bounds.end, bounds.start, true);
  9683. return !opts.bounds;
  9684. }
  9685. interpolate(point) {
  9686. const {x, y, radius} = this;
  9687. const angle = point.angle;
  9688. return {
  9689. x: x + Math.cos(angle) * radius,
  9690. y: y + Math.sin(angle) * radius,
  9691. angle
  9692. };
  9693. }
  9694. }
  9695. function computeCircularBoundary(source) {
  9696. const {scale, fill} = source;
  9697. const options = scale.options;
  9698. const length = scale.getLabels().length;
  9699. const target = [];
  9700. const start = options.reverse ? scale.max : scale.min;
  9701. const end = options.reverse ? scale.min : scale.max;
  9702. let i, center, value;
  9703. if (fill === 'start') {
  9704. value = start;
  9705. } else if (fill === 'end') {
  9706. value = end;
  9707. } else if (isObject(fill)) {
  9708. value = fill.value;
  9709. } else {
  9710. value = scale.getBaseValue();
  9711. }
  9712. if (options.grid.circular) {
  9713. center = scale.getPointPositionForValue(0, start);
  9714. return new simpleArc({
  9715. x: center.x,
  9716. y: center.y,
  9717. radius: scale.getDistanceFromCenterForValue(value)
  9718. });
  9719. }
  9720. for (i = 0; i < length; ++i) {
  9721. target.push(scale.getPointPositionForValue(i, value));
  9722. }
  9723. return target;
  9724. }
  9725. function computeBoundary(source) {
  9726. const scale = source.scale || {};
  9727. if (scale.getPointPositionForValue) {
  9728. return computeCircularBoundary(source);
  9729. }
  9730. return computeLinearBoundary(source);
  9731. }
  9732. function findSegmentEnd(start, end, points) {
  9733. for (;end > start; end--) {
  9734. const point = points[end];
  9735. if (!isNaN(point.x) && !isNaN(point.y)) {
  9736. break;
  9737. }
  9738. }
  9739. return end;
  9740. }
  9741. function pointsFromSegments(boundary, line) {
  9742. const {x = null, y = null} = boundary || {};
  9743. const linePoints = line.points;
  9744. const points = [];
  9745. line.segments.forEach(({start, end}) => {
  9746. end = findSegmentEnd(start, end, linePoints);
  9747. const first = linePoints[start];
  9748. const last = linePoints[end];
  9749. if (y !== null) {
  9750. points.push({x: first.x, y});
  9751. points.push({x: last.x, y});
  9752. } else if (x !== null) {
  9753. points.push({x, y: first.y});
  9754. points.push({x, y: last.y});
  9755. }
  9756. });
  9757. return points;
  9758. }
  9759. function buildStackLine(source) {
  9760. const {chart, scale, index, line} = source;
  9761. const points = [];
  9762. const segments = line.segments;
  9763. const sourcePoints = line.points;
  9764. const linesBelow = getLinesBelow(chart, index);
  9765. linesBelow.push(createBoundaryLine({x: null, y: scale.bottom}, line));
  9766. for (let i = 0; i < segments.length; i++) {
  9767. const segment = segments[i];
  9768. for (let j = segment.start; j <= segment.end; j++) {
  9769. addPointsBelow(points, sourcePoints[j], linesBelow);
  9770. }
  9771. }
  9772. return new LineElement({points, options: {}});
  9773. }
  9774. const isLineAndNotInHideAnimation = (meta) => meta.type === 'line' && !meta.hidden;
  9775. function getLinesBelow(chart, index) {
  9776. const below = [];
  9777. const metas = chart.getSortedVisibleDatasetMetas();
  9778. for (let i = 0; i < metas.length; i++) {
  9779. const meta = metas[i];
  9780. if (meta.index === index) {
  9781. break;
  9782. }
  9783. if (isLineAndNotInHideAnimation(meta)) {
  9784. below.unshift(meta.dataset);
  9785. }
  9786. }
  9787. return below;
  9788. }
  9789. function addPointsBelow(points, sourcePoint, linesBelow) {
  9790. const postponed = [];
  9791. for (let j = 0; j < linesBelow.length; j++) {
  9792. const line = linesBelow[j];
  9793. const {first, last, point} = findPoint(line, sourcePoint, 'x');
  9794. if (!point || (first && last)) {
  9795. continue;
  9796. }
  9797. if (first) {
  9798. postponed.unshift(point);
  9799. } else {
  9800. points.push(point);
  9801. if (!last) {
  9802. break;
  9803. }
  9804. }
  9805. }
  9806. points.push(...postponed);
  9807. }
  9808. function findPoint(line, sourcePoint, property) {
  9809. const point = line.interpolate(sourcePoint, property);
  9810. if (!point) {
  9811. return {};
  9812. }
  9813. const pointValue = point[property];
  9814. const segments = line.segments;
  9815. const linePoints = line.points;
  9816. let first = false;
  9817. let last = false;
  9818. for (let i = 0; i < segments.length; i++) {
  9819. const segment = segments[i];
  9820. const firstValue = linePoints[segment.start][property];
  9821. const lastValue = linePoints[segment.end][property];
  9822. if (pointValue >= firstValue && pointValue <= lastValue) {
  9823. first = pointValue === firstValue;
  9824. last = pointValue === lastValue;
  9825. break;
  9826. }
  9827. }
  9828. return {first, last, point};
  9829. }
  9830. function getTarget(source) {
  9831. const {chart, fill, line} = source;
  9832. if (isNumberFinite(fill)) {
  9833. return getLineByIndex(chart, fill);
  9834. }
  9835. if (fill === 'stack') {
  9836. return buildStackLine(source);
  9837. }
  9838. if (fill === 'shape') {
  9839. return true;
  9840. }
  9841. const boundary = computeBoundary(source);
  9842. if (boundary instanceof simpleArc) {
  9843. return boundary;
  9844. }
  9845. return createBoundaryLine(boundary, line);
  9846. }
  9847. function createBoundaryLine(boundary, line) {
  9848. let points = [];
  9849. let _loop = false;
  9850. if (isArray(boundary)) {
  9851. _loop = true;
  9852. points = boundary;
  9853. } else {
  9854. points = pointsFromSegments(boundary, line);
  9855. }
  9856. return points.length ? new LineElement({
  9857. points,
  9858. options: {tension: 0},
  9859. _loop,
  9860. _fullLoop: _loop
  9861. }) : null;
  9862. }
  9863. function resolveTarget(sources, index, propagate) {
  9864. const source = sources[index];
  9865. let fill = source.fill;
  9866. const visited = [index];
  9867. let target;
  9868. if (!propagate) {
  9869. return fill;
  9870. }
  9871. while (fill !== false && visited.indexOf(fill) === -1) {
  9872. if (!isNumberFinite(fill)) {
  9873. return fill;
  9874. }
  9875. target = sources[fill];
  9876. if (!target) {
  9877. return false;
  9878. }
  9879. if (target.visible) {
  9880. return fill;
  9881. }
  9882. visited.push(fill);
  9883. fill = target.fill;
  9884. }
  9885. return false;
  9886. }
  9887. function _clip(ctx, target, clipY) {
  9888. ctx.beginPath();
  9889. target.path(ctx);
  9890. ctx.lineTo(target.last().x, clipY);
  9891. ctx.lineTo(target.first().x, clipY);
  9892. ctx.closePath();
  9893. ctx.clip();
  9894. }
  9895. function getBounds(property, first, last, loop) {
  9896. if (loop) {
  9897. return;
  9898. }
  9899. let start = first[property];
  9900. let end = last[property];
  9901. if (property === 'angle') {
  9902. start = _normalizeAngle(start);
  9903. end = _normalizeAngle(end);
  9904. }
  9905. return {property, start, end};
  9906. }
  9907. function _getEdge(a, b, prop, fn) {
  9908. if (a && b) {
  9909. return fn(a[prop], b[prop]);
  9910. }
  9911. return a ? a[prop] : b ? b[prop] : 0;
  9912. }
  9913. function _segments(line, target, property) {
  9914. const segments = line.segments;
  9915. const points = line.points;
  9916. const tpoints = target.points;
  9917. const parts = [];
  9918. for (const segment of segments) {
  9919. let {start, end} = segment;
  9920. end = findSegmentEnd(start, end, points);
  9921. const bounds = getBounds(property, points[start], points[end], segment.loop);
  9922. if (!target.segments) {
  9923. parts.push({
  9924. source: segment,
  9925. target: bounds,
  9926. start: points[start],
  9927. end: points[end]
  9928. });
  9929. continue;
  9930. }
  9931. const targetSegments = _boundSegments(target, bounds);
  9932. for (const tgt of targetSegments) {
  9933. const subBounds = getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);
  9934. const fillSources = _boundSegment(segment, points, subBounds);
  9935. for (const fillSource of fillSources) {
  9936. parts.push({
  9937. source: fillSource,
  9938. target: tgt,
  9939. start: {
  9940. [property]: _getEdge(bounds, subBounds, 'start', Math.max)
  9941. },
  9942. end: {
  9943. [property]: _getEdge(bounds, subBounds, 'end', Math.min)
  9944. }
  9945. });
  9946. }
  9947. }
  9948. }
  9949. return parts;
  9950. }
  9951. function clipBounds(ctx, scale, bounds) {
  9952. const {top, bottom} = scale.chart.chartArea;
  9953. const {property, start, end} = bounds || {};
  9954. if (property === 'x') {
  9955. ctx.beginPath();
  9956. ctx.rect(start, top, end - start, bottom - top);
  9957. ctx.clip();
  9958. }
  9959. }
  9960. function interpolatedLineTo(ctx, target, point, property) {
  9961. const interpolatedPoint = target.interpolate(point, property);
  9962. if (interpolatedPoint) {
  9963. ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);
  9964. }
  9965. }
  9966. function _fill(ctx, cfg) {
  9967. const {line, target, property, color, scale} = cfg;
  9968. const segments = _segments(line, target, property);
  9969. for (const {source: src, target: tgt, start, end} of segments) {
  9970. const {style: {backgroundColor = color} = {}} = src;
  9971. const notShape = target !== true;
  9972. ctx.save();
  9973. ctx.fillStyle = backgroundColor;
  9974. clipBounds(ctx, scale, notShape && getBounds(property, start, end));
  9975. ctx.beginPath();
  9976. const lineLoop = !!line.pathSegment(ctx, src);
  9977. let loop;
  9978. if (notShape) {
  9979. if (lineLoop) {
  9980. ctx.closePath();
  9981. } else {
  9982. interpolatedLineTo(ctx, target, end, property);
  9983. }
  9984. const targetLoop = !!target.pathSegment(ctx, tgt, {move: lineLoop, reverse: true});
  9985. loop = lineLoop && targetLoop;
  9986. if (!loop) {
  9987. interpolatedLineTo(ctx, target, start, property);
  9988. }
  9989. }
  9990. ctx.closePath();
  9991. ctx.fill(loop ? 'evenodd' : 'nonzero');
  9992. ctx.restore();
  9993. }
  9994. }
  9995. function doFill(ctx, cfg) {
  9996. const {line, target, above, below, area, scale} = cfg;
  9997. const property = line._loop ? 'angle' : cfg.axis;
  9998. ctx.save();
  9999. if (property === 'x' && below !== above) {
  10000. _clip(ctx, target, area.top);
  10001. _fill(ctx, {line, target, color: above, scale, property});
  10002. ctx.restore();
  10003. ctx.save();
  10004. _clip(ctx, target, area.bottom);
  10005. }
  10006. _fill(ctx, {line, target, color: below, scale, property});
  10007. ctx.restore();
  10008. }
  10009. function drawfill(ctx, source, area) {
  10010. const target = getTarget(source);
  10011. const {line, scale, axis} = source;
  10012. const lineOpts = line.options;
  10013. const fillOption = lineOpts.fill;
  10014. const color = lineOpts.backgroundColor;
  10015. const {above = color, below = color} = fillOption || {};
  10016. if (target && line.points.length) {
  10017. clipArea(ctx, area);
  10018. doFill(ctx, {line, target, above, below, area, scale, axis});
  10019. unclipArea(ctx);
  10020. }
  10021. }
  10022. var plugin_filler = {
  10023. id: 'filler',
  10024. afterDatasetsUpdate(chart, _args, options) {
  10025. const count = (chart.data.datasets || []).length;
  10026. const sources = [];
  10027. let meta, i, line, source;
  10028. for (i = 0; i < count; ++i) {
  10029. meta = chart.getDatasetMeta(i);
  10030. line = meta.dataset;
  10031. source = null;
  10032. if (line && line.options && line instanceof LineElement) {
  10033. source = {
  10034. visible: chart.isDatasetVisible(i),
  10035. index: i,
  10036. fill: decodeFill(line, i, count),
  10037. chart,
  10038. axis: meta.controller.options.indexAxis,
  10039. scale: meta.vScale,
  10040. line,
  10041. };
  10042. }
  10043. meta.$filler = source;
  10044. sources.push(source);
  10045. }
  10046. for (i = 0; i < count; ++i) {
  10047. source = sources[i];
  10048. if (!source || source.fill === false) {
  10049. continue;
  10050. }
  10051. source.fill = resolveTarget(sources, i, options.propagate);
  10052. }
  10053. },
  10054. beforeDraw(chart, _args, options) {
  10055. const draw = options.drawTime === 'beforeDraw';
  10056. const metasets = chart.getSortedVisibleDatasetMetas();
  10057. const area = chart.chartArea;
  10058. for (let i = metasets.length - 1; i >= 0; --i) {
  10059. const source = metasets[i].$filler;
  10060. if (!source) {
  10061. continue;
  10062. }
  10063. source.line.updateControlPoints(area, source.axis);
  10064. if (draw) {
  10065. drawfill(chart.ctx, source, area);
  10066. }
  10067. }
  10068. },
  10069. beforeDatasetsDraw(chart, _args, options) {
  10070. if (options.drawTime !== 'beforeDatasetsDraw') {
  10071. return;
  10072. }
  10073. const metasets = chart.getSortedVisibleDatasetMetas();
  10074. for (let i = metasets.length - 1; i >= 0; --i) {
  10075. const source = metasets[i].$filler;
  10076. if (source) {
  10077. drawfill(chart.ctx, source, chart.chartArea);
  10078. }
  10079. }
  10080. },
  10081. beforeDatasetDraw(chart, args, options) {
  10082. const source = args.meta.$filler;
  10083. if (!source || source.fill === false || options.drawTime !== 'beforeDatasetDraw') {
  10084. return;
  10085. }
  10086. drawfill(chart.ctx, source, chart.chartArea);
  10087. },
  10088. defaults: {
  10089. propagate: true,
  10090. drawTime: 'beforeDatasetDraw'
  10091. }
  10092. };
  10093. const getBoxSize = (labelOpts, fontSize) => {
  10094. let {boxHeight = fontSize, boxWidth = fontSize} = labelOpts;
  10095. if (labelOpts.usePointStyle) {
  10096. boxHeight = Math.min(boxHeight, fontSize);
  10097. boxWidth = Math.min(boxWidth, fontSize);
  10098. }
  10099. return {
  10100. boxWidth,
  10101. boxHeight,
  10102. itemHeight: Math.max(fontSize, boxHeight)
  10103. };
  10104. };
  10105. const itemsEqual = (a, b) => a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;
  10106. class Legend extends Element {
  10107. constructor(config) {
  10108. super();
  10109. this._added = false;
  10110. this.legendHitBoxes = [];
  10111. this._hoveredItem = null;
  10112. this.doughnutMode = false;
  10113. this.chart = config.chart;
  10114. this.options = config.options;
  10115. this.ctx = config.ctx;
  10116. this.legendItems = undefined;
  10117. this.columnSizes = undefined;
  10118. this.lineWidths = undefined;
  10119. this.maxHeight = undefined;
  10120. this.maxWidth = undefined;
  10121. this.top = undefined;
  10122. this.bottom = undefined;
  10123. this.left = undefined;
  10124. this.right = undefined;
  10125. this.height = undefined;
  10126. this.width = undefined;
  10127. this._margins = undefined;
  10128. this.position = undefined;
  10129. this.weight = undefined;
  10130. this.fullSize = undefined;
  10131. }
  10132. update(maxWidth, maxHeight, margins) {
  10133. const me = this;
  10134. me.maxWidth = maxWidth;
  10135. me.maxHeight = maxHeight;
  10136. me._margins = margins;
  10137. me.setDimensions();
  10138. me.buildLabels();
  10139. me.fit();
  10140. }
  10141. setDimensions() {
  10142. const me = this;
  10143. if (me.isHorizontal()) {
  10144. me.width = me.maxWidth;
  10145. me.left = me._margins.left;
  10146. me.right = me.width;
  10147. } else {
  10148. me.height = me.maxHeight;
  10149. me.top = me._margins.top;
  10150. me.bottom = me.height;
  10151. }
  10152. }
  10153. buildLabels() {
  10154. const me = this;
  10155. const labelOpts = me.options.labels || {};
  10156. let legendItems = callback(labelOpts.generateLabels, [me.chart], me) || [];
  10157. if (labelOpts.filter) {
  10158. legendItems = legendItems.filter((item) => labelOpts.filter(item, me.chart.data));
  10159. }
  10160. if (labelOpts.sort) {
  10161. legendItems = legendItems.sort((a, b) => labelOpts.sort(a, b, me.chart.data));
  10162. }
  10163. if (me.options.reverse) {
  10164. legendItems.reverse();
  10165. }
  10166. me.legendItems = legendItems;
  10167. }
  10168. fit() {
  10169. const me = this;
  10170. const {options, ctx} = me;
  10171. if (!options.display) {
  10172. me.width = me.height = 0;
  10173. return;
  10174. }
  10175. const labelOpts = options.labels;
  10176. const labelFont = toFont(labelOpts.font);
  10177. const fontSize = labelFont.size;
  10178. const titleHeight = me._computeTitleHeight();
  10179. const {boxWidth, itemHeight} = getBoxSize(labelOpts, fontSize);
  10180. let width, height;
  10181. ctx.font = labelFont.string;
  10182. if (me.isHorizontal()) {
  10183. width = me.maxWidth;
  10184. height = me._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;
  10185. } else {
  10186. height = me.maxHeight;
  10187. width = me._fitCols(titleHeight, fontSize, boxWidth, itemHeight) + 10;
  10188. }
  10189. me.width = Math.min(width, options.maxWidth || me.maxWidth);
  10190. me.height = Math.min(height, options.maxHeight || me.maxHeight);
  10191. }
  10192. _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {
  10193. const me = this;
  10194. const {ctx, maxWidth, options: {labels: {padding}}} = me;
  10195. const hitboxes = me.legendHitBoxes = [];
  10196. const lineWidths = me.lineWidths = [0];
  10197. const lineHeight = itemHeight + padding;
  10198. let totalHeight = titleHeight;
  10199. ctx.textAlign = 'left';
  10200. ctx.textBaseline = 'middle';
  10201. let row = -1;
  10202. let top = -lineHeight;
  10203. me.legendItems.forEach((legendItem, i) => {
  10204. const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  10205. if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {
  10206. totalHeight += lineHeight;
  10207. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  10208. top += lineHeight;
  10209. row++;
  10210. }
  10211. hitboxes[i] = {left: 0, top, row, width: itemWidth, height: itemHeight};
  10212. lineWidths[lineWidths.length - 1] += itemWidth + padding;
  10213. });
  10214. return totalHeight;
  10215. }
  10216. _fitCols(titleHeight, fontSize, boxWidth, itemHeight) {
  10217. const me = this;
  10218. const {ctx, maxHeight, options: {labels: {padding}}} = me;
  10219. const hitboxes = me.legendHitBoxes = [];
  10220. const columnSizes = me.columnSizes = [];
  10221. const heightLimit = maxHeight - titleHeight;
  10222. let totalWidth = padding;
  10223. let currentColWidth = 0;
  10224. let currentColHeight = 0;
  10225. let left = 0;
  10226. let col = 0;
  10227. me.legendItems.forEach((legendItem, i) => {
  10228. const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  10229. if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) {
  10230. totalWidth += currentColWidth + padding;
  10231. columnSizes.push({width: currentColWidth, height: currentColHeight});
  10232. left += currentColWidth + padding;
  10233. col++;
  10234. currentColWidth = currentColHeight = 0;
  10235. }
  10236. hitboxes[i] = {left, top: currentColHeight, col, width: itemWidth, height: itemHeight};
  10237. currentColWidth = Math.max(currentColWidth, itemWidth);
  10238. currentColHeight += itemHeight + padding;
  10239. });
  10240. totalWidth += currentColWidth;
  10241. columnSizes.push({width: currentColWidth, height: currentColHeight});
  10242. return totalWidth;
  10243. }
  10244. adjustHitBoxes() {
  10245. const me = this;
  10246. if (!me.options.display) {
  10247. return;
  10248. }
  10249. const titleHeight = me._computeTitleHeight();
  10250. const {legendHitBoxes: hitboxes, options: {align, labels: {padding}, rtl}} = me;
  10251. const rtlHelper = getRtlAdapter(rtl, me.left, me.width);
  10252. if (this.isHorizontal()) {
  10253. let row = 0;
  10254. let left = _alignStartEnd(align, me.left + padding, me.right - me.lineWidths[row]);
  10255. for (const hitbox of hitboxes) {
  10256. if (row !== hitbox.row) {
  10257. row = hitbox.row;
  10258. left = _alignStartEnd(align, me.left + padding, me.right - me.lineWidths[row]);
  10259. }
  10260. hitbox.top += me.top + titleHeight + padding;
  10261. hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width);
  10262. left += hitbox.width + padding;
  10263. }
  10264. } else {
  10265. let col = 0;
  10266. let top = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - me.columnSizes[col].height);
  10267. for (const hitbox of hitboxes) {
  10268. if (hitbox.col !== col) {
  10269. col = hitbox.col;
  10270. top = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - me.columnSizes[col].height);
  10271. }
  10272. hitbox.top = top;
  10273. hitbox.left += me.left + padding;
  10274. hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width);
  10275. top += hitbox.height + padding;
  10276. }
  10277. }
  10278. }
  10279. isHorizontal() {
  10280. return this.options.position === 'top' || this.options.position === 'bottom';
  10281. }
  10282. draw() {
  10283. const me = this;
  10284. if (me.options.display) {
  10285. const ctx = me.ctx;
  10286. clipArea(ctx, me);
  10287. me._draw();
  10288. unclipArea(ctx);
  10289. }
  10290. }
  10291. _draw() {
  10292. const me = this;
  10293. const {options: opts, columnSizes, lineWidths, ctx} = me;
  10294. const {align, labels: labelOpts} = opts;
  10295. const defaultColor = defaults.color;
  10296. const rtlHelper = getRtlAdapter(opts.rtl, me.left, me.width);
  10297. const labelFont = toFont(labelOpts.font);
  10298. const {color: fontColor, padding} = labelOpts;
  10299. const fontSize = labelFont.size;
  10300. const halfFontSize = fontSize / 2;
  10301. let cursor;
  10302. me.drawTitle();
  10303. ctx.textAlign = rtlHelper.textAlign('left');
  10304. ctx.textBaseline = 'middle';
  10305. ctx.lineWidth = 0.5;
  10306. ctx.font = labelFont.string;
  10307. const {boxWidth, boxHeight, itemHeight} = getBoxSize(labelOpts, fontSize);
  10308. const drawLegendBox = function(x, y, legendItem) {
  10309. if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {
  10310. return;
  10311. }
  10312. ctx.save();
  10313. const lineWidth = valueOrDefault(legendItem.lineWidth, 1);
  10314. ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);
  10315. ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt');
  10316. ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0);
  10317. ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter');
  10318. ctx.lineWidth = lineWidth;
  10319. ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor);
  10320. ctx.setLineDash(valueOrDefault(legendItem.lineDash, []));
  10321. if (labelOpts.usePointStyle) {
  10322. const drawOptions = {
  10323. radius: boxWidth * Math.SQRT2 / 2,
  10324. pointStyle: legendItem.pointStyle,
  10325. rotation: legendItem.rotation,
  10326. borderWidth: lineWidth
  10327. };
  10328. const centerX = rtlHelper.xPlus(x, boxWidth / 2);
  10329. const centerY = y + halfFontSize;
  10330. drawPoint(ctx, drawOptions, centerX, centerY);
  10331. } else {
  10332. const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);
  10333. const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);
  10334. const borderRadius = toTRBLCorners(legendItem.borderRadius);
  10335. ctx.beginPath();
  10336. if (Object.values(borderRadius).some(v => v !== 0)) {
  10337. addRoundedRectPath(ctx, {
  10338. x: xBoxLeft,
  10339. y: yBoxTop,
  10340. w: boxWidth,
  10341. h: boxHeight,
  10342. radius: borderRadius,
  10343. });
  10344. } else {
  10345. ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);
  10346. }
  10347. ctx.fill();
  10348. if (lineWidth !== 0) {
  10349. ctx.stroke();
  10350. }
  10351. }
  10352. ctx.restore();
  10353. };
  10354. const fillText = function(x, y, legendItem) {
  10355. renderText(ctx, legendItem.text, x, y + (itemHeight / 2), labelFont, {
  10356. strikethrough: legendItem.hidden,
  10357. textAlign: rtlHelper.textAlign(legendItem.textAlign)
  10358. });
  10359. };
  10360. const isHorizontal = me.isHorizontal();
  10361. const titleHeight = this._computeTitleHeight();
  10362. if (isHorizontal) {
  10363. cursor = {
  10364. x: _alignStartEnd(align, me.left + padding, me.right - lineWidths[0]),
  10365. y: me.top + padding + titleHeight,
  10366. line: 0
  10367. };
  10368. } else {
  10369. cursor = {
  10370. x: me.left + padding,
  10371. y: _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - columnSizes[0].height),
  10372. line: 0
  10373. };
  10374. }
  10375. overrideTextDirection(me.ctx, opts.textDirection);
  10376. const lineHeight = itemHeight + padding;
  10377. me.legendItems.forEach((legendItem, i) => {
  10378. ctx.strokeStyle = legendItem.fontColor || fontColor;
  10379. ctx.fillStyle = legendItem.fontColor || fontColor;
  10380. const textWidth = ctx.measureText(legendItem.text).width;
  10381. const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));
  10382. const width = boxWidth + halfFontSize + textWidth;
  10383. let x = cursor.x;
  10384. let y = cursor.y;
  10385. rtlHelper.setWidth(me.width);
  10386. if (isHorizontal) {
  10387. if (i > 0 && x + width + padding > me.right) {
  10388. y = cursor.y += lineHeight;
  10389. cursor.line++;
  10390. x = cursor.x = _alignStartEnd(align, me.left + padding, me.right - lineWidths[cursor.line]);
  10391. }
  10392. } else if (i > 0 && y + lineHeight > me.bottom) {
  10393. x = cursor.x = x + columnSizes[cursor.line].width + padding;
  10394. cursor.line++;
  10395. y = cursor.y = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - columnSizes[cursor.line].height);
  10396. }
  10397. const realX = rtlHelper.x(x);
  10398. drawLegendBox(realX, y, legendItem);
  10399. x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : me.right, opts.rtl);
  10400. fillText(rtlHelper.x(x), y, legendItem);
  10401. if (isHorizontal) {
  10402. cursor.x += width + padding;
  10403. } else {
  10404. cursor.y += lineHeight;
  10405. }
  10406. });
  10407. restoreTextDirection(me.ctx, opts.textDirection);
  10408. }
  10409. drawTitle() {
  10410. const me = this;
  10411. const opts = me.options;
  10412. const titleOpts = opts.title;
  10413. const titleFont = toFont(titleOpts.font);
  10414. const titlePadding = toPadding(titleOpts.padding);
  10415. if (!titleOpts.display) {
  10416. return;
  10417. }
  10418. const rtlHelper = getRtlAdapter(opts.rtl, me.left, me.width);
  10419. const ctx = me.ctx;
  10420. const position = titleOpts.position;
  10421. const halfFontSize = titleFont.size / 2;
  10422. const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;
  10423. let y;
  10424. let left = me.left;
  10425. let maxWidth = me.width;
  10426. if (this.isHorizontal()) {
  10427. maxWidth = Math.max(...me.lineWidths);
  10428. y = me.top + topPaddingPlusHalfFontSize;
  10429. left = _alignStartEnd(opts.align, left, me.right - maxWidth);
  10430. } else {
  10431. const maxHeight = me.columnSizes.reduce((acc, size) => Math.max(acc, size.height), 0);
  10432. y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, me.top, me.bottom - maxHeight - opts.labels.padding - me._computeTitleHeight());
  10433. }
  10434. const x = _alignStartEnd(position, left, left + maxWidth);
  10435. ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position));
  10436. ctx.textBaseline = 'middle';
  10437. ctx.strokeStyle = titleOpts.color;
  10438. ctx.fillStyle = titleOpts.color;
  10439. ctx.font = titleFont.string;
  10440. renderText(ctx, titleOpts.text, x, y, titleFont);
  10441. }
  10442. _computeTitleHeight() {
  10443. const titleOpts = this.options.title;
  10444. const titleFont = toFont(titleOpts.font);
  10445. const titlePadding = toPadding(titleOpts.padding);
  10446. return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
  10447. }
  10448. _getLegendItemAt(x, y) {
  10449. const me = this;
  10450. let i, hitBox, lh;
  10451. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  10452. lh = me.legendHitBoxes;
  10453. for (i = 0; i < lh.length; ++i) {
  10454. hitBox = lh[i];
  10455. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  10456. return me.legendItems[i];
  10457. }
  10458. }
  10459. }
  10460. return null;
  10461. }
  10462. handleEvent(e) {
  10463. const me = this;
  10464. const opts = me.options;
  10465. if (!isListened(e.type, opts)) {
  10466. return;
  10467. }
  10468. const hoveredItem = me._getLegendItemAt(e.x, e.y);
  10469. if (e.type === 'mousemove') {
  10470. const previous = me._hoveredItem;
  10471. const sameItem = itemsEqual(previous, hoveredItem);
  10472. if (previous && !sameItem) {
  10473. callback(opts.onLeave, [e, previous, me], me);
  10474. }
  10475. me._hoveredItem = hoveredItem;
  10476. if (hoveredItem && !sameItem) {
  10477. callback(opts.onHover, [e, hoveredItem, me], me);
  10478. }
  10479. } else if (hoveredItem) {
  10480. callback(opts.onClick, [e, hoveredItem, me], me);
  10481. }
  10482. }
  10483. }
  10484. function isListened(type, opts) {
  10485. if (type === 'mousemove' && (opts.onHover || opts.onLeave)) {
  10486. return true;
  10487. }
  10488. if (opts.onClick && (type === 'click' || type === 'mouseup')) {
  10489. return true;
  10490. }
  10491. return false;
  10492. }
  10493. var plugin_legend = {
  10494. id: 'legend',
  10495. _element: Legend,
  10496. start(chart, _args, options) {
  10497. const legend = chart.legend = new Legend({ctx: chart.ctx, options, chart});
  10498. layouts.configure(chart, legend, options);
  10499. layouts.addBox(chart, legend);
  10500. },
  10501. stop(chart) {
  10502. layouts.removeBox(chart, chart.legend);
  10503. delete chart.legend;
  10504. },
  10505. beforeUpdate(chart, _args, options) {
  10506. const legend = chart.legend;
  10507. layouts.configure(chart, legend, options);
  10508. legend.options = options;
  10509. },
  10510. afterUpdate(chart) {
  10511. const legend = chart.legend;
  10512. legend.buildLabels();
  10513. legend.adjustHitBoxes();
  10514. },
  10515. afterEvent(chart, args) {
  10516. if (!args.replay) {
  10517. chart.legend.handleEvent(args.event);
  10518. }
  10519. },
  10520. defaults: {
  10521. display: true,
  10522. position: 'top',
  10523. align: 'center',
  10524. fullSize: true,
  10525. reverse: false,
  10526. weight: 1000,
  10527. onClick(e, legendItem, legend) {
  10528. const index = legendItem.datasetIndex;
  10529. const ci = legend.chart;
  10530. if (ci.isDatasetVisible(index)) {
  10531. ci.hide(index);
  10532. legendItem.hidden = true;
  10533. } else {
  10534. ci.show(index);
  10535. legendItem.hidden = false;
  10536. }
  10537. },
  10538. onHover: null,
  10539. onLeave: null,
  10540. labels: {
  10541. color: (ctx) => ctx.chart.options.color,
  10542. boxWidth: 40,
  10543. padding: 10,
  10544. generateLabels(chart) {
  10545. const datasets = chart.data.datasets;
  10546. const {labels: {usePointStyle, pointStyle, textAlign, color}} = chart.legend.options;
  10547. return chart._getSortedDatasetMetas().map((meta) => {
  10548. const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  10549. const borderWidth = toPadding(style.borderWidth);
  10550. return {
  10551. text: datasets[meta.index].label,
  10552. fillStyle: style.backgroundColor,
  10553. fontColor: color,
  10554. hidden: !meta.visible,
  10555. lineCap: style.borderCapStyle,
  10556. lineDash: style.borderDash,
  10557. lineDashOffset: style.borderDashOffset,
  10558. lineJoin: style.borderJoinStyle,
  10559. lineWidth: (borderWidth.width + borderWidth.height) / 4,
  10560. strokeStyle: style.borderColor,
  10561. pointStyle: pointStyle || style.pointStyle,
  10562. rotation: style.rotation,
  10563. textAlign: textAlign || style.textAlign,
  10564. borderRadius: 0,
  10565. datasetIndex: meta.index
  10566. };
  10567. }, this);
  10568. }
  10569. },
  10570. title: {
  10571. color: (ctx) => ctx.chart.options.color,
  10572. display: false,
  10573. position: 'center',
  10574. text: '',
  10575. }
  10576. },
  10577. descriptors: {
  10578. _scriptable: (name) => !name.startsWith('on'),
  10579. labels: {
  10580. _scriptable: (name) => !['generateLabels', 'filter', 'sort'].includes(name),
  10581. }
  10582. },
  10583. };
  10584. class Title extends Element {
  10585. constructor(config) {
  10586. super();
  10587. this.chart = config.chart;
  10588. this.options = config.options;
  10589. this.ctx = config.ctx;
  10590. this._padding = undefined;
  10591. this.top = undefined;
  10592. this.bottom = undefined;
  10593. this.left = undefined;
  10594. this.right = undefined;
  10595. this.width = undefined;
  10596. this.height = undefined;
  10597. this.position = undefined;
  10598. this.weight = undefined;
  10599. this.fullSize = undefined;
  10600. }
  10601. update(maxWidth, maxHeight) {
  10602. const me = this;
  10603. const opts = me.options;
  10604. me.left = 0;
  10605. me.top = 0;
  10606. if (!opts.display) {
  10607. me.width = me.height = me.right = me.bottom = 0;
  10608. return;
  10609. }
  10610. me.width = me.right = maxWidth;
  10611. me.height = me.bottom = maxHeight;
  10612. const lineCount = isArray(opts.text) ? opts.text.length : 1;
  10613. me._padding = toPadding(opts.padding);
  10614. const textSize = lineCount * toFont(opts.font).lineHeight + me._padding.height;
  10615. if (me.isHorizontal()) {
  10616. me.height = textSize;
  10617. } else {
  10618. me.width = textSize;
  10619. }
  10620. }
  10621. isHorizontal() {
  10622. const pos = this.options.position;
  10623. return pos === 'top' || pos === 'bottom';
  10624. }
  10625. _drawArgs(offset) {
  10626. const {top, left, bottom, right, options} = this;
  10627. const align = options.align;
  10628. let rotation = 0;
  10629. let maxWidth, titleX, titleY;
  10630. if (this.isHorizontal()) {
  10631. titleX = _alignStartEnd(align, left, right);
  10632. titleY = top + offset;
  10633. maxWidth = right - left;
  10634. } else {
  10635. if (options.position === 'left') {
  10636. titleX = left + offset;
  10637. titleY = _alignStartEnd(align, bottom, top);
  10638. rotation = PI * -0.5;
  10639. } else {
  10640. titleX = right - offset;
  10641. titleY = _alignStartEnd(align, top, bottom);
  10642. rotation = PI * 0.5;
  10643. }
  10644. maxWidth = bottom - top;
  10645. }
  10646. return {titleX, titleY, maxWidth, rotation};
  10647. }
  10648. draw() {
  10649. const me = this;
  10650. const ctx = me.ctx;
  10651. const opts = me.options;
  10652. if (!opts.display) {
  10653. return;
  10654. }
  10655. const fontOpts = toFont(opts.font);
  10656. const lineHeight = fontOpts.lineHeight;
  10657. const offset = lineHeight / 2 + me._padding.top;
  10658. const {titleX, titleY, maxWidth, rotation} = me._drawArgs(offset);
  10659. renderText(ctx, opts.text, 0, 0, fontOpts, {
  10660. color: opts.color,
  10661. maxWidth,
  10662. rotation,
  10663. textAlign: _toLeftRightCenter(opts.align),
  10664. textBaseline: 'middle',
  10665. translation: [titleX, titleY],
  10666. });
  10667. }
  10668. }
  10669. function createTitle(chart, titleOpts) {
  10670. const title = new Title({
  10671. ctx: chart.ctx,
  10672. options: titleOpts,
  10673. chart
  10674. });
  10675. layouts.configure(chart, title, titleOpts);
  10676. layouts.addBox(chart, title);
  10677. chart.titleBlock = title;
  10678. }
  10679. var plugin_title = {
  10680. id: 'title',
  10681. _element: Title,
  10682. start(chart, _args, options) {
  10683. createTitle(chart, options);
  10684. },
  10685. stop(chart) {
  10686. const titleBlock = chart.titleBlock;
  10687. layouts.removeBox(chart, titleBlock);
  10688. delete chart.titleBlock;
  10689. },
  10690. beforeUpdate(chart, _args, options) {
  10691. const title = chart.titleBlock;
  10692. layouts.configure(chart, title, options);
  10693. title.options = options;
  10694. },
  10695. defaults: {
  10696. align: 'center',
  10697. display: false,
  10698. font: {
  10699. weight: 'bold',
  10700. },
  10701. fullSize: true,
  10702. padding: 10,
  10703. position: 'top',
  10704. text: '',
  10705. weight: 2000
  10706. },
  10707. defaultRoutes: {
  10708. color: 'color'
  10709. },
  10710. descriptors: {
  10711. _scriptable: true,
  10712. _indexable: false,
  10713. },
  10714. };
  10715. const map = new WeakMap();
  10716. var plugin_subtitle = {
  10717. id: 'subtitle',
  10718. start(chart, _args, options) {
  10719. const title = new Title({
  10720. ctx: chart.ctx,
  10721. options,
  10722. chart
  10723. });
  10724. layouts.configure(chart, title, options);
  10725. layouts.addBox(chart, title);
  10726. map.set(chart, title);
  10727. },
  10728. stop(chart) {
  10729. layouts.removeBox(chart, map.get(chart));
  10730. map.delete(chart);
  10731. },
  10732. beforeUpdate(chart, _args, options) {
  10733. const title = map.get(chart);
  10734. layouts.configure(chart, title, options);
  10735. title.options = options;
  10736. },
  10737. defaults: {
  10738. align: 'center',
  10739. display: false,
  10740. font: {
  10741. weight: 'normal',
  10742. },
  10743. fullSize: true,
  10744. padding: 0,
  10745. position: 'top',
  10746. text: '',
  10747. weight: 1500
  10748. },
  10749. defaultRoutes: {
  10750. color: 'color'
  10751. },
  10752. descriptors: {
  10753. _scriptable: true,
  10754. _indexable: false,
  10755. },
  10756. };
  10757. const positioners = {
  10758. average(items) {
  10759. if (!items.length) {
  10760. return false;
  10761. }
  10762. let i, len;
  10763. let x = 0;
  10764. let y = 0;
  10765. let count = 0;
  10766. for (i = 0, len = items.length; i < len; ++i) {
  10767. const el = items[i].element;
  10768. if (el && el.hasValue()) {
  10769. const pos = el.tooltipPosition();
  10770. x += pos.x;
  10771. y += pos.y;
  10772. ++count;
  10773. }
  10774. }
  10775. return {
  10776. x: x / count,
  10777. y: y / count
  10778. };
  10779. },
  10780. nearest(items, eventPosition) {
  10781. if (!items.length) {
  10782. return false;
  10783. }
  10784. let x = eventPosition.x;
  10785. let y = eventPosition.y;
  10786. let minDistance = Number.POSITIVE_INFINITY;
  10787. let i, len, nearestElement;
  10788. for (i = 0, len = items.length; i < len; ++i) {
  10789. const el = items[i].element;
  10790. if (el && el.hasValue()) {
  10791. const center = el.getCenterPoint();
  10792. const d = distanceBetweenPoints(eventPosition, center);
  10793. if (d < minDistance) {
  10794. minDistance = d;
  10795. nearestElement = el;
  10796. }
  10797. }
  10798. }
  10799. if (nearestElement) {
  10800. const tp = nearestElement.tooltipPosition();
  10801. x = tp.x;
  10802. y = tp.y;
  10803. }
  10804. return {
  10805. x,
  10806. y
  10807. };
  10808. }
  10809. };
  10810. function pushOrConcat(base, toPush) {
  10811. if (toPush) {
  10812. if (isArray(toPush)) {
  10813. Array.prototype.push.apply(base, toPush);
  10814. } else {
  10815. base.push(toPush);
  10816. }
  10817. }
  10818. return base;
  10819. }
  10820. function splitNewlines(str) {
  10821. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  10822. return str.split('\n');
  10823. }
  10824. return str;
  10825. }
  10826. function createTooltipItem(chart, item) {
  10827. const {element, datasetIndex, index} = item;
  10828. const controller = chart.getDatasetMeta(datasetIndex).controller;
  10829. const {label, value} = controller.getLabelAndValue(index);
  10830. return {
  10831. chart,
  10832. label,
  10833. parsed: controller.getParsed(index),
  10834. raw: chart.data.datasets[datasetIndex].data[index],
  10835. formattedValue: value,
  10836. dataset: controller.getDataset(),
  10837. dataIndex: index,
  10838. datasetIndex,
  10839. element
  10840. };
  10841. }
  10842. function getTooltipSize(tooltip, options) {
  10843. const ctx = tooltip._chart.ctx;
  10844. const {body, footer, title} = tooltip;
  10845. const {boxWidth, boxHeight} = options;
  10846. const bodyFont = toFont(options.bodyFont);
  10847. const titleFont = toFont(options.titleFont);
  10848. const footerFont = toFont(options.footerFont);
  10849. const titleLineCount = title.length;
  10850. const footerLineCount = footer.length;
  10851. const bodyLineItemCount = body.length;
  10852. const padding = toPadding(options.padding);
  10853. let height = padding.height;
  10854. let width = 0;
  10855. let combinedBodyLength = body.reduce((count, bodyItem) => count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);
  10856. combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;
  10857. if (titleLineCount) {
  10858. height += titleLineCount * titleFont.lineHeight
  10859. + (titleLineCount - 1) * options.titleSpacing
  10860. + options.titleMarginBottom;
  10861. }
  10862. if (combinedBodyLength) {
  10863. const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;
  10864. height += bodyLineItemCount * bodyLineHeight
  10865. + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight
  10866. + (combinedBodyLength - 1) * options.bodySpacing;
  10867. }
  10868. if (footerLineCount) {
  10869. height += options.footerMarginTop
  10870. + footerLineCount * footerFont.lineHeight
  10871. + (footerLineCount - 1) * options.footerSpacing;
  10872. }
  10873. let widthPadding = 0;
  10874. const maxLineWidth = function(line) {
  10875. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  10876. };
  10877. ctx.save();
  10878. ctx.font = titleFont.string;
  10879. each(tooltip.title, maxLineWidth);
  10880. ctx.font = bodyFont.string;
  10881. each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);
  10882. widthPadding = options.displayColors ? (boxWidth + 2) : 0;
  10883. each(body, (bodyItem) => {
  10884. each(bodyItem.before, maxLineWidth);
  10885. each(bodyItem.lines, maxLineWidth);
  10886. each(bodyItem.after, maxLineWidth);
  10887. });
  10888. widthPadding = 0;
  10889. ctx.font = footerFont.string;
  10890. each(tooltip.footer, maxLineWidth);
  10891. ctx.restore();
  10892. width += padding.width;
  10893. return {width, height};
  10894. }
  10895. function determineYAlign(chart, size) {
  10896. const {y, height} = size;
  10897. if (y < height / 2) {
  10898. return 'top';
  10899. } else if (y > (chart.height - height / 2)) {
  10900. return 'bottom';
  10901. }
  10902. return 'center';
  10903. }
  10904. function doesNotFitWithAlign(xAlign, chart, options, size) {
  10905. const {x, width} = size;
  10906. const caret = options.caretSize + options.caretPadding;
  10907. if (xAlign === 'left' && x + width + caret > chart.width) {
  10908. return true;
  10909. }
  10910. if (xAlign === 'right' && x - width - caret < 0) {
  10911. return true;
  10912. }
  10913. }
  10914. function determineXAlign(chart, options, size, yAlign) {
  10915. const {x, width} = size;
  10916. const {width: chartWidth, chartArea: {left, right}} = chart;
  10917. let xAlign = 'center';
  10918. if (yAlign === 'center') {
  10919. xAlign = x <= (left + right) / 2 ? 'left' : 'right';
  10920. } else if (x <= width / 2) {
  10921. xAlign = 'left';
  10922. } else if (x >= chartWidth - width / 2) {
  10923. xAlign = 'right';
  10924. }
  10925. if (doesNotFitWithAlign(xAlign, chart, options, size)) {
  10926. xAlign = 'center';
  10927. }
  10928. return xAlign;
  10929. }
  10930. function determineAlignment(chart, options, size) {
  10931. const yAlign = options.yAlign || determineYAlign(chart, size);
  10932. return {
  10933. xAlign: options.xAlign || determineXAlign(chart, options, size, yAlign),
  10934. yAlign
  10935. };
  10936. }
  10937. function alignX(size, xAlign) {
  10938. let {x, width} = size;
  10939. if (xAlign === 'right') {
  10940. x -= width;
  10941. } else if (xAlign === 'center') {
  10942. x -= (width / 2);
  10943. }
  10944. return x;
  10945. }
  10946. function alignY(size, yAlign, paddingAndSize) {
  10947. let {y, height} = size;
  10948. if (yAlign === 'top') {
  10949. y += paddingAndSize;
  10950. } else if (yAlign === 'bottom') {
  10951. y -= height + paddingAndSize;
  10952. } else {
  10953. y -= (height / 2);
  10954. }
  10955. return y;
  10956. }
  10957. function getBackgroundPoint(options, size, alignment, chart) {
  10958. const {caretSize, caretPadding, cornerRadius} = options;
  10959. const {xAlign, yAlign} = alignment;
  10960. const paddingAndSize = caretSize + caretPadding;
  10961. const radiusAndPadding = cornerRadius + caretPadding;
  10962. let x = alignX(size, xAlign);
  10963. const y = alignY(size, yAlign, paddingAndSize);
  10964. if (yAlign === 'center') {
  10965. if (xAlign === 'left') {
  10966. x += paddingAndSize;
  10967. } else if (xAlign === 'right') {
  10968. x -= paddingAndSize;
  10969. }
  10970. } else if (xAlign === 'left') {
  10971. x -= radiusAndPadding;
  10972. } else if (xAlign === 'right') {
  10973. x += radiusAndPadding;
  10974. }
  10975. return {
  10976. x: _limitValue(x, 0, chart.width - size.width),
  10977. y: _limitValue(y, 0, chart.height - size.height)
  10978. };
  10979. }
  10980. function getAlignedX(tooltip, align, options) {
  10981. const padding = toPadding(options.padding);
  10982. return align === 'center'
  10983. ? tooltip.x + tooltip.width / 2
  10984. : align === 'right'
  10985. ? tooltip.x + tooltip.width - padding.right
  10986. : tooltip.x + padding.left;
  10987. }
  10988. function getBeforeAfterBodyLines(callback) {
  10989. return pushOrConcat([], splitNewlines(callback));
  10990. }
  10991. function createTooltipContext(parent, tooltip, tooltipItems) {
  10992. return Object.assign(Object.create(parent), {
  10993. tooltip,
  10994. tooltipItems,
  10995. type: 'tooltip'
  10996. });
  10997. }
  10998. function overrideCallbacks(callbacks, context) {
  10999. const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;
  11000. return override ? callbacks.override(override) : callbacks;
  11001. }
  11002. class Tooltip extends Element {
  11003. constructor(config) {
  11004. super();
  11005. this.opacity = 0;
  11006. this._active = [];
  11007. this._chart = config._chart;
  11008. this._eventPosition = undefined;
  11009. this._size = undefined;
  11010. this._cachedAnimations = undefined;
  11011. this._tooltipItems = [];
  11012. this.$animations = undefined;
  11013. this.$context = undefined;
  11014. this.options = config.options;
  11015. this.dataPoints = undefined;
  11016. this.title = undefined;
  11017. this.beforeBody = undefined;
  11018. this.body = undefined;
  11019. this.afterBody = undefined;
  11020. this.footer = undefined;
  11021. this.xAlign = undefined;
  11022. this.yAlign = undefined;
  11023. this.x = undefined;
  11024. this.y = undefined;
  11025. this.height = undefined;
  11026. this.width = undefined;
  11027. this.caretX = undefined;
  11028. this.caretY = undefined;
  11029. this.labelColors = undefined;
  11030. this.labelPointStyles = undefined;
  11031. this.labelTextColors = undefined;
  11032. }
  11033. initialize(options) {
  11034. this.options = options;
  11035. this._cachedAnimations = undefined;
  11036. this.$context = undefined;
  11037. }
  11038. _resolveAnimations() {
  11039. const me = this;
  11040. const cached = me._cachedAnimations;
  11041. if (cached) {
  11042. return cached;
  11043. }
  11044. const chart = me._chart;
  11045. const options = me.options.setContext(me.getContext());
  11046. const opts = options.enabled && chart.options.animation && options.animations;
  11047. const animations = new Animations(me._chart, opts);
  11048. if (opts._cacheable) {
  11049. me._cachedAnimations = Object.freeze(animations);
  11050. }
  11051. return animations;
  11052. }
  11053. getContext() {
  11054. const me = this;
  11055. return me.$context ||
  11056. (me.$context = createTooltipContext(me._chart.getContext(), me, me._tooltipItems));
  11057. }
  11058. getTitle(context, options) {
  11059. const me = this;
  11060. const {callbacks} = options;
  11061. const beforeTitle = callbacks.beforeTitle.apply(me, [context]);
  11062. const title = callbacks.title.apply(me, [context]);
  11063. const afterTitle = callbacks.afterTitle.apply(me, [context]);
  11064. let lines = [];
  11065. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  11066. lines = pushOrConcat(lines, splitNewlines(title));
  11067. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  11068. return lines;
  11069. }
  11070. getBeforeBody(tooltipItems, options) {
  11071. return getBeforeAfterBodyLines(options.callbacks.beforeBody.apply(this, [tooltipItems]));
  11072. }
  11073. getBody(tooltipItems, options) {
  11074. const me = this;
  11075. const {callbacks} = options;
  11076. const bodyItems = [];
  11077. each(tooltipItems, (context) => {
  11078. const bodyItem = {
  11079. before: [],
  11080. lines: [],
  11081. after: []
  11082. };
  11083. const scoped = overrideCallbacks(callbacks, context);
  11084. pushOrConcat(bodyItem.before, splitNewlines(scoped.beforeLabel.call(me, context)));
  11085. pushOrConcat(bodyItem.lines, scoped.label.call(me, context));
  11086. pushOrConcat(bodyItem.after, splitNewlines(scoped.afterLabel.call(me, context)));
  11087. bodyItems.push(bodyItem);
  11088. });
  11089. return bodyItems;
  11090. }
  11091. getAfterBody(tooltipItems, options) {
  11092. return getBeforeAfterBodyLines(options.callbacks.afterBody.apply(this, [tooltipItems]));
  11093. }
  11094. getFooter(tooltipItems, options) {
  11095. const me = this;
  11096. const {callbacks} = options;
  11097. const beforeFooter = callbacks.beforeFooter.apply(me, [tooltipItems]);
  11098. const footer = callbacks.footer.apply(me, [tooltipItems]);
  11099. const afterFooter = callbacks.afterFooter.apply(me, [tooltipItems]);
  11100. let lines = [];
  11101. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  11102. lines = pushOrConcat(lines, splitNewlines(footer));
  11103. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  11104. return lines;
  11105. }
  11106. _createItems(options) {
  11107. const me = this;
  11108. const active = me._active;
  11109. const data = me._chart.data;
  11110. const labelColors = [];
  11111. const labelPointStyles = [];
  11112. const labelTextColors = [];
  11113. let tooltipItems = [];
  11114. let i, len;
  11115. for (i = 0, len = active.length; i < len; ++i) {
  11116. tooltipItems.push(createTooltipItem(me._chart, active[i]));
  11117. }
  11118. if (options.filter) {
  11119. tooltipItems = tooltipItems.filter((element, index, array) => options.filter(element, index, array, data));
  11120. }
  11121. if (options.itemSort) {
  11122. tooltipItems = tooltipItems.sort((a, b) => options.itemSort(a, b, data));
  11123. }
  11124. each(tooltipItems, (context) => {
  11125. const scoped = overrideCallbacks(options.callbacks, context);
  11126. labelColors.push(scoped.labelColor.call(me, context));
  11127. labelPointStyles.push(scoped.labelPointStyle.call(me, context));
  11128. labelTextColors.push(scoped.labelTextColor.call(me, context));
  11129. });
  11130. me.labelColors = labelColors;
  11131. me.labelPointStyles = labelPointStyles;
  11132. me.labelTextColors = labelTextColors;
  11133. me.dataPoints = tooltipItems;
  11134. return tooltipItems;
  11135. }
  11136. update(changed, replay) {
  11137. const me = this;
  11138. const options = me.options.setContext(me.getContext());
  11139. const active = me._active;
  11140. let properties;
  11141. let tooltipItems = [];
  11142. if (!active.length) {
  11143. if (me.opacity !== 0) {
  11144. properties = {
  11145. opacity: 0
  11146. };
  11147. }
  11148. } else {
  11149. const position = positioners[options.position].call(me, active, me._eventPosition);
  11150. tooltipItems = me._createItems(options);
  11151. me.title = me.getTitle(tooltipItems, options);
  11152. me.beforeBody = me.getBeforeBody(tooltipItems, options);
  11153. me.body = me.getBody(tooltipItems, options);
  11154. me.afterBody = me.getAfterBody(tooltipItems, options);
  11155. me.footer = me.getFooter(tooltipItems, options);
  11156. const size = me._size = getTooltipSize(me, options);
  11157. const positionAndSize = Object.assign({}, position, size);
  11158. const alignment = determineAlignment(me._chart, options, positionAndSize);
  11159. const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, me._chart);
  11160. me.xAlign = alignment.xAlign;
  11161. me.yAlign = alignment.yAlign;
  11162. properties = {
  11163. opacity: 1,
  11164. x: backgroundPoint.x,
  11165. y: backgroundPoint.y,
  11166. width: size.width,
  11167. height: size.height,
  11168. caretX: position.x,
  11169. caretY: position.y
  11170. };
  11171. }
  11172. me._tooltipItems = tooltipItems;
  11173. me.$context = undefined;
  11174. if (properties) {
  11175. me._resolveAnimations().update(me, properties);
  11176. }
  11177. if (changed && options.external) {
  11178. options.external.call(me, {chart: me._chart, tooltip: me, replay});
  11179. }
  11180. }
  11181. drawCaret(tooltipPoint, ctx, size, options) {
  11182. const caretPosition = this.getCaretPosition(tooltipPoint, size, options);
  11183. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  11184. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  11185. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  11186. }
  11187. getCaretPosition(tooltipPoint, size, options) {
  11188. const {xAlign, yAlign} = this;
  11189. const {cornerRadius, caretSize} = options;
  11190. const {x: ptX, y: ptY} = tooltipPoint;
  11191. const {width, height} = size;
  11192. let x1, x2, x3, y1, y2, y3;
  11193. if (yAlign === 'center') {
  11194. y2 = ptY + (height / 2);
  11195. if (xAlign === 'left') {
  11196. x1 = ptX;
  11197. x2 = x1 - caretSize;
  11198. y1 = y2 + caretSize;
  11199. y3 = y2 - caretSize;
  11200. } else {
  11201. x1 = ptX + width;
  11202. x2 = x1 + caretSize;
  11203. y1 = y2 - caretSize;
  11204. y3 = y2 + caretSize;
  11205. }
  11206. x3 = x1;
  11207. } else {
  11208. if (xAlign === 'left') {
  11209. x2 = ptX + cornerRadius + (caretSize);
  11210. } else if (xAlign === 'right') {
  11211. x2 = ptX + width - cornerRadius - caretSize;
  11212. } else {
  11213. x2 = this.caretX;
  11214. }
  11215. if (yAlign === 'top') {
  11216. y1 = ptY;
  11217. y2 = y1 - caretSize;
  11218. x1 = x2 - caretSize;
  11219. x3 = x2 + caretSize;
  11220. } else {
  11221. y1 = ptY + height;
  11222. y2 = y1 + caretSize;
  11223. x1 = x2 + caretSize;
  11224. x3 = x2 - caretSize;
  11225. }
  11226. y3 = y1;
  11227. }
  11228. return {x1, x2, x3, y1, y2, y3};
  11229. }
  11230. drawTitle(pt, ctx, options) {
  11231. const me = this;
  11232. const title = me.title;
  11233. const length = title.length;
  11234. let titleFont, titleSpacing, i;
  11235. if (length) {
  11236. const rtlHelper = getRtlAdapter(options.rtl, me.x, me.width);
  11237. pt.x = getAlignedX(me, options.titleAlign, options);
  11238. ctx.textAlign = rtlHelper.textAlign(options.titleAlign);
  11239. ctx.textBaseline = 'middle';
  11240. titleFont = toFont(options.titleFont);
  11241. titleSpacing = options.titleSpacing;
  11242. ctx.fillStyle = options.titleColor;
  11243. ctx.font = titleFont.string;
  11244. for (i = 0; i < length; ++i) {
  11245. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);
  11246. pt.y += titleFont.lineHeight + titleSpacing;
  11247. if (i + 1 === length) {
  11248. pt.y += options.titleMarginBottom - titleSpacing;
  11249. }
  11250. }
  11251. }
  11252. }
  11253. _drawColorBox(ctx, pt, i, rtlHelper, options) {
  11254. const me = this;
  11255. const labelColors = me.labelColors[i];
  11256. const labelPointStyle = me.labelPointStyles[i];
  11257. const {boxHeight, boxWidth} = options;
  11258. const bodyFont = toFont(options.bodyFont);
  11259. const colorX = getAlignedX(me, 'left', options);
  11260. const rtlColorX = rtlHelper.x(colorX);
  11261. const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;
  11262. const colorY = pt.y + yOffSet;
  11263. if (options.usePointStyle) {
  11264. const drawOptions = {
  11265. radius: Math.min(boxWidth, boxHeight) / 2,
  11266. pointStyle: labelPointStyle.pointStyle,
  11267. rotation: labelPointStyle.rotation,
  11268. borderWidth: 1
  11269. };
  11270. const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;
  11271. const centerY = colorY + boxHeight / 2;
  11272. ctx.strokeStyle = options.multiKeyBackground;
  11273. ctx.fillStyle = options.multiKeyBackground;
  11274. drawPoint(ctx, drawOptions, centerX, centerY);
  11275. ctx.strokeStyle = labelColors.borderColor;
  11276. ctx.fillStyle = labelColors.backgroundColor;
  11277. drawPoint(ctx, drawOptions, centerX, centerY);
  11278. } else {
  11279. ctx.lineWidth = labelColors.borderWidth || 1;
  11280. ctx.strokeStyle = labelColors.borderColor;
  11281. ctx.setLineDash(labelColors.borderDash || []);
  11282. ctx.lineDashOffset = labelColors.borderDashOffset || 0;
  11283. const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth);
  11284. const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2);
  11285. const borderRadius = toTRBLCorners(labelColors.borderRadius);
  11286. if (Object.values(borderRadius).some(v => v !== 0)) {
  11287. ctx.beginPath();
  11288. ctx.fillStyle = options.multiKeyBackground;
  11289. addRoundedRectPath(ctx, {
  11290. x: outerX,
  11291. y: colorY,
  11292. w: boxWidth,
  11293. h: boxHeight,
  11294. radius: borderRadius,
  11295. });
  11296. ctx.fill();
  11297. ctx.stroke();
  11298. ctx.fillStyle = labelColors.backgroundColor;
  11299. ctx.beginPath();
  11300. addRoundedRectPath(ctx, {
  11301. x: innerX,
  11302. y: colorY + 1,
  11303. w: boxWidth - 2,
  11304. h: boxHeight - 2,
  11305. radius: borderRadius,
  11306. });
  11307. ctx.fill();
  11308. } else {
  11309. ctx.fillStyle = options.multiKeyBackground;
  11310. ctx.fillRect(outerX, colorY, boxWidth, boxHeight);
  11311. ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);
  11312. ctx.fillStyle = labelColors.backgroundColor;
  11313. ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);
  11314. }
  11315. }
  11316. ctx.fillStyle = me.labelTextColors[i];
  11317. }
  11318. drawBody(pt, ctx, options) {
  11319. const me = this;
  11320. const {body} = me;
  11321. const {bodySpacing, bodyAlign, displayColors, boxHeight, boxWidth} = options;
  11322. const bodyFont = toFont(options.bodyFont);
  11323. let bodyLineHeight = bodyFont.lineHeight;
  11324. let xLinePadding = 0;
  11325. const rtlHelper = getRtlAdapter(options.rtl, me.x, me.width);
  11326. const fillLineOfText = function(line) {
  11327. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);
  11328. pt.y += bodyLineHeight + bodySpacing;
  11329. };
  11330. const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  11331. let bodyItem, textColor, lines, i, j, ilen, jlen;
  11332. ctx.textAlign = bodyAlign;
  11333. ctx.textBaseline = 'middle';
  11334. ctx.font = bodyFont.string;
  11335. pt.x = getAlignedX(me, bodyAlignForCalculation, options);
  11336. ctx.fillStyle = options.bodyColor;
  11337. each(me.beforeBody, fillLineOfText);
  11338. xLinePadding = displayColors && bodyAlignForCalculation !== 'right'
  11339. ? bodyAlign === 'center' ? (boxWidth / 2 + 1) : (boxWidth + 2)
  11340. : 0;
  11341. for (i = 0, ilen = body.length; i < ilen; ++i) {
  11342. bodyItem = body[i];
  11343. textColor = me.labelTextColors[i];
  11344. ctx.fillStyle = textColor;
  11345. each(bodyItem.before, fillLineOfText);
  11346. lines = bodyItem.lines;
  11347. if (displayColors && lines.length) {
  11348. me._drawColorBox(ctx, pt, i, rtlHelper, options);
  11349. bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);
  11350. }
  11351. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  11352. fillLineOfText(lines[j]);
  11353. bodyLineHeight = bodyFont.lineHeight;
  11354. }
  11355. each(bodyItem.after, fillLineOfText);
  11356. }
  11357. xLinePadding = 0;
  11358. bodyLineHeight = bodyFont.lineHeight;
  11359. each(me.afterBody, fillLineOfText);
  11360. pt.y -= bodySpacing;
  11361. }
  11362. drawFooter(pt, ctx, options) {
  11363. const me = this;
  11364. const footer = me.footer;
  11365. const length = footer.length;
  11366. let footerFont, i;
  11367. if (length) {
  11368. const rtlHelper = getRtlAdapter(options.rtl, me.x, me.width);
  11369. pt.x = getAlignedX(me, options.footerAlign, options);
  11370. pt.y += options.footerMarginTop;
  11371. ctx.textAlign = rtlHelper.textAlign(options.footerAlign);
  11372. ctx.textBaseline = 'middle';
  11373. footerFont = toFont(options.footerFont);
  11374. ctx.fillStyle = options.footerColor;
  11375. ctx.font = footerFont.string;
  11376. for (i = 0; i < length; ++i) {
  11377. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);
  11378. pt.y += footerFont.lineHeight + options.footerSpacing;
  11379. }
  11380. }
  11381. }
  11382. drawBackground(pt, ctx, tooltipSize, options) {
  11383. const {xAlign, yAlign} = this;
  11384. const {x, y} = pt;
  11385. const {width, height} = tooltipSize;
  11386. const radius = options.cornerRadius;
  11387. ctx.fillStyle = options.backgroundColor;
  11388. ctx.strokeStyle = options.borderColor;
  11389. ctx.lineWidth = options.borderWidth;
  11390. ctx.beginPath();
  11391. ctx.moveTo(x + radius, y);
  11392. if (yAlign === 'top') {
  11393. this.drawCaret(pt, ctx, tooltipSize, options);
  11394. }
  11395. ctx.lineTo(x + width - radius, y);
  11396. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  11397. if (yAlign === 'center' && xAlign === 'right') {
  11398. this.drawCaret(pt, ctx, tooltipSize, options);
  11399. }
  11400. ctx.lineTo(x + width, y + height - radius);
  11401. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  11402. if (yAlign === 'bottom') {
  11403. this.drawCaret(pt, ctx, tooltipSize, options);
  11404. }
  11405. ctx.lineTo(x + radius, y + height);
  11406. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  11407. if (yAlign === 'center' && xAlign === 'left') {
  11408. this.drawCaret(pt, ctx, tooltipSize, options);
  11409. }
  11410. ctx.lineTo(x, y + radius);
  11411. ctx.quadraticCurveTo(x, y, x + radius, y);
  11412. ctx.closePath();
  11413. ctx.fill();
  11414. if (options.borderWidth > 0) {
  11415. ctx.stroke();
  11416. }
  11417. }
  11418. _updateAnimationTarget(options) {
  11419. const me = this;
  11420. const chart = me._chart;
  11421. const anims = me.$animations;
  11422. const animX = anims && anims.x;
  11423. const animY = anims && anims.y;
  11424. if (animX || animY) {
  11425. const position = positioners[options.position].call(me, me._active, me._eventPosition);
  11426. if (!position) {
  11427. return;
  11428. }
  11429. const size = me._size = getTooltipSize(me, options);
  11430. const positionAndSize = Object.assign({}, position, me._size);
  11431. const alignment = determineAlignment(chart, options, positionAndSize);
  11432. const point = getBackgroundPoint(options, positionAndSize, alignment, chart);
  11433. if (animX._to !== point.x || animY._to !== point.y) {
  11434. me.xAlign = alignment.xAlign;
  11435. me.yAlign = alignment.yAlign;
  11436. me.width = size.width;
  11437. me.height = size.height;
  11438. me.caretX = position.x;
  11439. me.caretY = position.y;
  11440. me._resolveAnimations().update(me, point);
  11441. }
  11442. }
  11443. }
  11444. draw(ctx) {
  11445. const me = this;
  11446. const options = me.options.setContext(me.getContext());
  11447. let opacity = me.opacity;
  11448. if (!opacity) {
  11449. return;
  11450. }
  11451. me._updateAnimationTarget(options);
  11452. const tooltipSize = {
  11453. width: me.width,
  11454. height: me.height
  11455. };
  11456. const pt = {
  11457. x: me.x,
  11458. y: me.y
  11459. };
  11460. opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
  11461. const padding = toPadding(options.padding);
  11462. const hasTooltipContent = me.title.length || me.beforeBody.length || me.body.length || me.afterBody.length || me.footer.length;
  11463. if (options.enabled && hasTooltipContent) {
  11464. ctx.save();
  11465. ctx.globalAlpha = opacity;
  11466. me.drawBackground(pt, ctx, tooltipSize, options);
  11467. overrideTextDirection(ctx, options.textDirection);
  11468. pt.y += padding.top;
  11469. me.drawTitle(pt, ctx, options);
  11470. me.drawBody(pt, ctx, options);
  11471. me.drawFooter(pt, ctx, options);
  11472. restoreTextDirection(ctx, options.textDirection);
  11473. ctx.restore();
  11474. }
  11475. }
  11476. getActiveElements() {
  11477. return this._active || [];
  11478. }
  11479. setActiveElements(activeElements, eventPosition) {
  11480. const me = this;
  11481. const lastActive = me._active;
  11482. const active = activeElements.map(({datasetIndex, index}) => {
  11483. const meta = me._chart.getDatasetMeta(datasetIndex);
  11484. if (!meta) {
  11485. throw new Error('Cannot find a dataset at index ' + datasetIndex);
  11486. }
  11487. return {
  11488. datasetIndex,
  11489. element: meta.data[index],
  11490. index,
  11491. };
  11492. });
  11493. const changed = !_elementsEqual(lastActive, active);
  11494. const positionChanged = me._positionChanged(active, eventPosition);
  11495. if (changed || positionChanged) {
  11496. me._active = active;
  11497. me._eventPosition = eventPosition;
  11498. me.update(true);
  11499. }
  11500. }
  11501. handleEvent(e, replay) {
  11502. const me = this;
  11503. const options = me.options;
  11504. const lastActive = me._active || [];
  11505. let changed = false;
  11506. let active = [];
  11507. if (e.type !== 'mouseout') {
  11508. active = me._chart.getElementsAtEventForMode(e, options.mode, options, replay);
  11509. if (options.reverse) {
  11510. active.reverse();
  11511. }
  11512. }
  11513. const positionChanged = me._positionChanged(active, e);
  11514. changed = replay || !_elementsEqual(active, lastActive) || positionChanged;
  11515. if (changed) {
  11516. me._active = active;
  11517. if (options.enabled || options.external) {
  11518. me._eventPosition = {
  11519. x: e.x,
  11520. y: e.y
  11521. };
  11522. me.update(true, replay);
  11523. }
  11524. }
  11525. return changed;
  11526. }
  11527. _positionChanged(active, e) {
  11528. const {caretX, caretY, options} = this;
  11529. const position = positioners[options.position].call(this, active, e);
  11530. return position !== false && (caretX !== position.x || caretY !== position.y);
  11531. }
  11532. }
  11533. Tooltip.positioners = positioners;
  11534. var plugin_tooltip = {
  11535. id: 'tooltip',
  11536. _element: Tooltip,
  11537. positioners,
  11538. afterInit(chart, _args, options) {
  11539. if (options) {
  11540. chart.tooltip = new Tooltip({_chart: chart, options});
  11541. }
  11542. },
  11543. beforeUpdate(chart, _args, options) {
  11544. if (chart.tooltip) {
  11545. chart.tooltip.initialize(options);
  11546. }
  11547. },
  11548. reset(chart, _args, options) {
  11549. if (chart.tooltip) {
  11550. chart.tooltip.initialize(options);
  11551. }
  11552. },
  11553. afterDraw(chart) {
  11554. const tooltip = chart.tooltip;
  11555. const args = {
  11556. tooltip
  11557. };
  11558. if (chart.notifyPlugins('beforeTooltipDraw', args) === false) {
  11559. return;
  11560. }
  11561. if (tooltip) {
  11562. tooltip.draw(chart.ctx);
  11563. }
  11564. chart.notifyPlugins('afterTooltipDraw', args);
  11565. },
  11566. afterEvent(chart, args) {
  11567. if (chart.tooltip) {
  11568. const useFinalPosition = args.replay;
  11569. if (chart.tooltip.handleEvent(args.event, useFinalPosition)) {
  11570. args.changed = true;
  11571. }
  11572. }
  11573. },
  11574. defaults: {
  11575. enabled: true,
  11576. external: null,
  11577. position: 'average',
  11578. backgroundColor: 'rgba(0,0,0,0.8)',
  11579. titleColor: '#fff',
  11580. titleFont: {
  11581. weight: 'bold',
  11582. },
  11583. titleSpacing: 2,
  11584. titleMarginBottom: 6,
  11585. titleAlign: 'left',
  11586. bodyColor: '#fff',
  11587. bodySpacing: 2,
  11588. bodyFont: {
  11589. },
  11590. bodyAlign: 'left',
  11591. footerColor: '#fff',
  11592. footerSpacing: 2,
  11593. footerMarginTop: 6,
  11594. footerFont: {
  11595. weight: 'bold',
  11596. },
  11597. footerAlign: 'left',
  11598. padding: 6,
  11599. caretPadding: 2,
  11600. caretSize: 5,
  11601. cornerRadius: 6,
  11602. boxHeight: (ctx, opts) => opts.bodyFont.size,
  11603. boxWidth: (ctx, opts) => opts.bodyFont.size,
  11604. multiKeyBackground: '#fff',
  11605. displayColors: true,
  11606. borderColor: 'rgba(0,0,0,0)',
  11607. borderWidth: 0,
  11608. animation: {
  11609. duration: 400,
  11610. easing: 'easeOutQuart',
  11611. },
  11612. animations: {
  11613. numbers: {
  11614. type: 'number',
  11615. properties: ['x', 'y', 'width', 'height', 'caretX', 'caretY'],
  11616. },
  11617. opacity: {
  11618. easing: 'linear',
  11619. duration: 200
  11620. }
  11621. },
  11622. callbacks: {
  11623. beforeTitle: noop,
  11624. title(tooltipItems) {
  11625. if (tooltipItems.length > 0) {
  11626. const item = tooltipItems[0];
  11627. const labels = item.chart.data.labels;
  11628. const labelCount = labels ? labels.length : 0;
  11629. if (this && this.options && this.options.mode === 'dataset') {
  11630. return item.dataset.label || '';
  11631. } else if (item.label) {
  11632. return item.label;
  11633. } else if (labelCount > 0 && item.dataIndex < labelCount) {
  11634. return labels[item.dataIndex];
  11635. }
  11636. }
  11637. return '';
  11638. },
  11639. afterTitle: noop,
  11640. beforeBody: noop,
  11641. beforeLabel: noop,
  11642. label(tooltipItem) {
  11643. if (this && this.options && this.options.mode === 'dataset') {
  11644. return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;
  11645. }
  11646. let label = tooltipItem.dataset.label || '';
  11647. if (label) {
  11648. label += ': ';
  11649. }
  11650. const value = tooltipItem.formattedValue;
  11651. if (!isNullOrUndef(value)) {
  11652. label += value;
  11653. }
  11654. return label;
  11655. },
  11656. labelColor(tooltipItem) {
  11657. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  11658. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  11659. return {
  11660. borderColor: options.borderColor,
  11661. backgroundColor: options.backgroundColor,
  11662. borderWidth: options.borderWidth,
  11663. borderDash: options.borderDash,
  11664. borderDashOffset: options.borderDashOffset,
  11665. borderRadius: 0,
  11666. };
  11667. },
  11668. labelTextColor() {
  11669. return this.options.bodyColor;
  11670. },
  11671. labelPointStyle(tooltipItem) {
  11672. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  11673. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  11674. return {
  11675. pointStyle: options.pointStyle,
  11676. rotation: options.rotation,
  11677. };
  11678. },
  11679. afterLabel: noop,
  11680. afterBody: noop,
  11681. beforeFooter: noop,
  11682. footer: noop,
  11683. afterFooter: noop
  11684. }
  11685. },
  11686. defaultRoutes: {
  11687. bodyFont: 'font',
  11688. footerFont: 'font',
  11689. titleFont: 'font'
  11690. },
  11691. descriptors: {
  11692. _scriptable: (name) => name !== 'filter' && name !== 'itemSort' && name !== 'external',
  11693. _indexable: false,
  11694. callbacks: {
  11695. _scriptable: false,
  11696. _indexable: false,
  11697. },
  11698. animation: {
  11699. _fallback: false
  11700. },
  11701. animations: {
  11702. _fallback: 'animation'
  11703. }
  11704. },
  11705. additionalOptionScopes: ['interaction']
  11706. };
  11707. var plugins = /*#__PURE__*/Object.freeze({
  11708. __proto__: null,
  11709. Decimation: plugin_decimation,
  11710. Filler: plugin_filler,
  11711. Legend: plugin_legend,
  11712. SubTitle: plugin_subtitle,
  11713. Title: plugin_title,
  11714. Tooltip: plugin_tooltip
  11715. });
  11716. const addIfString = (labels, raw, index) => typeof raw === 'string'
  11717. ? labels.push(raw) - 1
  11718. : isNaN(raw) ? null : index;
  11719. function findOrAddLabel(labels, raw, index) {
  11720. const first = labels.indexOf(raw);
  11721. if (first === -1) {
  11722. return addIfString(labels, raw, index);
  11723. }
  11724. const last = labels.lastIndexOf(raw);
  11725. return first !== last ? index : first;
  11726. }
  11727. const validIndex = (index, max) => index === null ? null : _limitValue(Math.round(index), 0, max);
  11728. class CategoryScale extends Scale {
  11729. constructor(cfg) {
  11730. super(cfg);
  11731. this._startValue = undefined;
  11732. this._valueRange = 0;
  11733. }
  11734. parse(raw, index) {
  11735. if (isNullOrUndef(raw)) {
  11736. return null;
  11737. }
  11738. const labels = this.getLabels();
  11739. index = isFinite(index) && labels[index] === raw ? index
  11740. : findOrAddLabel(labels, raw, valueOrDefault(index, raw));
  11741. return validIndex(index, labels.length - 1);
  11742. }
  11743. determineDataLimits() {
  11744. const me = this;
  11745. const {minDefined, maxDefined} = me.getUserBounds();
  11746. let {min, max} = me.getMinMax(true);
  11747. if (me.options.bounds === 'ticks') {
  11748. if (!minDefined) {
  11749. min = 0;
  11750. }
  11751. if (!maxDefined) {
  11752. max = me.getLabels().length - 1;
  11753. }
  11754. }
  11755. me.min = min;
  11756. me.max = max;
  11757. }
  11758. buildTicks() {
  11759. const me = this;
  11760. const min = me.min;
  11761. const max = me.max;
  11762. const offset = me.options.offset;
  11763. const ticks = [];
  11764. let labels = me.getLabels();
  11765. labels = (min === 0 && max === labels.length - 1) ? labels : labels.slice(min, max + 1);
  11766. me._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);
  11767. me._startValue = me.min - (offset ? 0.5 : 0);
  11768. for (let value = min; value <= max; value++) {
  11769. ticks.push({value});
  11770. }
  11771. return ticks;
  11772. }
  11773. getLabelForValue(value) {
  11774. const me = this;
  11775. const labels = me.getLabels();
  11776. if (value >= 0 && value < labels.length) {
  11777. return labels[value];
  11778. }
  11779. return value;
  11780. }
  11781. configure() {
  11782. const me = this;
  11783. super.configure();
  11784. if (!me.isHorizontal()) {
  11785. me._reversePixels = !me._reversePixels;
  11786. }
  11787. }
  11788. getPixelForValue(value) {
  11789. const me = this;
  11790. if (typeof value !== 'number') {
  11791. value = me.parse(value);
  11792. }
  11793. return value === null ? NaN : me.getPixelForDecimal((value - me._startValue) / me._valueRange);
  11794. }
  11795. getPixelForTick(index) {
  11796. const me = this;
  11797. const ticks = me.ticks;
  11798. if (index < 0 || index > ticks.length - 1) {
  11799. return null;
  11800. }
  11801. return me.getPixelForValue(ticks[index].value);
  11802. }
  11803. getValueForPixel(pixel) {
  11804. const me = this;
  11805. return Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
  11806. }
  11807. getBasePixel() {
  11808. return this.bottom;
  11809. }
  11810. }
  11811. CategoryScale.id = 'category';
  11812. CategoryScale.defaults = {
  11813. ticks: {
  11814. callback: CategoryScale.prototype.getLabelForValue
  11815. }
  11816. };
  11817. function generateTicks$1(generationOptions, dataRange) {
  11818. const ticks = [];
  11819. const MIN_SPACING = 1e-14;
  11820. const {bounds, step, min, max, precision, count, maxTicks, maxDigits, includeBounds} = generationOptions;
  11821. const unit = step || 1;
  11822. const maxSpaces = maxTicks - 1;
  11823. const {min: rmin, max: rmax} = dataRange;
  11824. const minDefined = !isNullOrUndef(min);
  11825. const maxDefined = !isNullOrUndef(max);
  11826. const countDefined = !isNullOrUndef(count);
  11827. const minSpacing = (rmax - rmin) / (maxDigits + 1);
  11828. let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit;
  11829. let factor, niceMin, niceMax, numSpaces;
  11830. if (spacing < MIN_SPACING && !minDefined && !maxDefined) {
  11831. return [{value: rmin}, {value: rmax}];
  11832. }
  11833. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  11834. if (numSpaces > maxSpaces) {
  11835. spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit;
  11836. }
  11837. if (!isNullOrUndef(precision)) {
  11838. factor = Math.pow(10, precision);
  11839. spacing = Math.ceil(spacing * factor) / factor;
  11840. }
  11841. if (bounds === 'ticks') {
  11842. niceMin = Math.floor(rmin / spacing) * spacing;
  11843. niceMax = Math.ceil(rmax / spacing) * spacing;
  11844. } else {
  11845. niceMin = rmin;
  11846. niceMax = rmax;
  11847. }
  11848. if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) {
  11849. numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks));
  11850. spacing = (max - min) / numSpaces;
  11851. niceMin = min;
  11852. niceMax = max;
  11853. } else if (countDefined) {
  11854. niceMin = minDefined ? min : niceMin;
  11855. niceMax = maxDefined ? max : niceMax;
  11856. numSpaces = count - 1;
  11857. spacing = (niceMax - niceMin) / numSpaces;
  11858. } else {
  11859. numSpaces = (niceMax - niceMin) / spacing;
  11860. if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  11861. numSpaces = Math.round(numSpaces);
  11862. } else {
  11863. numSpaces = Math.ceil(numSpaces);
  11864. }
  11865. }
  11866. const decimalPlaces = Math.max(
  11867. _decimalPlaces(spacing),
  11868. _decimalPlaces(niceMin)
  11869. );
  11870. factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision);
  11871. niceMin = Math.round(niceMin * factor) / factor;
  11872. niceMax = Math.round(niceMax * factor) / factor;
  11873. let j = 0;
  11874. if (minDefined) {
  11875. if (includeBounds && niceMin !== min) {
  11876. ticks.push({value: min});
  11877. if (niceMin < min) {
  11878. j++;
  11879. }
  11880. if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) {
  11881. j++;
  11882. }
  11883. } else if (niceMin < min) {
  11884. j++;
  11885. }
  11886. }
  11887. for (; j < numSpaces; ++j) {
  11888. ticks.push({value: Math.round((niceMin + j * spacing) * factor) / factor});
  11889. }
  11890. if (maxDefined && includeBounds && niceMax !== max) {
  11891. if (almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) {
  11892. ticks[ticks.length - 1].value = max;
  11893. } else {
  11894. ticks.push({value: max});
  11895. }
  11896. } else if (!maxDefined || niceMax === max) {
  11897. ticks.push({value: niceMax});
  11898. }
  11899. return ticks;
  11900. }
  11901. function relativeLabelSize(value, minSpacing, {horizontal, minRotation}) {
  11902. const rad = toRadians(minRotation);
  11903. const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001;
  11904. const length = 0.75 * minSpacing * ('' + value).length;
  11905. return Math.min(minSpacing / ratio, length);
  11906. }
  11907. class LinearScaleBase extends Scale {
  11908. constructor(cfg) {
  11909. super(cfg);
  11910. this.start = undefined;
  11911. this.end = undefined;
  11912. this._startValue = undefined;
  11913. this._endValue = undefined;
  11914. this._valueRange = 0;
  11915. }
  11916. parse(raw, index) {
  11917. if (isNullOrUndef(raw)) {
  11918. return null;
  11919. }
  11920. if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {
  11921. return null;
  11922. }
  11923. return +raw;
  11924. }
  11925. handleTickRangeOptions() {
  11926. const me = this;
  11927. const {beginAtZero} = me.options;
  11928. const {minDefined, maxDefined} = me.getUserBounds();
  11929. let {min, max} = me;
  11930. const setMin = v => (min = minDefined ? min : v);
  11931. const setMax = v => (max = maxDefined ? max : v);
  11932. if (beginAtZero) {
  11933. const minSign = sign(min);
  11934. const maxSign = sign(max);
  11935. if (minSign < 0 && maxSign < 0) {
  11936. setMax(0);
  11937. } else if (minSign > 0 && maxSign > 0) {
  11938. setMin(0);
  11939. }
  11940. }
  11941. if (min === max) {
  11942. let offset = 1;
  11943. if (max >= Number.MAX_SAFE_INTEGER || min <= Number.MIN_SAFE_INTEGER) {
  11944. offset = Math.abs(max * 0.05);
  11945. }
  11946. setMax(max + offset);
  11947. if (!beginAtZero) {
  11948. setMin(min - offset);
  11949. }
  11950. }
  11951. me.min = min;
  11952. me.max = max;
  11953. }
  11954. getTickLimit() {
  11955. const me = this;
  11956. const tickOpts = me.options.ticks;
  11957. let {maxTicksLimit, stepSize} = tickOpts;
  11958. let maxTicks;
  11959. if (stepSize) {
  11960. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  11961. } else {
  11962. maxTicks = me.computeTickLimit();
  11963. maxTicksLimit = maxTicksLimit || 11;
  11964. }
  11965. if (maxTicksLimit) {
  11966. maxTicks = Math.min(maxTicksLimit, maxTicks);
  11967. }
  11968. return maxTicks;
  11969. }
  11970. computeTickLimit() {
  11971. return Number.POSITIVE_INFINITY;
  11972. }
  11973. buildTicks() {
  11974. const me = this;
  11975. const opts = me.options;
  11976. const tickOpts = opts.ticks;
  11977. let maxTicks = me.getTickLimit();
  11978. maxTicks = Math.max(2, maxTicks);
  11979. const numericGeneratorOptions = {
  11980. maxTicks,
  11981. bounds: opts.bounds,
  11982. min: opts.min,
  11983. max: opts.max,
  11984. precision: tickOpts.precision,
  11985. step: tickOpts.stepSize,
  11986. count: tickOpts.count,
  11987. maxDigits: me._maxDigits(),
  11988. horizontal: me.isHorizontal(),
  11989. minRotation: tickOpts.minRotation || 0,
  11990. includeBounds: tickOpts.includeBounds !== false
  11991. };
  11992. const dataRange = me._range || me;
  11993. const ticks = generateTicks$1(numericGeneratorOptions, dataRange);
  11994. if (opts.bounds === 'ticks') {
  11995. _setMinAndMaxByKey(ticks, me, 'value');
  11996. }
  11997. if (opts.reverse) {
  11998. ticks.reverse();
  11999. me.start = me.max;
  12000. me.end = me.min;
  12001. } else {
  12002. me.start = me.min;
  12003. me.end = me.max;
  12004. }
  12005. return ticks;
  12006. }
  12007. configure() {
  12008. const me = this;
  12009. const ticks = me.ticks;
  12010. let start = me.min;
  12011. let end = me.max;
  12012. super.configure();
  12013. if (me.options.offset && ticks.length) {
  12014. const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  12015. start -= offset;
  12016. end += offset;
  12017. }
  12018. me._startValue = start;
  12019. me._endValue = end;
  12020. me._valueRange = end - start;
  12021. }
  12022. getLabelForValue(value) {
  12023. return formatNumber(value, this.chart.options.locale);
  12024. }
  12025. }
  12026. class LinearScale extends LinearScaleBase {
  12027. determineDataLimits() {
  12028. const me = this;
  12029. const {min, max} = me.getMinMax(true);
  12030. me.min = isNumberFinite(min) ? min : 0;
  12031. me.max = isNumberFinite(max) ? max : 1;
  12032. me.handleTickRangeOptions();
  12033. }
  12034. computeTickLimit() {
  12035. const me = this;
  12036. const horizontal = me.isHorizontal();
  12037. const length = horizontal ? me.width : me.height;
  12038. const minRotation = toRadians(me.options.ticks.minRotation);
  12039. const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001;
  12040. const tickFont = me._resolveTickFontOptions(0);
  12041. return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio));
  12042. }
  12043. getPixelForValue(value) {
  12044. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  12045. }
  12046. getValueForPixel(pixel) {
  12047. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  12048. }
  12049. }
  12050. LinearScale.id = 'linear';
  12051. LinearScale.defaults = {
  12052. ticks: {
  12053. callback: Ticks.formatters.numeric
  12054. }
  12055. };
  12056. function isMajor(tickVal) {
  12057. const remain = tickVal / (Math.pow(10, Math.floor(log10(tickVal))));
  12058. return remain === 1;
  12059. }
  12060. function generateTicks(generationOptions, dataRange) {
  12061. const endExp = Math.floor(log10(dataRange.max));
  12062. const endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  12063. const ticks = [];
  12064. let tickVal = finiteOrDefault(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  12065. let exp = Math.floor(log10(tickVal));
  12066. let significand = Math.floor(tickVal / Math.pow(10, exp));
  12067. let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  12068. do {
  12069. ticks.push({value: tickVal, major: isMajor(tickVal)});
  12070. ++significand;
  12071. if (significand === 10) {
  12072. significand = 1;
  12073. ++exp;
  12074. precision = exp >= 0 ? 1 : precision;
  12075. }
  12076. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  12077. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  12078. const lastTick = finiteOrDefault(generationOptions.max, tickVal);
  12079. ticks.push({value: lastTick, major: isMajor(tickVal)});
  12080. return ticks;
  12081. }
  12082. class LogarithmicScale extends Scale {
  12083. constructor(cfg) {
  12084. super(cfg);
  12085. this.start = undefined;
  12086. this.end = undefined;
  12087. this._startValue = undefined;
  12088. this._valueRange = 0;
  12089. }
  12090. parse(raw, index) {
  12091. const value = LinearScaleBase.prototype.parse.apply(this, [raw, index]);
  12092. if (value === 0) {
  12093. this._zero = true;
  12094. return undefined;
  12095. }
  12096. return isNumberFinite(value) && value > 0 ? value : null;
  12097. }
  12098. determineDataLimits() {
  12099. const me = this;
  12100. const {min, max} = me.getMinMax(true);
  12101. me.min = isNumberFinite(min) ? Math.max(0, min) : null;
  12102. me.max = isNumberFinite(max) ? Math.max(0, max) : null;
  12103. if (me.options.beginAtZero) {
  12104. me._zero = true;
  12105. }
  12106. me.handleTickRangeOptions();
  12107. }
  12108. handleTickRangeOptions() {
  12109. const me = this;
  12110. const {minDefined, maxDefined} = me.getUserBounds();
  12111. let min = me.min;
  12112. let max = me.max;
  12113. const setMin = v => (min = minDefined ? min : v);
  12114. const setMax = v => (max = maxDefined ? max : v);
  12115. const exp = (v, m) => Math.pow(10, Math.floor(log10(v)) + m);
  12116. if (min === max) {
  12117. if (min <= 0) {
  12118. setMin(1);
  12119. setMax(10);
  12120. } else {
  12121. setMin(exp(min, -1));
  12122. setMax(exp(max, +1));
  12123. }
  12124. }
  12125. if (min <= 0) {
  12126. setMin(exp(max, -1));
  12127. }
  12128. if (max <= 0) {
  12129. setMax(exp(min, +1));
  12130. }
  12131. if (me._zero && me.min !== me._suggestedMin && min === exp(me.min, 0)) {
  12132. setMin(exp(min, -1));
  12133. }
  12134. me.min = min;
  12135. me.max = max;
  12136. }
  12137. buildTicks() {
  12138. const me = this;
  12139. const opts = me.options;
  12140. const generationOptions = {
  12141. min: me._userMin,
  12142. max: me._userMax
  12143. };
  12144. const ticks = generateTicks(generationOptions, me);
  12145. if (opts.bounds === 'ticks') {
  12146. _setMinAndMaxByKey(ticks, me, 'value');
  12147. }
  12148. if (opts.reverse) {
  12149. ticks.reverse();
  12150. me.start = me.max;
  12151. me.end = me.min;
  12152. } else {
  12153. me.start = me.min;
  12154. me.end = me.max;
  12155. }
  12156. return ticks;
  12157. }
  12158. getLabelForValue(value) {
  12159. return value === undefined ? '0' : formatNumber(value, this.chart.options.locale);
  12160. }
  12161. configure() {
  12162. const me = this;
  12163. const start = me.min;
  12164. super.configure();
  12165. me._startValue = log10(start);
  12166. me._valueRange = log10(me.max) - log10(start);
  12167. }
  12168. getPixelForValue(value) {
  12169. const me = this;
  12170. if (value === undefined || value === 0) {
  12171. value = me.min;
  12172. }
  12173. if (value === null || isNaN(value)) {
  12174. return NaN;
  12175. }
  12176. return me.getPixelForDecimal(value === me.min
  12177. ? 0
  12178. : (log10(value) - me._startValue) / me._valueRange);
  12179. }
  12180. getValueForPixel(pixel) {
  12181. const me = this;
  12182. const decimal = me.getDecimalForPixel(pixel);
  12183. return Math.pow(10, me._startValue + decimal * me._valueRange);
  12184. }
  12185. }
  12186. LogarithmicScale.id = 'logarithmic';
  12187. LogarithmicScale.defaults = {
  12188. ticks: {
  12189. callback: Ticks.formatters.logarithmic,
  12190. major: {
  12191. enabled: true
  12192. }
  12193. }
  12194. };
  12195. function getTickBackdropHeight(opts) {
  12196. const tickOpts = opts.ticks;
  12197. if (tickOpts.display && opts.display) {
  12198. const padding = toPadding(tickOpts.backdropPadding);
  12199. return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height;
  12200. }
  12201. return 0;
  12202. }
  12203. function measureLabelSize(ctx, font, label) {
  12204. label = isArray(label) ? label : [label];
  12205. return {
  12206. w: _longestText(ctx, font.string, label),
  12207. h: label.length * font.lineHeight
  12208. };
  12209. }
  12210. function determineLimits(angle, pos, size, min, max) {
  12211. if (angle === min || angle === max) {
  12212. return {
  12213. start: pos - (size / 2),
  12214. end: pos + (size / 2)
  12215. };
  12216. } else if (angle < min || angle > max) {
  12217. return {
  12218. start: pos - size,
  12219. end: pos
  12220. };
  12221. }
  12222. return {
  12223. start: pos,
  12224. end: pos + size
  12225. };
  12226. }
  12227. function fitWithPointLabels(scale) {
  12228. const furthestLimits = {
  12229. l: 0,
  12230. r: scale.width,
  12231. t: 0,
  12232. b: scale.height - scale.paddingTop
  12233. };
  12234. const furthestAngles = {};
  12235. const labelSizes = [];
  12236. const padding = [];
  12237. const valueCount = scale.getLabels().length;
  12238. for (let i = 0; i < valueCount; i++) {
  12239. const opts = scale.options.pointLabels.setContext(scale.getPointLabelContext(i));
  12240. padding[i] = opts.padding;
  12241. const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i]);
  12242. const plFont = toFont(opts.font);
  12243. const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]);
  12244. labelSizes[i] = textSize;
  12245. const angleRadians = scale.getIndexAngle(i);
  12246. const angle = toDegrees(angleRadians);
  12247. const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  12248. const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  12249. if (hLimits.start < furthestLimits.l) {
  12250. furthestLimits.l = hLimits.start;
  12251. furthestAngles.l = angleRadians;
  12252. }
  12253. if (hLimits.end > furthestLimits.r) {
  12254. furthestLimits.r = hLimits.end;
  12255. furthestAngles.r = angleRadians;
  12256. }
  12257. if (vLimits.start < furthestLimits.t) {
  12258. furthestLimits.t = vLimits.start;
  12259. furthestAngles.t = angleRadians;
  12260. }
  12261. if (vLimits.end > furthestLimits.b) {
  12262. furthestLimits.b = vLimits.end;
  12263. furthestAngles.b = angleRadians;
  12264. }
  12265. }
  12266. scale._setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  12267. scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding);
  12268. }
  12269. function buildPointLabelItems(scale, labelSizes, padding) {
  12270. const items = [];
  12271. const valueCount = scale.getLabels().length;
  12272. const opts = scale.options;
  12273. const tickBackdropHeight = getTickBackdropHeight(opts);
  12274. const outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  12275. for (let i = 0; i < valueCount; i++) {
  12276. const extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  12277. const pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + padding[i]);
  12278. const angle = toDegrees(scale.getIndexAngle(i));
  12279. const size = labelSizes[i];
  12280. const y = yForAngle(pointLabelPosition.y, size.h, angle);
  12281. const textAlign = getTextAlignForAngle(angle);
  12282. const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign);
  12283. items.push({
  12284. x: pointLabelPosition.x,
  12285. y,
  12286. textAlign,
  12287. left,
  12288. top: y,
  12289. right: left + size.w,
  12290. bottom: y + size.h
  12291. });
  12292. }
  12293. return items;
  12294. }
  12295. function getTextAlignForAngle(angle) {
  12296. if (angle === 0 || angle === 180) {
  12297. return 'center';
  12298. } else if (angle < 180) {
  12299. return 'left';
  12300. }
  12301. return 'right';
  12302. }
  12303. function leftForTextAlign(x, w, align) {
  12304. if (align === 'right') {
  12305. x -= w;
  12306. } else if (align === 'center') {
  12307. x -= (w / 2);
  12308. }
  12309. return x;
  12310. }
  12311. function yForAngle(y, h, angle) {
  12312. if (angle === 90 || angle === 270) {
  12313. y -= (h / 2);
  12314. } else if (angle > 270 || angle < 90) {
  12315. y -= h;
  12316. }
  12317. return y;
  12318. }
  12319. function drawPointLabels(scale, labelCount) {
  12320. const {ctx, options: {pointLabels}} = scale;
  12321. for (let i = labelCount - 1; i >= 0; i--) {
  12322. const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i));
  12323. const plFont = toFont(optsAtIndex.font);
  12324. const {x, y, textAlign, left, top, right, bottom} = scale._pointLabelItems[i];
  12325. const {backdropColor} = optsAtIndex;
  12326. if (!isNullOrUndef(backdropColor)) {
  12327. const padding = toPadding(optsAtIndex.backdropPadding);
  12328. ctx.fillStyle = backdropColor;
  12329. ctx.fillRect(left - padding.left, top - padding.top, right - left + padding.width, bottom - top + padding.height);
  12330. }
  12331. renderText(
  12332. ctx,
  12333. scale._pointLabels[i],
  12334. x,
  12335. y + (plFont.lineHeight / 2),
  12336. plFont,
  12337. {
  12338. color: optsAtIndex.color,
  12339. textAlign: textAlign,
  12340. textBaseline: 'middle'
  12341. }
  12342. );
  12343. }
  12344. }
  12345. function pathRadiusLine(scale, radius, circular, labelCount) {
  12346. const {ctx} = scale;
  12347. if (circular) {
  12348. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU);
  12349. } else {
  12350. let pointPosition = scale.getPointPosition(0, radius);
  12351. ctx.moveTo(pointPosition.x, pointPosition.y);
  12352. for (let i = 1; i < labelCount; i++) {
  12353. pointPosition = scale.getPointPosition(i, radius);
  12354. ctx.lineTo(pointPosition.x, pointPosition.y);
  12355. }
  12356. }
  12357. }
  12358. function drawRadiusLine(scale, gridLineOpts, radius, labelCount) {
  12359. const ctx = scale.ctx;
  12360. const circular = gridLineOpts.circular;
  12361. const {color, lineWidth} = gridLineOpts;
  12362. if ((!circular && !labelCount) || !color || !lineWidth || radius < 0) {
  12363. return;
  12364. }
  12365. ctx.save();
  12366. ctx.strokeStyle = color;
  12367. ctx.lineWidth = lineWidth;
  12368. ctx.setLineDash(gridLineOpts.borderDash);
  12369. ctx.lineDashOffset = gridLineOpts.borderDashOffset;
  12370. ctx.beginPath();
  12371. pathRadiusLine(scale, radius, circular, labelCount);
  12372. ctx.closePath();
  12373. ctx.stroke();
  12374. ctx.restore();
  12375. }
  12376. function numberOrZero(param) {
  12377. return isNumber(param) ? param : 0;
  12378. }
  12379. function createPointLabelContext(parent, index, label) {
  12380. return Object.assign(Object.create(parent), {
  12381. label,
  12382. index,
  12383. type: 'pointLabel'
  12384. });
  12385. }
  12386. class RadialLinearScale extends LinearScaleBase {
  12387. constructor(cfg) {
  12388. super(cfg);
  12389. this.xCenter = undefined;
  12390. this.yCenter = undefined;
  12391. this.drawingArea = undefined;
  12392. this._pointLabels = [];
  12393. this._pointLabelItems = [];
  12394. }
  12395. setDimensions() {
  12396. const me = this;
  12397. me.width = me.maxWidth;
  12398. me.height = me.maxHeight;
  12399. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  12400. me.xCenter = Math.floor(me.width / 2);
  12401. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  12402. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  12403. }
  12404. determineDataLimits() {
  12405. const me = this;
  12406. const {min, max} = me.getMinMax(false);
  12407. me.min = isNumberFinite(min) && !isNaN(min) ? min : 0;
  12408. me.max = isNumberFinite(max) && !isNaN(max) ? max : 0;
  12409. me.handleTickRangeOptions();
  12410. }
  12411. computeTickLimit() {
  12412. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  12413. }
  12414. generateTickLabels(ticks) {
  12415. const me = this;
  12416. LinearScaleBase.prototype.generateTickLabels.call(me, ticks);
  12417. me._pointLabels = me.getLabels().map((value, index) => {
  12418. const label = callback(me.options.pointLabels.callback, [value, index], me);
  12419. return label || label === 0 ? label : '';
  12420. });
  12421. }
  12422. fit() {
  12423. const me = this;
  12424. const opts = me.options;
  12425. if (opts.display && opts.pointLabels.display) {
  12426. fitWithPointLabels(me);
  12427. } else {
  12428. me.setCenterPoint(0, 0, 0, 0);
  12429. }
  12430. }
  12431. _setReductions(largestPossibleRadius, furthestLimits, furthestAngles) {
  12432. const me = this;
  12433. let radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  12434. let radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  12435. let radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  12436. let radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  12437. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  12438. radiusReductionRight = numberOrZero(radiusReductionRight);
  12439. radiusReductionTop = numberOrZero(radiusReductionTop);
  12440. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  12441. me.drawingArea = Math.max(largestPossibleRadius / 2, Math.min(
  12442. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  12443. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2)));
  12444. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  12445. }
  12446. setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {
  12447. const me = this;
  12448. const maxRight = me.width - rightMovement - me.drawingArea;
  12449. const maxLeft = leftMovement + me.drawingArea;
  12450. const maxTop = topMovement + me.drawingArea;
  12451. const maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  12452. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  12453. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  12454. }
  12455. getIndexAngle(index) {
  12456. const angleMultiplier = TAU / this.getLabels().length;
  12457. const startAngle = this.options.startAngle || 0;
  12458. return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));
  12459. }
  12460. getDistanceFromCenterForValue(value) {
  12461. const me = this;
  12462. if (isNullOrUndef(value)) {
  12463. return NaN;
  12464. }
  12465. const scalingFactor = me.drawingArea / (me.max - me.min);
  12466. if (me.options.reverse) {
  12467. return (me.max - value) * scalingFactor;
  12468. }
  12469. return (value - me.min) * scalingFactor;
  12470. }
  12471. getValueForDistanceFromCenter(distance) {
  12472. if (isNullOrUndef(distance)) {
  12473. return NaN;
  12474. }
  12475. const me = this;
  12476. const scaledDistance = distance / (me.drawingArea / (me.max - me.min));
  12477. return me.options.reverse ? me.max - scaledDistance : me.min + scaledDistance;
  12478. }
  12479. getPointLabelContext(index) {
  12480. const me = this;
  12481. const pointLabels = me._pointLabels || [];
  12482. if (index >= 0 && index < pointLabels.length) {
  12483. const pointLabel = pointLabels[index];
  12484. return createPointLabelContext(me.getContext(), index, pointLabel);
  12485. }
  12486. }
  12487. getPointPosition(index, distanceFromCenter) {
  12488. const me = this;
  12489. const angle = me.getIndexAngle(index) - HALF_PI;
  12490. return {
  12491. x: Math.cos(angle) * distanceFromCenter + me.xCenter,
  12492. y: Math.sin(angle) * distanceFromCenter + me.yCenter,
  12493. angle
  12494. };
  12495. }
  12496. getPointPositionForValue(index, value) {
  12497. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  12498. }
  12499. getBasePosition(index) {
  12500. return this.getPointPositionForValue(index || 0, this.getBaseValue());
  12501. }
  12502. getPointLabelPosition(index) {
  12503. const {left, top, right, bottom} = this._pointLabelItems[index];
  12504. return {
  12505. left,
  12506. top,
  12507. right,
  12508. bottom,
  12509. };
  12510. }
  12511. drawBackground() {
  12512. const me = this;
  12513. const {backgroundColor, grid: {circular}} = me.options;
  12514. if (backgroundColor) {
  12515. const ctx = me.ctx;
  12516. ctx.save();
  12517. ctx.beginPath();
  12518. pathRadiusLine(me, me.getDistanceFromCenterForValue(me._endValue), circular, me.getLabels().length);
  12519. ctx.closePath();
  12520. ctx.fillStyle = backgroundColor;
  12521. ctx.fill();
  12522. ctx.restore();
  12523. }
  12524. }
  12525. drawGrid() {
  12526. const me = this;
  12527. const ctx = me.ctx;
  12528. const opts = me.options;
  12529. const {angleLines, grid} = opts;
  12530. const labelCount = me.getLabels().length;
  12531. let i, offset, position;
  12532. if (opts.pointLabels.display) {
  12533. drawPointLabels(me, labelCount);
  12534. }
  12535. if (grid.display) {
  12536. me.ticks.forEach((tick, index) => {
  12537. if (index !== 0) {
  12538. offset = me.getDistanceFromCenterForValue(tick.value);
  12539. const optsAtIndex = grid.setContext(me.getContext(index - 1));
  12540. drawRadiusLine(me, optsAtIndex, offset, labelCount);
  12541. }
  12542. });
  12543. }
  12544. if (angleLines.display) {
  12545. ctx.save();
  12546. for (i = me.getLabels().length - 1; i >= 0; i--) {
  12547. const optsAtIndex = angleLines.setContext(me.getPointLabelContext(i));
  12548. const {color, lineWidth} = optsAtIndex;
  12549. if (!lineWidth || !color) {
  12550. continue;
  12551. }
  12552. ctx.lineWidth = lineWidth;
  12553. ctx.strokeStyle = color;
  12554. ctx.setLineDash(optsAtIndex.borderDash);
  12555. ctx.lineDashOffset = optsAtIndex.borderDashOffset;
  12556. offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
  12557. position = me.getPointPosition(i, offset);
  12558. ctx.beginPath();
  12559. ctx.moveTo(me.xCenter, me.yCenter);
  12560. ctx.lineTo(position.x, position.y);
  12561. ctx.stroke();
  12562. }
  12563. ctx.restore();
  12564. }
  12565. }
  12566. drawBorder() {}
  12567. drawLabels() {
  12568. const me = this;
  12569. const ctx = me.ctx;
  12570. const opts = me.options;
  12571. const tickOpts = opts.ticks;
  12572. if (!tickOpts.display) {
  12573. return;
  12574. }
  12575. const startAngle = me.getIndexAngle(0);
  12576. let offset, width;
  12577. ctx.save();
  12578. ctx.translate(me.xCenter, me.yCenter);
  12579. ctx.rotate(startAngle);
  12580. ctx.textAlign = 'center';
  12581. ctx.textBaseline = 'middle';
  12582. me.ticks.forEach((tick, index) => {
  12583. if (index === 0 && !opts.reverse) {
  12584. return;
  12585. }
  12586. const optsAtIndex = tickOpts.setContext(me.getContext(index));
  12587. const tickFont = toFont(optsAtIndex.font);
  12588. offset = me.getDistanceFromCenterForValue(me.ticks[index].value);
  12589. if (optsAtIndex.showLabelBackdrop) {
  12590. ctx.font = tickFont.string;
  12591. width = ctx.measureText(tick.label).width;
  12592. ctx.fillStyle = optsAtIndex.backdropColor;
  12593. const padding = toPadding(optsAtIndex.backdropPadding);
  12594. ctx.fillRect(
  12595. -width / 2 - padding.left,
  12596. -offset - tickFont.size / 2 - padding.top,
  12597. width + padding.width,
  12598. tickFont.size + padding.height
  12599. );
  12600. }
  12601. renderText(ctx, tick.label, 0, -offset, tickFont, {
  12602. color: optsAtIndex.color,
  12603. });
  12604. });
  12605. ctx.restore();
  12606. }
  12607. drawTitle() {}
  12608. }
  12609. RadialLinearScale.id = 'radialLinear';
  12610. RadialLinearScale.defaults = {
  12611. display: true,
  12612. animate: true,
  12613. position: 'chartArea',
  12614. angleLines: {
  12615. display: true,
  12616. lineWidth: 1,
  12617. borderDash: [],
  12618. borderDashOffset: 0.0
  12619. },
  12620. grid: {
  12621. circular: false
  12622. },
  12623. startAngle: 0,
  12624. ticks: {
  12625. showLabelBackdrop: true,
  12626. callback: Ticks.formatters.numeric
  12627. },
  12628. pointLabels: {
  12629. backdropColor: undefined,
  12630. backdropPadding: 2,
  12631. display: true,
  12632. font: {
  12633. size: 10
  12634. },
  12635. callback(label) {
  12636. return label;
  12637. },
  12638. padding: 5
  12639. }
  12640. };
  12641. RadialLinearScale.defaultRoutes = {
  12642. 'angleLines.color': 'borderColor',
  12643. 'pointLabels.color': 'color',
  12644. 'ticks.color': 'color'
  12645. };
  12646. RadialLinearScale.descriptors = {
  12647. angleLines: {
  12648. _fallback: 'grid'
  12649. }
  12650. };
  12651. const INTERVALS = {
  12652. millisecond: {common: true, size: 1, steps: 1000},
  12653. second: {common: true, size: 1000, steps: 60},
  12654. minute: {common: true, size: 60000, steps: 60},
  12655. hour: {common: true, size: 3600000, steps: 24},
  12656. day: {common: true, size: 86400000, steps: 30},
  12657. week: {common: false, size: 604800000, steps: 4},
  12658. month: {common: true, size: 2.628e9, steps: 12},
  12659. quarter: {common: false, size: 7.884e9, steps: 4},
  12660. year: {common: true, size: 3.154e10}
  12661. };
  12662. const UNITS = (Object.keys(INTERVALS));
  12663. function sorter(a, b) {
  12664. return a - b;
  12665. }
  12666. function parse(scale, input) {
  12667. if (isNullOrUndef(input)) {
  12668. return null;
  12669. }
  12670. const adapter = scale._adapter;
  12671. const {parser, round, isoWeekday} = scale._parseOpts;
  12672. let value = input;
  12673. if (typeof parser === 'function') {
  12674. value = parser(value);
  12675. }
  12676. if (!isNumberFinite(value)) {
  12677. value = typeof parser === 'string'
  12678. ? adapter.parse(value, parser)
  12679. : adapter.parse(value);
  12680. }
  12681. if (value === null) {
  12682. return null;
  12683. }
  12684. if (round) {
  12685. value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true)
  12686. ? adapter.startOf(value, 'isoWeek', isoWeekday)
  12687. : adapter.startOf(value, round);
  12688. }
  12689. return +value;
  12690. }
  12691. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  12692. const ilen = UNITS.length;
  12693. for (let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  12694. const interval = INTERVALS[UNITS[i]];
  12695. const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;
  12696. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  12697. return UNITS[i];
  12698. }
  12699. }
  12700. return UNITS[ilen - 1];
  12701. }
  12702. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  12703. for (let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  12704. const unit = UNITS[i];
  12705. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  12706. return unit;
  12707. }
  12708. }
  12709. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  12710. }
  12711. function determineMajorUnit(unit) {
  12712. for (let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  12713. if (INTERVALS[UNITS[i]].common) {
  12714. return UNITS[i];
  12715. }
  12716. }
  12717. }
  12718. function addTick(ticks, time, timestamps) {
  12719. if (!timestamps) {
  12720. ticks[time] = true;
  12721. } else if (timestamps.length) {
  12722. const {lo, hi} = _lookup(timestamps, time);
  12723. const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];
  12724. ticks[timestamp] = true;
  12725. }
  12726. }
  12727. function setMajorTicks(scale, ticks, map, majorUnit) {
  12728. const adapter = scale._adapter;
  12729. const first = +adapter.startOf(ticks[0].value, majorUnit);
  12730. const last = ticks[ticks.length - 1].value;
  12731. let major, index;
  12732. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  12733. index = map[major];
  12734. if (index >= 0) {
  12735. ticks[index].major = true;
  12736. }
  12737. }
  12738. return ticks;
  12739. }
  12740. function ticksFromTimestamps(scale, values, majorUnit) {
  12741. const ticks = [];
  12742. const map = {};
  12743. const ilen = values.length;
  12744. let i, value;
  12745. for (i = 0; i < ilen; ++i) {
  12746. value = values[i];
  12747. map[value] = i;
  12748. ticks.push({
  12749. value,
  12750. major: false
  12751. });
  12752. }
  12753. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  12754. }
  12755. class TimeScale extends Scale {
  12756. constructor(props) {
  12757. super(props);
  12758. this._cache = {
  12759. data: [],
  12760. labels: [],
  12761. all: []
  12762. };
  12763. this._unit = 'day';
  12764. this._majorUnit = undefined;
  12765. this._offsets = {};
  12766. this._normalized = false;
  12767. this._parseOpts = undefined;
  12768. }
  12769. init(scaleOpts, opts) {
  12770. const time = scaleOpts.time || (scaleOpts.time = {});
  12771. const adapter = this._adapter = new _adapters._date(scaleOpts.adapters.date);
  12772. mergeIf(time.displayFormats, adapter.formats());
  12773. this._parseOpts = {
  12774. parser: time.parser,
  12775. round: time.round,
  12776. isoWeekday: time.isoWeekday
  12777. };
  12778. super.init(scaleOpts);
  12779. this._normalized = opts.normalized;
  12780. }
  12781. parse(raw, index) {
  12782. if (raw === undefined) {
  12783. return null;
  12784. }
  12785. return parse(this, raw);
  12786. }
  12787. beforeLayout() {
  12788. super.beforeLayout();
  12789. this._cache = {
  12790. data: [],
  12791. labels: [],
  12792. all: []
  12793. };
  12794. }
  12795. determineDataLimits() {
  12796. const me = this;
  12797. const options = me.options;
  12798. const adapter = me._adapter;
  12799. const unit = options.time.unit || 'day';
  12800. let {min, max, minDefined, maxDefined} = me.getUserBounds();
  12801. function _applyBounds(bounds) {
  12802. if (!minDefined && !isNaN(bounds.min)) {
  12803. min = Math.min(min, bounds.min);
  12804. }
  12805. if (!maxDefined && !isNaN(bounds.max)) {
  12806. max = Math.max(max, bounds.max);
  12807. }
  12808. }
  12809. if (!minDefined || !maxDefined) {
  12810. _applyBounds(me._getLabelBounds());
  12811. if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {
  12812. _applyBounds(me.getMinMax(false));
  12813. }
  12814. }
  12815. min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);
  12816. max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;
  12817. me.min = Math.min(min, max - 1);
  12818. me.max = Math.max(min + 1, max);
  12819. }
  12820. _getLabelBounds() {
  12821. const arr = this.getLabelTimestamps();
  12822. let min = Number.POSITIVE_INFINITY;
  12823. let max = Number.NEGATIVE_INFINITY;
  12824. if (arr.length) {
  12825. min = arr[0];
  12826. max = arr[arr.length - 1];
  12827. }
  12828. return {min, max};
  12829. }
  12830. buildTicks() {
  12831. const me = this;
  12832. const options = me.options;
  12833. const timeOpts = options.time;
  12834. const tickOpts = options.ticks;
  12835. const timestamps = tickOpts.source === 'labels' ? me.getLabelTimestamps() : me._generate();
  12836. if (options.bounds === 'ticks' && timestamps.length) {
  12837. me.min = me._userMin || timestamps[0];
  12838. me.max = me._userMax || timestamps[timestamps.length - 1];
  12839. }
  12840. const min = me.min;
  12841. const max = me.max;
  12842. const ticks = _filterBetween(timestamps, min, max);
  12843. me._unit = timeOpts.unit || (tickOpts.autoSkip
  12844. ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, me._getLabelCapacity(min))
  12845. : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
  12846. me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
  12847. : determineMajorUnit(me._unit);
  12848. me.initOffsets(timestamps);
  12849. if (options.reverse) {
  12850. ticks.reverse();
  12851. }
  12852. return ticksFromTimestamps(me, ticks, me._majorUnit);
  12853. }
  12854. initOffsets(timestamps) {
  12855. const me = this;
  12856. let start = 0;
  12857. let end = 0;
  12858. let first, last;
  12859. if (me.options.offset && timestamps.length) {
  12860. first = me.getDecimalForValue(timestamps[0]);
  12861. if (timestamps.length === 1) {
  12862. start = 1 - first;
  12863. } else {
  12864. start = (me.getDecimalForValue(timestamps[1]) - first) / 2;
  12865. }
  12866. last = me.getDecimalForValue(timestamps[timestamps.length - 1]);
  12867. if (timestamps.length === 1) {
  12868. end = last;
  12869. } else {
  12870. end = (last - me.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;
  12871. }
  12872. }
  12873. const limit = timestamps.length < 3 ? 0.5 : 0.25;
  12874. start = _limitValue(start, 0, limit);
  12875. end = _limitValue(end, 0, limit);
  12876. me._offsets = {start, end, factor: 1 / (start + 1 + end)};
  12877. }
  12878. _generate() {
  12879. const me = this;
  12880. const adapter = me._adapter;
  12881. const min = me.min;
  12882. const max = me.max;
  12883. const options = me.options;
  12884. const timeOpts = options.time;
  12885. const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, me._getLabelCapacity(min));
  12886. const stepSize = valueOrDefault(timeOpts.stepSize, 1);
  12887. const weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  12888. const hasWeekday = isNumber(weekday) || weekday === true;
  12889. const ticks = {};
  12890. let first = min;
  12891. let time, count;
  12892. if (hasWeekday) {
  12893. first = +adapter.startOf(first, 'isoWeek', weekday);
  12894. }
  12895. first = +adapter.startOf(first, hasWeekday ? 'day' : minor);
  12896. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  12897. throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);
  12898. }
  12899. const timestamps = options.ticks.source === 'data' && me.getDataTimestamps();
  12900. for (time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++) {
  12901. addTick(ticks, time, timestamps);
  12902. }
  12903. if (time === max || options.bounds === 'ticks' || count === 1) {
  12904. addTick(ticks, time, timestamps);
  12905. }
  12906. return Object.keys(ticks).sort((a, b) => a - b).map(x => +x);
  12907. }
  12908. getLabelForValue(value) {
  12909. const me = this;
  12910. const adapter = me._adapter;
  12911. const timeOpts = me.options.time;
  12912. if (timeOpts.tooltipFormat) {
  12913. return adapter.format(value, timeOpts.tooltipFormat);
  12914. }
  12915. return adapter.format(value, timeOpts.displayFormats.datetime);
  12916. }
  12917. _tickFormatFunction(time, index, ticks, format) {
  12918. const me = this;
  12919. const options = me.options;
  12920. const formats = options.time.displayFormats;
  12921. const unit = me._unit;
  12922. const majorUnit = me._majorUnit;
  12923. const minorFormat = unit && formats[unit];
  12924. const majorFormat = majorUnit && formats[majorUnit];
  12925. const tick = ticks[index];
  12926. const major = majorUnit && majorFormat && tick && tick.major;
  12927. const label = me._adapter.format(time, format || (major ? majorFormat : minorFormat));
  12928. const formatter = options.ticks.callback;
  12929. return formatter ? callback(formatter, [label, index, ticks], me) : label;
  12930. }
  12931. generateTickLabels(ticks) {
  12932. let i, ilen, tick;
  12933. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  12934. tick = ticks[i];
  12935. tick.label = this._tickFormatFunction(tick.value, i, ticks);
  12936. }
  12937. }
  12938. getDecimalForValue(value) {
  12939. const me = this;
  12940. return value === null ? NaN : (value - me.min) / (me.max - me.min);
  12941. }
  12942. getPixelForValue(value) {
  12943. const me = this;
  12944. const offsets = me._offsets;
  12945. const pos = me.getDecimalForValue(value);
  12946. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  12947. }
  12948. getValueForPixel(pixel) {
  12949. const me = this;
  12950. const offsets = me._offsets;
  12951. const pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  12952. return me.min + pos * (me.max - me.min);
  12953. }
  12954. _getLabelSize(label) {
  12955. const me = this;
  12956. const ticksOpts = me.options.ticks;
  12957. const tickLabelWidth = me.ctx.measureText(label).width;
  12958. const angle = toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  12959. const cosRotation = Math.cos(angle);
  12960. const sinRotation = Math.sin(angle);
  12961. const tickFontSize = me._resolveTickFontOptions(0).size;
  12962. return {
  12963. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  12964. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  12965. };
  12966. }
  12967. _getLabelCapacity(exampleTime) {
  12968. const me = this;
  12969. const timeOpts = me.options.time;
  12970. const displayFormats = timeOpts.displayFormats;
  12971. const format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  12972. const exampleLabel = me._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
  12973. const size = me._getLabelSize(exampleLabel);
  12974. const capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h) - 1;
  12975. return capacity > 0 ? capacity : 1;
  12976. }
  12977. getDataTimestamps() {
  12978. const me = this;
  12979. let timestamps = me._cache.data || [];
  12980. let i, ilen;
  12981. if (timestamps.length) {
  12982. return timestamps;
  12983. }
  12984. const metas = me.getMatchingVisibleMetas();
  12985. if (me._normalized && metas.length) {
  12986. return (me._cache.data = metas[0].controller.getAllParsedValues(me));
  12987. }
  12988. for (i = 0, ilen = metas.length; i < ilen; ++i) {
  12989. timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(me));
  12990. }
  12991. return (me._cache.data = me.normalize(timestamps));
  12992. }
  12993. getLabelTimestamps() {
  12994. const me = this;
  12995. const timestamps = me._cache.labels || [];
  12996. let i, ilen;
  12997. if (timestamps.length) {
  12998. return timestamps;
  12999. }
  13000. const labels = me.getLabels();
  13001. for (i = 0, ilen = labels.length; i < ilen; ++i) {
  13002. timestamps.push(parse(me, labels[i]));
  13003. }
  13004. return (me._cache.labels = me._normalized ? timestamps : me.normalize(timestamps));
  13005. }
  13006. normalize(values) {
  13007. return _arrayUnique(values.sort(sorter));
  13008. }
  13009. }
  13010. TimeScale.id = 'time';
  13011. TimeScale.defaults = {
  13012. bounds: 'data',
  13013. adapters: {},
  13014. time: {
  13015. parser: false,
  13016. unit: false,
  13017. round: false,
  13018. isoWeekday: false,
  13019. minUnit: 'millisecond',
  13020. displayFormats: {}
  13021. },
  13022. ticks: {
  13023. source: 'auto',
  13024. major: {
  13025. enabled: false
  13026. }
  13027. }
  13028. };
  13029. function interpolate(table, val, reverse) {
  13030. let lo = 0;
  13031. let hi = table.length - 1;
  13032. let prevSource, nextSource, prevTarget, nextTarget;
  13033. if (reverse) {
  13034. if (val >= table[lo].pos && val <= table[hi].pos) {
  13035. ({lo, hi} = _lookupByKey(table, 'pos', val));
  13036. }
  13037. ({pos: prevSource, time: prevTarget} = table[lo]);
  13038. ({pos: nextSource, time: nextTarget} = table[hi]);
  13039. } else {
  13040. if (val >= table[lo].time && val <= table[hi].time) {
  13041. ({lo, hi} = _lookupByKey(table, 'time', val));
  13042. }
  13043. ({time: prevSource, pos: prevTarget} = table[lo]);
  13044. ({time: nextSource, pos: nextTarget} = table[hi]);
  13045. }
  13046. const span = nextSource - prevSource;
  13047. return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;
  13048. }
  13049. class TimeSeriesScale extends TimeScale {
  13050. constructor(props) {
  13051. super(props);
  13052. this._table = [];
  13053. this._minPos = undefined;
  13054. this._tableRange = undefined;
  13055. }
  13056. initOffsets() {
  13057. const me = this;
  13058. const timestamps = me._getTimestampsForTable();
  13059. const table = me._table = me.buildLookupTable(timestamps);
  13060. me._minPos = interpolate(table, me.min);
  13061. me._tableRange = interpolate(table, me.max) - me._minPos;
  13062. super.initOffsets(timestamps);
  13063. }
  13064. buildLookupTable(timestamps) {
  13065. const {min, max} = this;
  13066. const items = [];
  13067. const table = [];
  13068. let i, ilen, prev, curr, next;
  13069. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  13070. curr = timestamps[i];
  13071. if (curr >= min && curr <= max) {
  13072. items.push(curr);
  13073. }
  13074. }
  13075. if (items.length < 2) {
  13076. return [
  13077. {time: min, pos: 0},
  13078. {time: max, pos: 1}
  13079. ];
  13080. }
  13081. for (i = 0, ilen = items.length; i < ilen; ++i) {
  13082. next = items[i + 1];
  13083. prev = items[i - 1];
  13084. curr = items[i];
  13085. if (Math.round((next + prev) / 2) !== curr) {
  13086. table.push({time: curr, pos: i / (ilen - 1)});
  13087. }
  13088. }
  13089. return table;
  13090. }
  13091. _getTimestampsForTable() {
  13092. const me = this;
  13093. let timestamps = me._cache.all || [];
  13094. if (timestamps.length) {
  13095. return timestamps;
  13096. }
  13097. const data = me.getDataTimestamps();
  13098. const label = me.getLabelTimestamps();
  13099. if (data.length && label.length) {
  13100. timestamps = me.normalize(data.concat(label));
  13101. } else {
  13102. timestamps = data.length ? data : label;
  13103. }
  13104. timestamps = me._cache.all = timestamps;
  13105. return timestamps;
  13106. }
  13107. getDecimalForValue(value) {
  13108. return (interpolate(this._table, value) - this._minPos) / this._tableRange;
  13109. }
  13110. getValueForPixel(pixel) {
  13111. const me = this;
  13112. const offsets = me._offsets;
  13113. const decimal = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  13114. return interpolate(me._table, decimal * me._tableRange + me._minPos, true);
  13115. }
  13116. }
  13117. TimeSeriesScale.id = 'timeseries';
  13118. TimeSeriesScale.defaults = TimeScale.defaults;
  13119. var scales = /*#__PURE__*/Object.freeze({
  13120. __proto__: null,
  13121. CategoryScale: CategoryScale,
  13122. LinearScale: LinearScale,
  13123. LogarithmicScale: LogarithmicScale,
  13124. RadialLinearScale: RadialLinearScale,
  13125. TimeScale: TimeScale,
  13126. TimeSeriesScale: TimeSeriesScale
  13127. });
  13128. Chart.register(controllers, scales, elements, plugins);
  13129. Chart.helpers = {...helpers};
  13130. Chart._adapters = _adapters;
  13131. Chart.Animation = Animation;
  13132. Chart.Animations = Animations;
  13133. Chart.animator = animator;
  13134. Chart.controllers = registry.controllers.items;
  13135. Chart.DatasetController = DatasetController;
  13136. Chart.Element = Element;
  13137. Chart.elements = elements;
  13138. Chart.Interaction = Interaction;
  13139. Chart.layouts = layouts;
  13140. Chart.platforms = platforms;
  13141. Chart.Scale = Scale;
  13142. Chart.Ticks = Ticks;
  13143. Object.assign(Chart, controllers, scales, elements, plugins, platforms);
  13144. Chart.Chart = Chart;
  13145. if (typeof window !== 'undefined') {
  13146. window.Chart = Chart;
  13147. }
  13148. return Chart;
  13149. })));