Chart.js 378 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832
  1. /*!
  2. * Chart.js v3.2.1
  3. * https://www.chartjs.org
  4. * (c) 2021 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. (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) => align === 'right' ? right : align === 'center' ? (left + right) / 2 : left;
  53. class Animator {
  54. constructor() {
  55. this._request = null;
  56. this._charts = new Map();
  57. this._running = false;
  58. this._lastDate = undefined;
  59. }
  60. _notify(chart, anims, date, type) {
  61. const callbacks = anims.listeners[type];
  62. const numSteps = anims.duration;
  63. callbacks.forEach(fn => fn({
  64. chart,
  65. initial: anims.initial,
  66. numSteps,
  67. currentStep: Math.min(date - anims.start, numSteps)
  68. }));
  69. }
  70. _refresh() {
  71. const me = this;
  72. if (me._request) {
  73. return;
  74. }
  75. me._running = true;
  76. me._request = requestAnimFrame.call(window, () => {
  77. me._update();
  78. me._request = null;
  79. if (me._running) {
  80. me._refresh();
  81. }
  82. });
  83. }
  84. _update(date = Date.now()) {
  85. const me = this;
  86. let remaining = 0;
  87. me._charts.forEach((anims, chart) => {
  88. if (!anims.running || !anims.items.length) {
  89. return;
  90. }
  91. const items = anims.items;
  92. let i = items.length - 1;
  93. let draw = false;
  94. let item;
  95. for (; i >= 0; --i) {
  96. item = items[i];
  97. if (item._active) {
  98. if (item._total > anims.duration) {
  99. anims.duration = item._total;
  100. }
  101. item.tick(date);
  102. draw = true;
  103. } else {
  104. items[i] = items[items.length - 1];
  105. items.pop();
  106. }
  107. }
  108. if (draw) {
  109. chart.draw();
  110. me._notify(chart, anims, date, 'progress');
  111. }
  112. if (!items.length) {
  113. anims.running = false;
  114. me._notify(chart, anims, date, 'complete');
  115. anims.initial = false;
  116. }
  117. remaining += items.length;
  118. });
  119. me._lastDate = date;
  120. if (remaining === 0) {
  121. me._running = false;
  122. }
  123. }
  124. _getAnims(chart) {
  125. const charts = this._charts;
  126. let anims = charts.get(chart);
  127. if (!anims) {
  128. anims = {
  129. running: false,
  130. initial: true,
  131. items: [],
  132. listeners: {
  133. complete: [],
  134. progress: []
  135. }
  136. };
  137. charts.set(chart, anims);
  138. }
  139. return anims;
  140. }
  141. listen(chart, event, cb) {
  142. this._getAnims(chart).listeners[event].push(cb);
  143. }
  144. add(chart, items) {
  145. if (!items || !items.length) {
  146. return;
  147. }
  148. this._getAnims(chart).items.push(...items);
  149. }
  150. has(chart) {
  151. return this._getAnims(chart).items.length > 0;
  152. }
  153. start(chart) {
  154. const anims = this._charts.get(chart);
  155. if (!anims) {
  156. return;
  157. }
  158. anims.running = true;
  159. anims.start = Date.now();
  160. anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0);
  161. this._refresh();
  162. }
  163. running(chart) {
  164. if (!this._running) {
  165. return false;
  166. }
  167. const anims = this._charts.get(chart);
  168. if (!anims || !anims.running || !anims.items.length) {
  169. return false;
  170. }
  171. return true;
  172. }
  173. stop(chart) {
  174. const anims = this._charts.get(chart);
  175. if (!anims || !anims.items.length) {
  176. return;
  177. }
  178. const items = anims.items;
  179. let i = items.length - 1;
  180. for (; i >= 0; --i) {
  181. items[i].cancel();
  182. }
  183. anims.items = [];
  184. this._notify(chart, anims, Date.now(), 'complete');
  185. }
  186. remove(chart) {
  187. return this._charts.delete(chart);
  188. }
  189. }
  190. var animator = new Animator();
  191. /*!
  192. * @kurkle/color v0.1.9
  193. * https://github.com/kurkle/color#readme
  194. * (c) 2020 Jukka Kurkela
  195. * Released under the MIT License
  196. */
  197. const map = {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};
  198. const hex = '0123456789ABCDEF';
  199. const h1 = (b) => hex[b & 0xF];
  200. const h2 = (b) => hex[(b & 0xF0) >> 4] + hex[b & 0xF];
  201. const eq = (b) => (((b & 0xF0) >> 4) === (b & 0xF));
  202. function isShort(v) {
  203. return eq(v.r) && eq(v.g) && eq(v.b) && eq(v.a);
  204. }
  205. function hexParse(str) {
  206. var len = str.length;
  207. var ret;
  208. if (str[0] === '#') {
  209. if (len === 4 || len === 5) {
  210. ret = {
  211. r: 255 & map[str[1]] * 17,
  212. g: 255 & map[str[2]] * 17,
  213. b: 255 & map[str[3]] * 17,
  214. a: len === 5 ? map[str[4]] * 17 : 255
  215. };
  216. } else if (len === 7 || len === 9) {
  217. ret = {
  218. r: map[str[1]] << 4 | map[str[2]],
  219. g: map[str[3]] << 4 | map[str[4]],
  220. b: map[str[5]] << 4 | map[str[6]],
  221. a: len === 9 ? (map[str[7]] << 4 | map[str[8]]) : 255
  222. };
  223. }
  224. }
  225. return ret;
  226. }
  227. function hexString(v) {
  228. var f = isShort(v) ? h1 : h2;
  229. return v
  230. ? '#' + f(v.r) + f(v.g) + f(v.b) + (v.a < 255 ? f(v.a) : '')
  231. : v;
  232. }
  233. function round(v) {
  234. return v + 0.5 | 0;
  235. }
  236. const lim = (v, l, h) => Math.max(Math.min(v, h), l);
  237. function p2b(v) {
  238. return lim(round(v * 2.55), 0, 255);
  239. }
  240. function n2b(v) {
  241. return lim(round(v * 255), 0, 255);
  242. }
  243. function b2n(v) {
  244. return lim(round(v / 2.55) / 100, 0, 1);
  245. }
  246. function n2p(v) {
  247. return lim(round(v * 100), 0, 100);
  248. }
  249. const RGB_RE = /^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;
  250. function rgbParse(str) {
  251. const m = RGB_RE.exec(str);
  252. let a = 255;
  253. let r, g, b;
  254. if (!m) {
  255. return;
  256. }
  257. if (m[7] !== r) {
  258. const v = +m[7];
  259. a = 255 & (m[8] ? p2b(v) : v * 255);
  260. }
  261. r = +m[1];
  262. g = +m[3];
  263. b = +m[5];
  264. r = 255 & (m[2] ? p2b(r) : r);
  265. g = 255 & (m[4] ? p2b(g) : g);
  266. b = 255 & (m[6] ? p2b(b) : b);
  267. return {
  268. r: r,
  269. g: g,
  270. b: b,
  271. a: a
  272. };
  273. }
  274. function rgbString(v) {
  275. return v && (
  276. v.a < 255
  277. ? `rgba(${v.r}, ${v.g}, ${v.b}, ${b2n(v.a)})`
  278. : `rgb(${v.r}, ${v.g}, ${v.b})`
  279. );
  280. }
  281. const HUE_RE = /^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;
  282. function hsl2rgbn(h, s, l) {
  283. const a = s * Math.min(l, 1 - l);
  284. const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
  285. return [f(0), f(8), f(4)];
  286. }
  287. function hsv2rgbn(h, s, v) {
  288. const f = (n, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0);
  289. return [f(5), f(3), f(1)];
  290. }
  291. function hwb2rgbn(h, w, b) {
  292. const rgb = hsl2rgbn(h, 1, 0.5);
  293. let i;
  294. if (w + b > 1) {
  295. i = 1 / (w + b);
  296. w *= i;
  297. b *= i;
  298. }
  299. for (i = 0; i < 3; i++) {
  300. rgb[i] *= 1 - w - b;
  301. rgb[i] += w;
  302. }
  303. return rgb;
  304. }
  305. function rgb2hsl(v) {
  306. const range = 255;
  307. const r = v.r / range;
  308. const g = v.g / range;
  309. const b = v.b / range;
  310. const max = Math.max(r, g, b);
  311. const min = Math.min(r, g, b);
  312. const l = (max + min) / 2;
  313. let h, s, d;
  314. if (max !== min) {
  315. d = max - min;
  316. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  317. h = max === r
  318. ? ((g - b) / d) + (g < b ? 6 : 0)
  319. : max === g
  320. ? (b - r) / d + 2
  321. : (r - g) / d + 4;
  322. h = h * 60 + 0.5;
  323. }
  324. return [h | 0, s || 0, l];
  325. }
  326. function calln(f, a, b, c) {
  327. return (
  328. Array.isArray(a)
  329. ? f(a[0], a[1], a[2])
  330. : f(a, b, c)
  331. ).map(n2b);
  332. }
  333. function hsl2rgb(h, s, l) {
  334. return calln(hsl2rgbn, h, s, l);
  335. }
  336. function hwb2rgb(h, w, b) {
  337. return calln(hwb2rgbn, h, w, b);
  338. }
  339. function hsv2rgb(h, s, v) {
  340. return calln(hsv2rgbn, h, s, v);
  341. }
  342. function hue(h) {
  343. return (h % 360 + 360) % 360;
  344. }
  345. function hueParse(str) {
  346. const m = HUE_RE.exec(str);
  347. let a = 255;
  348. let v;
  349. if (!m) {
  350. return;
  351. }
  352. if (m[5] !== v) {
  353. a = m[6] ? p2b(+m[5]) : n2b(+m[5]);
  354. }
  355. const h = hue(+m[2]);
  356. const p1 = +m[3] / 100;
  357. const p2 = +m[4] / 100;
  358. if (m[1] === 'hwb') {
  359. v = hwb2rgb(h, p1, p2);
  360. } else if (m[1] === 'hsv') {
  361. v = hsv2rgb(h, p1, p2);
  362. } else {
  363. v = hsl2rgb(h, p1, p2);
  364. }
  365. return {
  366. r: v[0],
  367. g: v[1],
  368. b: v[2],
  369. a: a
  370. };
  371. }
  372. function rotate(v, deg) {
  373. var h = rgb2hsl(v);
  374. h[0] = hue(h[0] + deg);
  375. h = hsl2rgb(h);
  376. v.r = h[0];
  377. v.g = h[1];
  378. v.b = h[2];
  379. }
  380. function hslString(v) {
  381. if (!v) {
  382. return;
  383. }
  384. const a = rgb2hsl(v);
  385. const h = a[0];
  386. const s = n2p(a[1]);
  387. const l = n2p(a[2]);
  388. return v.a < 255
  389. ? `hsla(${h}, ${s}%, ${l}%, ${b2n(v.a)})`
  390. : `hsl(${h}, ${s}%, ${l}%)`;
  391. }
  392. const map$1 = {
  393. x: 'dark',
  394. Z: 'light',
  395. Y: 're',
  396. X: 'blu',
  397. W: 'gr',
  398. V: 'medium',
  399. U: 'slate',
  400. A: 'ee',
  401. T: 'ol',
  402. S: 'or',
  403. B: 'ra',
  404. C: 'lateg',
  405. D: 'ights',
  406. R: 'in',
  407. Q: 'turquois',
  408. E: 'hi',
  409. P: 'ro',
  410. O: 'al',
  411. N: 'le',
  412. M: 'de',
  413. L: 'yello',
  414. F: 'en',
  415. K: 'ch',
  416. G: 'arks',
  417. H: 'ea',
  418. I: 'ightg',
  419. J: 'wh'
  420. };
  421. const names = {
  422. OiceXe: 'f0f8ff',
  423. antiquewEte: 'faebd7',
  424. aqua: 'ffff',
  425. aquamarRe: '7fffd4',
  426. azuY: 'f0ffff',
  427. beige: 'f5f5dc',
  428. bisque: 'ffe4c4',
  429. black: '0',
  430. blanKedOmond: 'ffebcd',
  431. Xe: 'ff',
  432. XeviTet: '8a2be2',
  433. bPwn: 'a52a2a',
  434. burlywood: 'deb887',
  435. caMtXe: '5f9ea0',
  436. KartYuse: '7fff00',
  437. KocTate: 'd2691e',
  438. cSO: 'ff7f50',
  439. cSnflowerXe: '6495ed',
  440. cSnsilk: 'fff8dc',
  441. crimson: 'dc143c',
  442. cyan: 'ffff',
  443. xXe: '8b',
  444. xcyan: '8b8b',
  445. xgTMnPd: 'b8860b',
  446. xWay: 'a9a9a9',
  447. xgYF: '6400',
  448. xgYy: 'a9a9a9',
  449. xkhaki: 'bdb76b',
  450. xmagFta: '8b008b',
  451. xTivegYF: '556b2f',
  452. xSange: 'ff8c00',
  453. xScEd: '9932cc',
  454. xYd: '8b0000',
  455. xsOmon: 'e9967a',
  456. xsHgYF: '8fbc8f',
  457. xUXe: '483d8b',
  458. xUWay: '2f4f4f',
  459. xUgYy: '2f4f4f',
  460. xQe: 'ced1',
  461. xviTet: '9400d3',
  462. dAppRk: 'ff1493',
  463. dApskyXe: 'bfff',
  464. dimWay: '696969',
  465. dimgYy: '696969',
  466. dodgerXe: '1e90ff',
  467. fiYbrick: 'b22222',
  468. flSOwEte: 'fffaf0',
  469. foYstWAn: '228b22',
  470. fuKsia: 'ff00ff',
  471. gaRsbSo: 'dcdcdc',
  472. ghostwEte: 'f8f8ff',
  473. gTd: 'ffd700',
  474. gTMnPd: 'daa520',
  475. Way: '808080',
  476. gYF: '8000',
  477. gYFLw: 'adff2f',
  478. gYy: '808080',
  479. honeyMw: 'f0fff0',
  480. hotpRk: 'ff69b4',
  481. RdianYd: 'cd5c5c',
  482. Rdigo: '4b0082',
  483. ivSy: 'fffff0',
  484. khaki: 'f0e68c',
  485. lavFMr: 'e6e6fa',
  486. lavFMrXsh: 'fff0f5',
  487. lawngYF: '7cfc00',
  488. NmoncEffon: 'fffacd',
  489. ZXe: 'add8e6',
  490. ZcSO: 'f08080',
  491. Zcyan: 'e0ffff',
  492. ZgTMnPdLw: 'fafad2',
  493. ZWay: 'd3d3d3',
  494. ZgYF: '90ee90',
  495. ZgYy: 'd3d3d3',
  496. ZpRk: 'ffb6c1',
  497. ZsOmon: 'ffa07a',
  498. ZsHgYF: '20b2aa',
  499. ZskyXe: '87cefa',
  500. ZUWay: '778899',
  501. ZUgYy: '778899',
  502. ZstAlXe: 'b0c4de',
  503. ZLw: 'ffffe0',
  504. lime: 'ff00',
  505. limegYF: '32cd32',
  506. lRF: 'faf0e6',
  507. magFta: 'ff00ff',
  508. maPon: '800000',
  509. VaquamarRe: '66cdaa',
  510. VXe: 'cd',
  511. VScEd: 'ba55d3',
  512. VpurpN: '9370db',
  513. VsHgYF: '3cb371',
  514. VUXe: '7b68ee',
  515. VsprRggYF: 'fa9a',
  516. VQe: '48d1cc',
  517. VviTetYd: 'c71585',
  518. midnightXe: '191970',
  519. mRtcYam: 'f5fffa',
  520. mistyPse: 'ffe4e1',
  521. moccasR: 'ffe4b5',
  522. navajowEte: 'ffdead',
  523. navy: '80',
  524. Tdlace: 'fdf5e6',
  525. Tive: '808000',
  526. TivedBb: '6b8e23',
  527. Sange: 'ffa500',
  528. SangeYd: 'ff4500',
  529. ScEd: 'da70d6',
  530. pOegTMnPd: 'eee8aa',
  531. pOegYF: '98fb98',
  532. pOeQe: 'afeeee',
  533. pOeviTetYd: 'db7093',
  534. papayawEp: 'ffefd5',
  535. pHKpuff: 'ffdab9',
  536. peru: 'cd853f',
  537. pRk: 'ffc0cb',
  538. plum: 'dda0dd',
  539. powMrXe: 'b0e0e6',
  540. purpN: '800080',
  541. YbeccapurpN: '663399',
  542. Yd: 'ff0000',
  543. Psybrown: 'bc8f8f',
  544. PyOXe: '4169e1',
  545. saddNbPwn: '8b4513',
  546. sOmon: 'fa8072',
  547. sandybPwn: 'f4a460',
  548. sHgYF: '2e8b57',
  549. sHshell: 'fff5ee',
  550. siFna: 'a0522d',
  551. silver: 'c0c0c0',
  552. skyXe: '87ceeb',
  553. UXe: '6a5acd',
  554. UWay: '708090',
  555. UgYy: '708090',
  556. snow: 'fffafa',
  557. sprRggYF: 'ff7f',
  558. stAlXe: '4682b4',
  559. tan: 'd2b48c',
  560. teO: '8080',
  561. tEstN: 'd8bfd8',
  562. tomato: 'ff6347',
  563. Qe: '40e0d0',
  564. viTet: 'ee82ee',
  565. JHt: 'f5deb3',
  566. wEte: 'ffffff',
  567. wEtesmoke: 'f5f5f5',
  568. Lw: 'ffff00',
  569. LwgYF: '9acd32'
  570. };
  571. function unpack() {
  572. const unpacked = {};
  573. const keys = Object.keys(names);
  574. const tkeys = Object.keys(map$1);
  575. let i, j, k, ok, nk;
  576. for (i = 0; i < keys.length; i++) {
  577. ok = nk = keys[i];
  578. for (j = 0; j < tkeys.length; j++) {
  579. k = tkeys[j];
  580. nk = nk.replace(k, map$1[k]);
  581. }
  582. k = parseInt(names[ok], 16);
  583. unpacked[nk] = [k >> 16 & 0xFF, k >> 8 & 0xFF, k & 0xFF];
  584. }
  585. return unpacked;
  586. }
  587. let names$1;
  588. function nameParse(str) {
  589. if (!names$1) {
  590. names$1 = unpack();
  591. names$1.transparent = [0, 0, 0, 0];
  592. }
  593. const a = names$1[str.toLowerCase()];
  594. return a && {
  595. r: a[0],
  596. g: a[1],
  597. b: a[2],
  598. a: a.length === 4 ? a[3] : 255
  599. };
  600. }
  601. function modHSL(v, i, ratio) {
  602. if (v) {
  603. let tmp = rgb2hsl(v);
  604. tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1));
  605. tmp = hsl2rgb(tmp);
  606. v.r = tmp[0];
  607. v.g = tmp[1];
  608. v.b = tmp[2];
  609. }
  610. }
  611. function clone$1(v, proto) {
  612. return v ? Object.assign(proto || {}, v) : v;
  613. }
  614. function fromObject(input) {
  615. var v = {r: 0, g: 0, b: 0, a: 255};
  616. if (Array.isArray(input)) {
  617. if (input.length >= 3) {
  618. v = {r: input[0], g: input[1], b: input[2], a: 255};
  619. if (input.length > 3) {
  620. v.a = n2b(input[3]);
  621. }
  622. }
  623. } else {
  624. v = clone$1(input, {r: 0, g: 0, b: 0, a: 1});
  625. v.a = n2b(v.a);
  626. }
  627. return v;
  628. }
  629. function functionParse(str) {
  630. if (str.charAt(0) === 'r') {
  631. return rgbParse(str);
  632. }
  633. return hueParse(str);
  634. }
  635. class Color {
  636. constructor(input) {
  637. if (input instanceof Color) {
  638. return input;
  639. }
  640. const type = typeof input;
  641. let v;
  642. if (type === 'object') {
  643. v = fromObject(input);
  644. } else if (type === 'string') {
  645. v = hexParse(input) || nameParse(input) || functionParse(input);
  646. }
  647. this._rgb = v;
  648. this._valid = !!v;
  649. }
  650. get valid() {
  651. return this._valid;
  652. }
  653. get rgb() {
  654. var v = clone$1(this._rgb);
  655. if (v) {
  656. v.a = b2n(v.a);
  657. }
  658. return v;
  659. }
  660. set rgb(obj) {
  661. this._rgb = fromObject(obj);
  662. }
  663. rgbString() {
  664. return this._valid ? rgbString(this._rgb) : this._rgb;
  665. }
  666. hexString() {
  667. return this._valid ? hexString(this._rgb) : this._rgb;
  668. }
  669. hslString() {
  670. return this._valid ? hslString(this._rgb) : this._rgb;
  671. }
  672. mix(color, weight) {
  673. const me = this;
  674. if (color) {
  675. const c1 = me.rgb;
  676. const c2 = color.rgb;
  677. let w2;
  678. const p = weight === w2 ? 0.5 : weight;
  679. const w = 2 * p - 1;
  680. const a = c1.a - c2.a;
  681. const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  682. w2 = 1 - w1;
  683. c1.r = 0xFF & w1 * c1.r + w2 * c2.r + 0.5;
  684. c1.g = 0xFF & w1 * c1.g + w2 * c2.g + 0.5;
  685. c1.b = 0xFF & w1 * c1.b + w2 * c2.b + 0.5;
  686. c1.a = p * c1.a + (1 - p) * c2.a;
  687. me.rgb = c1;
  688. }
  689. return me;
  690. }
  691. clone() {
  692. return new Color(this.rgb);
  693. }
  694. alpha(a) {
  695. this._rgb.a = n2b(a);
  696. return this;
  697. }
  698. clearer(ratio) {
  699. const rgb = this._rgb;
  700. rgb.a *= 1 - ratio;
  701. return this;
  702. }
  703. greyscale() {
  704. const rgb = this._rgb;
  705. const val = round(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11);
  706. rgb.r = rgb.g = rgb.b = val;
  707. return this;
  708. }
  709. opaquer(ratio) {
  710. const rgb = this._rgb;
  711. rgb.a *= 1 + ratio;
  712. return this;
  713. }
  714. negate() {
  715. const v = this._rgb;
  716. v.r = 255 - v.r;
  717. v.g = 255 - v.g;
  718. v.b = 255 - v.b;
  719. return this;
  720. }
  721. lighten(ratio) {
  722. modHSL(this._rgb, 2, ratio);
  723. return this;
  724. }
  725. darken(ratio) {
  726. modHSL(this._rgb, 2, -ratio);
  727. return this;
  728. }
  729. saturate(ratio) {
  730. modHSL(this._rgb, 1, ratio);
  731. return this;
  732. }
  733. desaturate(ratio) {
  734. modHSL(this._rgb, 1, -ratio);
  735. return this;
  736. }
  737. rotate(deg) {
  738. rotate(this._rgb, deg);
  739. return this;
  740. }
  741. }
  742. function index_esm(input) {
  743. return new Color(input);
  744. }
  745. const isPatternOrGradient = (value) => value instanceof CanvasGradient || value instanceof CanvasPattern;
  746. function color(value) {
  747. return isPatternOrGradient(value) ? value : index_esm(value);
  748. }
  749. function getHoverColor(value) {
  750. return isPatternOrGradient(value)
  751. ? value
  752. : index_esm(value).saturate(0.5).darken(0.1).hexString();
  753. }
  754. function noop() {}
  755. const uid = (function() {
  756. let id = 0;
  757. return function() {
  758. return id++;
  759. };
  760. }());
  761. function isNullOrUndef(value) {
  762. return value === null || typeof value === 'undefined';
  763. }
  764. function isArray(value) {
  765. if (Array.isArray && Array.isArray(value)) {
  766. return true;
  767. }
  768. const type = Object.prototype.toString.call(value);
  769. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  770. return true;
  771. }
  772. return false;
  773. }
  774. function isObject(value) {
  775. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  776. }
  777. const isNumberFinite = (value) => (typeof value === 'number' || value instanceof Number) && isFinite(+value);
  778. function finiteOrDefault(value, defaultValue) {
  779. return isNumberFinite(value) ? value : defaultValue;
  780. }
  781. function valueOrDefault(value, defaultValue) {
  782. return typeof value === 'undefined' ? defaultValue : value;
  783. }
  784. const toPercentage = (value, dimension) =>
  785. typeof value === 'string' && value.endsWith('%') ?
  786. parseFloat(value) / 100
  787. : value / dimension;
  788. const toDimension = (value, dimension) =>
  789. typeof value === 'string' && value.endsWith('%') ?
  790. parseFloat(value) / 100 * dimension
  791. : +value;
  792. function callback(fn, args, thisArg) {
  793. if (fn && typeof fn.call === 'function') {
  794. return fn.apply(thisArg, args);
  795. }
  796. }
  797. function each(loopable, fn, thisArg, reverse) {
  798. let i, len, keys;
  799. if (isArray(loopable)) {
  800. len = loopable.length;
  801. if (reverse) {
  802. for (i = len - 1; i >= 0; i--) {
  803. fn.call(thisArg, loopable[i], i);
  804. }
  805. } else {
  806. for (i = 0; i < len; i++) {
  807. fn.call(thisArg, loopable[i], i);
  808. }
  809. }
  810. } else if (isObject(loopable)) {
  811. keys = Object.keys(loopable);
  812. len = keys.length;
  813. for (i = 0; i < len; i++) {
  814. fn.call(thisArg, loopable[keys[i]], keys[i]);
  815. }
  816. }
  817. }
  818. function _elementsEqual(a0, a1) {
  819. let i, ilen, v0, v1;
  820. if (!a0 || !a1 || a0.length !== a1.length) {
  821. return false;
  822. }
  823. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  824. v0 = a0[i];
  825. v1 = a1[i];
  826. if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) {
  827. return false;
  828. }
  829. }
  830. return true;
  831. }
  832. function clone(source) {
  833. if (isArray(source)) {
  834. return source.map(clone);
  835. }
  836. if (isObject(source)) {
  837. const target = Object.create(null);
  838. const keys = Object.keys(source);
  839. const klen = keys.length;
  840. let k = 0;
  841. for (; k < klen; ++k) {
  842. target[keys[k]] = clone(source[keys[k]]);
  843. }
  844. return target;
  845. }
  846. return source;
  847. }
  848. function isValidKey(key) {
  849. return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1;
  850. }
  851. function _merger(key, target, source, options) {
  852. if (!isValidKey(key)) {
  853. return;
  854. }
  855. const tval = target[key];
  856. const sval = source[key];
  857. if (isObject(tval) && isObject(sval)) {
  858. merge(tval, sval, options);
  859. } else {
  860. target[key] = clone(sval);
  861. }
  862. }
  863. function merge(target, source, options) {
  864. const sources = isArray(source) ? source : [source];
  865. const ilen = sources.length;
  866. if (!isObject(target)) {
  867. return target;
  868. }
  869. options = options || {};
  870. const merger = options.merger || _merger;
  871. for (let i = 0; i < ilen; ++i) {
  872. source = sources[i];
  873. if (!isObject(source)) {
  874. continue;
  875. }
  876. const keys = Object.keys(source);
  877. for (let k = 0, klen = keys.length; k < klen; ++k) {
  878. merger(keys[k], target, source, options);
  879. }
  880. }
  881. return target;
  882. }
  883. function mergeIf(target, source) {
  884. return merge(target, source, {merger: _mergerIf});
  885. }
  886. function _mergerIf(key, target, source) {
  887. if (!isValidKey(key)) {
  888. return;
  889. }
  890. const tval = target[key];
  891. const sval = source[key];
  892. if (isObject(tval) && isObject(sval)) {
  893. mergeIf(tval, sval);
  894. } else if (!Object.prototype.hasOwnProperty.call(target, key)) {
  895. target[key] = clone(sval);
  896. }
  897. }
  898. function _deprecated(scope, value, previous, current) {
  899. if (value !== undefined) {
  900. console.warn(scope + ': "' + previous +
  901. '" is deprecated. Please use "' + current + '" instead');
  902. }
  903. }
  904. const emptyString = '';
  905. const dot = '.';
  906. function indexOfDotOrLength(key, start) {
  907. const idx = key.indexOf(dot, start);
  908. return idx === -1 ? key.length : idx;
  909. }
  910. function resolveObjectKey(obj, key) {
  911. if (key === emptyString) {
  912. return obj;
  913. }
  914. let pos = 0;
  915. let idx = indexOfDotOrLength(key, pos);
  916. while (obj && idx > pos) {
  917. obj = obj[key.substr(pos, idx - pos)];
  918. pos = idx + 1;
  919. idx = indexOfDotOrLength(key, pos);
  920. }
  921. return obj;
  922. }
  923. function _capitalize(str) {
  924. return str.charAt(0).toUpperCase() + str.slice(1);
  925. }
  926. const defined = (value) => typeof value !== 'undefined';
  927. const isFunction = (value) => typeof value === 'function';
  928. const setsEqual = (a, b) => {
  929. if (a.size !== b.size) {
  930. return false;
  931. }
  932. for (const item of a) {
  933. if (!b.has(item)) {
  934. return false;
  935. }
  936. }
  937. return true;
  938. };
  939. const overrides = Object.create(null);
  940. const descriptors = Object.create(null);
  941. function getScope$1(node, key) {
  942. if (!key) {
  943. return node;
  944. }
  945. const keys = key.split('.');
  946. for (let i = 0, n = keys.length; i < n; ++i) {
  947. const k = keys[i];
  948. node = node[k] || (node[k] = Object.create(null));
  949. }
  950. return node;
  951. }
  952. function set(root, scope, values) {
  953. if (typeof scope === 'string') {
  954. return merge(getScope$1(root, scope), values);
  955. }
  956. return merge(getScope$1(root, ''), scope);
  957. }
  958. class Defaults {
  959. constructor(_descriptors) {
  960. this.animation = undefined;
  961. this.backgroundColor = 'rgba(0,0,0,0.1)';
  962. this.borderColor = 'rgba(0,0,0,0.1)';
  963. this.color = '#666';
  964. this.datasets = {};
  965. this.devicePixelRatio = (context) => context.chart.platform.getDevicePixelRatio();
  966. this.elements = {};
  967. this.events = [
  968. 'mousemove',
  969. 'mouseout',
  970. 'click',
  971. 'touchstart',
  972. 'touchmove'
  973. ];
  974. this.font = {
  975. family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  976. size: 12,
  977. style: 'normal',
  978. lineHeight: 1.2,
  979. weight: null
  980. };
  981. this.hover = {};
  982. this.hoverBackgroundColor = (ctx, options) => getHoverColor(options.backgroundColor);
  983. this.hoverBorderColor = (ctx, options) => getHoverColor(options.borderColor);
  984. this.hoverColor = (ctx, options) => getHoverColor(options.color);
  985. this.indexAxis = 'x';
  986. this.interaction = {
  987. mode: 'nearest',
  988. intersect: true
  989. };
  990. this.maintainAspectRatio = true;
  991. this.onHover = null;
  992. this.onClick = null;
  993. this.parsing = true;
  994. this.plugins = {};
  995. this.responsive = true;
  996. this.scale = undefined;
  997. this.scales = {};
  998. this.showLine = true;
  999. this.describe(_descriptors);
  1000. }
  1001. set(scope, values) {
  1002. return set(this, scope, values);
  1003. }
  1004. get(scope) {
  1005. return getScope$1(this, scope);
  1006. }
  1007. describe(scope, values) {
  1008. return set(descriptors, scope, values);
  1009. }
  1010. override(scope, values) {
  1011. return set(overrides, scope, values);
  1012. }
  1013. route(scope, name, targetScope, targetName) {
  1014. const scopeObject = getScope$1(this, scope);
  1015. const targetScopeObject = getScope$1(this, targetScope);
  1016. const privateName = '_' + name;
  1017. Object.defineProperties(scopeObject, {
  1018. [privateName]: {
  1019. value: scopeObject[name],
  1020. writable: true
  1021. },
  1022. [name]: {
  1023. enumerable: true,
  1024. get() {
  1025. const local = this[privateName];
  1026. const target = targetScopeObject[targetName];
  1027. if (isObject(local)) {
  1028. return Object.assign({}, target, local);
  1029. }
  1030. return valueOrDefault(local, target);
  1031. },
  1032. set(value) {
  1033. this[privateName] = value;
  1034. }
  1035. }
  1036. });
  1037. }
  1038. }
  1039. var defaults = new Defaults({
  1040. _scriptable: (name) => !name.startsWith('on'),
  1041. _indexable: (name) => name !== 'events',
  1042. hover: {
  1043. _fallback: 'interaction'
  1044. },
  1045. interaction: {
  1046. _scriptable: false,
  1047. _indexable: false,
  1048. }
  1049. });
  1050. const PI = Math.PI;
  1051. const TAU = 2 * PI;
  1052. const PITAU = TAU + PI;
  1053. const INFINITY = Number.POSITIVE_INFINITY;
  1054. const RAD_PER_DEG = PI / 180;
  1055. const HALF_PI = PI / 2;
  1056. const QUARTER_PI = PI / 4;
  1057. const TWO_THIRDS_PI = PI * 2 / 3;
  1058. const log10 = Math.log10;
  1059. const sign = Math.sign;
  1060. function niceNum(range) {
  1061. const niceRange = Math.pow(10, Math.floor(log10(range)));
  1062. const fraction = range / niceRange;
  1063. const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
  1064. return niceFraction * niceRange;
  1065. }
  1066. function _factorize(value) {
  1067. const result = [];
  1068. const sqrt = Math.sqrt(value);
  1069. let i;
  1070. for (i = 1; i < sqrt; i++) {
  1071. if (value % i === 0) {
  1072. result.push(i);
  1073. result.push(value / i);
  1074. }
  1075. }
  1076. if (sqrt === (sqrt | 0)) {
  1077. result.push(sqrt);
  1078. }
  1079. result.sort((a, b) => a - b).pop();
  1080. return result;
  1081. }
  1082. function isNumber(n) {
  1083. return !isNaN(parseFloat(n)) && isFinite(n);
  1084. }
  1085. function almostEquals(x, y, epsilon) {
  1086. return Math.abs(x - y) < epsilon;
  1087. }
  1088. function almostWhole(x, epsilon) {
  1089. const rounded = Math.round(x);
  1090. return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
  1091. }
  1092. function _setMinAndMaxByKey(array, target, property) {
  1093. let i, ilen, value;
  1094. for (i = 0, ilen = array.length; i < ilen; i++) {
  1095. value = array[i][property];
  1096. if (!isNaN(value)) {
  1097. target.min = Math.min(target.min, value);
  1098. target.max = Math.max(target.max, value);
  1099. }
  1100. }
  1101. }
  1102. function toRadians(degrees) {
  1103. return degrees * (PI / 180);
  1104. }
  1105. function toDegrees(radians) {
  1106. return radians * (180 / PI);
  1107. }
  1108. function _decimalPlaces(x) {
  1109. if (!isNumberFinite(x)) {
  1110. return;
  1111. }
  1112. let e = 1;
  1113. let p = 0;
  1114. while (Math.round(x * e) / e !== x) {
  1115. e *= 10;
  1116. p++;
  1117. }
  1118. return p;
  1119. }
  1120. function getAngleFromPoint(centrePoint, anglePoint) {
  1121. const distanceFromXCenter = anglePoint.x - centrePoint.x;
  1122. const distanceFromYCenter = anglePoint.y - centrePoint.y;
  1123. const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  1124. let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  1125. if (angle < (-0.5 * PI)) {
  1126. angle += TAU;
  1127. }
  1128. return {
  1129. angle,
  1130. distance: radialDistanceFromCenter
  1131. };
  1132. }
  1133. function distanceBetweenPoints(pt1, pt2) {
  1134. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  1135. }
  1136. function _angleDiff(a, b) {
  1137. return (a - b + PITAU) % TAU - PI;
  1138. }
  1139. function _normalizeAngle(a) {
  1140. return (a % TAU + TAU) % TAU;
  1141. }
  1142. function _angleBetween(angle, start, end) {
  1143. const a = _normalizeAngle(angle);
  1144. const s = _normalizeAngle(start);
  1145. const e = _normalizeAngle(end);
  1146. const angleToStart = _normalizeAngle(s - a);
  1147. const angleToEnd = _normalizeAngle(e - a);
  1148. const startToAngle = _normalizeAngle(a - s);
  1149. const endToAngle = _normalizeAngle(a - e);
  1150. return a === s || a === e || (angleToStart > angleToEnd && startToAngle < endToAngle);
  1151. }
  1152. function _limitValue(value, min, max) {
  1153. return Math.max(min, Math.min(max, value));
  1154. }
  1155. function _int16Range(value) {
  1156. return _limitValue(value, -32768, 32767);
  1157. }
  1158. function toFontString(font) {
  1159. if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) {
  1160. return null;
  1161. }
  1162. return (font.style ? font.style + ' ' : '')
  1163. + (font.weight ? font.weight + ' ' : '')
  1164. + font.size + 'px '
  1165. + font.family;
  1166. }
  1167. function _measureText(ctx, data, gc, longest, string) {
  1168. let textWidth = data[string];
  1169. if (!textWidth) {
  1170. textWidth = data[string] = ctx.measureText(string).width;
  1171. gc.push(string);
  1172. }
  1173. if (textWidth > longest) {
  1174. longest = textWidth;
  1175. }
  1176. return longest;
  1177. }
  1178. function _longestText(ctx, font, arrayOfThings, cache) {
  1179. cache = cache || {};
  1180. let data = cache.data = cache.data || {};
  1181. let gc = cache.garbageCollect = cache.garbageCollect || [];
  1182. if (cache.font !== font) {
  1183. data = cache.data = {};
  1184. gc = cache.garbageCollect = [];
  1185. cache.font = font;
  1186. }
  1187. ctx.save();
  1188. ctx.font = font;
  1189. let longest = 0;
  1190. const ilen = arrayOfThings.length;
  1191. let i, j, jlen, thing, nestedThing;
  1192. for (i = 0; i < ilen; i++) {
  1193. thing = arrayOfThings[i];
  1194. if (thing !== undefined && thing !== null && isArray(thing) !== true) {
  1195. longest = _measureText(ctx, data, gc, longest, thing);
  1196. } else if (isArray(thing)) {
  1197. for (j = 0, jlen = thing.length; j < jlen; j++) {
  1198. nestedThing = thing[j];
  1199. if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) {
  1200. longest = _measureText(ctx, data, gc, longest, nestedThing);
  1201. }
  1202. }
  1203. }
  1204. }
  1205. ctx.restore();
  1206. const gcLen = gc.length / 2;
  1207. if (gcLen > arrayOfThings.length) {
  1208. for (i = 0; i < gcLen; i++) {
  1209. delete data[gc[i]];
  1210. }
  1211. gc.splice(0, gcLen);
  1212. }
  1213. return longest;
  1214. }
  1215. function _alignPixel(chart, pixel, width) {
  1216. const devicePixelRatio = chart.currentDevicePixelRatio;
  1217. const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0;
  1218. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  1219. }
  1220. function clearCanvas(canvas, ctx) {
  1221. ctx = ctx || canvas.getContext('2d');
  1222. ctx.save();
  1223. ctx.resetTransform();
  1224. ctx.clearRect(0, 0, canvas.width, canvas.height);
  1225. ctx.restore();
  1226. }
  1227. function drawPoint(ctx, options, x, y) {
  1228. let type, xOffset, yOffset, size, cornerRadius;
  1229. const style = options.pointStyle;
  1230. const rotation = options.rotation;
  1231. const radius = options.radius;
  1232. let rad = (rotation || 0) * RAD_PER_DEG;
  1233. if (style && typeof style === 'object') {
  1234. type = style.toString();
  1235. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  1236. ctx.save();
  1237. ctx.translate(x, y);
  1238. ctx.rotate(rad);
  1239. ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
  1240. ctx.restore();
  1241. return;
  1242. }
  1243. }
  1244. if (isNaN(radius) || radius <= 0) {
  1245. return;
  1246. }
  1247. ctx.beginPath();
  1248. switch (style) {
  1249. default:
  1250. ctx.arc(x, y, radius, 0, TAU);
  1251. ctx.closePath();
  1252. break;
  1253. case 'triangle':
  1254. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  1255. rad += TWO_THIRDS_PI;
  1256. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  1257. rad += TWO_THIRDS_PI;
  1258. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  1259. ctx.closePath();
  1260. break;
  1261. case 'rectRounded':
  1262. cornerRadius = radius * 0.516;
  1263. size = radius - cornerRadius;
  1264. xOffset = Math.cos(rad + QUARTER_PI) * size;
  1265. yOffset = Math.sin(rad + QUARTER_PI) * size;
  1266. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  1267. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  1268. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  1269. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  1270. ctx.closePath();
  1271. break;
  1272. case 'rect':
  1273. if (!rotation) {
  1274. size = Math.SQRT1_2 * radius;
  1275. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  1276. break;
  1277. }
  1278. rad += QUARTER_PI;
  1279. case 'rectRot':
  1280. xOffset = Math.cos(rad) * radius;
  1281. yOffset = Math.sin(rad) * radius;
  1282. ctx.moveTo(x - xOffset, y - yOffset);
  1283. ctx.lineTo(x + yOffset, y - xOffset);
  1284. ctx.lineTo(x + xOffset, y + yOffset);
  1285. ctx.lineTo(x - yOffset, y + xOffset);
  1286. ctx.closePath();
  1287. break;
  1288. case 'crossRot':
  1289. rad += QUARTER_PI;
  1290. case 'cross':
  1291. xOffset = Math.cos(rad) * radius;
  1292. yOffset = Math.sin(rad) * radius;
  1293. ctx.moveTo(x - xOffset, y - yOffset);
  1294. ctx.lineTo(x + xOffset, y + yOffset);
  1295. ctx.moveTo(x + yOffset, y - xOffset);
  1296. ctx.lineTo(x - yOffset, y + xOffset);
  1297. break;
  1298. case 'star':
  1299. xOffset = Math.cos(rad) * radius;
  1300. yOffset = Math.sin(rad) * radius;
  1301. ctx.moveTo(x - xOffset, y - yOffset);
  1302. ctx.lineTo(x + xOffset, y + yOffset);
  1303. ctx.moveTo(x + yOffset, y - xOffset);
  1304. ctx.lineTo(x - yOffset, y + xOffset);
  1305. rad += QUARTER_PI;
  1306. xOffset = Math.cos(rad) * radius;
  1307. yOffset = Math.sin(rad) * radius;
  1308. ctx.moveTo(x - xOffset, y - yOffset);
  1309. ctx.lineTo(x + xOffset, y + yOffset);
  1310. ctx.moveTo(x + yOffset, y - xOffset);
  1311. ctx.lineTo(x - yOffset, y + xOffset);
  1312. break;
  1313. case 'line':
  1314. xOffset = Math.cos(rad) * radius;
  1315. yOffset = Math.sin(rad) * radius;
  1316. ctx.moveTo(x - xOffset, y - yOffset);
  1317. ctx.lineTo(x + xOffset, y + yOffset);
  1318. break;
  1319. case 'dash':
  1320. ctx.moveTo(x, y);
  1321. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  1322. break;
  1323. }
  1324. ctx.fill();
  1325. if (options.borderWidth > 0) {
  1326. ctx.stroke();
  1327. }
  1328. }
  1329. function _isPointInArea(point, area, margin) {
  1330. margin = margin || 0.5;
  1331. return point && point.x > area.left - margin && point.x < area.right + margin &&
  1332. point.y > area.top - margin && point.y < area.bottom + margin;
  1333. }
  1334. function clipArea(ctx, area) {
  1335. ctx.save();
  1336. ctx.beginPath();
  1337. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  1338. ctx.clip();
  1339. }
  1340. function unclipArea(ctx) {
  1341. ctx.restore();
  1342. }
  1343. function _steppedLineTo(ctx, previous, target, flip, mode) {
  1344. if (!previous) {
  1345. return ctx.lineTo(target.x, target.y);
  1346. }
  1347. if (mode === 'middle') {
  1348. const midpoint = (previous.x + target.x) / 2.0;
  1349. ctx.lineTo(midpoint, previous.y);
  1350. ctx.lineTo(midpoint, target.y);
  1351. } else if (mode === 'after' !== !!flip) {
  1352. ctx.lineTo(previous.x, target.y);
  1353. } else {
  1354. ctx.lineTo(target.x, previous.y);
  1355. }
  1356. ctx.lineTo(target.x, target.y);
  1357. }
  1358. function _bezierCurveTo(ctx, previous, target, flip) {
  1359. if (!previous) {
  1360. return ctx.lineTo(target.x, target.y);
  1361. }
  1362. ctx.bezierCurveTo(
  1363. flip ? previous.cp1x : previous.cp2x,
  1364. flip ? previous.cp1y : previous.cp2y,
  1365. flip ? target.cp2x : target.cp1x,
  1366. flip ? target.cp2y : target.cp1y,
  1367. target.x,
  1368. target.y);
  1369. }
  1370. function renderText(ctx, text, x, y, font, opts = {}) {
  1371. const lines = isArray(text) ? text : [text];
  1372. const stroke = opts.strokeWidth > 0 && opts.strokeColor !== '';
  1373. let i, line;
  1374. ctx.save();
  1375. if (opts.translation) {
  1376. ctx.translate(opts.translation[0], opts.translation[1]);
  1377. }
  1378. if (!isNullOrUndef(opts.rotation)) {
  1379. ctx.rotate(opts.rotation);
  1380. }
  1381. ctx.font = font.string;
  1382. if (opts.color) {
  1383. ctx.fillStyle = opts.color;
  1384. }
  1385. if (opts.textAlign) {
  1386. ctx.textAlign = opts.textAlign;
  1387. }
  1388. if (opts.textBaseline) {
  1389. ctx.textBaseline = opts.textBaseline;
  1390. }
  1391. for (i = 0; i < lines.length; ++i) {
  1392. line = lines[i];
  1393. if (stroke) {
  1394. if (opts.strokeColor) {
  1395. ctx.strokeStyle = opts.strokeColor;
  1396. }
  1397. if (!isNullOrUndef(opts.strokeWidth)) {
  1398. ctx.lineWidth = opts.strokeWidth;
  1399. }
  1400. ctx.strokeText(line, x, y, opts.maxWidth);
  1401. }
  1402. ctx.fillText(line, x, y, opts.maxWidth);
  1403. if (opts.strikethrough || opts.underline) {
  1404. const metrics = ctx.measureText(line);
  1405. const left = x - metrics.actualBoundingBoxLeft;
  1406. const right = x + metrics.actualBoundingBoxRight;
  1407. const top = y - metrics.actualBoundingBoxAscent;
  1408. const bottom = y + metrics.actualBoundingBoxDescent;
  1409. const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom;
  1410. ctx.strokeStyle = ctx.fillStyle;
  1411. ctx.beginPath();
  1412. ctx.lineWidth = opts.decorationWidth || 2;
  1413. ctx.moveTo(left, yDecoration);
  1414. ctx.lineTo(right, yDecoration);
  1415. ctx.stroke();
  1416. }
  1417. y += font.lineHeight;
  1418. }
  1419. ctx.restore();
  1420. }
  1421. function addRoundedRectPath(ctx, rect) {
  1422. const {x, y, w, h, radius} = rect;
  1423. ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, -HALF_PI, PI, true);
  1424. ctx.lineTo(x, y + h - radius.bottomLeft);
  1425. ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true);
  1426. ctx.lineTo(x + w - radius.bottomRight, y + h);
  1427. ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true);
  1428. ctx.lineTo(x + w, y + radius.topRight);
  1429. ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true);
  1430. ctx.lineTo(x + radius.topLeft, y);
  1431. }
  1432. function _lookup(table, value, cmp) {
  1433. cmp = cmp || ((index) => table[index] < value);
  1434. let hi = table.length - 1;
  1435. let lo = 0;
  1436. let mid;
  1437. while (hi - lo > 1) {
  1438. mid = (lo + hi) >> 1;
  1439. if (cmp(mid)) {
  1440. lo = mid;
  1441. } else {
  1442. hi = mid;
  1443. }
  1444. }
  1445. return {lo, hi};
  1446. }
  1447. const _lookupByKey = (table, key, value) =>
  1448. _lookup(table, value, index => table[index][key] < value);
  1449. const _rlookupByKey = (table, key, value) =>
  1450. _lookup(table, value, index => table[index][key] >= value);
  1451. function _filterBetween(values, min, max) {
  1452. let start = 0;
  1453. let end = values.length;
  1454. while (start < end && values[start] < min) {
  1455. start++;
  1456. }
  1457. while (end > start && values[end - 1] > max) {
  1458. end--;
  1459. }
  1460. return start > 0 || end < values.length
  1461. ? values.slice(start, end)
  1462. : values;
  1463. }
  1464. const arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  1465. function listenArrayEvents(array, listener) {
  1466. if (array._chartjs) {
  1467. array._chartjs.listeners.push(listener);
  1468. return;
  1469. }
  1470. Object.defineProperty(array, '_chartjs', {
  1471. configurable: true,
  1472. enumerable: false,
  1473. value: {
  1474. listeners: [listener]
  1475. }
  1476. });
  1477. arrayEvents.forEach((key) => {
  1478. const method = '_onData' + _capitalize(key);
  1479. const base = array[key];
  1480. Object.defineProperty(array, key, {
  1481. configurable: true,
  1482. enumerable: false,
  1483. value(...args) {
  1484. const res = base.apply(this, args);
  1485. array._chartjs.listeners.forEach((object) => {
  1486. if (typeof object[method] === 'function') {
  1487. object[method](...args);
  1488. }
  1489. });
  1490. return res;
  1491. }
  1492. });
  1493. });
  1494. }
  1495. function unlistenArrayEvents(array, listener) {
  1496. const stub = array._chartjs;
  1497. if (!stub) {
  1498. return;
  1499. }
  1500. const listeners = stub.listeners;
  1501. const index = listeners.indexOf(listener);
  1502. if (index !== -1) {
  1503. listeners.splice(index, 1);
  1504. }
  1505. if (listeners.length > 0) {
  1506. return;
  1507. }
  1508. arrayEvents.forEach((key) => {
  1509. delete array[key];
  1510. });
  1511. delete array._chartjs;
  1512. }
  1513. function _arrayUnique(items) {
  1514. const set = new Set();
  1515. let i, ilen;
  1516. for (i = 0, ilen = items.length; i < ilen; ++i) {
  1517. set.add(items[i]);
  1518. }
  1519. if (set.size === ilen) {
  1520. return items;
  1521. }
  1522. const result = [];
  1523. set.forEach(item => {
  1524. result.push(item);
  1525. });
  1526. return result;
  1527. }
  1528. function _getParentNode(domNode) {
  1529. let parent = domNode.parentNode;
  1530. if (parent && parent.toString() === '[object ShadowRoot]') {
  1531. parent = parent.host;
  1532. }
  1533. return parent;
  1534. }
  1535. function parseMaxStyle(styleValue, node, parentProperty) {
  1536. let valueInPixels;
  1537. if (typeof styleValue === 'string') {
  1538. valueInPixels = parseInt(styleValue, 10);
  1539. if (styleValue.indexOf('%') !== -1) {
  1540. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  1541. }
  1542. } else {
  1543. valueInPixels = styleValue;
  1544. }
  1545. return valueInPixels;
  1546. }
  1547. const getComputedStyle = (element) => window.getComputedStyle(element, null);
  1548. function getStyle(el, property) {
  1549. return getComputedStyle(el).getPropertyValue(property);
  1550. }
  1551. const positions = ['top', 'right', 'bottom', 'left'];
  1552. function getPositionedStyle(styles, style, suffix) {
  1553. const result = {};
  1554. suffix = suffix ? '-' + suffix : '';
  1555. for (let i = 0; i < 4; i++) {
  1556. const pos = positions[i];
  1557. result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0;
  1558. }
  1559. result.width = result.left + result.right;
  1560. result.height = result.top + result.bottom;
  1561. return result;
  1562. }
  1563. const useOffsetPos = (x, y, target) => (x > 0 || y > 0) && (!target || !target.shadowRoot);
  1564. function getCanvasPosition(evt, canvas) {
  1565. const e = evt.native || evt;
  1566. const touches = e.touches;
  1567. const source = touches && touches.length ? touches[0] : e;
  1568. const {offsetX, offsetY} = source;
  1569. let box = false;
  1570. let x, y;
  1571. if (useOffsetPos(offsetX, offsetY, e.target)) {
  1572. x = offsetX;
  1573. y = offsetY;
  1574. } else {
  1575. const rect = canvas.getBoundingClientRect();
  1576. x = source.clientX - rect.left;
  1577. y = source.clientY - rect.top;
  1578. box = true;
  1579. }
  1580. return {x, y, box};
  1581. }
  1582. function getRelativePosition$1(evt, chart) {
  1583. const {canvas, currentDevicePixelRatio} = chart;
  1584. const style = getComputedStyle(canvas);
  1585. const borderBox = style.boxSizing === 'border-box';
  1586. const paddings = getPositionedStyle(style, 'padding');
  1587. const borders = getPositionedStyle(style, 'border', 'width');
  1588. const {x, y, box} = getCanvasPosition(evt, canvas);
  1589. const xOffset = paddings.left + (box && borders.left);
  1590. const yOffset = paddings.top + (box && borders.top);
  1591. let {width, height} = chart;
  1592. if (borderBox) {
  1593. width -= paddings.width + borders.width;
  1594. height -= paddings.height + borders.height;
  1595. }
  1596. return {
  1597. x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio),
  1598. y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio)
  1599. };
  1600. }
  1601. function getContainerSize(canvas, width, height) {
  1602. let maxWidth, maxHeight;
  1603. if (width === undefined || height === undefined) {
  1604. const container = _getParentNode(canvas);
  1605. if (!container) {
  1606. width = canvas.clientWidth;
  1607. height = canvas.clientHeight;
  1608. } else {
  1609. const rect = container.getBoundingClientRect();
  1610. const containerStyle = getComputedStyle(container);
  1611. const containerBorder = getPositionedStyle(containerStyle, 'border', 'width');
  1612. const containerPadding = getPositionedStyle(containerStyle, 'padding');
  1613. width = rect.width - containerPadding.width - containerBorder.width;
  1614. height = rect.height - containerPadding.height - containerBorder.height;
  1615. maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth');
  1616. maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight');
  1617. }
  1618. }
  1619. return {
  1620. width,
  1621. height,
  1622. maxWidth: maxWidth || INFINITY,
  1623. maxHeight: maxHeight || INFINITY
  1624. };
  1625. }
  1626. const round1 = v => Math.round(v * 10) / 10;
  1627. function getMaximumSize(canvas, bbWidth, bbHeight, aspectRatio) {
  1628. const style = getComputedStyle(canvas);
  1629. const margins = getPositionedStyle(style, 'margin');
  1630. const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY;
  1631. const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY;
  1632. const containerSize = getContainerSize(canvas, bbWidth, bbHeight);
  1633. let {width, height} = containerSize;
  1634. if (style.boxSizing === 'content-box') {
  1635. const borders = getPositionedStyle(style, 'border', 'width');
  1636. const paddings = getPositionedStyle(style, 'padding');
  1637. width -= paddings.width + borders.width;
  1638. height -= paddings.height + borders.height;
  1639. }
  1640. width = Math.max(0, width - margins.width);
  1641. height = Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height - margins.height);
  1642. width = round1(Math.min(width, maxWidth, containerSize.maxWidth));
  1643. height = round1(Math.min(height, maxHeight, containerSize.maxHeight));
  1644. if (width && !height) {
  1645. height = round1(width / 2);
  1646. }
  1647. return {
  1648. width,
  1649. height
  1650. };
  1651. }
  1652. function retinaScale(chart, forceRatio, forceStyle) {
  1653. const pixelRatio = chart.currentDevicePixelRatio = forceRatio || 1;
  1654. const {canvas, width, height} = chart;
  1655. canvas.height = height * pixelRatio;
  1656. canvas.width = width * pixelRatio;
  1657. chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
  1658. if (canvas.style && (forceStyle || (!canvas.style.height && !canvas.style.width))) {
  1659. canvas.style.height = height + 'px';
  1660. canvas.style.width = width + 'px';
  1661. }
  1662. }
  1663. const supportsEventListenerOptions = (function() {
  1664. let passiveSupported = false;
  1665. try {
  1666. const options = {
  1667. get passive() {
  1668. passiveSupported = true;
  1669. return false;
  1670. }
  1671. };
  1672. window.addEventListener('test', null, options);
  1673. window.removeEventListener('test', null, options);
  1674. } catch (e) {
  1675. }
  1676. return passiveSupported;
  1677. }());
  1678. function readUsedSize(element, property) {
  1679. const value = getStyle(element, property);
  1680. const matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  1681. return matches ? +matches[1] : undefined;
  1682. }
  1683. function getRelativePosition(e, chart) {
  1684. if ('native' in e) {
  1685. return {
  1686. x: e.x,
  1687. y: e.y
  1688. };
  1689. }
  1690. return getRelativePosition$1(e, chart);
  1691. }
  1692. function evaluateAllVisibleItems(chart, handler) {
  1693. const metasets = chart.getSortedVisibleDatasetMetas();
  1694. let index, data, element;
  1695. for (let i = 0, ilen = metasets.length; i < ilen; ++i) {
  1696. ({index, data} = metasets[i]);
  1697. for (let j = 0, jlen = data.length; j < jlen; ++j) {
  1698. element = data[j];
  1699. if (!element.skip) {
  1700. handler(element, index, j);
  1701. }
  1702. }
  1703. }
  1704. }
  1705. function binarySearch(metaset, axis, value, intersect) {
  1706. const {controller, data, _sorted} = metaset;
  1707. const iScale = controller._cachedMeta.iScale;
  1708. if (iScale && axis === iScale.axis && _sorted && data.length) {
  1709. const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey;
  1710. if (!intersect) {
  1711. return lookupMethod(data, axis, value);
  1712. } else if (controller._sharedOptions) {
  1713. const el = data[0];
  1714. const range = typeof el.getRange === 'function' && el.getRange(axis);
  1715. if (range) {
  1716. const start = lookupMethod(data, axis, value - range);
  1717. const end = lookupMethod(data, axis, value + range);
  1718. return {lo: start.lo, hi: end.hi};
  1719. }
  1720. }
  1721. }
  1722. return {lo: 0, hi: data.length - 1};
  1723. }
  1724. function optimizedEvaluateItems(chart, axis, position, handler, intersect) {
  1725. const metasets = chart.getSortedVisibleDatasetMetas();
  1726. const value = position[axis];
  1727. for (let i = 0, ilen = metasets.length; i < ilen; ++i) {
  1728. const {index, data} = metasets[i];
  1729. const {lo, hi} = binarySearch(metasets[i], axis, value, intersect);
  1730. for (let j = lo; j <= hi; ++j) {
  1731. const element = data[j];
  1732. if (!element.skip) {
  1733. handler(element, index, j);
  1734. }
  1735. }
  1736. }
  1737. }
  1738. function getDistanceMetricForAxis(axis) {
  1739. const useX = axis.indexOf('x') !== -1;
  1740. const useY = axis.indexOf('y') !== -1;
  1741. return function(pt1, pt2) {
  1742. const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  1743. const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  1744. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  1745. };
  1746. }
  1747. function getIntersectItems(chart, position, axis, useFinalPosition) {
  1748. const items = [];
  1749. if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) {
  1750. return items;
  1751. }
  1752. const evaluationFunc = function(element, datasetIndex, index) {
  1753. if (element.inRange(position.x, position.y, useFinalPosition)) {
  1754. items.push({element, datasetIndex, index});
  1755. }
  1756. };
  1757. optimizedEvaluateItems(chart, axis, position, evaluationFunc, true);
  1758. return items;
  1759. }
  1760. function getNearestItems(chart, position, axis, intersect, useFinalPosition) {
  1761. const distanceMetric = getDistanceMetricForAxis(axis);
  1762. let minDistance = Number.POSITIVE_INFINITY;
  1763. let items = [];
  1764. if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) {
  1765. return items;
  1766. }
  1767. const evaluationFunc = function(element, datasetIndex, index) {
  1768. if (intersect && !element.inRange(position.x, position.y, useFinalPosition)) {
  1769. return;
  1770. }
  1771. const center = element.getCenterPoint(useFinalPosition);
  1772. const distance = distanceMetric(position, center);
  1773. if (distance < minDistance) {
  1774. items = [{element, datasetIndex, index}];
  1775. minDistance = distance;
  1776. } else if (distance === minDistance) {
  1777. items.push({element, datasetIndex, index});
  1778. }
  1779. };
  1780. optimizedEvaluateItems(chart, axis, position, evaluationFunc);
  1781. return items;
  1782. }
  1783. function getAxisItems(chart, e, options, useFinalPosition) {
  1784. const position = getRelativePosition(e, chart);
  1785. const items = [];
  1786. const axis = options.axis;
  1787. const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange';
  1788. let intersectsItem = false;
  1789. evaluateAllVisibleItems(chart, (element, datasetIndex, index) => {
  1790. if (element[rangeMethod](position[axis], useFinalPosition)) {
  1791. items.push({element, datasetIndex, index});
  1792. }
  1793. if (element.inRange(position.x, position.y, useFinalPosition)) {
  1794. intersectsItem = true;
  1795. }
  1796. });
  1797. if (options.intersect && !intersectsItem) {
  1798. return [];
  1799. }
  1800. return items;
  1801. }
  1802. var Interaction = {
  1803. modes: {
  1804. index(chart, e, options, useFinalPosition) {
  1805. const position = getRelativePosition(e, chart);
  1806. const axis = options.axis || 'x';
  1807. const items = options.intersect
  1808. ? getIntersectItems(chart, position, axis, useFinalPosition)
  1809. : getNearestItems(chart, position, axis, false, useFinalPosition);
  1810. const elements = [];
  1811. if (!items.length) {
  1812. return [];
  1813. }
  1814. chart.getSortedVisibleDatasetMetas().forEach((meta) => {
  1815. const index = items[0].index;
  1816. const element = meta.data[index];
  1817. if (element && !element.skip) {
  1818. elements.push({element, datasetIndex: meta.index, index});
  1819. }
  1820. });
  1821. return elements;
  1822. },
  1823. dataset(chart, e, options, useFinalPosition) {
  1824. const position = getRelativePosition(e, chart);
  1825. const axis = options.axis || 'xy';
  1826. let items = options.intersect
  1827. ? getIntersectItems(chart, position, axis, useFinalPosition) :
  1828. getNearestItems(chart, position, axis, false, useFinalPosition);
  1829. if (items.length > 0) {
  1830. const datasetIndex = items[0].datasetIndex;
  1831. const data = chart.getDatasetMeta(datasetIndex).data;
  1832. items = [];
  1833. for (let i = 0; i < data.length; ++i) {
  1834. items.push({element: data[i], datasetIndex, index: i});
  1835. }
  1836. }
  1837. return items;
  1838. },
  1839. point(chart, e, options, useFinalPosition) {
  1840. const position = getRelativePosition(e, chart);
  1841. const axis = options.axis || 'xy';
  1842. return getIntersectItems(chart, position, axis, useFinalPosition);
  1843. },
  1844. nearest(chart, e, options, useFinalPosition) {
  1845. const position = getRelativePosition(e, chart);
  1846. const axis = options.axis || 'xy';
  1847. return getNearestItems(chart, position, axis, options.intersect, useFinalPosition);
  1848. },
  1849. x(chart, e, options, useFinalPosition) {
  1850. options.axis = 'x';
  1851. return getAxisItems(chart, e, options, useFinalPosition);
  1852. },
  1853. y(chart, e, options, useFinalPosition) {
  1854. options.axis = 'y';
  1855. return getAxisItems(chart, e, options, useFinalPosition);
  1856. }
  1857. }
  1858. };
  1859. const LINE_HEIGHT = new RegExp(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  1860. const FONT_STYLE = new RegExp(/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/);
  1861. function toLineHeight(value, size) {
  1862. const matches = ('' + value).match(LINE_HEIGHT);
  1863. if (!matches || matches[1] === 'normal') {
  1864. return size * 1.2;
  1865. }
  1866. value = +matches[2];
  1867. switch (matches[3]) {
  1868. case 'px':
  1869. return value;
  1870. case '%':
  1871. value /= 100;
  1872. break;
  1873. }
  1874. return size * value;
  1875. }
  1876. const numberOrZero$1 = v => +v || 0;
  1877. function _readValueToProps(value, props) {
  1878. const ret = {};
  1879. const objProps = isObject(props);
  1880. const keys = objProps ? Object.keys(props) : props;
  1881. const read = isObject(value)
  1882. ? objProps
  1883. ? prop => valueOrDefault(value[prop], value[props[prop]])
  1884. : prop => value[prop]
  1885. : () => value;
  1886. for (const prop of keys) {
  1887. ret[prop] = numberOrZero$1(read(prop));
  1888. }
  1889. return ret;
  1890. }
  1891. function toTRBL(value) {
  1892. return _readValueToProps(value, {top: 'y', right: 'x', bottom: 'y', left: 'x'});
  1893. }
  1894. function toTRBLCorners(value) {
  1895. return _readValueToProps(value, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']);
  1896. }
  1897. function toPadding(value) {
  1898. const obj = toTRBL(value);
  1899. obj.width = obj.left + obj.right;
  1900. obj.height = obj.top + obj.bottom;
  1901. return obj;
  1902. }
  1903. function toFont(options, fallback) {
  1904. options = options || {};
  1905. fallback = fallback || defaults.font;
  1906. let size = valueOrDefault(options.size, fallback.size);
  1907. if (typeof size === 'string') {
  1908. size = parseInt(size, 10);
  1909. }
  1910. let style = valueOrDefault(options.style, fallback.style);
  1911. if (style && !('' + style).match(FONT_STYLE)) {
  1912. console.warn('Invalid font style specified: "' + style + '"');
  1913. style = '';
  1914. }
  1915. const font = {
  1916. family: valueOrDefault(options.family, fallback.family),
  1917. lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size),
  1918. size,
  1919. style,
  1920. weight: valueOrDefault(options.weight, fallback.weight),
  1921. string: ''
  1922. };
  1923. font.string = toFontString(font);
  1924. return font;
  1925. }
  1926. function resolve(inputs, context, index, info) {
  1927. let cacheable = true;
  1928. let i, ilen, value;
  1929. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  1930. value = inputs[i];
  1931. if (value === undefined) {
  1932. continue;
  1933. }
  1934. if (context !== undefined && typeof value === 'function') {
  1935. value = value(context);
  1936. cacheable = false;
  1937. }
  1938. if (index !== undefined && isArray(value)) {
  1939. value = value[index % value.length];
  1940. cacheable = false;
  1941. }
  1942. if (value !== undefined) {
  1943. if (info && !cacheable) {
  1944. info.cacheable = false;
  1945. }
  1946. return value;
  1947. }
  1948. }
  1949. }
  1950. function _addGrace(minmax, grace) {
  1951. const {min, max} = minmax;
  1952. return {
  1953. min: min - Math.abs(toDimension(grace, min)),
  1954. max: max + toDimension(grace, max)
  1955. };
  1956. }
  1957. const STATIC_POSITIONS = ['left', 'top', 'right', 'bottom'];
  1958. function filterByPosition(array, position) {
  1959. return array.filter(v => v.pos === position);
  1960. }
  1961. function filterDynamicPositionByAxis(array, axis) {
  1962. return array.filter(v => STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis);
  1963. }
  1964. function sortByWeight(array, reverse) {
  1965. return array.sort((a, b) => {
  1966. const v0 = reverse ? b : a;
  1967. const v1 = reverse ? a : b;
  1968. return v0.weight === v1.weight ?
  1969. v0.index - v1.index :
  1970. v0.weight - v1.weight;
  1971. });
  1972. }
  1973. function wrapBoxes(boxes) {
  1974. const layoutBoxes = [];
  1975. let i, ilen, box;
  1976. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  1977. box = boxes[i];
  1978. layoutBoxes.push({
  1979. index: i,
  1980. box,
  1981. pos: box.position,
  1982. horizontal: box.isHorizontal(),
  1983. weight: box.weight
  1984. });
  1985. }
  1986. return layoutBoxes;
  1987. }
  1988. function setLayoutDims(layouts, params) {
  1989. let i, ilen, layout;
  1990. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  1991. layout = layouts[i];
  1992. if (layout.horizontal) {
  1993. layout.width = layout.box.fullSize && params.availableWidth;
  1994. layout.height = params.hBoxMaxHeight;
  1995. } else {
  1996. layout.width = params.vBoxMaxWidth;
  1997. layout.height = layout.box.fullSize && params.availableHeight;
  1998. }
  1999. }
  2000. }
  2001. function buildLayoutBoxes(boxes) {
  2002. const layoutBoxes = wrapBoxes(boxes);
  2003. const fullSize = sortByWeight(layoutBoxes.filter(wrap => wrap.box.fullSize), true);
  2004. const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  2005. const right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  2006. const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  2007. const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  2008. const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x');
  2009. const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y');
  2010. return {
  2011. fullSize,
  2012. leftAndTop: left.concat(top),
  2013. rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal),
  2014. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  2015. vertical: left.concat(right).concat(centerVertical),
  2016. horizontal: top.concat(bottom).concat(centerHorizontal)
  2017. };
  2018. }
  2019. function getCombinedMax(maxPadding, chartArea, a, b) {
  2020. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  2021. }
  2022. function updateMaxPadding(maxPadding, boxPadding) {
  2023. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  2024. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  2025. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  2026. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  2027. }
  2028. function updateDims(chartArea, params, layout) {
  2029. const box = layout.box;
  2030. const maxPadding = chartArea.maxPadding;
  2031. if (!isObject(layout.pos)) {
  2032. if (layout.size) {
  2033. chartArea[layout.pos] -= layout.size;
  2034. }
  2035. layout.size = layout.horizontal ? box.height : box.width;
  2036. chartArea[layout.pos] += layout.size;
  2037. }
  2038. if (box.getPadding) {
  2039. updateMaxPadding(maxPadding, box.getPadding());
  2040. }
  2041. const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right'));
  2042. const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom'));
  2043. const widthChanged = newWidth !== chartArea.w;
  2044. const heightChanged = newHeight !== chartArea.h;
  2045. chartArea.w = newWidth;
  2046. chartArea.h = newHeight;
  2047. return layout.horizontal
  2048. ? {same: widthChanged, other: heightChanged}
  2049. : {same: heightChanged, other: widthChanged};
  2050. }
  2051. function handleMaxPadding(chartArea) {
  2052. const maxPadding = chartArea.maxPadding;
  2053. function updatePos(pos) {
  2054. const change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  2055. chartArea[pos] += change;
  2056. return change;
  2057. }
  2058. chartArea.y += updatePos('top');
  2059. chartArea.x += updatePos('left');
  2060. updatePos('right');
  2061. updatePos('bottom');
  2062. }
  2063. function getMargins(horizontal, chartArea) {
  2064. const maxPadding = chartArea.maxPadding;
  2065. function marginForPositions(positions) {
  2066. const margin = {left: 0, top: 0, right: 0, bottom: 0};
  2067. positions.forEach((pos) => {
  2068. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  2069. });
  2070. return margin;
  2071. }
  2072. return horizontal
  2073. ? marginForPositions(['left', 'right'])
  2074. : marginForPositions(['top', 'bottom']);
  2075. }
  2076. function fitBoxes(boxes, chartArea, params) {
  2077. const refitBoxes = [];
  2078. let i, ilen, layout, box, refit, changed;
  2079. for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) {
  2080. layout = boxes[i];
  2081. box = layout.box;
  2082. box.update(
  2083. layout.width || chartArea.w,
  2084. layout.height || chartArea.h,
  2085. getMargins(layout.horizontal, chartArea)
  2086. );
  2087. const {same, other} = updateDims(chartArea, params, layout);
  2088. refit |= same && refitBoxes.length;
  2089. changed = changed || other;
  2090. if (!box.fullSize) {
  2091. refitBoxes.push(layout);
  2092. }
  2093. }
  2094. return refit && fitBoxes(refitBoxes, chartArea, params) || changed;
  2095. }
  2096. function placeBoxes(boxes, chartArea, params) {
  2097. const userPadding = params.padding;
  2098. let x = chartArea.x;
  2099. let y = chartArea.y;
  2100. let i, ilen, layout, box;
  2101. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  2102. layout = boxes[i];
  2103. box = layout.box;
  2104. if (layout.horizontal) {
  2105. box.left = box.fullSize ? userPadding.left : chartArea.left;
  2106. box.right = box.fullSize ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;
  2107. box.top = y;
  2108. box.bottom = y + box.height;
  2109. box.width = box.right - box.left;
  2110. y = box.bottom;
  2111. } else {
  2112. box.left = x;
  2113. box.right = x + box.width;
  2114. box.top = box.fullSize ? userPadding.top : chartArea.top;
  2115. box.bottom = box.fullSize ? params.outerHeight - userPadding.right : chartArea.top + chartArea.h;
  2116. box.height = box.bottom - box.top;
  2117. x = box.right;
  2118. }
  2119. }
  2120. chartArea.x = x;
  2121. chartArea.y = y;
  2122. }
  2123. defaults.set('layout', {
  2124. padding: {
  2125. top: 0,
  2126. right: 0,
  2127. bottom: 0,
  2128. left: 0
  2129. }
  2130. });
  2131. var layouts = {
  2132. addBox(chart, item) {
  2133. if (!chart.boxes) {
  2134. chart.boxes = [];
  2135. }
  2136. item.fullSize = item.fullSize || false;
  2137. item.position = item.position || 'top';
  2138. item.weight = item.weight || 0;
  2139. item._layers = item._layers || function() {
  2140. return [{
  2141. z: 0,
  2142. draw(chartArea) {
  2143. item.draw(chartArea);
  2144. }
  2145. }];
  2146. };
  2147. chart.boxes.push(item);
  2148. },
  2149. removeBox(chart, layoutItem) {
  2150. const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  2151. if (index !== -1) {
  2152. chart.boxes.splice(index, 1);
  2153. }
  2154. },
  2155. configure(chart, item, options) {
  2156. item.fullSize = options.fullSize;
  2157. item.position = options.position;
  2158. item.weight = options.weight;
  2159. },
  2160. update(chart, width, height, minPadding) {
  2161. if (!chart) {
  2162. return;
  2163. }
  2164. const padding = toPadding(chart.options.layout.padding);
  2165. const availableWidth = width - padding.width;
  2166. const availableHeight = height - padding.height;
  2167. const boxes = buildLayoutBoxes(chart.boxes);
  2168. const verticalBoxes = boxes.vertical;
  2169. const horizontalBoxes = boxes.horizontal;
  2170. each(chart.boxes, box => {
  2171. if (typeof box.beforeLayout === 'function') {
  2172. box.beforeLayout();
  2173. }
  2174. });
  2175. const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) =>
  2176. wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1;
  2177. const params = Object.freeze({
  2178. outerWidth: width,
  2179. outerHeight: height,
  2180. padding,
  2181. availableWidth,
  2182. availableHeight,
  2183. vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount,
  2184. hBoxMaxHeight: availableHeight / 2
  2185. });
  2186. const maxPadding = Object.assign({}, padding);
  2187. updateMaxPadding(maxPadding, toPadding(minPadding));
  2188. const chartArea = Object.assign({
  2189. maxPadding,
  2190. w: availableWidth,
  2191. h: availableHeight,
  2192. x: padding.left,
  2193. y: padding.top
  2194. }, padding);
  2195. setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  2196. fitBoxes(boxes.fullSize, chartArea, params);
  2197. fitBoxes(verticalBoxes, chartArea, params);
  2198. if (fitBoxes(horizontalBoxes, chartArea, params)) {
  2199. fitBoxes(verticalBoxes, chartArea, params);
  2200. }
  2201. handleMaxPadding(chartArea);
  2202. placeBoxes(boxes.leftAndTop, chartArea, params);
  2203. chartArea.x += chartArea.w;
  2204. chartArea.y += chartArea.h;
  2205. placeBoxes(boxes.rightAndBottom, chartArea, params);
  2206. chart.chartArea = {
  2207. left: chartArea.left,
  2208. top: chartArea.top,
  2209. right: chartArea.left + chartArea.w,
  2210. bottom: chartArea.top + chartArea.h,
  2211. height: chartArea.h,
  2212. width: chartArea.w,
  2213. };
  2214. each(boxes.chartArea, (layout) => {
  2215. const box = layout.box;
  2216. Object.assign(box, chart.chartArea);
  2217. box.update(chartArea.w, chartArea.h);
  2218. });
  2219. }
  2220. };
  2221. class BasePlatform {
  2222. acquireContext(canvas, aspectRatio) {}
  2223. releaseContext(context) {
  2224. return false;
  2225. }
  2226. addEventListener(chart, type, listener) {}
  2227. removeEventListener(chart, type, listener) {}
  2228. getDevicePixelRatio() {
  2229. return 1;
  2230. }
  2231. getMaximumSize(element, width, height, aspectRatio) {
  2232. width = Math.max(0, width || element.width);
  2233. height = height || element.height;
  2234. return {
  2235. width,
  2236. height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height)
  2237. };
  2238. }
  2239. isAttached(canvas) {
  2240. return true;
  2241. }
  2242. }
  2243. class BasicPlatform extends BasePlatform {
  2244. acquireContext(item) {
  2245. return item && item.getContext && item.getContext('2d') || null;
  2246. }
  2247. }
  2248. const EXPANDO_KEY = '$chartjs';
  2249. const EVENT_TYPES = {
  2250. touchstart: 'mousedown',
  2251. touchmove: 'mousemove',
  2252. touchend: 'mouseup',
  2253. pointerenter: 'mouseenter',
  2254. pointerdown: 'mousedown',
  2255. pointermove: 'mousemove',
  2256. pointerup: 'mouseup',
  2257. pointerleave: 'mouseout',
  2258. pointerout: 'mouseout'
  2259. };
  2260. const isNullOrEmpty = value => value === null || value === '';
  2261. function initCanvas(canvas, aspectRatio) {
  2262. const style = canvas.style;
  2263. const renderHeight = canvas.getAttribute('height');
  2264. const renderWidth = canvas.getAttribute('width');
  2265. canvas[EXPANDO_KEY] = {
  2266. initial: {
  2267. height: renderHeight,
  2268. width: renderWidth,
  2269. style: {
  2270. display: style.display,
  2271. height: style.height,
  2272. width: style.width
  2273. }
  2274. }
  2275. };
  2276. style.display = style.display || 'block';
  2277. style.boxSizing = style.boxSizing || 'border-box';
  2278. if (isNullOrEmpty(renderWidth)) {
  2279. const displayWidth = readUsedSize(canvas, 'width');
  2280. if (displayWidth !== undefined) {
  2281. canvas.width = displayWidth;
  2282. }
  2283. }
  2284. if (isNullOrEmpty(renderHeight)) {
  2285. if (canvas.style.height === '') {
  2286. canvas.height = canvas.width / (aspectRatio || 2);
  2287. } else {
  2288. const displayHeight = readUsedSize(canvas, 'height');
  2289. if (displayHeight !== undefined) {
  2290. canvas.height = displayHeight;
  2291. }
  2292. }
  2293. }
  2294. return canvas;
  2295. }
  2296. const eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  2297. function addListener(node, type, listener) {
  2298. node.addEventListener(type, listener, eventListenerOptions);
  2299. }
  2300. function removeListener(chart, type, listener) {
  2301. chart.canvas.removeEventListener(type, listener, eventListenerOptions);
  2302. }
  2303. function fromNativeEvent(event, chart) {
  2304. const type = EVENT_TYPES[event.type] || event.type;
  2305. const {x, y} = getRelativePosition$1(event, chart);
  2306. return {
  2307. type,
  2308. chart,
  2309. native: event,
  2310. x: x !== undefined ? x : null,
  2311. y: y !== undefined ? y : null,
  2312. };
  2313. }
  2314. function createAttachObserver(chart, type, listener) {
  2315. const canvas = chart.canvas;
  2316. const container = canvas && _getParentNode(canvas);
  2317. const element = container || canvas;
  2318. const observer = new MutationObserver(entries => {
  2319. const parent = _getParentNode(element);
  2320. entries.forEach(entry => {
  2321. for (let i = 0; i < entry.addedNodes.length; i++) {
  2322. const added = entry.addedNodes[i];
  2323. if (added === element || added === parent) {
  2324. listener(entry.target);
  2325. }
  2326. }
  2327. });
  2328. });
  2329. observer.observe(document, {childList: true, subtree: true});
  2330. return observer;
  2331. }
  2332. function createDetachObserver(chart, type, listener) {
  2333. const canvas = chart.canvas;
  2334. const container = canvas && _getParentNode(canvas);
  2335. if (!container) {
  2336. return;
  2337. }
  2338. const observer = new MutationObserver(entries => {
  2339. entries.forEach(entry => {
  2340. for (let i = 0; i < entry.removedNodes.length; i++) {
  2341. if (entry.removedNodes[i] === canvas) {
  2342. listener();
  2343. break;
  2344. }
  2345. }
  2346. });
  2347. });
  2348. observer.observe(container, {childList: true});
  2349. return observer;
  2350. }
  2351. const drpListeningCharts = new Map();
  2352. let oldDevicePixelRatio = 0;
  2353. function onWindowResize() {
  2354. const dpr = window.devicePixelRatio;
  2355. if (dpr === oldDevicePixelRatio) {
  2356. return;
  2357. }
  2358. oldDevicePixelRatio = dpr;
  2359. drpListeningCharts.forEach((resize, chart) => {
  2360. if (chart.currentDevicePixelRatio !== dpr) {
  2361. resize();
  2362. }
  2363. });
  2364. }
  2365. function listenDevicePixelRatioChanges(chart, resize) {
  2366. if (!drpListeningCharts.size) {
  2367. window.addEventListener('resize', onWindowResize);
  2368. }
  2369. drpListeningCharts.set(chart, resize);
  2370. }
  2371. function unlistenDevicePixelRatioChanges(chart) {
  2372. drpListeningCharts.delete(chart);
  2373. if (!drpListeningCharts.size) {
  2374. window.removeEventListener('resize', onWindowResize);
  2375. }
  2376. }
  2377. function createResizeObserver(chart, type, listener) {
  2378. const canvas = chart.canvas;
  2379. const container = canvas && _getParentNode(canvas);
  2380. if (!container) {
  2381. return;
  2382. }
  2383. const resize = throttled((width, height) => {
  2384. const w = container.clientWidth;
  2385. listener(width, height);
  2386. if (w < container.clientWidth) {
  2387. listener();
  2388. }
  2389. }, window);
  2390. const observer = new ResizeObserver(entries => {
  2391. const entry = entries[0];
  2392. const width = entry.contentRect.width;
  2393. const height = entry.contentRect.height;
  2394. if (width === 0 && height === 0) {
  2395. return;
  2396. }
  2397. resize(width, height);
  2398. });
  2399. observer.observe(container);
  2400. listenDevicePixelRatioChanges(chart, resize);
  2401. return observer;
  2402. }
  2403. function releaseObserver(chart, type, observer) {
  2404. if (observer) {
  2405. observer.disconnect();
  2406. }
  2407. if (type === 'resize') {
  2408. unlistenDevicePixelRatioChanges(chart);
  2409. }
  2410. }
  2411. function createProxyAndListen(chart, type, listener) {
  2412. const canvas = chart.canvas;
  2413. const proxy = throttled((event) => {
  2414. if (chart.ctx !== null) {
  2415. listener(fromNativeEvent(event, chart));
  2416. }
  2417. }, chart, (args) => {
  2418. const event = args[0];
  2419. return [event, event.offsetX, event.offsetY];
  2420. });
  2421. addListener(canvas, type, proxy);
  2422. return proxy;
  2423. }
  2424. class DomPlatform extends BasePlatform {
  2425. acquireContext(canvas, aspectRatio) {
  2426. const context = canvas && canvas.getContext && canvas.getContext('2d');
  2427. if (context && context.canvas === canvas) {
  2428. initCanvas(canvas, aspectRatio);
  2429. return context;
  2430. }
  2431. return null;
  2432. }
  2433. releaseContext(context) {
  2434. const canvas = context.canvas;
  2435. if (!canvas[EXPANDO_KEY]) {
  2436. return false;
  2437. }
  2438. const initial = canvas[EXPANDO_KEY].initial;
  2439. ['height', 'width'].forEach((prop) => {
  2440. const value = initial[prop];
  2441. if (isNullOrUndef(value)) {
  2442. canvas.removeAttribute(prop);
  2443. } else {
  2444. canvas.setAttribute(prop, value);
  2445. }
  2446. });
  2447. const style = initial.style || {};
  2448. Object.keys(style).forEach((key) => {
  2449. canvas.style[key] = style[key];
  2450. });
  2451. canvas.width = canvas.width;
  2452. delete canvas[EXPANDO_KEY];
  2453. return true;
  2454. }
  2455. addEventListener(chart, type, listener) {
  2456. this.removeEventListener(chart, type);
  2457. const proxies = chart.$proxies || (chart.$proxies = {});
  2458. const handlers = {
  2459. attach: createAttachObserver,
  2460. detach: createDetachObserver,
  2461. resize: createResizeObserver
  2462. };
  2463. const handler = handlers[type] || createProxyAndListen;
  2464. proxies[type] = handler(chart, type, listener);
  2465. }
  2466. removeEventListener(chart, type) {
  2467. const proxies = chart.$proxies || (chart.$proxies = {});
  2468. const proxy = proxies[type];
  2469. if (!proxy) {
  2470. return;
  2471. }
  2472. const handlers = {
  2473. attach: releaseObserver,
  2474. detach: releaseObserver,
  2475. resize: releaseObserver
  2476. };
  2477. const handler = handlers[type] || removeListener;
  2478. handler(chart, type, proxy);
  2479. proxies[type] = undefined;
  2480. }
  2481. getDevicePixelRatio() {
  2482. return window.devicePixelRatio;
  2483. }
  2484. getMaximumSize(canvas, width, height, aspectRatio) {
  2485. return getMaximumSize(canvas, width, height, aspectRatio);
  2486. }
  2487. isAttached(canvas) {
  2488. const container = _getParentNode(canvas);
  2489. return !!(container && _getParentNode(container));
  2490. }
  2491. }
  2492. var platforms = /*#__PURE__*/Object.freeze({
  2493. __proto__: null,
  2494. BasePlatform: BasePlatform,
  2495. BasicPlatform: BasicPlatform,
  2496. DomPlatform: DomPlatform
  2497. });
  2498. const atEdge = (t) => t === 0 || t === 1;
  2499. const elasticIn = (t, s, p) => -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p));
  2500. const elasticOut = (t, s, p) => Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1;
  2501. const effects = {
  2502. linear: t => t,
  2503. easeInQuad: t => t * t,
  2504. easeOutQuad: t => -t * (t - 2),
  2505. easeInOutQuad: t => ((t /= 0.5) < 1)
  2506. ? 0.5 * t * t
  2507. : -0.5 * ((--t) * (t - 2) - 1),
  2508. easeInCubic: t => t * t * t,
  2509. easeOutCubic: t => (t -= 1) * t * t + 1,
  2510. easeInOutCubic: t => ((t /= 0.5) < 1)
  2511. ? 0.5 * t * t * t
  2512. : 0.5 * ((t -= 2) * t * t + 2),
  2513. easeInQuart: t => t * t * t * t,
  2514. easeOutQuart: t => -((t -= 1) * t * t * t - 1),
  2515. easeInOutQuart: t => ((t /= 0.5) < 1)
  2516. ? 0.5 * t * t * t * t
  2517. : -0.5 * ((t -= 2) * t * t * t - 2),
  2518. easeInQuint: t => t * t * t * t * t,
  2519. easeOutQuint: t => (t -= 1) * t * t * t * t + 1,
  2520. easeInOutQuint: t => ((t /= 0.5) < 1)
  2521. ? 0.5 * t * t * t * t * t
  2522. : 0.5 * ((t -= 2) * t * t * t * t + 2),
  2523. easeInSine: t => -Math.cos(t * HALF_PI) + 1,
  2524. easeOutSine: t => Math.sin(t * HALF_PI),
  2525. easeInOutSine: t => -0.5 * (Math.cos(PI * t) - 1),
  2526. easeInExpo: t => (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)),
  2527. easeOutExpo: t => (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1,
  2528. easeInOutExpo: t => atEdge(t) ? t : t < 0.5
  2529. ? 0.5 * Math.pow(2, 10 * (t * 2 - 1))
  2530. : 0.5 * (-Math.pow(2, -10 * (t * 2 - 1)) + 2),
  2531. easeInCirc: t => (t >= 1) ? t : -(Math.sqrt(1 - t * t) - 1),
  2532. easeOutCirc: t => Math.sqrt(1 - (t -= 1) * t),
  2533. easeInOutCirc: t => ((t /= 0.5) < 1)
  2534. ? -0.5 * (Math.sqrt(1 - t * t) - 1)
  2535. : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1),
  2536. easeInElastic: t => atEdge(t) ? t : elasticIn(t, 0.075, 0.3),
  2537. easeOutElastic: t => atEdge(t) ? t : elasticOut(t, 0.075, 0.3),
  2538. easeInOutElastic(t) {
  2539. const s = 0.1125;
  2540. const p = 0.45;
  2541. return atEdge(t) ? t :
  2542. t < 0.5
  2543. ? 0.5 * elasticIn(t * 2, s, p)
  2544. : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p);
  2545. },
  2546. easeInBack(t) {
  2547. const s = 1.70158;
  2548. return t * t * ((s + 1) * t - s);
  2549. },
  2550. easeOutBack(t) {
  2551. const s = 1.70158;
  2552. return (t -= 1) * t * ((s + 1) * t + s) + 1;
  2553. },
  2554. easeInOutBack(t) {
  2555. let s = 1.70158;
  2556. if ((t /= 0.5) < 1) {
  2557. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  2558. }
  2559. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  2560. },
  2561. easeInBounce: t => 1 - effects.easeOutBounce(1 - t),
  2562. easeOutBounce(t) {
  2563. const m = 7.5625;
  2564. const d = 2.75;
  2565. if (t < (1 / d)) {
  2566. return m * t * t;
  2567. }
  2568. if (t < (2 / d)) {
  2569. return m * (t -= (1.5 / d)) * t + 0.75;
  2570. }
  2571. if (t < (2.5 / d)) {
  2572. return m * (t -= (2.25 / d)) * t + 0.9375;
  2573. }
  2574. return m * (t -= (2.625 / d)) * t + 0.984375;
  2575. },
  2576. easeInOutBounce: t => (t < 0.5)
  2577. ? effects.easeInBounce(t * 2) * 0.5
  2578. : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5,
  2579. };
  2580. const transparent = 'transparent';
  2581. const interpolators = {
  2582. boolean(from, to, factor) {
  2583. return factor > 0.5 ? to : from;
  2584. },
  2585. color(from, to, factor) {
  2586. const c0 = color(from || transparent);
  2587. const c1 = c0.valid && color(to || transparent);
  2588. return c1 && c1.valid
  2589. ? c1.mix(c0, factor).hexString()
  2590. : to;
  2591. },
  2592. number(from, to, factor) {
  2593. return from + (to - from) * factor;
  2594. }
  2595. };
  2596. class Animation {
  2597. constructor(cfg, target, prop, to) {
  2598. const currentValue = target[prop];
  2599. to = resolve([cfg.to, to, currentValue, cfg.from]);
  2600. const from = resolve([cfg.from, currentValue, to]);
  2601. this._active = true;
  2602. this._fn = cfg.fn || interpolators[cfg.type || typeof from];
  2603. this._easing = effects[cfg.easing] || effects.linear;
  2604. this._start = Math.floor(Date.now() + (cfg.delay || 0));
  2605. this._duration = this._total = Math.floor(cfg.duration);
  2606. this._loop = !!cfg.loop;
  2607. this._target = target;
  2608. this._prop = prop;
  2609. this._from = from;
  2610. this._to = to;
  2611. this._promises = undefined;
  2612. }
  2613. active() {
  2614. return this._active;
  2615. }
  2616. update(cfg, to, date) {
  2617. const me = this;
  2618. if (me._active) {
  2619. me._notify(false);
  2620. const currentValue = me._target[me._prop];
  2621. const elapsed = date - me._start;
  2622. const remain = me._duration - elapsed;
  2623. me._start = date;
  2624. me._duration = Math.floor(Math.max(remain, cfg.duration));
  2625. me._total += elapsed;
  2626. me._loop = !!cfg.loop;
  2627. me._to = resolve([cfg.to, to, currentValue, cfg.from]);
  2628. me._from = resolve([cfg.from, currentValue, to]);
  2629. }
  2630. }
  2631. cancel() {
  2632. const me = this;
  2633. if (me._active) {
  2634. me.tick(Date.now());
  2635. me._active = false;
  2636. me._notify(false);
  2637. }
  2638. }
  2639. tick(date) {
  2640. const me = this;
  2641. const elapsed = date - me._start;
  2642. const duration = me._duration;
  2643. const prop = me._prop;
  2644. const from = me._from;
  2645. const loop = me._loop;
  2646. const to = me._to;
  2647. let factor;
  2648. me._active = from !== to && (loop || (elapsed < duration));
  2649. if (!me._active) {
  2650. me._target[prop] = to;
  2651. me._notify(true);
  2652. return;
  2653. }
  2654. if (elapsed < 0) {
  2655. me._target[prop] = from;
  2656. return;
  2657. }
  2658. factor = (elapsed / duration) % 2;
  2659. factor = loop && factor > 1 ? 2 - factor : factor;
  2660. factor = me._easing(Math.min(1, Math.max(0, factor)));
  2661. me._target[prop] = me._fn(from, to, factor);
  2662. }
  2663. wait() {
  2664. const promises = this._promises || (this._promises = []);
  2665. return new Promise((res, rej) => {
  2666. promises.push({res, rej});
  2667. });
  2668. }
  2669. _notify(resolved) {
  2670. const method = resolved ? 'res' : 'rej';
  2671. const promises = this._promises || [];
  2672. for (let i = 0; i < promises.length; i++) {
  2673. promises[i][method]();
  2674. }
  2675. }
  2676. }
  2677. const numbers = ['x', 'y', 'borderWidth', 'radius', 'tension'];
  2678. const colors = ['color', 'borderColor', 'backgroundColor'];
  2679. defaults.set('animation', {
  2680. delay: undefined,
  2681. duration: 1000,
  2682. easing: 'easeOutQuart',
  2683. fn: undefined,
  2684. from: undefined,
  2685. loop: undefined,
  2686. to: undefined,
  2687. type: undefined,
  2688. });
  2689. const animationOptions = Object.keys(defaults.animation);
  2690. defaults.describe('animation', {
  2691. _fallback: false,
  2692. _indexable: false,
  2693. _scriptable: (name) => name !== 'onProgress' && name !== 'onComplete' && name !== 'fn',
  2694. });
  2695. defaults.set('animations', {
  2696. colors: {
  2697. type: 'color',
  2698. properties: colors
  2699. },
  2700. numbers: {
  2701. type: 'number',
  2702. properties: numbers
  2703. },
  2704. });
  2705. defaults.describe('animations', {
  2706. _fallback: 'animation',
  2707. });
  2708. defaults.set('transitions', {
  2709. active: {
  2710. animation: {
  2711. duration: 400
  2712. }
  2713. },
  2714. resize: {
  2715. animation: {
  2716. duration: 0
  2717. }
  2718. },
  2719. show: {
  2720. animations: {
  2721. colors: {
  2722. from: 'transparent'
  2723. },
  2724. visible: {
  2725. type: 'boolean',
  2726. duration: 0
  2727. },
  2728. }
  2729. },
  2730. hide: {
  2731. animations: {
  2732. colors: {
  2733. to: 'transparent'
  2734. },
  2735. visible: {
  2736. type: 'boolean',
  2737. easing: 'linear',
  2738. fn: v => v | 0
  2739. },
  2740. }
  2741. }
  2742. });
  2743. class Animations {
  2744. constructor(chart, config) {
  2745. this._chart = chart;
  2746. this._properties = new Map();
  2747. this.configure(config);
  2748. }
  2749. configure(config) {
  2750. if (!isObject(config)) {
  2751. return;
  2752. }
  2753. const animatedProps = this._properties;
  2754. Object.getOwnPropertyNames(config).forEach(key => {
  2755. const cfg = config[key];
  2756. if (!isObject(cfg)) {
  2757. return;
  2758. }
  2759. const resolved = {};
  2760. for (const option of animationOptions) {
  2761. resolved[option] = cfg[option];
  2762. }
  2763. (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => {
  2764. if (prop === key || !animatedProps.has(prop)) {
  2765. animatedProps.set(prop, resolved);
  2766. }
  2767. });
  2768. });
  2769. }
  2770. _animateOptions(target, values) {
  2771. const newOptions = values.options;
  2772. const options = resolveTargetOptions(target, newOptions);
  2773. if (!options) {
  2774. return [];
  2775. }
  2776. const animations = this._createAnimations(options, newOptions);
  2777. if (newOptions.$shared) {
  2778. awaitAll(target.options.$animations, newOptions).then(() => {
  2779. target.options = newOptions;
  2780. }, () => {
  2781. });
  2782. }
  2783. return animations;
  2784. }
  2785. _createAnimations(target, values) {
  2786. const animatedProps = this._properties;
  2787. const animations = [];
  2788. const running = target.$animations || (target.$animations = {});
  2789. const props = Object.keys(values);
  2790. const date = Date.now();
  2791. let i;
  2792. for (i = props.length - 1; i >= 0; --i) {
  2793. const prop = props[i];
  2794. if (prop.charAt(0) === '$') {
  2795. continue;
  2796. }
  2797. if (prop === 'options') {
  2798. animations.push(...this._animateOptions(target, values));
  2799. continue;
  2800. }
  2801. const value = values[prop];
  2802. let animation = running[prop];
  2803. const cfg = animatedProps.get(prop);
  2804. if (animation) {
  2805. if (cfg && animation.active()) {
  2806. animation.update(cfg, value, date);
  2807. continue;
  2808. } else {
  2809. animation.cancel();
  2810. }
  2811. }
  2812. if (!cfg || !cfg.duration) {
  2813. target[prop] = value;
  2814. continue;
  2815. }
  2816. running[prop] = animation = new Animation(cfg, target, prop, value);
  2817. animations.push(animation);
  2818. }
  2819. return animations;
  2820. }
  2821. update(target, values) {
  2822. if (this._properties.size === 0) {
  2823. Object.assign(target, values);
  2824. return;
  2825. }
  2826. const animations = this._createAnimations(target, values);
  2827. if (animations.length) {
  2828. animator.add(this._chart, animations);
  2829. return true;
  2830. }
  2831. }
  2832. }
  2833. function awaitAll(animations, properties) {
  2834. const running = [];
  2835. const keys = Object.keys(properties);
  2836. for (let i = 0; i < keys.length; i++) {
  2837. const anim = animations[keys[i]];
  2838. if (anim && anim.active()) {
  2839. running.push(anim.wait());
  2840. }
  2841. }
  2842. return Promise.all(running);
  2843. }
  2844. function resolveTargetOptions(target, newOptions) {
  2845. if (!newOptions) {
  2846. return;
  2847. }
  2848. let options = target.options;
  2849. if (!options) {
  2850. target.options = newOptions;
  2851. return;
  2852. }
  2853. if (options.$shared) {
  2854. target.options = options = Object.assign({}, options, {$shared: false, $animations: {}});
  2855. }
  2856. return options;
  2857. }
  2858. function scaleClip(scale, allowedOverflow) {
  2859. const opts = scale && scale.options || {};
  2860. const reverse = opts.reverse;
  2861. const min = opts.min === undefined ? allowedOverflow : 0;
  2862. const max = opts.max === undefined ? allowedOverflow : 0;
  2863. return {
  2864. start: reverse ? max : min,
  2865. end: reverse ? min : max
  2866. };
  2867. }
  2868. function defaultClip(xScale, yScale, allowedOverflow) {
  2869. if (allowedOverflow === false) {
  2870. return false;
  2871. }
  2872. const x = scaleClip(xScale, allowedOverflow);
  2873. const y = scaleClip(yScale, allowedOverflow);
  2874. return {
  2875. top: y.end,
  2876. right: x.end,
  2877. bottom: y.start,
  2878. left: x.start
  2879. };
  2880. }
  2881. function toClip(value) {
  2882. let t, r, b, l;
  2883. if (isObject(value)) {
  2884. t = value.top;
  2885. r = value.right;
  2886. b = value.bottom;
  2887. l = value.left;
  2888. } else {
  2889. t = r = b = l = value;
  2890. }
  2891. return {
  2892. top: t,
  2893. right: r,
  2894. bottom: b,
  2895. left: l
  2896. };
  2897. }
  2898. function getSortedDatasetIndices(chart, filterVisible) {
  2899. const keys = [];
  2900. const metasets = chart._getSortedDatasetMetas(filterVisible);
  2901. let i, ilen;
  2902. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  2903. keys.push(metasets[i].index);
  2904. }
  2905. return keys;
  2906. }
  2907. function applyStack(stack, value, dsIndex, options) {
  2908. const keys = stack.keys;
  2909. const singleMode = options.mode === 'single';
  2910. let i, ilen, datasetIndex, otherValue;
  2911. if (value === null) {
  2912. return;
  2913. }
  2914. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  2915. datasetIndex = +keys[i];
  2916. if (datasetIndex === dsIndex) {
  2917. if (options.all) {
  2918. continue;
  2919. }
  2920. break;
  2921. }
  2922. otherValue = stack.values[datasetIndex];
  2923. if (isNumberFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) {
  2924. value += otherValue;
  2925. }
  2926. }
  2927. return value;
  2928. }
  2929. function convertObjectDataToArray(data) {
  2930. const keys = Object.keys(data);
  2931. const adata = new Array(keys.length);
  2932. let i, ilen, key;
  2933. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  2934. key = keys[i];
  2935. adata[i] = {
  2936. x: key,
  2937. y: data[key]
  2938. };
  2939. }
  2940. return adata;
  2941. }
  2942. function isStacked(scale, meta) {
  2943. const stacked = scale && scale.options.stacked;
  2944. return stacked || (stacked === undefined && meta.stack !== undefined);
  2945. }
  2946. function getStackKey(indexScale, valueScale, meta) {
  2947. return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`;
  2948. }
  2949. function getUserBounds(scale) {
  2950. const {min, max, minDefined, maxDefined} = scale.getUserBounds();
  2951. return {
  2952. min: minDefined ? min : Number.NEGATIVE_INFINITY,
  2953. max: maxDefined ? max : Number.POSITIVE_INFINITY
  2954. };
  2955. }
  2956. function getOrCreateStack(stacks, stackKey, indexValue) {
  2957. const subStack = stacks[stackKey] || (stacks[stackKey] = {});
  2958. return subStack[indexValue] || (subStack[indexValue] = {});
  2959. }
  2960. function getLastIndexInStack(stack, vScale, positive) {
  2961. for (const meta of vScale.getMatchingVisibleMetas('bar').reverse()) {
  2962. const value = stack[meta.index];
  2963. if ((positive && value > 0) || (!positive && value < 0)) {
  2964. return meta.index;
  2965. }
  2966. }
  2967. return null;
  2968. }
  2969. function updateStacks(controller, parsed) {
  2970. const {chart, _cachedMeta: meta} = controller;
  2971. const stacks = chart._stacks || (chart._stacks = {});
  2972. const {iScale, vScale, index: datasetIndex} = meta;
  2973. const iAxis = iScale.axis;
  2974. const vAxis = vScale.axis;
  2975. const key = getStackKey(iScale, vScale, meta);
  2976. const ilen = parsed.length;
  2977. let stack;
  2978. for (let i = 0; i < ilen; ++i) {
  2979. const item = parsed[i];
  2980. const {[iAxis]: index, [vAxis]: value} = item;
  2981. const itemStacks = item._stacks || (item._stacks = {});
  2982. stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index);
  2983. stack[datasetIndex] = value;
  2984. stack._top = getLastIndexInStack(stack, vScale, true);
  2985. stack._bottom = getLastIndexInStack(stack, vScale, false);
  2986. }
  2987. }
  2988. function getFirstScaleId(chart, axis) {
  2989. const scales = chart.scales;
  2990. return Object.keys(scales).filter(key => scales[key].axis === axis).shift();
  2991. }
  2992. function createDatasetContext(parent, index) {
  2993. return Object.assign(Object.create(parent),
  2994. {
  2995. active: false,
  2996. dataset: undefined,
  2997. datasetIndex: index,
  2998. index,
  2999. mode: 'default',
  3000. type: 'dataset'
  3001. }
  3002. );
  3003. }
  3004. function createDataContext(parent, index, element) {
  3005. return Object.assign(Object.create(parent), {
  3006. active: false,
  3007. dataIndex: index,
  3008. parsed: undefined,
  3009. raw: undefined,
  3010. element,
  3011. index,
  3012. mode: 'default',
  3013. type: 'data'
  3014. });
  3015. }
  3016. function clearStacks(meta, items) {
  3017. items = items || meta._parsed;
  3018. for (const parsed of items) {
  3019. const stacks = parsed._stacks;
  3020. if (!stacks || stacks[meta.vScale.id] === undefined || stacks[meta.vScale.id][meta.index] === undefined) {
  3021. return;
  3022. }
  3023. delete stacks[meta.vScale.id][meta.index];
  3024. }
  3025. }
  3026. const isDirectUpdateMode = (mode) => mode === 'reset' || mode === 'none';
  3027. const cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached);
  3028. class DatasetController {
  3029. constructor(chart, datasetIndex) {
  3030. this.chart = chart;
  3031. this._ctx = chart.ctx;
  3032. this.index = datasetIndex;
  3033. this._cachedDataOpts = {};
  3034. this._cachedMeta = this.getMeta();
  3035. this._type = this._cachedMeta.type;
  3036. this.options = undefined;
  3037. this._parsing = false;
  3038. this._data = undefined;
  3039. this._objectData = undefined;
  3040. this._sharedOptions = undefined;
  3041. this._drawStart = undefined;
  3042. this._drawCount = undefined;
  3043. this.enableOptionSharing = false;
  3044. this.$context = undefined;
  3045. this.initialize();
  3046. }
  3047. initialize() {
  3048. const me = this;
  3049. const meta = me._cachedMeta;
  3050. me.configure();
  3051. me.linkScales();
  3052. meta._stacked = isStacked(meta.vScale, meta);
  3053. me.addElements();
  3054. }
  3055. updateIndex(datasetIndex) {
  3056. this.index = datasetIndex;
  3057. }
  3058. linkScales() {
  3059. const me = this;
  3060. const chart = me.chart;
  3061. const meta = me._cachedMeta;
  3062. const dataset = me.getDataset();
  3063. const chooseId = (axis, x, y, r) => axis === 'x' ? x : axis === 'r' ? r : y;
  3064. const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x'));
  3065. const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y'));
  3066. const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r'));
  3067. const indexAxis = meta.indexAxis;
  3068. const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid);
  3069. const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid);
  3070. meta.xScale = me.getScaleForId(xid);
  3071. meta.yScale = me.getScaleForId(yid);
  3072. meta.rScale = me.getScaleForId(rid);
  3073. meta.iScale = me.getScaleForId(iid);
  3074. meta.vScale = me.getScaleForId(vid);
  3075. }
  3076. getDataset() {
  3077. return this.chart.data.datasets[this.index];
  3078. }
  3079. getMeta() {
  3080. return this.chart.getDatasetMeta(this.index);
  3081. }
  3082. getScaleForId(scaleID) {
  3083. return this.chart.scales[scaleID];
  3084. }
  3085. _getOtherScale(scale) {
  3086. const meta = this._cachedMeta;
  3087. return scale === meta.iScale
  3088. ? meta.vScale
  3089. : meta.iScale;
  3090. }
  3091. reset() {
  3092. this._update('reset');
  3093. }
  3094. _destroy() {
  3095. const meta = this._cachedMeta;
  3096. if (this._data) {
  3097. unlistenArrayEvents(this._data, this);
  3098. }
  3099. if (meta._stacked) {
  3100. clearStacks(meta);
  3101. }
  3102. }
  3103. _dataCheck() {
  3104. const me = this;
  3105. const dataset = me.getDataset();
  3106. const data = dataset.data || (dataset.data = []);
  3107. if (isObject(data)) {
  3108. me._data = convertObjectDataToArray(data);
  3109. } else if (me._data !== data) {
  3110. if (me._data) {
  3111. unlistenArrayEvents(me._data, me);
  3112. clearStacks(me._cachedMeta);
  3113. }
  3114. if (data && Object.isExtensible(data)) {
  3115. listenArrayEvents(data, me);
  3116. }
  3117. me._data = data;
  3118. }
  3119. }
  3120. addElements() {
  3121. const me = this;
  3122. const meta = me._cachedMeta;
  3123. me._dataCheck();
  3124. if (me.datasetElementType) {
  3125. meta.dataset = new me.datasetElementType();
  3126. }
  3127. }
  3128. buildOrUpdateElements(resetNewElements) {
  3129. const me = this;
  3130. const meta = me._cachedMeta;
  3131. const dataset = me.getDataset();
  3132. let stackChanged = false;
  3133. me._dataCheck();
  3134. meta._stacked = isStacked(meta.vScale, meta);
  3135. if (meta.stack !== dataset.stack) {
  3136. stackChanged = true;
  3137. clearStacks(meta);
  3138. meta.stack = dataset.stack;
  3139. }
  3140. me._resyncElements(resetNewElements);
  3141. if (stackChanged) {
  3142. updateStacks(me, meta._parsed);
  3143. }
  3144. }
  3145. configure() {
  3146. const me = this;
  3147. const config = me.chart.config;
  3148. const scopeKeys = config.datasetScopeKeys(me._type);
  3149. const scopes = config.getOptionScopes(me.getDataset(), scopeKeys, true);
  3150. me.options = config.createResolver(scopes, me.getContext());
  3151. me._parsing = me.options.parsing;
  3152. }
  3153. parse(start, count) {
  3154. const me = this;
  3155. const {_cachedMeta: meta, _data: data} = me;
  3156. const {iScale, _stacked} = meta;
  3157. const iAxis = iScale.axis;
  3158. let sorted = start === 0 && count === data.length ? true : meta._sorted;
  3159. let prev = start > 0 && meta._parsed[start - 1];
  3160. let i, cur, parsed;
  3161. if (me._parsing === false) {
  3162. meta._parsed = data;
  3163. meta._sorted = true;
  3164. parsed = data;
  3165. } else {
  3166. if (isArray(data[start])) {
  3167. parsed = me.parseArrayData(meta, data, start, count);
  3168. } else if (isObject(data[start])) {
  3169. parsed = me.parseObjectData(meta, data, start, count);
  3170. } else {
  3171. parsed = me.parsePrimitiveData(meta, data, start, count);
  3172. }
  3173. const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]);
  3174. for (i = 0; i < count; ++i) {
  3175. meta._parsed[i + start] = cur = parsed[i];
  3176. if (sorted) {
  3177. if (isNotInOrderComparedToPrev()) {
  3178. sorted = false;
  3179. }
  3180. prev = cur;
  3181. }
  3182. }
  3183. meta._sorted = sorted;
  3184. }
  3185. if (_stacked) {
  3186. updateStacks(me, parsed);
  3187. }
  3188. }
  3189. parsePrimitiveData(meta, data, start, count) {
  3190. const {iScale, vScale} = meta;
  3191. const iAxis = iScale.axis;
  3192. const vAxis = vScale.axis;
  3193. const labels = iScale.getLabels();
  3194. const singleScale = iScale === vScale;
  3195. const parsed = new Array(count);
  3196. let i, ilen, index;
  3197. for (i = 0, ilen = count; i < ilen; ++i) {
  3198. index = i + start;
  3199. parsed[i] = {
  3200. [iAxis]: singleScale || iScale.parse(labels[index], index),
  3201. [vAxis]: vScale.parse(data[index], index)
  3202. };
  3203. }
  3204. return parsed;
  3205. }
  3206. parseArrayData(meta, data, start, count) {
  3207. const {xScale, yScale} = meta;
  3208. const parsed = new Array(count);
  3209. let i, ilen, index, item;
  3210. for (i = 0, ilen = count; i < ilen; ++i) {
  3211. index = i + start;
  3212. item = data[index];
  3213. parsed[i] = {
  3214. x: xScale.parse(item[0], index),
  3215. y: yScale.parse(item[1], index)
  3216. };
  3217. }
  3218. return parsed;
  3219. }
  3220. parseObjectData(meta, data, start, count) {
  3221. const {xScale, yScale} = meta;
  3222. const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;
  3223. const parsed = new Array(count);
  3224. let i, ilen, index, item;
  3225. for (i = 0, ilen = count; i < ilen; ++i) {
  3226. index = i + start;
  3227. item = data[index];
  3228. parsed[i] = {
  3229. x: xScale.parse(resolveObjectKey(item, xAxisKey), index),
  3230. y: yScale.parse(resolveObjectKey(item, yAxisKey), index)
  3231. };
  3232. }
  3233. return parsed;
  3234. }
  3235. getParsed(index) {
  3236. return this._cachedMeta._parsed[index];
  3237. }
  3238. getDataElement(index) {
  3239. return this._cachedMeta.data[index];
  3240. }
  3241. applyStack(scale, parsed, mode) {
  3242. const chart = this.chart;
  3243. const meta = this._cachedMeta;
  3244. const value = parsed[scale.axis];
  3245. const stack = {
  3246. keys: getSortedDatasetIndices(chart, true),
  3247. values: parsed._stacks[scale.axis]
  3248. };
  3249. return applyStack(stack, value, meta.index, {mode});
  3250. }
  3251. updateRangeFromParsed(range, scale, parsed, stack) {
  3252. const parsedValue = parsed[scale.axis];
  3253. let value = parsedValue === null ? NaN : parsedValue;
  3254. const values = stack && parsed._stacks[scale.axis];
  3255. if (stack && values) {
  3256. stack.values = values;
  3257. range.min = Math.min(range.min, value);
  3258. range.max = Math.max(range.max, value);
  3259. value = applyStack(stack, parsedValue, this._cachedMeta.index, {all: true});
  3260. }
  3261. range.min = Math.min(range.min, value);
  3262. range.max = Math.max(range.max, value);
  3263. }
  3264. getMinMax(scale, canStack) {
  3265. const me = this;
  3266. const meta = me._cachedMeta;
  3267. const _parsed = meta._parsed;
  3268. const sorted = meta._sorted && scale === meta.iScale;
  3269. const ilen = _parsed.length;
  3270. const otherScale = me._getOtherScale(scale);
  3271. const stack = canStack && meta._stacked && {keys: getSortedDatasetIndices(me.chart, true), values: null};
  3272. const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY};
  3273. const {min: otherMin, max: otherMax} = getUserBounds(otherScale);
  3274. let i, value, parsed, otherValue;
  3275. function _skip() {
  3276. parsed = _parsed[i];
  3277. value = parsed[scale.axis];
  3278. otherValue = parsed[otherScale.axis];
  3279. return !isNumberFinite(value) || otherMin > otherValue || otherMax < otherValue;
  3280. }
  3281. for (i = 0; i < ilen; ++i) {
  3282. if (_skip()) {
  3283. continue;
  3284. }
  3285. me.updateRangeFromParsed(range, scale, parsed, stack);
  3286. if (sorted) {
  3287. break;
  3288. }
  3289. }
  3290. if (sorted) {
  3291. for (i = ilen - 1; i >= 0; --i) {
  3292. if (_skip()) {
  3293. continue;
  3294. }
  3295. me.updateRangeFromParsed(range, scale, parsed, stack);
  3296. break;
  3297. }
  3298. }
  3299. return range;
  3300. }
  3301. getAllParsedValues(scale) {
  3302. const parsed = this._cachedMeta._parsed;
  3303. const values = [];
  3304. let i, ilen, value;
  3305. for (i = 0, ilen = parsed.length; i < ilen; ++i) {
  3306. value = parsed[i][scale.axis];
  3307. if (isNumberFinite(value)) {
  3308. values.push(value);
  3309. }
  3310. }
  3311. return values;
  3312. }
  3313. getMaxOverflow() {
  3314. return false;
  3315. }
  3316. getLabelAndValue(index) {
  3317. const me = this;
  3318. const meta = me._cachedMeta;
  3319. const iScale = meta.iScale;
  3320. const vScale = meta.vScale;
  3321. const parsed = me.getParsed(index);
  3322. return {
  3323. label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '',
  3324. value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : ''
  3325. };
  3326. }
  3327. _update(mode) {
  3328. const me = this;
  3329. const meta = me._cachedMeta;
  3330. me.configure();
  3331. me._cachedDataOpts = {};
  3332. me.update(mode || 'default');
  3333. meta._clip = toClip(valueOrDefault(me.options.clip, defaultClip(meta.xScale, meta.yScale, me.getMaxOverflow())));
  3334. }
  3335. update(mode) {}
  3336. draw() {
  3337. const me = this;
  3338. const ctx = me._ctx;
  3339. const chart = me.chart;
  3340. const meta = me._cachedMeta;
  3341. const elements = meta.data || [];
  3342. const area = chart.chartArea;
  3343. const active = [];
  3344. const start = me._drawStart || 0;
  3345. const count = me._drawCount || (elements.length - start);
  3346. let i;
  3347. if (meta.dataset) {
  3348. meta.dataset.draw(ctx, area, start, count);
  3349. }
  3350. for (i = start; i < start + count; ++i) {
  3351. const element = elements[i];
  3352. if (element.active) {
  3353. active.push(element);
  3354. } else {
  3355. element.draw(ctx, area);
  3356. }
  3357. }
  3358. for (i = 0; i < active.length; ++i) {
  3359. active[i].draw(ctx, area);
  3360. }
  3361. }
  3362. getStyle(index, active) {
  3363. const mode = active ? 'active' : 'default';
  3364. return index === undefined && this._cachedMeta.dataset
  3365. ? this.resolveDatasetElementOptions(mode)
  3366. : this.resolveDataElementOptions(index || 0, mode);
  3367. }
  3368. getContext(index, active, mode) {
  3369. const me = this;
  3370. const dataset = me.getDataset();
  3371. let context;
  3372. if (index >= 0 && index < me._cachedMeta.data.length) {
  3373. const element = me._cachedMeta.data[index];
  3374. context = element.$context ||
  3375. (element.$context = createDataContext(me.getContext(), index, element));
  3376. context.parsed = me.getParsed(index);
  3377. context.raw = dataset.data[index];
  3378. } else {
  3379. context = me.$context ||
  3380. (me.$context = createDatasetContext(me.chart.getContext(), me.index));
  3381. context.dataset = dataset;
  3382. }
  3383. context.active = !!active;
  3384. context.mode = mode;
  3385. return context;
  3386. }
  3387. resolveDatasetElementOptions(mode) {
  3388. return this._resolveElementOptions(this.datasetElementType.id, mode);
  3389. }
  3390. resolveDataElementOptions(index, mode) {
  3391. return this._resolveElementOptions(this.dataElementType.id, mode, index);
  3392. }
  3393. _resolveElementOptions(elementType, mode = 'default', index) {
  3394. const me = this;
  3395. const active = mode === 'active';
  3396. const cache = me._cachedDataOpts;
  3397. const cacheKey = elementType + '-' + mode;
  3398. const cached = cache[cacheKey];
  3399. const sharing = me.enableOptionSharing && defined(index);
  3400. if (cached) {
  3401. return cloneIfNotShared(cached, sharing);
  3402. }
  3403. const config = me.chart.config;
  3404. const scopeKeys = config.datasetElementScopeKeys(me._type, elementType);
  3405. const prefixes = active ? [`${elementType}Hover`, 'hover', elementType, ''] : [elementType, ''];
  3406. const scopes = config.getOptionScopes(me.getDataset(), scopeKeys);
  3407. const names = Object.keys(defaults.elements[elementType]);
  3408. const context = () => me.getContext(index, active);
  3409. const values = config.resolveNamedOptions(scopes, names, context, prefixes);
  3410. if (values.$shared) {
  3411. values.$shared = sharing;
  3412. cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing));
  3413. }
  3414. return values;
  3415. }
  3416. _resolveAnimations(index, transition, active) {
  3417. const me = this;
  3418. const chart = me.chart;
  3419. const cache = me._cachedDataOpts;
  3420. const cacheKey = `animation-${transition}`;
  3421. const cached = cache[cacheKey];
  3422. if (cached) {
  3423. return cached;
  3424. }
  3425. let options;
  3426. if (chart.options.animation !== false) {
  3427. const config = me.chart.config;
  3428. const scopeKeys = config.datasetAnimationScopeKeys(me._type, transition);
  3429. const scopes = config.getOptionScopes(me.getDataset(), scopeKeys);
  3430. options = config.createResolver(scopes, me.getContext(index, active, transition));
  3431. }
  3432. const animations = new Animations(chart, options && options.animations);
  3433. if (options && options._cacheable) {
  3434. cache[cacheKey] = Object.freeze(animations);
  3435. }
  3436. return animations;
  3437. }
  3438. getSharedOptions(options) {
  3439. if (!options.$shared) {
  3440. return;
  3441. }
  3442. return this._sharedOptions || (this._sharedOptions = Object.assign({}, options));
  3443. }
  3444. includeOptions(mode, sharedOptions) {
  3445. return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled;
  3446. }
  3447. updateElement(element, index, properties, mode) {
  3448. if (isDirectUpdateMode(mode)) {
  3449. Object.assign(element, properties);
  3450. } else {
  3451. this._resolveAnimations(index, mode).update(element, properties);
  3452. }
  3453. }
  3454. updateSharedOptions(sharedOptions, mode, newOptions) {
  3455. if (sharedOptions && !isDirectUpdateMode(mode)) {
  3456. this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions);
  3457. }
  3458. }
  3459. _setStyle(element, index, mode, active) {
  3460. element.active = active;
  3461. const options = this.getStyle(index, active);
  3462. this._resolveAnimations(index, mode, active).update(element, {
  3463. options: (!active && this.getSharedOptions(options)) || options
  3464. });
  3465. }
  3466. removeHoverStyle(element, datasetIndex, index) {
  3467. this._setStyle(element, index, 'active', false);
  3468. }
  3469. setHoverStyle(element, datasetIndex, index) {
  3470. this._setStyle(element, index, 'active', true);
  3471. }
  3472. _removeDatasetHoverStyle() {
  3473. const element = this._cachedMeta.dataset;
  3474. if (element) {
  3475. this._setStyle(element, undefined, 'active', false);
  3476. }
  3477. }
  3478. _setDatasetHoverStyle() {
  3479. const element = this._cachedMeta.dataset;
  3480. if (element) {
  3481. this._setStyle(element, undefined, 'active', true);
  3482. }
  3483. }
  3484. _resyncElements(resetNewElements) {
  3485. const me = this;
  3486. const numMeta = me._cachedMeta.data.length;
  3487. const numData = me._data.length;
  3488. if (numData > numMeta) {
  3489. me._insertElements(numMeta, numData - numMeta, resetNewElements);
  3490. } else if (numData < numMeta) {
  3491. me._removeElements(numData, numMeta - numData);
  3492. }
  3493. const count = Math.min(numData, numMeta);
  3494. if (count) {
  3495. me.parse(0, count);
  3496. }
  3497. }
  3498. _insertElements(start, count, resetNewElements = true) {
  3499. const me = this;
  3500. const meta = me._cachedMeta;
  3501. const data = meta.data;
  3502. const end = start + count;
  3503. let i;
  3504. const move = (arr) => {
  3505. arr.length += count;
  3506. for (i = arr.length - 1; i >= end; i--) {
  3507. arr[i] = arr[i - count];
  3508. }
  3509. };
  3510. move(data);
  3511. for (i = start; i < end; ++i) {
  3512. data[i] = new me.dataElementType();
  3513. }
  3514. if (me._parsing) {
  3515. move(meta._parsed);
  3516. }
  3517. me.parse(start, count);
  3518. if (resetNewElements) {
  3519. me.updateElements(data, start, count, 'reset');
  3520. }
  3521. }
  3522. updateElements(element, start, count, mode) {}
  3523. _removeElements(start, count) {
  3524. const me = this;
  3525. const meta = me._cachedMeta;
  3526. if (me._parsing) {
  3527. const removed = meta._parsed.splice(start, count);
  3528. if (meta._stacked) {
  3529. clearStacks(meta, removed);
  3530. }
  3531. }
  3532. meta.data.splice(start, count);
  3533. }
  3534. _onDataPush() {
  3535. const count = arguments.length;
  3536. this._insertElements(this.getDataset().data.length - count, count);
  3537. }
  3538. _onDataPop() {
  3539. this._removeElements(this._cachedMeta.data.length - 1, 1);
  3540. }
  3541. _onDataShift() {
  3542. this._removeElements(0, 1);
  3543. }
  3544. _onDataSplice(start, count) {
  3545. this._removeElements(start, count);
  3546. this._insertElements(start, arguments.length - 2);
  3547. }
  3548. _onDataUnshift() {
  3549. this._insertElements(0, arguments.length);
  3550. }
  3551. }
  3552. DatasetController.defaults = {};
  3553. DatasetController.prototype.datasetElementType = null;
  3554. DatasetController.prototype.dataElementType = null;
  3555. class Element {
  3556. constructor() {
  3557. this.x = undefined;
  3558. this.y = undefined;
  3559. this.active = false;
  3560. this.options = undefined;
  3561. this.$animations = undefined;
  3562. }
  3563. tooltipPosition(useFinalPosition) {
  3564. const {x, y} = this.getProps(['x', 'y'], useFinalPosition);
  3565. return {x, y};
  3566. }
  3567. hasValue() {
  3568. return isNumber(this.x) && isNumber(this.y);
  3569. }
  3570. getProps(props, final) {
  3571. const me = this;
  3572. const anims = this.$animations;
  3573. if (!final || !anims) {
  3574. return me;
  3575. }
  3576. const ret = {};
  3577. props.forEach(prop => {
  3578. ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : me[prop];
  3579. });
  3580. return ret;
  3581. }
  3582. }
  3583. Element.defaults = {};
  3584. Element.defaultRoutes = undefined;
  3585. const intlCache = new Map();
  3586. function getNumberFormat(locale, options) {
  3587. options = options || {};
  3588. const cacheKey = locale + JSON.stringify(options);
  3589. let formatter = intlCache.get(cacheKey);
  3590. if (!formatter) {
  3591. formatter = new Intl.NumberFormat(locale, options);
  3592. intlCache.set(cacheKey, formatter);
  3593. }
  3594. return formatter;
  3595. }
  3596. function formatNumber(num, locale, options) {
  3597. return getNumberFormat(locale, options).format(num);
  3598. }
  3599. const formatters = {
  3600. values(value) {
  3601. return isArray(value) ? value : '' + value;
  3602. },
  3603. numeric(tickValue, index, ticks) {
  3604. if (tickValue === 0) {
  3605. return '0';
  3606. }
  3607. const locale = this.chart.options.locale;
  3608. let notation;
  3609. let delta = tickValue;
  3610. if (ticks.length > 1) {
  3611. const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value));
  3612. if (maxTick < 1e-4 || maxTick > 1e+15) {
  3613. notation = 'scientific';
  3614. }
  3615. delta = calculateDelta(tickValue, ticks);
  3616. }
  3617. const logDelta = log10(Math.abs(delta));
  3618. const numDecimal = Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0);
  3619. const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal};
  3620. Object.assign(options, this.options.ticks.format);
  3621. return formatNumber(tickValue, locale, options);
  3622. },
  3623. logarithmic(tickValue, index, ticks) {
  3624. if (tickValue === 0) {
  3625. return '0';
  3626. }
  3627. const remain = tickValue / (Math.pow(10, Math.floor(log10(tickValue))));
  3628. if (remain === 1 || remain === 2 || remain === 5) {
  3629. return formatters.numeric.call(this, tickValue, index, ticks);
  3630. }
  3631. return '';
  3632. }
  3633. };
  3634. function calculateDelta(tickValue, ticks) {
  3635. let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value;
  3636. if (Math.abs(delta) > 1 && tickValue !== Math.floor(tickValue)) {
  3637. delta = tickValue - Math.floor(tickValue);
  3638. }
  3639. return delta;
  3640. }
  3641. var Ticks = {formatters};
  3642. defaults.set('scale', {
  3643. display: true,
  3644. offset: false,
  3645. reverse: false,
  3646. beginAtZero: false,
  3647. bounds: 'ticks',
  3648. grace: 0,
  3649. grid: {
  3650. display: true,
  3651. lineWidth: 1,
  3652. drawBorder: true,
  3653. drawOnChartArea: true,
  3654. drawTicks: true,
  3655. tickLength: 8,
  3656. tickWidth: (_ctx, options) => options.lineWidth,
  3657. tickColor: (_ctx, options) => options.color,
  3658. offset: false,
  3659. borderDash: [],
  3660. borderDashOffset: 0.0,
  3661. borderWidth: 1
  3662. },
  3663. title: {
  3664. display: false,
  3665. text: '',
  3666. padding: {
  3667. top: 4,
  3668. bottom: 4
  3669. }
  3670. },
  3671. ticks: {
  3672. minRotation: 0,
  3673. maxRotation: 50,
  3674. mirror: false,
  3675. textStrokeWidth: 0,
  3676. textStrokeColor: '',
  3677. padding: 3,
  3678. display: true,
  3679. autoSkip: true,
  3680. autoSkipPadding: 3,
  3681. labelOffset: 0,
  3682. callback: Ticks.formatters.values,
  3683. minor: {},
  3684. major: {},
  3685. align: 'center',
  3686. crossAlign: 'near',
  3687. showLabelBackdrop: false,
  3688. backdropColor: 'rgba(255, 255, 255, 0.75)',
  3689. backdropPadding: 2,
  3690. }
  3691. });
  3692. defaults.route('scale.ticks', 'color', '', 'color');
  3693. defaults.route('scale.grid', 'color', '', 'borderColor');
  3694. defaults.route('scale.grid', 'borderColor', '', 'borderColor');
  3695. defaults.route('scale.title', 'color', '', 'color');
  3696. defaults.describe('scale', {
  3697. _fallback: false,
  3698. _scriptable: (name) => !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser',
  3699. _indexable: (name) => name !== 'borderDash' && name !== 'tickBorderDash',
  3700. });
  3701. defaults.describe('scales', {
  3702. _fallback: 'scale',
  3703. });
  3704. function autoSkip(scale, ticks) {
  3705. const tickOpts = scale.options.ticks;
  3706. const ticksLimit = tickOpts.maxTicksLimit || determineMaxTicks(scale);
  3707. const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  3708. const numMajorIndices = majorIndices.length;
  3709. const first = majorIndices[0];
  3710. const last = majorIndices[numMajorIndices - 1];
  3711. const newTicks = [];
  3712. if (numMajorIndices > ticksLimit) {
  3713. skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit);
  3714. return newTicks;
  3715. }
  3716. const spacing = calculateSpacing(majorIndices, ticks, ticksLimit);
  3717. if (numMajorIndices > 0) {
  3718. let i, ilen;
  3719. const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null;
  3720. skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  3721. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  3722. skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]);
  3723. }
  3724. skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  3725. return newTicks;
  3726. }
  3727. skip(ticks, newTicks, spacing);
  3728. return newTicks;
  3729. }
  3730. function determineMaxTicks(scale) {
  3731. const offset = scale.options.offset;
  3732. const tickLength = scale._tickSize();
  3733. const maxScale = scale._length / tickLength + (offset ? 0 : 1);
  3734. const maxChart = scale._maxLength / tickLength;
  3735. return Math.floor(Math.min(maxScale, maxChart));
  3736. }
  3737. function calculateSpacing(majorIndices, ticks, ticksLimit) {
  3738. const evenMajorSpacing = getEvenSpacing(majorIndices);
  3739. const spacing = ticks.length / ticksLimit;
  3740. if (!evenMajorSpacing) {
  3741. return Math.max(spacing, 1);
  3742. }
  3743. const factors = _factorize(evenMajorSpacing);
  3744. for (let i = 0, ilen = factors.length - 1; i < ilen; i++) {
  3745. const factor = factors[i];
  3746. if (factor > spacing) {
  3747. return factor;
  3748. }
  3749. }
  3750. return Math.max(spacing, 1);
  3751. }
  3752. function getMajorIndices(ticks) {
  3753. const result = [];
  3754. let i, ilen;
  3755. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  3756. if (ticks[i].major) {
  3757. result.push(i);
  3758. }
  3759. }
  3760. return result;
  3761. }
  3762. function skipMajors(ticks, newTicks, majorIndices, spacing) {
  3763. let count = 0;
  3764. let next = majorIndices[0];
  3765. let i;
  3766. spacing = Math.ceil(spacing);
  3767. for (i = 0; i < ticks.length; i++) {
  3768. if (i === next) {
  3769. newTicks.push(ticks[i]);
  3770. count++;
  3771. next = majorIndices[count * spacing];
  3772. }
  3773. }
  3774. }
  3775. function skip(ticks, newTicks, spacing, majorStart, majorEnd) {
  3776. const start = valueOrDefault(majorStart, 0);
  3777. const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length);
  3778. let count = 0;
  3779. let length, i, next;
  3780. spacing = Math.ceil(spacing);
  3781. if (majorEnd) {
  3782. length = majorEnd - majorStart;
  3783. spacing = length / Math.floor(length / spacing);
  3784. }
  3785. next = start;
  3786. while (next < 0) {
  3787. count++;
  3788. next = Math.round(start + count * spacing);
  3789. }
  3790. for (i = Math.max(start, 0); i < end; i++) {
  3791. if (i === next) {
  3792. newTicks.push(ticks[i]);
  3793. count++;
  3794. next = Math.round(start + count * spacing);
  3795. }
  3796. }
  3797. }
  3798. function getEvenSpacing(arr) {
  3799. const len = arr.length;
  3800. let i, diff;
  3801. if (len < 2) {
  3802. return false;
  3803. }
  3804. for (diff = arr[0], i = 1; i < len; ++i) {
  3805. if (arr[i] - arr[i - 1] !== diff) {
  3806. return false;
  3807. }
  3808. }
  3809. return diff;
  3810. }
  3811. const reverseAlign = (align) => align === 'left' ? 'right' : align === 'right' ? 'left' : align;
  3812. const offsetFromEdge = (scale, edge, offset) => edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset;
  3813. function sample(arr, numItems) {
  3814. const result = [];
  3815. const increment = arr.length / numItems;
  3816. const len = arr.length;
  3817. let i = 0;
  3818. for (; i < len; i += increment) {
  3819. result.push(arr[Math.floor(i)]);
  3820. }
  3821. return result;
  3822. }
  3823. function getPixelForGridLine(scale, index, offsetGridLines) {
  3824. const length = scale.ticks.length;
  3825. const validIndex = Math.min(index, length - 1);
  3826. const start = scale._startPixel;
  3827. const end = scale._endPixel;
  3828. const epsilon = 1e-6;
  3829. let lineValue = scale.getPixelForTick(validIndex);
  3830. let offset;
  3831. if (offsetGridLines) {
  3832. if (length === 1) {
  3833. offset = Math.max(lineValue - start, end - lineValue);
  3834. } else if (index === 0) {
  3835. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  3836. } else {
  3837. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  3838. }
  3839. lineValue += validIndex < index ? offset : -offset;
  3840. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  3841. return;
  3842. }
  3843. }
  3844. return lineValue;
  3845. }
  3846. function garbageCollect(caches, length) {
  3847. each(caches, (cache) => {
  3848. const gc = cache.gc;
  3849. const gcLen = gc.length / 2;
  3850. let i;
  3851. if (gcLen > length) {
  3852. for (i = 0; i < gcLen; ++i) {
  3853. delete cache.data[gc[i]];
  3854. }
  3855. gc.splice(0, gcLen);
  3856. }
  3857. });
  3858. }
  3859. function getTickMarkLength(options) {
  3860. return options.drawTicks ? options.tickLength : 0;
  3861. }
  3862. function getTitleHeight(options, fallback) {
  3863. if (!options.display) {
  3864. return 0;
  3865. }
  3866. const font = toFont(options.font, fallback);
  3867. const padding = toPadding(options.padding);
  3868. const lines = isArray(options.text) ? options.text.length : 1;
  3869. return (lines * font.lineHeight) + padding.height;
  3870. }
  3871. function createScaleContext(parent, scale) {
  3872. return Object.assign(Object.create(parent), {
  3873. scale,
  3874. type: 'scale'
  3875. });
  3876. }
  3877. function createTickContext(parent, index, tick) {
  3878. return Object.assign(Object.create(parent), {
  3879. tick,
  3880. index,
  3881. type: 'tick'
  3882. });
  3883. }
  3884. function titleAlign(align, position, reverse) {
  3885. let ret = _toLeftRightCenter(align);
  3886. if ((reverse && position !== 'right') || (!reverse && position === 'right')) {
  3887. ret = reverseAlign(ret);
  3888. }
  3889. return ret;
  3890. }
  3891. function titleArgs(scale, offset, position, align) {
  3892. const {top, left, bottom, right} = scale;
  3893. let rotation = 0;
  3894. let maxWidth, titleX, titleY;
  3895. if (scale.isHorizontal()) {
  3896. titleX = _alignStartEnd(align, left, right);
  3897. titleY = offsetFromEdge(scale, position, offset);
  3898. maxWidth = right - left;
  3899. } else {
  3900. titleX = offsetFromEdge(scale, position, offset);
  3901. titleY = _alignStartEnd(align, bottom, top);
  3902. rotation = position === 'left' ? -HALF_PI : HALF_PI;
  3903. }
  3904. return {titleX, titleY, maxWidth, rotation};
  3905. }
  3906. class Scale extends Element {
  3907. constructor(cfg) {
  3908. super();
  3909. this.id = cfg.id;
  3910. this.type = cfg.type;
  3911. this.options = undefined;
  3912. this.ctx = cfg.ctx;
  3913. this.chart = cfg.chart;
  3914. this.top = undefined;
  3915. this.bottom = undefined;
  3916. this.left = undefined;
  3917. this.right = undefined;
  3918. this.width = undefined;
  3919. this.height = undefined;
  3920. this._margins = {
  3921. left: 0,
  3922. right: 0,
  3923. top: 0,
  3924. bottom: 0
  3925. };
  3926. this.maxWidth = undefined;
  3927. this.maxHeight = undefined;
  3928. this.paddingTop = undefined;
  3929. this.paddingBottom = undefined;
  3930. this.paddingLeft = undefined;
  3931. this.paddingRight = undefined;
  3932. this.axis = undefined;
  3933. this.labelRotation = undefined;
  3934. this.min = undefined;
  3935. this.max = undefined;
  3936. this._range = undefined;
  3937. this.ticks = [];
  3938. this._gridLineItems = null;
  3939. this._labelItems = null;
  3940. this._labelSizes = null;
  3941. this._length = 0;
  3942. this._maxLength = 0;
  3943. this._longestTextCache = {};
  3944. this._startPixel = undefined;
  3945. this._endPixel = undefined;
  3946. this._reversePixels = false;
  3947. this._userMax = undefined;
  3948. this._userMin = undefined;
  3949. this._suggestedMax = undefined;
  3950. this._suggestedMin = undefined;
  3951. this._ticksLength = 0;
  3952. this._borderValue = 0;
  3953. this._cache = {};
  3954. this._dataLimitsCached = false;
  3955. this.$context = undefined;
  3956. }
  3957. init(options) {
  3958. const me = this;
  3959. me.options = options.setContext(me.getContext());
  3960. me.axis = options.axis;
  3961. me._userMin = me.parse(options.min);
  3962. me._userMax = me.parse(options.max);
  3963. me._suggestedMin = me.parse(options.suggestedMin);
  3964. me._suggestedMax = me.parse(options.suggestedMax);
  3965. }
  3966. parse(raw, index) {
  3967. return raw;
  3968. }
  3969. getUserBounds() {
  3970. let {_userMin, _userMax, _suggestedMin, _suggestedMax} = this;
  3971. _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY);
  3972. _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY);
  3973. _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY);
  3974. _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY);
  3975. return {
  3976. min: finiteOrDefault(_userMin, _suggestedMin),
  3977. max: finiteOrDefault(_userMax, _suggestedMax),
  3978. minDefined: isNumberFinite(_userMin),
  3979. maxDefined: isNumberFinite(_userMax)
  3980. };
  3981. }
  3982. getMinMax(canStack) {
  3983. const me = this;
  3984. let {min, max, minDefined, maxDefined} = me.getUserBounds();
  3985. let range;
  3986. if (minDefined && maxDefined) {
  3987. return {min, max};
  3988. }
  3989. const metas = me.getMatchingVisibleMetas();
  3990. for (let i = 0, ilen = metas.length; i < ilen; ++i) {
  3991. range = metas[i].controller.getMinMax(me, canStack);
  3992. if (!minDefined) {
  3993. min = Math.min(min, range.min);
  3994. }
  3995. if (!maxDefined) {
  3996. max = Math.max(max, range.max);
  3997. }
  3998. }
  3999. return {
  4000. min: finiteOrDefault(min, finiteOrDefault(max, min)),
  4001. max: finiteOrDefault(max, finiteOrDefault(min, max))
  4002. };
  4003. }
  4004. getPadding() {
  4005. const me = this;
  4006. return {
  4007. left: me.paddingLeft || 0,
  4008. top: me.paddingTop || 0,
  4009. right: me.paddingRight || 0,
  4010. bottom: me.paddingBottom || 0
  4011. };
  4012. }
  4013. getTicks() {
  4014. return this.ticks;
  4015. }
  4016. getLabels() {
  4017. const data = this.chart.data;
  4018. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  4019. }
  4020. beforeLayout() {
  4021. this._cache = {};
  4022. this._dataLimitsCached = false;
  4023. }
  4024. beforeUpdate() {
  4025. callback(this.options.beforeUpdate, [this]);
  4026. }
  4027. update(maxWidth, maxHeight, margins) {
  4028. const me = this;
  4029. const tickOpts = me.options.ticks;
  4030. const sampleSize = tickOpts.sampleSize;
  4031. me.beforeUpdate();
  4032. me.maxWidth = maxWidth;
  4033. me.maxHeight = maxHeight;
  4034. me._margins = margins = Object.assign({
  4035. left: 0,
  4036. right: 0,
  4037. top: 0,
  4038. bottom: 0
  4039. }, margins);
  4040. me.ticks = null;
  4041. me._labelSizes = null;
  4042. me._gridLineItems = null;
  4043. me._labelItems = null;
  4044. me.beforeSetDimensions();
  4045. me.setDimensions();
  4046. me.afterSetDimensions();
  4047. me._maxLength = me.isHorizontal()
  4048. ? me.width + margins.left + margins.right
  4049. : me.height + margins.top + margins.bottom;
  4050. if (!me._dataLimitsCached) {
  4051. me.beforeDataLimits();
  4052. me.determineDataLimits();
  4053. me.afterDataLimits();
  4054. me._range = _addGrace(me, me.options.grace);
  4055. me._dataLimitsCached = true;
  4056. }
  4057. me.beforeBuildTicks();
  4058. me.ticks = me.buildTicks() || [];
  4059. me.afterBuildTicks();
  4060. const samplingEnabled = sampleSize < me.ticks.length;
  4061. me._convertTicksToLabels(samplingEnabled ? sample(me.ticks, sampleSize) : me.ticks);
  4062. me.configure();
  4063. me.beforeCalculateLabelRotation();
  4064. me.calculateLabelRotation();
  4065. me.afterCalculateLabelRotation();
  4066. if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) {
  4067. me.ticks = autoSkip(me, me.ticks);
  4068. me._labelSizes = null;
  4069. }
  4070. if (samplingEnabled) {
  4071. me._convertTicksToLabels(me.ticks);
  4072. }
  4073. me.beforeFit();
  4074. me.fit();
  4075. me.afterFit();
  4076. me.afterUpdate();
  4077. }
  4078. configure() {
  4079. const me = this;
  4080. let reversePixels = me.options.reverse;
  4081. let startPixel, endPixel;
  4082. if (me.isHorizontal()) {
  4083. startPixel = me.left;
  4084. endPixel = me.right;
  4085. } else {
  4086. startPixel = me.top;
  4087. endPixel = me.bottom;
  4088. reversePixels = !reversePixels;
  4089. }
  4090. me._startPixel = startPixel;
  4091. me._endPixel = endPixel;
  4092. me._reversePixels = reversePixels;
  4093. me._length = endPixel - startPixel;
  4094. me._alignToPixels = me.options.alignToPixels;
  4095. }
  4096. afterUpdate() {
  4097. callback(this.options.afterUpdate, [this]);
  4098. }
  4099. beforeSetDimensions() {
  4100. callback(this.options.beforeSetDimensions, [this]);
  4101. }
  4102. setDimensions() {
  4103. const me = this;
  4104. if (me.isHorizontal()) {
  4105. me.width = me.maxWidth;
  4106. me.left = 0;
  4107. me.right = me.width;
  4108. } else {
  4109. me.height = me.maxHeight;
  4110. me.top = 0;
  4111. me.bottom = me.height;
  4112. }
  4113. me.paddingLeft = 0;
  4114. me.paddingTop = 0;
  4115. me.paddingRight = 0;
  4116. me.paddingBottom = 0;
  4117. }
  4118. afterSetDimensions() {
  4119. callback(this.options.afterSetDimensions, [this]);
  4120. }
  4121. _callHooks(name) {
  4122. const me = this;
  4123. me.chart.notifyPlugins(name, me.getContext());
  4124. callback(me.options[name], [me]);
  4125. }
  4126. beforeDataLimits() {
  4127. this._callHooks('beforeDataLimits');
  4128. }
  4129. determineDataLimits() {}
  4130. afterDataLimits() {
  4131. this._callHooks('afterDataLimits');
  4132. }
  4133. beforeBuildTicks() {
  4134. this._callHooks('beforeBuildTicks');
  4135. }
  4136. buildTicks() {
  4137. return [];
  4138. }
  4139. afterBuildTicks() {
  4140. this._callHooks('afterBuildTicks');
  4141. }
  4142. beforeTickToLabelConversion() {
  4143. callback(this.options.beforeTickToLabelConversion, [this]);
  4144. }
  4145. generateTickLabels(ticks) {
  4146. const me = this;
  4147. const tickOpts = me.options.ticks;
  4148. let i, ilen, tick;
  4149. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  4150. tick = ticks[i];
  4151. tick.label = callback(tickOpts.callback, [tick.value, i, ticks], me);
  4152. }
  4153. for (i = 0; i < ilen; i++) {
  4154. if (isNullOrUndef(ticks[i].label)) {
  4155. ticks.splice(i, 1);
  4156. ilen--;
  4157. i--;
  4158. }
  4159. }
  4160. }
  4161. afterTickToLabelConversion() {
  4162. callback(this.options.afterTickToLabelConversion, [this]);
  4163. }
  4164. beforeCalculateLabelRotation() {
  4165. callback(this.options.beforeCalculateLabelRotation, [this]);
  4166. }
  4167. calculateLabelRotation() {
  4168. const me = this;
  4169. const options = me.options;
  4170. const tickOpts = options.ticks;
  4171. const numTicks = me.ticks.length;
  4172. const minRotation = tickOpts.minRotation || 0;
  4173. const maxRotation = tickOpts.maxRotation;
  4174. let labelRotation = minRotation;
  4175. let tickWidth, maxHeight, maxLabelDiagonal;
  4176. if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
  4177. me.labelRotation = minRotation;
  4178. return;
  4179. }
  4180. const labelSizes = me._getLabelSizes();
  4181. const maxLabelWidth = labelSizes.widest.width;
  4182. const maxLabelHeight = labelSizes.highest.height;
  4183. const maxWidth = _limitValue(me.chart.width - maxLabelWidth, 0, me.maxWidth);
  4184. tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
  4185. if (maxLabelWidth + 6 > tickWidth) {
  4186. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  4187. maxHeight = me.maxHeight - getTickMarkLength(options.grid)
  4188. - tickOpts.padding - getTitleHeight(options.title, me.chart.options.font);
  4189. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  4190. labelRotation = toDegrees(Math.min(
  4191. Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
  4192. Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
  4193. ));
  4194. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  4195. }
  4196. me.labelRotation = labelRotation;
  4197. }
  4198. afterCalculateLabelRotation() {
  4199. callback(this.options.afterCalculateLabelRotation, [this]);
  4200. }
  4201. beforeFit() {
  4202. callback(this.options.beforeFit, [this]);
  4203. }
  4204. fit() {
  4205. const me = this;
  4206. const minSize = {
  4207. width: 0,
  4208. height: 0
  4209. };
  4210. const {chart, options: {ticks: tickOpts, title: titleOpts, grid: gridOpts}} = me;
  4211. const display = me._isVisible();
  4212. const isHorizontal = me.isHorizontal();
  4213. if (display) {
  4214. const titleHeight = getTitleHeight(titleOpts, chart.options.font);
  4215. if (isHorizontal) {
  4216. minSize.width = me.maxWidth;
  4217. minSize.height = getTickMarkLength(gridOpts) + titleHeight;
  4218. } else {
  4219. minSize.height = me.maxHeight;
  4220. minSize.width = getTickMarkLength(gridOpts) + titleHeight;
  4221. }
  4222. if (tickOpts.display && me.ticks.length) {
  4223. const {first, last, widest, highest} = me._getLabelSizes();
  4224. const tickPadding = tickOpts.padding * 2;
  4225. const angleRadians = toRadians(me.labelRotation);
  4226. const cos = Math.cos(angleRadians);
  4227. const sin = Math.sin(angleRadians);
  4228. if (isHorizontal) {
  4229. const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height;
  4230. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  4231. } else {
  4232. const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height;
  4233. minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth + tickPadding);
  4234. }
  4235. me._calculatePadding(first, last, sin, cos);
  4236. }
  4237. }
  4238. me._handleMargins();
  4239. if (isHorizontal) {
  4240. me.width = me._length = chart.width - me._margins.left - me._margins.right;
  4241. me.height = minSize.height;
  4242. } else {
  4243. me.width = minSize.width;
  4244. me.height = me._length = chart.height - me._margins.top - me._margins.bottom;
  4245. }
  4246. }
  4247. _calculatePadding(first, last, sin, cos) {
  4248. const me = this;
  4249. const {ticks: {align, padding}, position} = me.options;
  4250. const isRotated = me.labelRotation !== 0;
  4251. const labelsBelowTicks = position !== 'top' && me.axis === 'x';
  4252. if (me.isHorizontal()) {
  4253. const offsetLeft = me.getPixelForTick(0) - me.left;
  4254. const offsetRight = me.right - me.getPixelForTick(me.ticks.length - 1);
  4255. let paddingLeft = 0;
  4256. let paddingRight = 0;
  4257. if (isRotated) {
  4258. if (labelsBelowTicks) {
  4259. paddingLeft = cos * first.width;
  4260. paddingRight = sin * last.height;
  4261. } else {
  4262. paddingLeft = sin * first.height;
  4263. paddingRight = cos * last.width;
  4264. }
  4265. } else if (align === 'start') {
  4266. paddingRight = last.width;
  4267. } else if (align === 'end') {
  4268. paddingLeft = first.width;
  4269. } else {
  4270. paddingLeft = first.width / 2;
  4271. paddingRight = last.width / 2;
  4272. }
  4273. me.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * me.width / (me.width - offsetLeft), 0);
  4274. me.paddingRight = Math.max((paddingRight - offsetRight + padding) * me.width / (me.width - offsetRight), 0);
  4275. } else {
  4276. let paddingTop = last.height / 2;
  4277. let paddingBottom = first.height / 2;
  4278. if (align === 'start') {
  4279. paddingTop = 0;
  4280. paddingBottom = first.height;
  4281. } else if (align === 'end') {
  4282. paddingTop = last.height;
  4283. paddingBottom = 0;
  4284. }
  4285. me.paddingTop = paddingTop + padding;
  4286. me.paddingBottom = paddingBottom + padding;
  4287. }
  4288. }
  4289. _handleMargins() {
  4290. const me = this;
  4291. if (me._margins) {
  4292. me._margins.left = Math.max(me.paddingLeft, me._margins.left);
  4293. me._margins.top = Math.max(me.paddingTop, me._margins.top);
  4294. me._margins.right = Math.max(me.paddingRight, me._margins.right);
  4295. me._margins.bottom = Math.max(me.paddingBottom, me._margins.bottom);
  4296. }
  4297. }
  4298. afterFit() {
  4299. callback(this.options.afterFit, [this]);
  4300. }
  4301. isHorizontal() {
  4302. const {axis, position} = this.options;
  4303. return position === 'top' || position === 'bottom' || axis === 'x';
  4304. }
  4305. isFullSize() {
  4306. return this.options.fullSize;
  4307. }
  4308. _convertTicksToLabels(ticks) {
  4309. const me = this;
  4310. me.beforeTickToLabelConversion();
  4311. me.generateTickLabels(ticks);
  4312. me.afterTickToLabelConversion();
  4313. }
  4314. _getLabelSizes() {
  4315. const me = this;
  4316. let labelSizes = me._labelSizes;
  4317. if (!labelSizes) {
  4318. const sampleSize = me.options.ticks.sampleSize;
  4319. let ticks = me.ticks;
  4320. if (sampleSize < ticks.length) {
  4321. ticks = sample(ticks, sampleSize);
  4322. }
  4323. me._labelSizes = labelSizes = me._computeLabelSizes(ticks, ticks.length);
  4324. }
  4325. return labelSizes;
  4326. }
  4327. _computeLabelSizes(ticks, length) {
  4328. const {ctx, _longestTextCache: caches} = this;
  4329. const widths = [];
  4330. const heights = [];
  4331. let widestLabelSize = 0;
  4332. let highestLabelSize = 0;
  4333. let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel;
  4334. for (i = 0; i < length; ++i) {
  4335. label = ticks[i].label;
  4336. tickFont = this._resolveTickFontOptions(i);
  4337. ctx.font = fontString = tickFont.string;
  4338. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  4339. lineHeight = tickFont.lineHeight;
  4340. width = height = 0;
  4341. if (!isNullOrUndef(label) && !isArray(label)) {
  4342. width = _measureText(ctx, cache.data, cache.gc, width, label);
  4343. height = lineHeight;
  4344. } else if (isArray(label)) {
  4345. for (j = 0, jlen = label.length; j < jlen; ++j) {
  4346. nestedLabel = label[j];
  4347. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  4348. width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  4349. height += lineHeight;
  4350. }
  4351. }
  4352. }
  4353. widths.push(width);
  4354. heights.push(height);
  4355. widestLabelSize = Math.max(width, widestLabelSize);
  4356. highestLabelSize = Math.max(height, highestLabelSize);
  4357. }
  4358. garbageCollect(caches, length);
  4359. const widest = widths.indexOf(widestLabelSize);
  4360. const highest = heights.indexOf(highestLabelSize);
  4361. const valueAt = (idx) => ({width: widths[idx] || 0, height: heights[idx] || 0});
  4362. return {
  4363. first: valueAt(0),
  4364. last: valueAt(length - 1),
  4365. widest: valueAt(widest),
  4366. highest: valueAt(highest),
  4367. widths,
  4368. heights,
  4369. };
  4370. }
  4371. getLabelForValue(value) {
  4372. return value;
  4373. }
  4374. getPixelForValue(value, index) {
  4375. return NaN;
  4376. }
  4377. getValueForPixel(pixel) {}
  4378. getPixelForTick(index) {
  4379. const ticks = this.ticks;
  4380. if (index < 0 || index > ticks.length - 1) {
  4381. return null;
  4382. }
  4383. return this.getPixelForValue(ticks[index].value);
  4384. }
  4385. getPixelForDecimal(decimal) {
  4386. const me = this;
  4387. if (me._reversePixels) {
  4388. decimal = 1 - decimal;
  4389. }
  4390. const pixel = me._startPixel + decimal * me._length;
  4391. return _int16Range(me._alignToPixels ? _alignPixel(me.chart, pixel, 0) : pixel);
  4392. }
  4393. getDecimalForPixel(pixel) {
  4394. const decimal = (pixel - this._startPixel) / this._length;
  4395. return this._reversePixels ? 1 - decimal : decimal;
  4396. }
  4397. getBasePixel() {
  4398. return this.getPixelForValue(this.getBaseValue());
  4399. }
  4400. getBaseValue() {
  4401. const {min, max} = this;
  4402. return min < 0 && max < 0 ? max :
  4403. min > 0 && max > 0 ? min :
  4404. 0;
  4405. }
  4406. getContext(index) {
  4407. const me = this;
  4408. const ticks = me.ticks || [];
  4409. if (index >= 0 && index < ticks.length) {
  4410. const tick = ticks[index];
  4411. return tick.$context ||
  4412. (tick.$context = createTickContext(me.getContext(), index, tick));
  4413. }
  4414. return me.$context ||
  4415. (me.$context = createScaleContext(me.chart.getContext(), me));
  4416. }
  4417. _tickSize() {
  4418. const me = this;
  4419. const optionTicks = me.options.ticks;
  4420. const rot = toRadians(me.labelRotation);
  4421. const cos = Math.abs(Math.cos(rot));
  4422. const sin = Math.abs(Math.sin(rot));
  4423. const labelSizes = me._getLabelSizes();
  4424. const padding = optionTicks.autoSkipPadding || 0;
  4425. const w = labelSizes ? labelSizes.widest.width + padding : 0;
  4426. const h = labelSizes ? labelSizes.highest.height + padding : 0;
  4427. return me.isHorizontal()
  4428. ? h * cos > w * sin ? w / cos : h / sin
  4429. : h * sin < w * cos ? h / cos : w / sin;
  4430. }
  4431. _isVisible() {
  4432. const display = this.options.display;
  4433. if (display !== 'auto') {
  4434. return !!display;
  4435. }
  4436. return this.getMatchingVisibleMetas().length > 0;
  4437. }
  4438. _computeGridLineItems(chartArea) {
  4439. const me = this;
  4440. const axis = me.axis;
  4441. const chart = me.chart;
  4442. const options = me.options;
  4443. const {grid, position} = options;
  4444. const offset = grid.offset;
  4445. const isHorizontal = me.isHorizontal();
  4446. const ticks = me.ticks;
  4447. const ticksLength = ticks.length + (offset ? 1 : 0);
  4448. const tl = getTickMarkLength(grid);
  4449. const items = [];
  4450. const borderOpts = grid.setContext(me.getContext());
  4451. const axisWidth = borderOpts.drawBorder ? borderOpts.borderWidth : 0;
  4452. const axisHalfWidth = axisWidth / 2;
  4453. const alignBorderValue = function(pixel) {
  4454. return _alignPixel(chart, pixel, axisWidth);
  4455. };
  4456. let borderValue, i, lineValue, alignedLineValue;
  4457. let tx1, ty1, tx2, ty2, x1, y1, x2, y2;
  4458. if (position === 'top') {
  4459. borderValue = alignBorderValue(me.bottom);
  4460. ty1 = me.bottom - tl;
  4461. ty2 = borderValue - axisHalfWidth;
  4462. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  4463. y2 = chartArea.bottom;
  4464. } else if (position === 'bottom') {
  4465. borderValue = alignBorderValue(me.top);
  4466. y1 = chartArea.top;
  4467. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  4468. ty1 = borderValue + axisHalfWidth;
  4469. ty2 = me.top + tl;
  4470. } else if (position === 'left') {
  4471. borderValue = alignBorderValue(me.right);
  4472. tx1 = me.right - tl;
  4473. tx2 = borderValue - axisHalfWidth;
  4474. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  4475. x2 = chartArea.right;
  4476. } else if (position === 'right') {
  4477. borderValue = alignBorderValue(me.left);
  4478. x1 = chartArea.left;
  4479. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  4480. tx1 = borderValue + axisHalfWidth;
  4481. tx2 = me.left + tl;
  4482. } else if (axis === 'x') {
  4483. if (position === 'center') {
  4484. borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5);
  4485. } else if (isObject(position)) {
  4486. const positionAxisID = Object.keys(position)[0];
  4487. const value = position[positionAxisID];
  4488. borderValue = alignBorderValue(me.chart.scales[positionAxisID].getPixelForValue(value));
  4489. }
  4490. y1 = chartArea.top;
  4491. y2 = chartArea.bottom;
  4492. ty1 = borderValue + axisHalfWidth;
  4493. ty2 = ty1 + tl;
  4494. } else if (axis === 'y') {
  4495. if (position === 'center') {
  4496. borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2);
  4497. } else if (isObject(position)) {
  4498. const positionAxisID = Object.keys(position)[0];
  4499. const value = position[positionAxisID];
  4500. borderValue = alignBorderValue(me.chart.scales[positionAxisID].getPixelForValue(value));
  4501. }
  4502. tx1 = borderValue - axisHalfWidth;
  4503. tx2 = tx1 - tl;
  4504. x1 = chartArea.left;
  4505. x2 = chartArea.right;
  4506. }
  4507. for (i = 0; i < ticksLength; ++i) {
  4508. const optsAtIndex = grid.setContext(me.getContext(i));
  4509. const lineWidth = optsAtIndex.lineWidth;
  4510. const lineColor = optsAtIndex.color;
  4511. const borderDash = grid.borderDash || [];
  4512. const borderDashOffset = optsAtIndex.borderDashOffset;
  4513. const tickWidth = optsAtIndex.tickWidth;
  4514. const tickColor = optsAtIndex.tickColor;
  4515. const tickBorderDash = optsAtIndex.tickBorderDash || [];
  4516. const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset;
  4517. lineValue = getPixelForGridLine(me, i, offset);
  4518. if (lineValue === undefined) {
  4519. continue;
  4520. }
  4521. alignedLineValue = _alignPixel(chart, lineValue, lineWidth);
  4522. if (isHorizontal) {
  4523. tx1 = tx2 = x1 = x2 = alignedLineValue;
  4524. } else {
  4525. ty1 = ty2 = y1 = y2 = alignedLineValue;
  4526. }
  4527. items.push({
  4528. tx1,
  4529. ty1,
  4530. tx2,
  4531. ty2,
  4532. x1,
  4533. y1,
  4534. x2,
  4535. y2,
  4536. width: lineWidth,
  4537. color: lineColor,
  4538. borderDash,
  4539. borderDashOffset,
  4540. tickWidth,
  4541. tickColor,
  4542. tickBorderDash,
  4543. tickBorderDashOffset,
  4544. });
  4545. }
  4546. me._ticksLength = ticksLength;
  4547. me._borderValue = borderValue;
  4548. return items;
  4549. }
  4550. _computeLabelItems(chartArea) {
  4551. const me = this;
  4552. const axis = me.axis;
  4553. const options = me.options;
  4554. const {position, ticks: optionTicks} = options;
  4555. const isHorizontal = me.isHorizontal();
  4556. const ticks = me.ticks;
  4557. const {align, crossAlign, padding, mirror} = optionTicks;
  4558. const tl = getTickMarkLength(options.grid);
  4559. const tickAndPadding = tl + padding;
  4560. const hTickAndPadding = mirror ? -padding : tickAndPadding;
  4561. const rotation = -toRadians(me.labelRotation);
  4562. const items = [];
  4563. let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  4564. let textBaseline = 'middle';
  4565. if (position === 'top') {
  4566. y = me.bottom - hTickAndPadding;
  4567. textAlign = me._getXAxisLabelAlignment();
  4568. } else if (position === 'bottom') {
  4569. y = me.top + hTickAndPadding;
  4570. textAlign = me._getXAxisLabelAlignment();
  4571. } else if (position === 'left') {
  4572. const ret = me._getYAxisLabelAlignment(tl);
  4573. textAlign = ret.textAlign;
  4574. x = ret.x;
  4575. } else if (position === 'right') {
  4576. const ret = me._getYAxisLabelAlignment(tl);
  4577. textAlign = ret.textAlign;
  4578. x = ret.x;
  4579. } else if (axis === 'x') {
  4580. if (position === 'center') {
  4581. y = ((chartArea.top + chartArea.bottom) / 2) + tickAndPadding;
  4582. } else if (isObject(position)) {
  4583. const positionAxisID = Object.keys(position)[0];
  4584. const value = position[positionAxisID];
  4585. y = me.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding;
  4586. }
  4587. textAlign = me._getXAxisLabelAlignment();
  4588. } else if (axis === 'y') {
  4589. if (position === 'center') {
  4590. x = ((chartArea.left + chartArea.right) / 2) - tickAndPadding;
  4591. } else if (isObject(position)) {
  4592. const positionAxisID = Object.keys(position)[0];
  4593. const value = position[positionAxisID];
  4594. x = me.chart.scales[positionAxisID].getPixelForValue(value);
  4595. }
  4596. textAlign = me._getYAxisLabelAlignment(tl).textAlign;
  4597. }
  4598. if (axis === 'y') {
  4599. if (align === 'start') {
  4600. textBaseline = 'top';
  4601. } else if (align === 'end') {
  4602. textBaseline = 'bottom';
  4603. }
  4604. }
  4605. const labelSizes = me._getLabelSizes();
  4606. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  4607. tick = ticks[i];
  4608. label = tick.label;
  4609. const optsAtIndex = optionTicks.setContext(me.getContext(i));
  4610. pixel = me.getPixelForTick(i) + optionTicks.labelOffset;
  4611. font = me._resolveTickFontOptions(i);
  4612. lineHeight = font.lineHeight;
  4613. lineCount = isArray(label) ? label.length : 1;
  4614. const halfCount = lineCount / 2;
  4615. const color = optsAtIndex.color;
  4616. const strokeColor = optsAtIndex.textStrokeColor;
  4617. const strokeWidth = optsAtIndex.textStrokeWidth;
  4618. if (isHorizontal) {
  4619. x = pixel;
  4620. if (position === 'top') {
  4621. if (crossAlign === 'near' || rotation !== 0) {
  4622. textOffset = -lineCount * lineHeight + lineHeight / 2;
  4623. } else if (crossAlign === 'center') {
  4624. textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight;
  4625. } else {
  4626. textOffset = -labelSizes.highest.height + lineHeight / 2;
  4627. }
  4628. } else {
  4629. if (crossAlign === 'near' || rotation !== 0) {
  4630. textOffset = lineHeight / 2;
  4631. } else if (crossAlign === 'center') {
  4632. textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight;
  4633. } else {
  4634. textOffset = labelSizes.highest.height - lineCount * lineHeight;
  4635. }
  4636. }
  4637. if (mirror) {
  4638. textOffset *= -1;
  4639. }
  4640. } else {
  4641. y = pixel;
  4642. textOffset = (1 - lineCount) * lineHeight / 2;
  4643. }
  4644. let backdrop;
  4645. if (optsAtIndex.showLabelBackdrop) {
  4646. const labelPadding = toPadding(optsAtIndex.backdropPadding);
  4647. const height = labelSizes.heights[i];
  4648. const width = labelSizes.widths[i];
  4649. let top = y + textOffset - labelPadding.top;
  4650. let left = x - labelPadding.left;
  4651. switch (textBaseline) {
  4652. case 'middle':
  4653. top -= height / 2;
  4654. break;
  4655. case 'bottom':
  4656. top -= height;
  4657. break;
  4658. }
  4659. switch (textAlign) {
  4660. case 'center':
  4661. left -= width / 2;
  4662. break;
  4663. case 'right':
  4664. left -= width;
  4665. break;
  4666. }
  4667. backdrop = {
  4668. left,
  4669. top,
  4670. width: width + labelPadding.width,
  4671. height: height + labelPadding.height,
  4672. color: optsAtIndex.backdropColor,
  4673. };
  4674. }
  4675. items.push({
  4676. rotation,
  4677. label,
  4678. font,
  4679. color,
  4680. strokeColor,
  4681. strokeWidth,
  4682. textOffset,
  4683. textAlign,
  4684. textBaseline,
  4685. translation: [x, y],
  4686. backdrop,
  4687. });
  4688. }
  4689. return items;
  4690. }
  4691. _getXAxisLabelAlignment() {
  4692. const me = this;
  4693. const {position, ticks} = me.options;
  4694. const rotation = -toRadians(me.labelRotation);
  4695. if (rotation) {
  4696. return position === 'top' ? 'left' : 'right';
  4697. }
  4698. let align = 'center';
  4699. if (ticks.align === 'start') {
  4700. align = 'left';
  4701. } else if (ticks.align === 'end') {
  4702. align = 'right';
  4703. }
  4704. return align;
  4705. }
  4706. _getYAxisLabelAlignment(tl) {
  4707. const me = this;
  4708. const {position, ticks: {crossAlign, mirror, padding}} = me.options;
  4709. const labelSizes = me._getLabelSizes();
  4710. const tickAndPadding = tl + padding;
  4711. const widest = labelSizes.widest.width;
  4712. let textAlign;
  4713. let x;
  4714. if (position === 'left') {
  4715. if (mirror) {
  4716. textAlign = 'left';
  4717. x = me.right + padding;
  4718. } else {
  4719. x = me.right - tickAndPadding;
  4720. if (crossAlign === 'near') {
  4721. textAlign = 'right';
  4722. } else if (crossAlign === 'center') {
  4723. textAlign = 'center';
  4724. x -= (widest / 2);
  4725. } else {
  4726. textAlign = 'left';
  4727. x = me.left;
  4728. }
  4729. }
  4730. } else if (position === 'right') {
  4731. if (mirror) {
  4732. textAlign = 'right';
  4733. x = me.left + padding;
  4734. } else {
  4735. x = me.left + tickAndPadding;
  4736. if (crossAlign === 'near') {
  4737. textAlign = 'left';
  4738. } else if (crossAlign === 'center') {
  4739. textAlign = 'center';
  4740. x += widest / 2;
  4741. } else {
  4742. textAlign = 'right';
  4743. x = me.right;
  4744. }
  4745. }
  4746. } else {
  4747. textAlign = 'right';
  4748. }
  4749. return {textAlign, x};
  4750. }
  4751. _computeLabelArea() {
  4752. const me = this;
  4753. if (me.options.ticks.mirror) {
  4754. return;
  4755. }
  4756. const chart = me.chart;
  4757. const position = me.options.position;
  4758. if (position === 'left' || position === 'right') {
  4759. return {top: 0, left: me.left, bottom: chart.height, right: me.right};
  4760. } if (position === 'top' || position === 'bottom') {
  4761. return {top: me.top, left: 0, bottom: me.bottom, right: chart.width};
  4762. }
  4763. }
  4764. drawBackground() {
  4765. const {ctx, options: {backgroundColor}, left, top, width, height} = this;
  4766. if (backgroundColor) {
  4767. ctx.save();
  4768. ctx.fillStyle = backgroundColor;
  4769. ctx.fillRect(left, top, width, height);
  4770. ctx.restore();
  4771. }
  4772. }
  4773. getLineWidthForValue(value) {
  4774. const me = this;
  4775. const grid = me.options.grid;
  4776. if (!me._isVisible() || !grid.display) {
  4777. return 0;
  4778. }
  4779. const ticks = me.ticks;
  4780. const index = ticks.findIndex(t => t.value === value);
  4781. if (index >= 0) {
  4782. const opts = grid.setContext(me.getContext(index));
  4783. return opts.lineWidth;
  4784. }
  4785. return 0;
  4786. }
  4787. drawGrid(chartArea) {
  4788. const me = this;
  4789. const grid = me.options.grid;
  4790. const ctx = me.ctx;
  4791. const items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
  4792. let i, ilen;
  4793. const drawLine = (p1, p2, style) => {
  4794. if (!style.width || !style.color) {
  4795. return;
  4796. }
  4797. ctx.save();
  4798. ctx.lineWidth = style.width;
  4799. ctx.strokeStyle = style.color;
  4800. ctx.setLineDash(style.borderDash || []);
  4801. ctx.lineDashOffset = style.borderDashOffset;
  4802. ctx.beginPath();
  4803. ctx.moveTo(p1.x, p1.y);
  4804. ctx.lineTo(p2.x, p2.y);
  4805. ctx.stroke();
  4806. ctx.restore();
  4807. };
  4808. if (grid.display) {
  4809. for (i = 0, ilen = items.length; i < ilen; ++i) {
  4810. const item = items[i];
  4811. if (grid.drawOnChartArea) {
  4812. drawLine(
  4813. {x: item.x1, y: item.y1},
  4814. {x: item.x2, y: item.y2},
  4815. item
  4816. );
  4817. }
  4818. if (grid.drawTicks) {
  4819. drawLine(
  4820. {x: item.tx1, y: item.ty1},
  4821. {x: item.tx2, y: item.ty2},
  4822. {
  4823. color: item.tickColor,
  4824. width: item.tickWidth,
  4825. borderDash: item.tickBorderDash,
  4826. borderDashOffset: item.tickBorderDashOffset
  4827. }
  4828. );
  4829. }
  4830. }
  4831. }
  4832. }
  4833. drawBorder() {
  4834. const me = this;
  4835. const {chart, ctx, options: {grid}} = me;
  4836. const borderOpts = grid.setContext(me.getContext());
  4837. const axisWidth = grid.drawBorder ? borderOpts.borderWidth : 0;
  4838. if (!axisWidth) {
  4839. return;
  4840. }
  4841. const lastLineWidth = grid.setContext(me.getContext(0)).lineWidth;
  4842. const borderValue = me._borderValue;
  4843. let x1, x2, y1, y2;
  4844. if (me.isHorizontal()) {
  4845. x1 = _alignPixel(chart, me.left, axisWidth) - axisWidth / 2;
  4846. x2 = _alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  4847. y1 = y2 = borderValue;
  4848. } else {
  4849. y1 = _alignPixel(chart, me.top, axisWidth) - axisWidth / 2;
  4850. y2 = _alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  4851. x1 = x2 = borderValue;
  4852. }
  4853. ctx.save();
  4854. ctx.lineWidth = borderOpts.borderWidth;
  4855. ctx.strokeStyle = borderOpts.borderColor;
  4856. ctx.beginPath();
  4857. ctx.moveTo(x1, y1);
  4858. ctx.lineTo(x2, y2);
  4859. ctx.stroke();
  4860. ctx.restore();
  4861. }
  4862. drawLabels(chartArea) {
  4863. const me = this;
  4864. const optionTicks = me.options.ticks;
  4865. if (!optionTicks.display) {
  4866. return;
  4867. }
  4868. const ctx = me.ctx;
  4869. const area = me._computeLabelArea();
  4870. if (area) {
  4871. clipArea(ctx, area);
  4872. }
  4873. const items = me._labelItems || (me._labelItems = me._computeLabelItems(chartArea));
  4874. let i, ilen;
  4875. for (i = 0, ilen = items.length; i < ilen; ++i) {
  4876. const item = items[i];
  4877. const tickFont = item.font;
  4878. const label = item.label;
  4879. if (item.backdrop) {
  4880. ctx.fillStyle = item.backdrop.color;
  4881. ctx.fillRect(item.backdrop.left, item.backdrop.top, item.backdrop.width, item.backdrop.height);
  4882. }
  4883. let y = item.textOffset;
  4884. renderText(ctx, label, 0, y, tickFont, item);
  4885. }
  4886. if (area) {
  4887. unclipArea(ctx);
  4888. }
  4889. }
  4890. drawTitle() {
  4891. const {ctx, options: {position, title, reverse}} = this;
  4892. if (!title.display) {
  4893. return;
  4894. }
  4895. const font = toFont(title.font);
  4896. const padding = toPadding(title.padding);
  4897. const align = title.align;
  4898. let offset = font.lineHeight / 2;
  4899. if (position === 'bottom') {
  4900. offset += padding.bottom;
  4901. if (isArray(title.text)) {
  4902. offset += font.lineHeight * (title.text.length - 1);
  4903. }
  4904. } else {
  4905. offset += padding.top;
  4906. }
  4907. const {titleX, titleY, maxWidth, rotation} = titleArgs(this, offset, position, align);
  4908. renderText(ctx, title.text, 0, 0, font, {
  4909. color: title.color,
  4910. maxWidth,
  4911. rotation,
  4912. textAlign: titleAlign(align, position, reverse),
  4913. textBaseline: 'middle',
  4914. translation: [titleX, titleY],
  4915. });
  4916. }
  4917. draw(chartArea) {
  4918. const me = this;
  4919. if (!me._isVisible()) {
  4920. return;
  4921. }
  4922. me.drawBackground();
  4923. me.drawGrid(chartArea);
  4924. me.drawBorder();
  4925. me.drawTitle();
  4926. me.drawLabels(chartArea);
  4927. }
  4928. _layers() {
  4929. const me = this;
  4930. const opts = me.options;
  4931. const tz = opts.ticks && opts.ticks.z || 0;
  4932. const gz = opts.grid && opts.grid.z || 0;
  4933. if (!me._isVisible() || me.draw !== Scale.prototype.draw) {
  4934. return [{
  4935. z: tz,
  4936. draw(chartArea) {
  4937. me.draw(chartArea);
  4938. }
  4939. }];
  4940. }
  4941. return [{
  4942. z: gz,
  4943. draw(chartArea) {
  4944. me.drawBackground();
  4945. me.drawGrid(chartArea);
  4946. me.drawTitle();
  4947. }
  4948. }, {
  4949. z: gz + 1,
  4950. draw() {
  4951. me.drawBorder();
  4952. }
  4953. }, {
  4954. z: tz,
  4955. draw(chartArea) {
  4956. me.drawLabels(chartArea);
  4957. }
  4958. }];
  4959. }
  4960. getMatchingVisibleMetas(type) {
  4961. const me = this;
  4962. const metas = me.chart.getSortedVisibleDatasetMetas();
  4963. const axisID = me.axis + 'AxisID';
  4964. const result = [];
  4965. let i, ilen;
  4966. for (i = 0, ilen = metas.length; i < ilen; ++i) {
  4967. const meta = metas[i];
  4968. if (meta[axisID] === me.id && (!type || meta.type === type)) {
  4969. result.push(meta);
  4970. }
  4971. }
  4972. return result;
  4973. }
  4974. _resolveTickFontOptions(index) {
  4975. const opts = this.options.ticks.setContext(this.getContext(index));
  4976. return toFont(opts.font);
  4977. }
  4978. _maxDigits() {
  4979. const me = this;
  4980. const fontSize = me._resolveTickFontOptions(0).lineHeight;
  4981. return me.isHorizontal() ? me.width / fontSize / 0.7 : me.height / fontSize;
  4982. }
  4983. }
  4984. function _createResolver(scopes, prefixes = [''], rootScopes = scopes, fallback, getTarget = () => scopes[0]) {
  4985. if (!defined(fallback)) {
  4986. fallback = _resolve('_fallback', scopes);
  4987. }
  4988. const cache = {
  4989. [Symbol.toStringTag]: 'Object',
  4990. _cacheable: true,
  4991. _scopes: scopes,
  4992. _rootScopes: rootScopes,
  4993. _fallback: fallback,
  4994. _getTarget: getTarget,
  4995. override: (scope) => _createResolver([scope, ...scopes], prefixes, rootScopes, fallback),
  4996. };
  4997. return new Proxy(cache, {
  4998. deleteProperty(target, prop) {
  4999. delete target[prop];
  5000. delete target._keys;
  5001. delete scopes[0][prop];
  5002. return true;
  5003. },
  5004. get(target, prop) {
  5005. return _cached(target, prop,
  5006. () => _resolveWithPrefixes(prop, prefixes, scopes, target));
  5007. },
  5008. getOwnPropertyDescriptor(target, prop) {
  5009. return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop);
  5010. },
  5011. getPrototypeOf() {
  5012. return Reflect.getPrototypeOf(scopes[0]);
  5013. },
  5014. has(target, prop) {
  5015. return getKeysFromAllScopes(target).includes(prop);
  5016. },
  5017. ownKeys(target) {
  5018. return getKeysFromAllScopes(target);
  5019. },
  5020. set(target, prop, value) {
  5021. const storage = target._storage || (target._storage = getTarget());
  5022. storage[prop] = value;
  5023. delete target[prop];
  5024. delete target._keys;
  5025. return true;
  5026. }
  5027. });
  5028. }
  5029. function _attachContext(proxy, context, subProxy, descriptorDefaults) {
  5030. const cache = {
  5031. _cacheable: false,
  5032. _proxy: proxy,
  5033. _context: context,
  5034. _subProxy: subProxy,
  5035. _stack: new Set(),
  5036. _descriptors: _descriptors(proxy, descriptorDefaults),
  5037. setContext: (ctx) => _attachContext(proxy, ctx, subProxy, descriptorDefaults),
  5038. override: (scope) => _attachContext(proxy.override(scope), context, subProxy, descriptorDefaults)
  5039. };
  5040. return new Proxy(cache, {
  5041. deleteProperty(target, prop) {
  5042. delete target[prop];
  5043. delete proxy[prop];
  5044. return true;
  5045. },
  5046. get(target, prop, receiver) {
  5047. return _cached(target, prop,
  5048. () => _resolveWithContext(target, prop, receiver));
  5049. },
  5050. getOwnPropertyDescriptor(target, prop) {
  5051. return target._descriptors.allKeys
  5052. ? Reflect.has(proxy, prop) ? {enumerable: true, configurable: true} : undefined
  5053. : Reflect.getOwnPropertyDescriptor(proxy, prop);
  5054. },
  5055. getPrototypeOf() {
  5056. return Reflect.getPrototypeOf(proxy);
  5057. },
  5058. has(target, prop) {
  5059. return Reflect.has(proxy, prop);
  5060. },
  5061. ownKeys() {
  5062. return Reflect.ownKeys(proxy);
  5063. },
  5064. set(target, prop, value) {
  5065. proxy[prop] = value;
  5066. delete target[prop];
  5067. return true;
  5068. }
  5069. });
  5070. }
  5071. function _descriptors(proxy, defaults = {scriptable: true, indexable: true}) {
  5072. const {_scriptable = defaults.scriptable, _indexable = defaults.indexable, _allKeys = defaults.allKeys} = proxy;
  5073. return {
  5074. allKeys: _allKeys,
  5075. scriptable: _scriptable,
  5076. indexable: _indexable,
  5077. isScriptable: isFunction(_scriptable) ? _scriptable : () => _scriptable,
  5078. isIndexable: isFunction(_indexable) ? _indexable : () => _indexable
  5079. };
  5080. }
  5081. const readKey = (prefix, name) => prefix ? prefix + _capitalize(name) : name;
  5082. const needsSubResolver = (prop, value) => isObject(value) && prop !== 'adapters';
  5083. function _cached(target, prop, resolve) {
  5084. let value = target[prop];
  5085. if (defined(value)) {
  5086. return value;
  5087. }
  5088. value = resolve();
  5089. if (defined(value)) {
  5090. target[prop] = value;
  5091. }
  5092. return value;
  5093. }
  5094. function _resolveWithContext(target, prop, receiver) {
  5095. const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;
  5096. let value = _proxy[prop];
  5097. if (isFunction(value) && descriptors.isScriptable(prop)) {
  5098. value = _resolveScriptable(prop, value, target, receiver);
  5099. }
  5100. if (isArray(value) && value.length) {
  5101. value = _resolveArray(prop, value, target, descriptors.isIndexable);
  5102. }
  5103. if (needsSubResolver(prop, value)) {
  5104. value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors);
  5105. }
  5106. return value;
  5107. }
  5108. function _resolveScriptable(prop, value, target, receiver) {
  5109. const {_proxy, _context, _subProxy, _stack} = target;
  5110. if (_stack.has(prop)) {
  5111. throw new Error('Recursion detected: ' + [..._stack].join('->') + '->' + prop);
  5112. }
  5113. _stack.add(prop);
  5114. value = value(_context, _subProxy || receiver);
  5115. _stack.delete(prop);
  5116. if (isObject(value)) {
  5117. value = createSubResolver(_proxy._scopes, _proxy, prop, value);
  5118. }
  5119. return value;
  5120. }
  5121. function _resolveArray(prop, value, target, isIndexable) {
  5122. const {_proxy, _context, _subProxy, _descriptors: descriptors} = target;
  5123. if (defined(_context.index) && isIndexable(prop)) {
  5124. value = value[_context.index % value.length];
  5125. } else if (isObject(value[0])) {
  5126. const arr = value;
  5127. const scopes = _proxy._scopes.filter(s => s !== arr);
  5128. value = [];
  5129. for (const item of arr) {
  5130. const resolver = createSubResolver(scopes, _proxy, prop, item);
  5131. value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors));
  5132. }
  5133. }
  5134. return value;
  5135. }
  5136. function resolveFallback(fallback, prop, value) {
  5137. return isFunction(fallback) ? fallback(prop, value) : fallback;
  5138. }
  5139. const getScope = (key, parent) => key === true ? parent
  5140. : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined;
  5141. function addScopes(set, parentScopes, key, parentFallback) {
  5142. for (const parent of parentScopes) {
  5143. const scope = getScope(key, parent);
  5144. if (scope) {
  5145. set.add(scope);
  5146. const fallback = resolveFallback(scope._fallback, key, scope);
  5147. if (defined(fallback) && fallback !== key && fallback !== parentFallback) {
  5148. return fallback;
  5149. }
  5150. } else if (scope === false && defined(parentFallback) && key !== parentFallback) {
  5151. return null;
  5152. }
  5153. }
  5154. return false;
  5155. }
  5156. function createSubResolver(parentScopes, resolver, prop, value) {
  5157. const rootScopes = resolver._rootScopes;
  5158. const fallback = resolveFallback(resolver._fallback, prop, value);
  5159. const allScopes = [...parentScopes, ...rootScopes];
  5160. const set = new Set();
  5161. set.add(value);
  5162. let key = addScopesFromKey(set, allScopes, prop, fallback || prop);
  5163. if (key === null) {
  5164. return false;
  5165. }
  5166. if (defined(fallback) && fallback !== prop) {
  5167. key = addScopesFromKey(set, allScopes, fallback, key);
  5168. if (key === null) {
  5169. return false;
  5170. }
  5171. }
  5172. return _createResolver([...set], [''], rootScopes, fallback, () => {
  5173. const parent = resolver._getTarget();
  5174. if (!(prop in parent)) {
  5175. parent[prop] = {};
  5176. }
  5177. return parent[prop];
  5178. });
  5179. }
  5180. function addScopesFromKey(set, allScopes, key, fallback) {
  5181. while (key) {
  5182. key = addScopes(set, allScopes, key, fallback);
  5183. }
  5184. return key;
  5185. }
  5186. function _resolveWithPrefixes(prop, prefixes, scopes, proxy) {
  5187. let value;
  5188. for (const prefix of prefixes) {
  5189. value = _resolve(readKey(prefix, prop), scopes);
  5190. if (defined(value)) {
  5191. return needsSubResolver(prop, value)
  5192. ? createSubResolver(scopes, proxy, prop, value)
  5193. : value;
  5194. }
  5195. }
  5196. }
  5197. function _resolve(key, scopes) {
  5198. for (const scope of scopes) {
  5199. if (!scope) {
  5200. continue;
  5201. }
  5202. const value = scope[key];
  5203. if (defined(value)) {
  5204. return value;
  5205. }
  5206. }
  5207. }
  5208. function getKeysFromAllScopes(target) {
  5209. let keys = target._keys;
  5210. if (!keys) {
  5211. keys = target._keys = resolveKeysFromAllScopes(target._scopes);
  5212. }
  5213. return keys;
  5214. }
  5215. function resolveKeysFromAllScopes(scopes) {
  5216. const set = new Set();
  5217. for (const scope of scopes) {
  5218. for (const key of Object.keys(scope).filter(k => !k.startsWith('_'))) {
  5219. set.add(key);
  5220. }
  5221. }
  5222. return [...set];
  5223. }
  5224. const EPSILON = Number.EPSILON || 1e-14;
  5225. const getPoint = (points, i) => i < points.length && !points[i].skip && points[i];
  5226. function splineCurve(firstPoint, middlePoint, afterPoint, t) {
  5227. const previous = firstPoint.skip ? middlePoint : firstPoint;
  5228. const current = middlePoint;
  5229. const next = afterPoint.skip ? middlePoint : afterPoint;
  5230. const d01 = distanceBetweenPoints(current, previous);
  5231. const d12 = distanceBetweenPoints(next, current);
  5232. let s01 = d01 / (d01 + d12);
  5233. let s12 = d12 / (d01 + d12);
  5234. s01 = isNaN(s01) ? 0 : s01;
  5235. s12 = isNaN(s12) ? 0 : s12;
  5236. const fa = t * s01;
  5237. const fb = t * s12;
  5238. return {
  5239. previous: {
  5240. x: current.x - fa * (next.x - previous.x),
  5241. y: current.y - fa * (next.y - previous.y)
  5242. },
  5243. next: {
  5244. x: current.x + fb * (next.x - previous.x),
  5245. y: current.y + fb * (next.y - previous.y)
  5246. }
  5247. };
  5248. }
  5249. function monotoneAdjust(points, deltaK, mK) {
  5250. const pointsLen = points.length;
  5251. let alphaK, betaK, tauK, squaredMagnitude, pointCurrent;
  5252. let pointAfter = getPoint(points, 0);
  5253. for (let i = 0; i < pointsLen - 1; ++i) {
  5254. pointCurrent = pointAfter;
  5255. pointAfter = getPoint(points, i + 1);
  5256. if (!pointCurrent || !pointAfter) {
  5257. continue;
  5258. }
  5259. if (almostEquals(deltaK[i], 0, EPSILON)) {
  5260. mK[i] = mK[i + 1] = 0;
  5261. continue;
  5262. }
  5263. alphaK = mK[i] / deltaK[i];
  5264. betaK = mK[i + 1] / deltaK[i];
  5265. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  5266. if (squaredMagnitude <= 9) {
  5267. continue;
  5268. }
  5269. tauK = 3 / Math.sqrt(squaredMagnitude);
  5270. mK[i] = alphaK * tauK * deltaK[i];
  5271. mK[i + 1] = betaK * tauK * deltaK[i];
  5272. }
  5273. }
  5274. function monotoneCompute(points, mK) {
  5275. const pointsLen = points.length;
  5276. let deltaX, pointBefore, pointCurrent;
  5277. let pointAfter = getPoint(points, 0);
  5278. for (let i = 0; i < pointsLen; ++i) {
  5279. pointBefore = pointCurrent;
  5280. pointCurrent = pointAfter;
  5281. pointAfter = getPoint(points, i + 1);
  5282. if (!pointCurrent) {
  5283. continue;
  5284. }
  5285. const {x, y} = pointCurrent;
  5286. if (pointBefore) {
  5287. deltaX = (x - pointBefore.x) / 3;
  5288. pointCurrent.cp1x = x - deltaX;
  5289. pointCurrent.cp1y = y - deltaX * mK[i];
  5290. }
  5291. if (pointAfter) {
  5292. deltaX = (pointAfter.x - x) / 3;
  5293. pointCurrent.cp2x = x + deltaX;
  5294. pointCurrent.cp2y = y + deltaX * mK[i];
  5295. }
  5296. }
  5297. }
  5298. function splineCurveMonotone(points) {
  5299. const pointsLen = points.length;
  5300. const deltaK = Array(pointsLen).fill(0);
  5301. const mK = Array(pointsLen);
  5302. let i, pointBefore, pointCurrent;
  5303. let pointAfter = getPoint(points, 0);
  5304. for (i = 0; i < pointsLen; ++i) {
  5305. pointBefore = pointCurrent;
  5306. pointCurrent = pointAfter;
  5307. pointAfter = getPoint(points, i + 1);
  5308. if (!pointCurrent) {
  5309. continue;
  5310. }
  5311. if (pointAfter) {
  5312. const slopeDeltaX = (pointAfter.x - pointCurrent.x);
  5313. deltaK[i] = slopeDeltaX !== 0 ? (pointAfter.y - pointCurrent.y) / slopeDeltaX : 0;
  5314. }
  5315. mK[i] = !pointBefore ? deltaK[i]
  5316. : !pointAfter ? deltaK[i - 1]
  5317. : (sign(deltaK[i - 1]) !== sign(deltaK[i])) ? 0
  5318. : (deltaK[i - 1] + deltaK[i]) / 2;
  5319. }
  5320. monotoneAdjust(points, deltaK, mK);
  5321. monotoneCompute(points, mK);
  5322. }
  5323. function capControlPoint(pt, min, max) {
  5324. return Math.max(Math.min(pt, max), min);
  5325. }
  5326. function capBezierPoints(points, area) {
  5327. let i, ilen, point, inArea, inAreaPrev;
  5328. let inAreaNext = _isPointInArea(points[0], area);
  5329. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5330. inAreaPrev = inArea;
  5331. inArea = inAreaNext;
  5332. inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area);
  5333. if (!inArea) {
  5334. continue;
  5335. }
  5336. point = points[i];
  5337. if (inAreaPrev) {
  5338. point.cp1x = capControlPoint(point.cp1x, area.left, area.right);
  5339. point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom);
  5340. }
  5341. if (inAreaNext) {
  5342. point.cp2x = capControlPoint(point.cp2x, area.left, area.right);
  5343. point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom);
  5344. }
  5345. }
  5346. }
  5347. function _updateBezierControlPoints(points, options, area, loop) {
  5348. let i, ilen, point, controlPoints;
  5349. if (options.spanGaps) {
  5350. points = points.filter((pt) => !pt.skip);
  5351. }
  5352. if (options.cubicInterpolationMode === 'monotone') {
  5353. splineCurveMonotone(points);
  5354. } else {
  5355. let prev = loop ? points[points.length - 1] : points[0];
  5356. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5357. point = points[i];
  5358. controlPoints = splineCurve(
  5359. prev,
  5360. point,
  5361. points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen],
  5362. options.tension
  5363. );
  5364. point.cp1x = controlPoints.previous.x;
  5365. point.cp1y = controlPoints.previous.y;
  5366. point.cp2x = controlPoints.next.x;
  5367. point.cp2y = controlPoints.next.y;
  5368. prev = point;
  5369. }
  5370. }
  5371. if (options.capBezierPoints) {
  5372. capBezierPoints(points, area);
  5373. }
  5374. }
  5375. function _pointInLine(p1, p2, t, mode) {
  5376. return {
  5377. x: p1.x + t * (p2.x - p1.x),
  5378. y: p1.y + t * (p2.y - p1.y)
  5379. };
  5380. }
  5381. function _steppedInterpolation(p1, p2, t, mode) {
  5382. return {
  5383. x: p1.x + t * (p2.x - p1.x),
  5384. y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y
  5385. : mode === 'after' ? t < 1 ? p1.y : p2.y
  5386. : t > 0 ? p2.y : p1.y
  5387. };
  5388. }
  5389. function _bezierInterpolation(p1, p2, t, mode) {
  5390. const cp1 = {x: p1.cp2x, y: p1.cp2y};
  5391. const cp2 = {x: p2.cp1x, y: p2.cp1y};
  5392. const a = _pointInLine(p1, cp1, t);
  5393. const b = _pointInLine(cp1, cp2, t);
  5394. const c = _pointInLine(cp2, p2, t);
  5395. const d = _pointInLine(a, b, t);
  5396. const e = _pointInLine(b, c, t);
  5397. return _pointInLine(d, e, t);
  5398. }
  5399. const getRightToLeftAdapter = function(rectX, width) {
  5400. return {
  5401. x(x) {
  5402. return rectX + rectX + width - x;
  5403. },
  5404. setWidth(w) {
  5405. width = w;
  5406. },
  5407. textAlign(align) {
  5408. if (align === 'center') {
  5409. return align;
  5410. }
  5411. return align === 'right' ? 'left' : 'right';
  5412. },
  5413. xPlus(x, value) {
  5414. return x - value;
  5415. },
  5416. leftForLtr(x, itemWidth) {
  5417. return x - itemWidth;
  5418. },
  5419. };
  5420. };
  5421. const getLeftToRightAdapter = function() {
  5422. return {
  5423. x(x) {
  5424. return x;
  5425. },
  5426. setWidth(w) {
  5427. },
  5428. textAlign(align) {
  5429. return align;
  5430. },
  5431. xPlus(x, value) {
  5432. return x + value;
  5433. },
  5434. leftForLtr(x, _itemWidth) {
  5435. return x;
  5436. },
  5437. };
  5438. };
  5439. function getRtlAdapter(rtl, rectX, width) {
  5440. return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter();
  5441. }
  5442. function overrideTextDirection(ctx, direction) {
  5443. let style, original;
  5444. if (direction === 'ltr' || direction === 'rtl') {
  5445. style = ctx.canvas.style;
  5446. original = [
  5447. style.getPropertyValue('direction'),
  5448. style.getPropertyPriority('direction'),
  5449. ];
  5450. style.setProperty('direction', direction, 'important');
  5451. ctx.prevTextDirection = original;
  5452. }
  5453. }
  5454. function restoreTextDirection(ctx, original) {
  5455. if (original !== undefined) {
  5456. delete ctx.prevTextDirection;
  5457. ctx.canvas.style.setProperty('direction', original[0], original[1]);
  5458. }
  5459. }
  5460. function propertyFn(property) {
  5461. if (property === 'angle') {
  5462. return {
  5463. between: _angleBetween,
  5464. compare: _angleDiff,
  5465. normalize: _normalizeAngle,
  5466. };
  5467. }
  5468. return {
  5469. between: (n, s, e) => n >= Math.min(s, e) && n <= Math.max(e, s),
  5470. compare: (a, b) => a - b,
  5471. normalize: x => x
  5472. };
  5473. }
  5474. function normalizeSegment({start, end, count, loop, style}) {
  5475. return {
  5476. start: start % count,
  5477. end: end % count,
  5478. loop: loop && (end - start + 1) % count === 0,
  5479. style
  5480. };
  5481. }
  5482. function getSegment(segment, points, bounds) {
  5483. const {property, start: startBound, end: endBound} = bounds;
  5484. const {between, normalize} = propertyFn(property);
  5485. const count = points.length;
  5486. let {start, end, loop} = segment;
  5487. let i, ilen;
  5488. if (loop) {
  5489. start += count;
  5490. end += count;
  5491. for (i = 0, ilen = count; i < ilen; ++i) {
  5492. if (!between(normalize(points[start % count][property]), startBound, endBound)) {
  5493. break;
  5494. }
  5495. start--;
  5496. end--;
  5497. }
  5498. start %= count;
  5499. end %= count;
  5500. }
  5501. if (end < start) {
  5502. end += count;
  5503. }
  5504. return {start, end, loop, style: segment.style};
  5505. }
  5506. function _boundSegment(segment, points, bounds) {
  5507. if (!bounds) {
  5508. return [segment];
  5509. }
  5510. const {property, start: startBound, end: endBound} = bounds;
  5511. const count = points.length;
  5512. const {compare, between, normalize} = propertyFn(property);
  5513. const {start, end, loop, style} = getSegment(segment, points, bounds);
  5514. const result = [];
  5515. let inside = false;
  5516. let subStart = null;
  5517. let value, point, prevValue;
  5518. const startIsBefore = () => between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0;
  5519. const endIsBefore = () => compare(endBound, value) === 0 || between(endBound, prevValue, value);
  5520. const shouldStart = () => inside || startIsBefore();
  5521. const shouldStop = () => !inside || endIsBefore();
  5522. for (let i = start, prev = start; i <= end; ++i) {
  5523. point = points[i % count];
  5524. if (point.skip) {
  5525. continue;
  5526. }
  5527. value = normalize(point[property]);
  5528. inside = between(value, startBound, endBound);
  5529. if (subStart === null && shouldStart()) {
  5530. subStart = compare(value, startBound) === 0 ? i : prev;
  5531. }
  5532. if (subStart !== null && shouldStop()) {
  5533. result.push(normalizeSegment({start: subStart, end: i, loop, count, style}));
  5534. subStart = null;
  5535. }
  5536. prev = i;
  5537. prevValue = value;
  5538. }
  5539. if (subStart !== null) {
  5540. result.push(normalizeSegment({start: subStart, end, loop, count, style}));
  5541. }
  5542. return result;
  5543. }
  5544. function _boundSegments(line, bounds) {
  5545. const result = [];
  5546. const segments = line.segments;
  5547. for (let i = 0; i < segments.length; i++) {
  5548. const sub = _boundSegment(segments[i], line.points, bounds);
  5549. if (sub.length) {
  5550. result.push(...sub);
  5551. }
  5552. }
  5553. return result;
  5554. }
  5555. function findStartAndEnd(points, count, loop, spanGaps) {
  5556. let start = 0;
  5557. let end = count - 1;
  5558. if (loop && !spanGaps) {
  5559. while (start < count && !points[start].skip) {
  5560. start++;
  5561. }
  5562. }
  5563. while (start < count && points[start].skip) {
  5564. start++;
  5565. }
  5566. start %= count;
  5567. if (loop) {
  5568. end += start;
  5569. }
  5570. while (end > start && points[end % count].skip) {
  5571. end--;
  5572. }
  5573. end %= count;
  5574. return {start, end};
  5575. }
  5576. function solidSegments(points, start, max, loop) {
  5577. const count = points.length;
  5578. const result = [];
  5579. let last = start;
  5580. let prev = points[start];
  5581. let end;
  5582. for (end = start + 1; end <= max; ++end) {
  5583. const cur = points[end % count];
  5584. if (cur.skip || cur.stop) {
  5585. if (!prev.skip) {
  5586. loop = false;
  5587. result.push({start: start % count, end: (end - 1) % count, loop});
  5588. start = last = cur.stop ? end : null;
  5589. }
  5590. } else {
  5591. last = end;
  5592. if (prev.skip) {
  5593. start = end;
  5594. }
  5595. }
  5596. prev = cur;
  5597. }
  5598. if (last !== null) {
  5599. result.push({start: start % count, end: last % count, loop});
  5600. }
  5601. return result;
  5602. }
  5603. function _computeSegments(line, segmentOptions) {
  5604. const points = line.points;
  5605. const spanGaps = line.options.spanGaps;
  5606. const count = points.length;
  5607. if (!count) {
  5608. return [];
  5609. }
  5610. const loop = !!line._loop;
  5611. const {start, end} = findStartAndEnd(points, count, loop, spanGaps);
  5612. if (spanGaps === true) {
  5613. return splitByStyles([{start, end, loop}], points, segmentOptions);
  5614. }
  5615. const max = end < start ? end + count : end;
  5616. const completeLoop = !!line._fullLoop && start === 0 && end === count - 1;
  5617. return splitByStyles(solidSegments(points, start, max, completeLoop), points, segmentOptions);
  5618. }
  5619. function splitByStyles(segments, points, segmentOptions) {
  5620. if (!segmentOptions || !segmentOptions.setContext || !points) {
  5621. return segments;
  5622. }
  5623. return doSplitByStyles(segments, points, segmentOptions);
  5624. }
  5625. function doSplitByStyles(segments, points, segmentOptions) {
  5626. const count = points.length;
  5627. const result = [];
  5628. let start = segments[0].start;
  5629. let i = start;
  5630. for (const segment of segments) {
  5631. let prevStyle, style;
  5632. let prev = points[start % count];
  5633. for (i = start + 1; i <= segment.end; i++) {
  5634. const pt = points[i % count];
  5635. style = readStyle(segmentOptions.setContext({type: 'segment', p0: prev, p1: pt}));
  5636. if (styleChanged(style, prevStyle)) {
  5637. result.push({start: start, end: i - 1, loop: segment.loop, style: prevStyle});
  5638. prevStyle = style;
  5639. start = i - 1;
  5640. }
  5641. prev = pt;
  5642. prevStyle = style;
  5643. }
  5644. if (start < i - 1) {
  5645. result.push({start, end: i - 1, loop: segment.loop, style});
  5646. start = i - 1;
  5647. }
  5648. }
  5649. return result;
  5650. }
  5651. function readStyle(options) {
  5652. return {
  5653. backgroundColor: options.backgroundColor,
  5654. borderCapStyle: options.borderCapStyle,
  5655. borderDash: options.borderDash,
  5656. borderDashOffset: options.borderDashOffset,
  5657. borderJoinStyle: options.borderJoinStyle,
  5658. borderWidth: options.borderWidth,
  5659. borderColor: options.borderColor
  5660. };
  5661. }
  5662. function styleChanged(style, prevStyle) {
  5663. return prevStyle && JSON.stringify(style) !== JSON.stringify(prevStyle);
  5664. }
  5665. var helpers = /*#__PURE__*/Object.freeze({
  5666. __proto__: null,
  5667. easingEffects: effects,
  5668. color: color,
  5669. getHoverColor: getHoverColor,
  5670. noop: noop,
  5671. uid: uid,
  5672. isNullOrUndef: isNullOrUndef,
  5673. isArray: isArray,
  5674. isObject: isObject,
  5675. isFinite: isNumberFinite,
  5676. finiteOrDefault: finiteOrDefault,
  5677. valueOrDefault: valueOrDefault,
  5678. toPercentage: toPercentage,
  5679. toDimension: toDimension,
  5680. callback: callback,
  5681. each: each,
  5682. _elementsEqual: _elementsEqual,
  5683. clone: clone,
  5684. _merger: _merger,
  5685. merge: merge,
  5686. mergeIf: mergeIf,
  5687. _mergerIf: _mergerIf,
  5688. _deprecated: _deprecated,
  5689. resolveObjectKey: resolveObjectKey,
  5690. _capitalize: _capitalize,
  5691. defined: defined,
  5692. isFunction: isFunction,
  5693. setsEqual: setsEqual,
  5694. toFontString: toFontString,
  5695. _measureText: _measureText,
  5696. _longestText: _longestText,
  5697. _alignPixel: _alignPixel,
  5698. clearCanvas: clearCanvas,
  5699. drawPoint: drawPoint,
  5700. _isPointInArea: _isPointInArea,
  5701. clipArea: clipArea,
  5702. unclipArea: unclipArea,
  5703. _steppedLineTo: _steppedLineTo,
  5704. _bezierCurveTo: _bezierCurveTo,
  5705. renderText: renderText,
  5706. addRoundedRectPath: addRoundedRectPath,
  5707. _lookup: _lookup,
  5708. _lookupByKey: _lookupByKey,
  5709. _rlookupByKey: _rlookupByKey,
  5710. _filterBetween: _filterBetween,
  5711. listenArrayEvents: listenArrayEvents,
  5712. unlistenArrayEvents: unlistenArrayEvents,
  5713. _arrayUnique: _arrayUnique,
  5714. _createResolver: _createResolver,
  5715. _attachContext: _attachContext,
  5716. _descriptors: _descriptors,
  5717. splineCurve: splineCurve,
  5718. splineCurveMonotone: splineCurveMonotone,
  5719. _updateBezierControlPoints: _updateBezierControlPoints,
  5720. _getParentNode: _getParentNode,
  5721. getStyle: getStyle,
  5722. getRelativePosition: getRelativePosition$1,
  5723. getMaximumSize: getMaximumSize,
  5724. retinaScale: retinaScale,
  5725. supportsEventListenerOptions: supportsEventListenerOptions,
  5726. readUsedSize: readUsedSize,
  5727. fontString: fontString,
  5728. requestAnimFrame: requestAnimFrame,
  5729. throttled: throttled,
  5730. debounce: debounce,
  5731. _toLeftRightCenter: _toLeftRightCenter,
  5732. _alignStartEnd: _alignStartEnd,
  5733. _textX: _textX,
  5734. _pointInLine: _pointInLine,
  5735. _steppedInterpolation: _steppedInterpolation,
  5736. _bezierInterpolation: _bezierInterpolation,
  5737. formatNumber: formatNumber,
  5738. toLineHeight: toLineHeight,
  5739. _readValueToProps: _readValueToProps,
  5740. toTRBL: toTRBL,
  5741. toTRBLCorners: toTRBLCorners,
  5742. toPadding: toPadding,
  5743. toFont: toFont,
  5744. resolve: resolve,
  5745. _addGrace: _addGrace,
  5746. PI: PI,
  5747. TAU: TAU,
  5748. PITAU: PITAU,
  5749. INFINITY: INFINITY,
  5750. RAD_PER_DEG: RAD_PER_DEG,
  5751. HALF_PI: HALF_PI,
  5752. QUARTER_PI: QUARTER_PI,
  5753. TWO_THIRDS_PI: TWO_THIRDS_PI,
  5754. log10: log10,
  5755. sign: sign,
  5756. niceNum: niceNum,
  5757. _factorize: _factorize,
  5758. isNumber: isNumber,
  5759. almostEquals: almostEquals,
  5760. almostWhole: almostWhole,
  5761. _setMinAndMaxByKey: _setMinAndMaxByKey,
  5762. toRadians: toRadians,
  5763. toDegrees: toDegrees,
  5764. _decimalPlaces: _decimalPlaces,
  5765. getAngleFromPoint: getAngleFromPoint,
  5766. distanceBetweenPoints: distanceBetweenPoints,
  5767. _angleDiff: _angleDiff,
  5768. _normalizeAngle: _normalizeAngle,
  5769. _angleBetween: _angleBetween,
  5770. _limitValue: _limitValue,
  5771. _int16Range: _int16Range,
  5772. getRtlAdapter: getRtlAdapter,
  5773. overrideTextDirection: overrideTextDirection,
  5774. restoreTextDirection: restoreTextDirection,
  5775. _boundSegment: _boundSegment,
  5776. _boundSegments: _boundSegments,
  5777. _computeSegments: _computeSegments
  5778. });
  5779. class TypedRegistry {
  5780. constructor(type, scope, override) {
  5781. this.type = type;
  5782. this.scope = scope;
  5783. this.override = override;
  5784. this.items = Object.create(null);
  5785. }
  5786. isForType(type) {
  5787. return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype);
  5788. }
  5789. register(item) {
  5790. const me = this;
  5791. const proto = Object.getPrototypeOf(item);
  5792. let parentScope;
  5793. if (isIChartComponent(proto)) {
  5794. parentScope = me.register(proto);
  5795. }
  5796. const items = me.items;
  5797. const id = item.id;
  5798. const scope = me.scope + '.' + id;
  5799. if (!id) {
  5800. throw new Error('class does not have id: ' + item);
  5801. }
  5802. if (id in items) {
  5803. return scope;
  5804. }
  5805. items[id] = item;
  5806. registerDefaults(item, scope, parentScope);
  5807. if (me.override) {
  5808. defaults.override(item.id, item.overrides);
  5809. }
  5810. return scope;
  5811. }
  5812. get(id) {
  5813. return this.items[id];
  5814. }
  5815. unregister(item) {
  5816. const items = this.items;
  5817. const id = item.id;
  5818. const scope = this.scope;
  5819. if (id in items) {
  5820. delete items[id];
  5821. }
  5822. if (scope && id in defaults[scope]) {
  5823. delete defaults[scope][id];
  5824. if (this.override) {
  5825. delete overrides[id];
  5826. }
  5827. }
  5828. }
  5829. }
  5830. function registerDefaults(item, scope, parentScope) {
  5831. const itemDefaults = merge(Object.create(null), [
  5832. parentScope ? defaults.get(parentScope) : {},
  5833. defaults.get(scope),
  5834. item.defaults
  5835. ]);
  5836. defaults.set(scope, itemDefaults);
  5837. if (item.defaultRoutes) {
  5838. routeDefaults(scope, item.defaultRoutes);
  5839. }
  5840. if (item.descriptors) {
  5841. defaults.describe(scope, item.descriptors);
  5842. }
  5843. }
  5844. function routeDefaults(scope, routes) {
  5845. Object.keys(routes).forEach(property => {
  5846. const propertyParts = property.split('.');
  5847. const sourceName = propertyParts.pop();
  5848. const sourceScope = [scope].concat(propertyParts).join('.');
  5849. const parts = routes[property].split('.');
  5850. const targetName = parts.pop();
  5851. const targetScope = parts.join('.');
  5852. defaults.route(sourceScope, sourceName, targetScope, targetName);
  5853. });
  5854. }
  5855. function isIChartComponent(proto) {
  5856. return 'id' in proto && 'defaults' in proto;
  5857. }
  5858. class Registry {
  5859. constructor() {
  5860. this.controllers = new TypedRegistry(DatasetController, 'datasets', true);
  5861. this.elements = new TypedRegistry(Element, 'elements');
  5862. this.plugins = new TypedRegistry(Object, 'plugins');
  5863. this.scales = new TypedRegistry(Scale, 'scales');
  5864. this._typedRegistries = [this.controllers, this.scales, this.elements];
  5865. }
  5866. add(...args) {
  5867. this._each('register', args);
  5868. }
  5869. remove(...args) {
  5870. this._each('unregister', args);
  5871. }
  5872. addControllers(...args) {
  5873. this._each('register', args, this.controllers);
  5874. }
  5875. addElements(...args) {
  5876. this._each('register', args, this.elements);
  5877. }
  5878. addPlugins(...args) {
  5879. this._each('register', args, this.plugins);
  5880. }
  5881. addScales(...args) {
  5882. this._each('register', args, this.scales);
  5883. }
  5884. getController(id) {
  5885. return this._get(id, this.controllers, 'controller');
  5886. }
  5887. getElement(id) {
  5888. return this._get(id, this.elements, 'element');
  5889. }
  5890. getPlugin(id) {
  5891. return this._get(id, this.plugins, 'plugin');
  5892. }
  5893. getScale(id) {
  5894. return this._get(id, this.scales, 'scale');
  5895. }
  5896. removeControllers(...args) {
  5897. this._each('unregister', args, this.controllers);
  5898. }
  5899. removeElements(...args) {
  5900. this._each('unregister', args, this.elements);
  5901. }
  5902. removePlugins(...args) {
  5903. this._each('unregister', args, this.plugins);
  5904. }
  5905. removeScales(...args) {
  5906. this._each('unregister', args, this.scales);
  5907. }
  5908. _each(method, args, typedRegistry) {
  5909. const me = this;
  5910. [...args].forEach(arg => {
  5911. const reg = typedRegistry || me._getRegistryForType(arg);
  5912. if (typedRegistry || reg.isForType(arg) || (reg === me.plugins && arg.id)) {
  5913. me._exec(method, reg, arg);
  5914. } else {
  5915. each(arg, item => {
  5916. const itemReg = typedRegistry || me._getRegistryForType(item);
  5917. me._exec(method, itemReg, item);
  5918. });
  5919. }
  5920. });
  5921. }
  5922. _exec(method, registry, component) {
  5923. const camelMethod = _capitalize(method);
  5924. callback(component['before' + camelMethod], [], component);
  5925. registry[method](component);
  5926. callback(component['after' + camelMethod], [], component);
  5927. }
  5928. _getRegistryForType(type) {
  5929. for (let i = 0; i < this._typedRegistries.length; i++) {
  5930. const reg = this._typedRegistries[i];
  5931. if (reg.isForType(type)) {
  5932. return reg;
  5933. }
  5934. }
  5935. return this.plugins;
  5936. }
  5937. _get(id, typedRegistry, type) {
  5938. const item = typedRegistry.get(id);
  5939. if (item === undefined) {
  5940. throw new Error('"' + id + '" is not a registered ' + type + '.');
  5941. }
  5942. return item;
  5943. }
  5944. }
  5945. var registry = new Registry();
  5946. class PluginService {
  5947. constructor() {
  5948. this._init = [];
  5949. }
  5950. notify(chart, hook, args, filter) {
  5951. const me = this;
  5952. if (hook === 'beforeInit') {
  5953. me._init = me._createDescriptors(chart, true);
  5954. me._notify(me._init, chart, 'install');
  5955. }
  5956. const descriptors = filter ? me._descriptors(chart).filter(filter) : me._descriptors(chart);
  5957. const result = me._notify(descriptors, chart, hook, args);
  5958. if (hook === 'destroy') {
  5959. me._notify(descriptors, chart, 'stop');
  5960. me._notify(me._init, chart, 'uninstall');
  5961. }
  5962. return result;
  5963. }
  5964. _notify(descriptors, chart, hook, args) {
  5965. args = args || {};
  5966. for (const descriptor of descriptors) {
  5967. const plugin = descriptor.plugin;
  5968. const method = plugin[hook];
  5969. const params = [chart, args, descriptor.options];
  5970. if (callback(method, params, plugin) === false && args.cancelable) {
  5971. return false;
  5972. }
  5973. }
  5974. return true;
  5975. }
  5976. invalidate() {
  5977. if (!isNullOrUndef(this._cache)) {
  5978. this._oldCache = this._cache;
  5979. this._cache = undefined;
  5980. }
  5981. }
  5982. _descriptors(chart) {
  5983. if (this._cache) {
  5984. return this._cache;
  5985. }
  5986. const descriptors = this._cache = this._createDescriptors(chart);
  5987. this._notifyStateChanges(chart);
  5988. return descriptors;
  5989. }
  5990. _createDescriptors(chart, all) {
  5991. const config = chart && chart.config;
  5992. const options = valueOrDefault(config.options && config.options.plugins, {});
  5993. const plugins = allPlugins(config);
  5994. return options === false && !all ? [] : createDescriptors(chart, plugins, options, all);
  5995. }
  5996. _notifyStateChanges(chart) {
  5997. const previousDescriptors = this._oldCache || [];
  5998. const descriptors = this._cache;
  5999. const diff = (a, b) => a.filter(x => !b.some(y => x.plugin.id === y.plugin.id));
  6000. this._notify(diff(previousDescriptors, descriptors), chart, 'stop');
  6001. this._notify(diff(descriptors, previousDescriptors), chart, 'start');
  6002. }
  6003. }
  6004. function allPlugins(config) {
  6005. const plugins = [];
  6006. const keys = Object.keys(registry.plugins.items);
  6007. for (let i = 0; i < keys.length; i++) {
  6008. plugins.push(registry.getPlugin(keys[i]));
  6009. }
  6010. const local = config.plugins || [];
  6011. for (let i = 0; i < local.length; i++) {
  6012. const plugin = local[i];
  6013. if (plugins.indexOf(plugin) === -1) {
  6014. plugins.push(plugin);
  6015. }
  6016. }
  6017. return plugins;
  6018. }
  6019. function getOpts(options, all) {
  6020. if (!all && options === false) {
  6021. return null;
  6022. }
  6023. if (options === true) {
  6024. return {};
  6025. }
  6026. return options;
  6027. }
  6028. function createDescriptors(chart, plugins, options, all) {
  6029. const result = [];
  6030. const context = chart.getContext();
  6031. for (let i = 0; i < plugins.length; i++) {
  6032. const plugin = plugins[i];
  6033. const id = plugin.id;
  6034. const opts = getOpts(options[id], all);
  6035. if (opts === null) {
  6036. continue;
  6037. }
  6038. result.push({
  6039. plugin,
  6040. options: pluginOpts(chart.config, plugin, opts, context)
  6041. });
  6042. }
  6043. return result;
  6044. }
  6045. function pluginOpts(config, plugin, opts, context) {
  6046. const keys = config.pluginScopeKeys(plugin);
  6047. const scopes = config.getOptionScopes(opts, keys);
  6048. return config.createResolver(scopes, context, [''], {scriptable: false, indexable: false, allKeys: true});
  6049. }
  6050. function getIndexAxis(type, options) {
  6051. const datasetDefaults = defaults.datasets[type] || {};
  6052. const datasetOptions = (options.datasets || {})[type] || {};
  6053. return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x';
  6054. }
  6055. function getAxisFromDefaultScaleID(id, indexAxis) {
  6056. let axis = id;
  6057. if (id === '_index_') {
  6058. axis = indexAxis;
  6059. } else if (id === '_value_') {
  6060. axis = indexAxis === 'x' ? 'y' : 'x';
  6061. }
  6062. return axis;
  6063. }
  6064. function getDefaultScaleIDFromAxis(axis, indexAxis) {
  6065. return axis === indexAxis ? '_index_' : '_value_';
  6066. }
  6067. function axisFromPosition(position) {
  6068. if (position === 'top' || position === 'bottom') {
  6069. return 'x';
  6070. }
  6071. if (position === 'left' || position === 'right') {
  6072. return 'y';
  6073. }
  6074. }
  6075. function determineAxis(id, scaleOptions) {
  6076. if (id === 'x' || id === 'y') {
  6077. return id;
  6078. }
  6079. return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id.charAt(0).toLowerCase();
  6080. }
  6081. function mergeScaleConfig(config, options) {
  6082. const chartDefaults = overrides[config.type] || {scales: {}};
  6083. const configScales = options.scales || {};
  6084. const chartIndexAxis = getIndexAxis(config.type, options);
  6085. const firstIDs = Object.create(null);
  6086. const scales = Object.create(null);
  6087. Object.keys(configScales).forEach(id => {
  6088. const scaleConf = configScales[id];
  6089. const axis = determineAxis(id, scaleConf);
  6090. const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis);
  6091. const defaultScaleOptions = chartDefaults.scales || {};
  6092. firstIDs[axis] = firstIDs[axis] || id;
  6093. scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, defaultScaleOptions[axis], defaultScaleOptions[defaultId]]);
  6094. });
  6095. config.data.datasets.forEach(dataset => {
  6096. const type = dataset.type || config.type;
  6097. const indexAxis = dataset.indexAxis || getIndexAxis(type, options);
  6098. const datasetDefaults = overrides[type] || {};
  6099. const defaultScaleOptions = datasetDefaults.scales || {};
  6100. Object.keys(defaultScaleOptions).forEach(defaultID => {
  6101. const axis = getAxisFromDefaultScaleID(defaultID, indexAxis);
  6102. const id = dataset[axis + 'AxisID'] || firstIDs[axis] || axis;
  6103. scales[id] = scales[id] || Object.create(null);
  6104. mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]);
  6105. });
  6106. });
  6107. Object.keys(scales).forEach(key => {
  6108. const scale = scales[key];
  6109. mergeIf(scale, [defaults.scales[scale.type], defaults.scale]);
  6110. });
  6111. return scales;
  6112. }
  6113. function initOptions(config) {
  6114. const options = config.options || (config.options = {});
  6115. options.plugins = valueOrDefault(options.plugins, {});
  6116. options.scales = mergeScaleConfig(config, options);
  6117. }
  6118. function initData(data) {
  6119. data = data || {};
  6120. data.datasets = data.datasets || [];
  6121. data.labels = data.labels || [];
  6122. return data;
  6123. }
  6124. function initConfig(config) {
  6125. config = config || {};
  6126. config.data = initData(config.data);
  6127. initOptions(config);
  6128. return config;
  6129. }
  6130. const keyCache = new Map();
  6131. const keysCached = new Set();
  6132. function cachedKeys(cacheKey, generate) {
  6133. let keys = keyCache.get(cacheKey);
  6134. if (!keys) {
  6135. keys = generate();
  6136. keyCache.set(cacheKey, keys);
  6137. keysCached.add(keys);
  6138. }
  6139. return keys;
  6140. }
  6141. const addIfFound = (set, obj, key) => {
  6142. const opts = resolveObjectKey(obj, key);
  6143. if (opts !== undefined) {
  6144. set.add(opts);
  6145. }
  6146. };
  6147. class Config {
  6148. constructor(config) {
  6149. this._config = initConfig(config);
  6150. this._scopeCache = new Map();
  6151. this._resolverCache = new Map();
  6152. }
  6153. get type() {
  6154. return this._config.type;
  6155. }
  6156. set type(type) {
  6157. this._config.type = type;
  6158. }
  6159. get data() {
  6160. return this._config.data;
  6161. }
  6162. set data(data) {
  6163. this._config.data = initData(data);
  6164. }
  6165. get options() {
  6166. return this._config.options;
  6167. }
  6168. set options(options) {
  6169. this._config.options = options;
  6170. }
  6171. get plugins() {
  6172. return this._config.plugins;
  6173. }
  6174. update() {
  6175. const config = this._config;
  6176. this.clearCache();
  6177. initOptions(config);
  6178. }
  6179. clearCache() {
  6180. this._scopeCache.clear();
  6181. this._resolverCache.clear();
  6182. }
  6183. datasetScopeKeys(datasetType) {
  6184. return cachedKeys(datasetType,
  6185. () => [[
  6186. `datasets.${datasetType}`,
  6187. ''
  6188. ]]);
  6189. }
  6190. datasetAnimationScopeKeys(datasetType, transition) {
  6191. return cachedKeys(`${datasetType}.transition.${transition}`,
  6192. () => [
  6193. [
  6194. `datasets.${datasetType}.transitions.${transition}`,
  6195. `transitions.${transition}`,
  6196. ],
  6197. [
  6198. `datasets.${datasetType}`,
  6199. ''
  6200. ]
  6201. ]);
  6202. }
  6203. datasetElementScopeKeys(datasetType, elementType) {
  6204. return cachedKeys(`${datasetType}-${elementType}`,
  6205. () => [[
  6206. `datasets.${datasetType}.elements.${elementType}`,
  6207. `datasets.${datasetType}`,
  6208. `elements.${elementType}`,
  6209. ''
  6210. ]]);
  6211. }
  6212. pluginScopeKeys(plugin) {
  6213. const id = plugin.id;
  6214. const type = this.type;
  6215. return cachedKeys(`${type}-plugin-${id}`,
  6216. () => [[
  6217. `plugins.${id}`,
  6218. ...plugin.additionalOptionScopes || [],
  6219. ]]);
  6220. }
  6221. _cachedScopes(mainScope, resetCache) {
  6222. const _scopeCache = this._scopeCache;
  6223. let cache = _scopeCache.get(mainScope);
  6224. if (!cache || resetCache) {
  6225. cache = new Map();
  6226. _scopeCache.set(mainScope, cache);
  6227. }
  6228. return cache;
  6229. }
  6230. getOptionScopes(mainScope, keyLists, resetCache) {
  6231. const {options, type} = this;
  6232. const cache = this._cachedScopes(mainScope, resetCache);
  6233. const cached = cache.get(keyLists);
  6234. if (cached) {
  6235. return cached;
  6236. }
  6237. const scopes = new Set();
  6238. keyLists.forEach(keys => {
  6239. if (mainScope) {
  6240. scopes.add(mainScope);
  6241. keys.forEach(key => addIfFound(scopes, mainScope, key));
  6242. }
  6243. keys.forEach(key => addIfFound(scopes, options, key));
  6244. keys.forEach(key => addIfFound(scopes, overrides[type] || {}, key));
  6245. keys.forEach(key => addIfFound(scopes, defaults, key));
  6246. keys.forEach(key => addIfFound(scopes, descriptors, key));
  6247. });
  6248. const array = [...scopes];
  6249. if (keysCached.has(keyLists)) {
  6250. cache.set(keyLists, array);
  6251. }
  6252. return array;
  6253. }
  6254. chartOptionScopes() {
  6255. const {options, type} = this;
  6256. return [
  6257. options,
  6258. overrides[type] || {},
  6259. defaults.datasets[type] || {},
  6260. {type},
  6261. defaults,
  6262. descriptors
  6263. ];
  6264. }
  6265. resolveNamedOptions(scopes, names, context, prefixes = ['']) {
  6266. const result = {$shared: true};
  6267. const {resolver, subPrefixes} = getResolver(this._resolverCache, scopes, prefixes);
  6268. let options = resolver;
  6269. if (needContext(resolver, names)) {
  6270. result.$shared = false;
  6271. context = isFunction(context) ? context() : context;
  6272. const subResolver = this.createResolver(scopes, context, subPrefixes);
  6273. options = _attachContext(resolver, context, subResolver);
  6274. }
  6275. for (const prop of names) {
  6276. result[prop] = options[prop];
  6277. }
  6278. return result;
  6279. }
  6280. createResolver(scopes, context, prefixes = [''], descriptorDefaults) {
  6281. const {resolver} = getResolver(this._resolverCache, scopes, prefixes);
  6282. return isObject(context)
  6283. ? _attachContext(resolver, context, undefined, descriptorDefaults)
  6284. : resolver;
  6285. }
  6286. }
  6287. function getResolver(resolverCache, scopes, prefixes) {
  6288. let cache = resolverCache.get(scopes);
  6289. if (!cache) {
  6290. cache = new Map();
  6291. resolverCache.set(scopes, cache);
  6292. }
  6293. const cacheKey = prefixes.join();
  6294. let cached = cache.get(cacheKey);
  6295. if (!cached) {
  6296. const resolver = _createResolver(scopes, prefixes);
  6297. cached = {
  6298. resolver,
  6299. subPrefixes: prefixes.filter(p => !p.toLowerCase().includes('hover'))
  6300. };
  6301. cache.set(cacheKey, cached);
  6302. }
  6303. return cached;
  6304. }
  6305. function needContext(proxy, names) {
  6306. const {isScriptable, isIndexable} = _descriptors(proxy);
  6307. for (const prop of names) {
  6308. if ((isScriptable(prop) && isFunction(proxy[prop]))
  6309. || (isIndexable(prop) && isArray(proxy[prop]))) {
  6310. return true;
  6311. }
  6312. }
  6313. return false;
  6314. }
  6315. var version = "3.2.1";
  6316. const KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea'];
  6317. function positionIsHorizontal(position, axis) {
  6318. return position === 'top' || position === 'bottom' || (KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x');
  6319. }
  6320. function compare2Level(l1, l2) {
  6321. return function(a, b) {
  6322. return a[l1] === b[l1]
  6323. ? a[l2] - b[l2]
  6324. : a[l1] - b[l1];
  6325. };
  6326. }
  6327. function onAnimationsComplete(context) {
  6328. const chart = context.chart;
  6329. const animationOptions = chart.options.animation;
  6330. chart.notifyPlugins('afterRender');
  6331. callback(animationOptions && animationOptions.onComplete, [context], chart);
  6332. }
  6333. function onAnimationProgress(context) {
  6334. const chart = context.chart;
  6335. const animationOptions = chart.options.animation;
  6336. callback(animationOptions && animationOptions.onProgress, [context], chart);
  6337. }
  6338. function isDomSupported() {
  6339. return typeof window !== 'undefined' && typeof document !== 'undefined';
  6340. }
  6341. function getCanvas(item) {
  6342. if (isDomSupported() && typeof item === 'string') {
  6343. item = document.getElementById(item);
  6344. } else if (item && item.length) {
  6345. item = item[0];
  6346. }
  6347. if (item && item.canvas) {
  6348. item = item.canvas;
  6349. }
  6350. return item;
  6351. }
  6352. const instances = {};
  6353. const getChart = (key) => {
  6354. const canvas = getCanvas(key);
  6355. return Object.values(instances).filter((c) => c.canvas === canvas).pop();
  6356. };
  6357. class Chart {
  6358. constructor(item, config) {
  6359. const me = this;
  6360. this.config = config = new Config(config);
  6361. const initialCanvas = getCanvas(item);
  6362. const existingChart = getChart(initialCanvas);
  6363. if (existingChart) {
  6364. throw new Error(
  6365. 'Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' +
  6366. ' must be destroyed before the canvas can be reused.'
  6367. );
  6368. }
  6369. const options = config.createResolver(config.chartOptionScopes(), me.getContext());
  6370. this.platform = me._initializePlatform(initialCanvas, config);
  6371. const context = me.platform.acquireContext(initialCanvas, options.aspectRatio);
  6372. const canvas = context && context.canvas;
  6373. const height = canvas && canvas.height;
  6374. const width = canvas && canvas.width;
  6375. this.id = uid();
  6376. this.ctx = context;
  6377. this.canvas = canvas;
  6378. this.width = width;
  6379. this.height = height;
  6380. this._options = options;
  6381. this._aspectRatio = this.aspectRatio;
  6382. this._layers = [];
  6383. this._metasets = [];
  6384. this._stacks = undefined;
  6385. this.boxes = [];
  6386. this.currentDevicePixelRatio = undefined;
  6387. this.chartArea = undefined;
  6388. this._active = [];
  6389. this._lastEvent = undefined;
  6390. this._listeners = {};
  6391. this._sortedMetasets = [];
  6392. this.scales = {};
  6393. this.scale = undefined;
  6394. this._plugins = new PluginService();
  6395. this.$proxies = {};
  6396. this._hiddenIndices = {};
  6397. this.attached = false;
  6398. this._animationsDisabled = undefined;
  6399. this.$context = undefined;
  6400. this._doResize = debounce(() => this.update('resize'), options.resizeDelay || 0);
  6401. instances[me.id] = me;
  6402. if (!context || !canvas) {
  6403. console.error("Failed to create chart: can't acquire context from the given item");
  6404. return;
  6405. }
  6406. animator.listen(me, 'complete', onAnimationsComplete);
  6407. animator.listen(me, 'progress', onAnimationProgress);
  6408. me._initialize();
  6409. if (me.attached) {
  6410. me.update();
  6411. }
  6412. }
  6413. get aspectRatio() {
  6414. const {options: {aspectRatio, maintainAspectRatio}, width, height, _aspectRatio} = this;
  6415. if (!isNullOrUndef(aspectRatio)) {
  6416. return aspectRatio;
  6417. }
  6418. if (maintainAspectRatio && _aspectRatio) {
  6419. return _aspectRatio;
  6420. }
  6421. return height ? width / height : null;
  6422. }
  6423. get data() {
  6424. return this.config.data;
  6425. }
  6426. set data(data) {
  6427. this.config.data = data;
  6428. }
  6429. get options() {
  6430. return this._options;
  6431. }
  6432. set options(options) {
  6433. this.config.options = options;
  6434. }
  6435. _initialize() {
  6436. const me = this;
  6437. me.notifyPlugins('beforeInit');
  6438. if (me.options.responsive) {
  6439. me.resize();
  6440. } else {
  6441. retinaScale(me, me.options.devicePixelRatio);
  6442. }
  6443. me.bindEvents();
  6444. me.notifyPlugins('afterInit');
  6445. return me;
  6446. }
  6447. _initializePlatform(canvas, config) {
  6448. if (config.platform) {
  6449. return new config.platform();
  6450. } else if (!isDomSupported() || (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) {
  6451. return new BasicPlatform();
  6452. }
  6453. return new DomPlatform();
  6454. }
  6455. clear() {
  6456. clearCanvas(this.canvas, this.ctx);
  6457. return this;
  6458. }
  6459. stop() {
  6460. animator.stop(this);
  6461. return this;
  6462. }
  6463. resize(width, height) {
  6464. if (!animator.running(this)) {
  6465. this._resize(width, height);
  6466. } else {
  6467. this._resizeBeforeDraw = {width, height};
  6468. }
  6469. }
  6470. _resize(width, height) {
  6471. const me = this;
  6472. const options = me.options;
  6473. const canvas = me.canvas;
  6474. const aspectRatio = options.maintainAspectRatio && me.aspectRatio;
  6475. const newSize = me.platform.getMaximumSize(canvas, width, height, aspectRatio);
  6476. const oldRatio = me.currentDevicePixelRatio;
  6477. const newRatio = options.devicePixelRatio || me.platform.getDevicePixelRatio();
  6478. if (me.width === newSize.width && me.height === newSize.height && oldRatio === newRatio) {
  6479. return;
  6480. }
  6481. me.width = newSize.width;
  6482. me.height = newSize.height;
  6483. me._aspectRatio = me.aspectRatio;
  6484. retinaScale(me, newRatio, true);
  6485. me.notifyPlugins('resize', {size: newSize});
  6486. callback(options.onResize, [me, newSize], me);
  6487. if (me.attached) {
  6488. if (me._doResize()) {
  6489. me.render();
  6490. }
  6491. }
  6492. }
  6493. ensureScalesHaveIDs() {
  6494. const options = this.options;
  6495. const scalesOptions = options.scales || {};
  6496. each(scalesOptions, (axisOptions, axisID) => {
  6497. axisOptions.id = axisID;
  6498. });
  6499. }
  6500. buildOrUpdateScales() {
  6501. const me = this;
  6502. const options = me.options;
  6503. const scaleOpts = options.scales;
  6504. const scales = me.scales;
  6505. const updated = Object.keys(scales).reduce((obj, id) => {
  6506. obj[id] = false;
  6507. return obj;
  6508. }, {});
  6509. let items = [];
  6510. if (scaleOpts) {
  6511. items = items.concat(
  6512. Object.keys(scaleOpts).map((id) => {
  6513. const scaleOptions = scaleOpts[id];
  6514. const axis = determineAxis(id, scaleOptions);
  6515. const isRadial = axis === 'r';
  6516. const isHorizontal = axis === 'x';
  6517. return {
  6518. options: scaleOptions,
  6519. dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left',
  6520. dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear'
  6521. };
  6522. })
  6523. );
  6524. }
  6525. each(items, (item) => {
  6526. const scaleOptions = item.options;
  6527. const id = scaleOptions.id;
  6528. const axis = determineAxis(id, scaleOptions);
  6529. const scaleType = valueOrDefault(scaleOptions.type, item.dtype);
  6530. if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) {
  6531. scaleOptions.position = item.dposition;
  6532. }
  6533. updated[id] = true;
  6534. let scale = null;
  6535. if (id in scales && scales[id].type === scaleType) {
  6536. scale = scales[id];
  6537. } else {
  6538. const scaleClass = registry.getScale(scaleType);
  6539. scale = new scaleClass({
  6540. id,
  6541. type: scaleType,
  6542. ctx: me.ctx,
  6543. chart: me
  6544. });
  6545. scales[scale.id] = scale;
  6546. }
  6547. scale.init(scaleOptions, options);
  6548. });
  6549. each(updated, (hasUpdated, id) => {
  6550. if (!hasUpdated) {
  6551. delete scales[id];
  6552. }
  6553. });
  6554. each(scales, (scale) => {
  6555. layouts.configure(me, scale, scale.options);
  6556. layouts.addBox(me, scale);
  6557. });
  6558. }
  6559. _updateMetasetIndex(meta, index) {
  6560. const metasets = this._metasets;
  6561. const oldIndex = meta.index;
  6562. if (oldIndex !== index) {
  6563. metasets[oldIndex] = metasets[index];
  6564. metasets[index] = meta;
  6565. meta.index = index;
  6566. }
  6567. }
  6568. _updateMetasets() {
  6569. const me = this;
  6570. const metasets = me._metasets;
  6571. const numData = me.data.datasets.length;
  6572. const numMeta = metasets.length;
  6573. if (numMeta > numData) {
  6574. for (let i = numData; i < numMeta; ++i) {
  6575. me._destroyDatasetMeta(i);
  6576. }
  6577. metasets.splice(numData, numMeta - numData);
  6578. }
  6579. me._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index'));
  6580. }
  6581. _removeUnreferencedMetasets() {
  6582. const me = this;
  6583. const {_metasets: metasets, data: {datasets}} = me;
  6584. if (metasets.length > datasets.length) {
  6585. delete me._stacks;
  6586. }
  6587. metasets.forEach((meta, index) => {
  6588. if (datasets.filter(x => x === meta._dataset).length === 0) {
  6589. me._destroyDatasetMeta(index);
  6590. }
  6591. });
  6592. }
  6593. buildOrUpdateControllers() {
  6594. const me = this;
  6595. const newControllers = [];
  6596. const datasets = me.data.datasets;
  6597. let i, ilen;
  6598. me._removeUnreferencedMetasets();
  6599. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  6600. const dataset = datasets[i];
  6601. let meta = me.getDatasetMeta(i);
  6602. const type = dataset.type || me.config.type;
  6603. if (meta.type && meta.type !== type) {
  6604. me._destroyDatasetMeta(i);
  6605. meta = me.getDatasetMeta(i);
  6606. }
  6607. meta.type = type;
  6608. meta.indexAxis = dataset.indexAxis || getIndexAxis(type, me.options);
  6609. meta.order = dataset.order || 0;
  6610. me._updateMetasetIndex(meta, i);
  6611. meta.label = '' + dataset.label;
  6612. meta.visible = me.isDatasetVisible(i);
  6613. if (meta.controller) {
  6614. meta.controller.updateIndex(i);
  6615. meta.controller.linkScales();
  6616. } else {
  6617. const ControllerClass = registry.getController(type);
  6618. const {datasetElementType, dataElementType} = defaults.datasets[type];
  6619. Object.assign(ControllerClass.prototype, {
  6620. dataElementType: registry.getElement(dataElementType),
  6621. datasetElementType: datasetElementType && registry.getElement(datasetElementType)
  6622. });
  6623. meta.controller = new ControllerClass(me, i);
  6624. newControllers.push(meta.controller);
  6625. }
  6626. }
  6627. me._updateMetasets();
  6628. return newControllers;
  6629. }
  6630. _resetElements() {
  6631. const me = this;
  6632. each(me.data.datasets, (dataset, datasetIndex) => {
  6633. me.getDatasetMeta(datasetIndex).controller.reset();
  6634. }, me);
  6635. }
  6636. reset() {
  6637. this._resetElements();
  6638. this.notifyPlugins('reset');
  6639. }
  6640. update(mode) {
  6641. const me = this;
  6642. const config = me.config;
  6643. config.update();
  6644. me._options = config.createResolver(config.chartOptionScopes(), me.getContext());
  6645. each(me.scales, (scale) => {
  6646. layouts.removeBox(me, scale);
  6647. });
  6648. const animsDisabled = me._animationsDisabled = !me.options.animation;
  6649. me.ensureScalesHaveIDs();
  6650. me.buildOrUpdateScales();
  6651. const existingEvents = new Set(Object.keys(me._listeners));
  6652. const newEvents = new Set(me.options.events);
  6653. if (!setsEqual(existingEvents, newEvents)) {
  6654. me.unbindEvents();
  6655. me.bindEvents();
  6656. }
  6657. me._plugins.invalidate();
  6658. if (me.notifyPlugins('beforeUpdate', {mode, cancelable: true}) === false) {
  6659. return;
  6660. }
  6661. const newControllers = me.buildOrUpdateControllers();
  6662. me.notifyPlugins('beforeElementsUpdate');
  6663. let minPadding = 0;
  6664. for (let i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
  6665. const {controller} = me.getDatasetMeta(i);
  6666. const reset = !animsDisabled && newControllers.indexOf(controller) === -1;
  6667. controller.buildOrUpdateElements(reset);
  6668. minPadding = Math.max(+controller.getMaxOverflow(), minPadding);
  6669. }
  6670. me._minPadding = minPadding;
  6671. me._updateLayout(minPadding);
  6672. if (!animsDisabled) {
  6673. each(newControllers, (controller) => {
  6674. controller.reset();
  6675. });
  6676. }
  6677. me._updateDatasets(mode);
  6678. me.notifyPlugins('afterUpdate', {mode});
  6679. me._layers.sort(compare2Level('z', '_idx'));
  6680. if (me._lastEvent) {
  6681. me._eventHandler(me._lastEvent, true);
  6682. }
  6683. me.render();
  6684. }
  6685. _updateLayout(minPadding) {
  6686. const me = this;
  6687. if (me.notifyPlugins('beforeLayout', {cancelable: true}) === false) {
  6688. return;
  6689. }
  6690. layouts.update(me, me.width, me.height, minPadding);
  6691. const area = me.chartArea;
  6692. const noArea = area.width <= 0 || area.height <= 0;
  6693. me._layers = [];
  6694. each(me.boxes, (box) => {
  6695. if (noArea && box.position === 'chartArea') {
  6696. return;
  6697. }
  6698. if (box.configure) {
  6699. box.configure();
  6700. }
  6701. me._layers.push(...box._layers());
  6702. }, me);
  6703. me._layers.forEach((item, index) => {
  6704. item._idx = index;
  6705. });
  6706. me.notifyPlugins('afterLayout');
  6707. }
  6708. _updateDatasets(mode) {
  6709. const me = this;
  6710. const isFunction = typeof mode === 'function';
  6711. if (me.notifyPlugins('beforeDatasetsUpdate', {mode, cancelable: true}) === false) {
  6712. return;
  6713. }
  6714. for (let i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  6715. me._updateDataset(i, isFunction ? mode({datasetIndex: i}) : mode);
  6716. }
  6717. me.notifyPlugins('afterDatasetsUpdate', {mode});
  6718. }
  6719. _updateDataset(index, mode) {
  6720. const me = this;
  6721. const meta = me.getDatasetMeta(index);
  6722. const args = {meta, index, mode, cancelable: true};
  6723. if (me.notifyPlugins('beforeDatasetUpdate', args) === false) {
  6724. return;
  6725. }
  6726. meta.controller._update(mode);
  6727. args.cancelable = false;
  6728. me.notifyPlugins('afterDatasetUpdate', args);
  6729. }
  6730. render() {
  6731. const me = this;
  6732. if (me.notifyPlugins('beforeRender', {cancelable: true}) === false) {
  6733. return;
  6734. }
  6735. if (animator.has(me)) {
  6736. if (me.attached && !animator.running(me)) {
  6737. animator.start(me);
  6738. }
  6739. } else {
  6740. me.draw();
  6741. onAnimationsComplete({chart: me});
  6742. }
  6743. }
  6744. draw() {
  6745. const me = this;
  6746. let i;
  6747. if (me._resizeBeforeDraw) {
  6748. const {width, height} = me._resizeBeforeDraw;
  6749. me._resize(width, height);
  6750. me._resizeBeforeDraw = null;
  6751. }
  6752. me.clear();
  6753. if (me.width <= 0 || me.height <= 0) {
  6754. return;
  6755. }
  6756. if (me.notifyPlugins('beforeDraw', {cancelable: true}) === false) {
  6757. return;
  6758. }
  6759. const layers = me._layers;
  6760. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  6761. layers[i].draw(me.chartArea);
  6762. }
  6763. me._drawDatasets();
  6764. for (; i < layers.length; ++i) {
  6765. layers[i].draw(me.chartArea);
  6766. }
  6767. me.notifyPlugins('afterDraw');
  6768. }
  6769. _getSortedDatasetMetas(filterVisible) {
  6770. const me = this;
  6771. const metasets = me._sortedMetasets;
  6772. const result = [];
  6773. let i, ilen;
  6774. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  6775. const meta = metasets[i];
  6776. if (!filterVisible || meta.visible) {
  6777. result.push(meta);
  6778. }
  6779. }
  6780. return result;
  6781. }
  6782. getSortedVisibleDatasetMetas() {
  6783. return this._getSortedDatasetMetas(true);
  6784. }
  6785. _drawDatasets() {
  6786. const me = this;
  6787. if (me.notifyPlugins('beforeDatasetsDraw', {cancelable: true}) === false) {
  6788. return;
  6789. }
  6790. const metasets = me.getSortedVisibleDatasetMetas();
  6791. for (let i = metasets.length - 1; i >= 0; --i) {
  6792. me._drawDataset(metasets[i]);
  6793. }
  6794. me.notifyPlugins('afterDatasetsDraw');
  6795. }
  6796. _drawDataset(meta) {
  6797. const me = this;
  6798. const ctx = me.ctx;
  6799. const clip = meta._clip;
  6800. const area = me.chartArea;
  6801. const args = {
  6802. meta,
  6803. index: meta.index,
  6804. cancelable: true
  6805. };
  6806. if (me.notifyPlugins('beforeDatasetDraw', args) === false) {
  6807. return;
  6808. }
  6809. clipArea(ctx, {
  6810. left: clip.left === false ? 0 : area.left - clip.left,
  6811. right: clip.right === false ? me.width : area.right + clip.right,
  6812. top: clip.top === false ? 0 : area.top - clip.top,
  6813. bottom: clip.bottom === false ? me.height : area.bottom + clip.bottom
  6814. });
  6815. meta.controller.draw();
  6816. unclipArea(ctx);
  6817. args.cancelable = false;
  6818. me.notifyPlugins('afterDatasetDraw', args);
  6819. }
  6820. getElementsAtEventForMode(e, mode, options, useFinalPosition) {
  6821. const method = Interaction.modes[mode];
  6822. if (typeof method === 'function') {
  6823. return method(this, e, options, useFinalPosition);
  6824. }
  6825. return [];
  6826. }
  6827. getDatasetMeta(datasetIndex) {
  6828. const me = this;
  6829. const dataset = me.data.datasets[datasetIndex];
  6830. const metasets = me._metasets;
  6831. let meta = metasets.filter(x => x && x._dataset === dataset).pop();
  6832. if (!meta) {
  6833. meta = metasets[datasetIndex] = {
  6834. type: null,
  6835. data: [],
  6836. dataset: null,
  6837. controller: null,
  6838. hidden: null,
  6839. xAxisID: null,
  6840. yAxisID: null,
  6841. order: dataset && dataset.order || 0,
  6842. index: datasetIndex,
  6843. _dataset: dataset,
  6844. _parsed: [],
  6845. _sorted: false
  6846. };
  6847. }
  6848. return meta;
  6849. }
  6850. getContext() {
  6851. return this.$context || (this.$context = {chart: this, type: 'chart'});
  6852. }
  6853. getVisibleDatasetCount() {
  6854. return this.getSortedVisibleDatasetMetas().length;
  6855. }
  6856. isDatasetVisible(datasetIndex) {
  6857. const dataset = this.data.datasets[datasetIndex];
  6858. if (!dataset) {
  6859. return false;
  6860. }
  6861. const meta = this.getDatasetMeta(datasetIndex);
  6862. return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden;
  6863. }
  6864. setDatasetVisibility(datasetIndex, visible) {
  6865. const meta = this.getDatasetMeta(datasetIndex);
  6866. meta.hidden = !visible;
  6867. }
  6868. toggleDataVisibility(index) {
  6869. this._hiddenIndices[index] = !this._hiddenIndices[index];
  6870. }
  6871. getDataVisibility(index) {
  6872. return !this._hiddenIndices[index];
  6873. }
  6874. _updateDatasetVisibility(datasetIndex, visible) {
  6875. const me = this;
  6876. const mode = visible ? 'show' : 'hide';
  6877. const meta = me.getDatasetMeta(datasetIndex);
  6878. const anims = meta.controller._resolveAnimations(undefined, mode);
  6879. me.setDatasetVisibility(datasetIndex, visible);
  6880. anims.update(meta, {visible});
  6881. me.update((ctx) => ctx.datasetIndex === datasetIndex ? mode : undefined);
  6882. }
  6883. hide(datasetIndex) {
  6884. this._updateDatasetVisibility(datasetIndex, false);
  6885. }
  6886. show(datasetIndex) {
  6887. this._updateDatasetVisibility(datasetIndex, true);
  6888. }
  6889. _destroyDatasetMeta(datasetIndex) {
  6890. const me = this;
  6891. const meta = me._metasets && me._metasets[datasetIndex];
  6892. if (meta && meta.controller) {
  6893. meta.controller._destroy();
  6894. delete me._metasets[datasetIndex];
  6895. }
  6896. }
  6897. destroy() {
  6898. const me = this;
  6899. const {canvas, ctx} = me;
  6900. let i, ilen;
  6901. me.stop();
  6902. animator.remove(me);
  6903. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  6904. me._destroyDatasetMeta(i);
  6905. }
  6906. me.config.clearCache();
  6907. if (canvas) {
  6908. me.unbindEvents();
  6909. clearCanvas(canvas, ctx);
  6910. me.platform.releaseContext(ctx);
  6911. me.canvas = null;
  6912. me.ctx = null;
  6913. }
  6914. me.notifyPlugins('destroy');
  6915. delete instances[me.id];
  6916. }
  6917. toBase64Image(...args) {
  6918. return this.canvas.toDataURL(...args);
  6919. }
  6920. bindEvents() {
  6921. const me = this;
  6922. const listeners = me._listeners;
  6923. const platform = me.platform;
  6924. const _add = (type, listener) => {
  6925. platform.addEventListener(me, type, listener);
  6926. listeners[type] = listener;
  6927. };
  6928. const _remove = (type, listener) => {
  6929. if (listeners[type]) {
  6930. platform.removeEventListener(me, type, listener);
  6931. delete listeners[type];
  6932. }
  6933. };
  6934. let listener = function(e, x, y) {
  6935. e.offsetX = x;
  6936. e.offsetY = y;
  6937. me._eventHandler(e);
  6938. };
  6939. each(me.options.events, (type) => _add(type, listener));
  6940. if (me.options.responsive) {
  6941. listener = (width, height) => {
  6942. if (me.canvas) {
  6943. me.resize(width, height);
  6944. }
  6945. };
  6946. let detached;
  6947. const attached = () => {
  6948. _remove('attach', attached);
  6949. me.attached = true;
  6950. me.resize();
  6951. _add('resize', listener);
  6952. _add('detach', detached);
  6953. };
  6954. detached = () => {
  6955. me.attached = false;
  6956. _remove('resize', listener);
  6957. _add('attach', attached);
  6958. };
  6959. if (platform.isAttached(me.canvas)) {
  6960. attached();
  6961. } else {
  6962. detached();
  6963. }
  6964. } else {
  6965. me.attached = true;
  6966. }
  6967. }
  6968. unbindEvents() {
  6969. const me = this;
  6970. const listeners = me._listeners;
  6971. if (!listeners) {
  6972. return;
  6973. }
  6974. me._listeners = {};
  6975. each(listeners, (listener, type) => {
  6976. me.platform.removeEventListener(me, type, listener);
  6977. });
  6978. }
  6979. updateHoverStyle(items, mode, enabled) {
  6980. const prefix = enabled ? 'set' : 'remove';
  6981. let meta, item, i, ilen;
  6982. if (mode === 'dataset') {
  6983. meta = this.getDatasetMeta(items[0].datasetIndex);
  6984. meta.controller['_' + prefix + 'DatasetHoverStyle']();
  6985. }
  6986. for (i = 0, ilen = items.length; i < ilen; ++i) {
  6987. item = items[i];
  6988. const controller = item && this.getDatasetMeta(item.datasetIndex).controller;
  6989. if (controller) {
  6990. controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
  6991. }
  6992. }
  6993. }
  6994. getActiveElements() {
  6995. return this._active || [];
  6996. }
  6997. setActiveElements(activeElements) {
  6998. const me = this;
  6999. const lastActive = me._active || [];
  7000. const active = activeElements.map(({datasetIndex, index}) => {
  7001. const meta = me.getDatasetMeta(datasetIndex);
  7002. if (!meta) {
  7003. throw new Error('No dataset found at index ' + datasetIndex);
  7004. }
  7005. return {
  7006. datasetIndex,
  7007. element: meta.data[index],
  7008. index,
  7009. };
  7010. });
  7011. const changed = !_elementsEqual(active, lastActive);
  7012. if (changed) {
  7013. me._active = active;
  7014. me._updateHoverStyles(active, lastActive);
  7015. }
  7016. }
  7017. notifyPlugins(hook, args, filter) {
  7018. return this._plugins.notify(this, hook, args, filter);
  7019. }
  7020. _updateHoverStyles(active, lastActive, replay) {
  7021. const me = this;
  7022. const hoverOptions = me.options.hover;
  7023. const diff = (a, b) => a.filter(x => !b.some(y => x.datasetIndex === y.datasetIndex && x.index === y.index));
  7024. const deactivated = diff(lastActive, active);
  7025. const activated = replay ? active : diff(active, lastActive);
  7026. if (deactivated.length) {
  7027. me.updateHoverStyle(deactivated, hoverOptions.mode, false);
  7028. }
  7029. if (activated.length && hoverOptions.mode) {
  7030. me.updateHoverStyle(activated, hoverOptions.mode, true);
  7031. }
  7032. }
  7033. _eventHandler(e, replay) {
  7034. const me = this;
  7035. const args = {event: e, replay, cancelable: true};
  7036. const eventFilter = (plugin) => (plugin.options.events || this.options.events).includes(e.type);
  7037. if (me.notifyPlugins('beforeEvent', args, eventFilter) === false) {
  7038. return;
  7039. }
  7040. const changed = me._handleEvent(e, replay);
  7041. args.cancelable = false;
  7042. me.notifyPlugins('afterEvent', args, eventFilter);
  7043. if (changed || args.changed) {
  7044. me.render();
  7045. }
  7046. return me;
  7047. }
  7048. _handleEvent(e, replay) {
  7049. const me = this;
  7050. const {_active: lastActive = [], options} = me;
  7051. const hoverOptions = options.hover;
  7052. const useFinalPosition = replay;
  7053. let active = [];
  7054. let changed = false;
  7055. let lastEvent = null;
  7056. if (e.type !== 'mouseout') {
  7057. active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition);
  7058. lastEvent = e.type === 'click' ? me._lastEvent : e;
  7059. }
  7060. me._lastEvent = null;
  7061. if (_isPointInArea(e, me.chartArea, me._minPadding)) {
  7062. callback(options.onHover, [e, active, me], me);
  7063. if (e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu') {
  7064. callback(options.onClick, [e, active, me], me);
  7065. }
  7066. }
  7067. changed = !_elementsEqual(active, lastActive);
  7068. if (changed || replay) {
  7069. me._active = active;
  7070. me._updateHoverStyles(active, lastActive, replay);
  7071. }
  7072. me._lastEvent = lastEvent;
  7073. return changed;
  7074. }
  7075. }
  7076. const invalidatePlugins = () => each(Chart.instances, (chart) => chart._plugins.invalidate());
  7077. const enumerable = true;
  7078. Object.defineProperties(Chart, {
  7079. defaults: {
  7080. enumerable,
  7081. value: defaults
  7082. },
  7083. instances: {
  7084. enumerable,
  7085. value: instances
  7086. },
  7087. overrides: {
  7088. enumerable,
  7089. value: overrides
  7090. },
  7091. registry: {
  7092. enumerable,
  7093. value: registry
  7094. },
  7095. version: {
  7096. enumerable,
  7097. value: version
  7098. },
  7099. getChart: {
  7100. enumerable,
  7101. value: getChart
  7102. },
  7103. register: {
  7104. enumerable,
  7105. value: (...items) => {
  7106. registry.add(...items);
  7107. invalidatePlugins();
  7108. }
  7109. },
  7110. unregister: {
  7111. enumerable,
  7112. value: (...items) => {
  7113. registry.remove(...items);
  7114. invalidatePlugins();
  7115. }
  7116. }
  7117. });
  7118. function abstract() {
  7119. throw new Error('This method is not implemented: either no adapter can be found or an incomplete integration was provided.');
  7120. }
  7121. class DateAdapter {
  7122. constructor(options) {
  7123. this.options = options || {};
  7124. }
  7125. formats() {
  7126. return abstract();
  7127. }
  7128. parse(value, format) {
  7129. return abstract();
  7130. }
  7131. format(timestamp, format) {
  7132. return abstract();
  7133. }
  7134. add(timestamp, amount, unit) {
  7135. return abstract();
  7136. }
  7137. diff(a, b, unit) {
  7138. return abstract();
  7139. }
  7140. startOf(timestamp, unit, weekday) {
  7141. return abstract();
  7142. }
  7143. endOf(timestamp, unit) {
  7144. return abstract();
  7145. }
  7146. }
  7147. DateAdapter.override = function(members) {
  7148. Object.assign(DateAdapter.prototype, members);
  7149. };
  7150. var _adapters = {
  7151. _date: DateAdapter
  7152. };
  7153. function getAllScaleValues(scale) {
  7154. if (!scale._cache.$bar) {
  7155. const metas = scale.getMatchingVisibleMetas('bar');
  7156. let values = [];
  7157. for (let i = 0, ilen = metas.length; i < ilen; i++) {
  7158. values = values.concat(metas[i].controller.getAllParsedValues(scale));
  7159. }
  7160. scale._cache.$bar = _arrayUnique(values.sort((a, b) => a - b));
  7161. }
  7162. return scale._cache.$bar;
  7163. }
  7164. function computeMinSampleSize(scale) {
  7165. const values = getAllScaleValues(scale);
  7166. let min = scale._length;
  7167. let i, ilen, curr, prev;
  7168. const updateMinAndPrev = () => {
  7169. if (curr === 32767 || curr === -32768) {
  7170. return;
  7171. }
  7172. if (defined(prev)) {
  7173. min = Math.min(min, Math.abs(curr - prev) || min);
  7174. }
  7175. prev = curr;
  7176. };
  7177. for (i = 0, ilen = values.length; i < ilen; ++i) {
  7178. curr = scale.getPixelForValue(values[i]);
  7179. updateMinAndPrev();
  7180. }
  7181. prev = undefined;
  7182. for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) {
  7183. curr = scale.getPixelForTick(i);
  7184. updateMinAndPrev();
  7185. }
  7186. return min;
  7187. }
  7188. function computeFitCategoryTraits(index, ruler, options, stackCount) {
  7189. const thickness = options.barThickness;
  7190. let size, ratio;
  7191. if (isNullOrUndef(thickness)) {
  7192. size = ruler.min * options.categoryPercentage;
  7193. ratio = options.barPercentage;
  7194. } else {
  7195. size = thickness * stackCount;
  7196. ratio = 1;
  7197. }
  7198. return {
  7199. chunk: size / stackCount,
  7200. ratio,
  7201. start: ruler.pixels[index] - (size / 2)
  7202. };
  7203. }
  7204. function computeFlexCategoryTraits(index, ruler, options, stackCount) {
  7205. const pixels = ruler.pixels;
  7206. const curr = pixels[index];
  7207. let prev = index > 0 ? pixels[index - 1] : null;
  7208. let next = index < pixels.length - 1 ? pixels[index + 1] : null;
  7209. const percent = options.categoryPercentage;
  7210. if (prev === null) {
  7211. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  7212. }
  7213. if (next === null) {
  7214. next = curr + curr - prev;
  7215. }
  7216. const start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  7217. const size = Math.abs(next - prev) / 2 * percent;
  7218. return {
  7219. chunk: size / stackCount,
  7220. ratio: options.barPercentage,
  7221. start
  7222. };
  7223. }
  7224. function parseFloatBar(entry, item, vScale, i) {
  7225. const startValue = vScale.parse(entry[0], i);
  7226. const endValue = vScale.parse(entry[1], i);
  7227. const min = Math.min(startValue, endValue);
  7228. const max = Math.max(startValue, endValue);
  7229. let barStart = min;
  7230. let barEnd = max;
  7231. if (Math.abs(min) > Math.abs(max)) {
  7232. barStart = max;
  7233. barEnd = min;
  7234. }
  7235. item[vScale.axis] = barEnd;
  7236. item._custom = {
  7237. barStart,
  7238. barEnd,
  7239. start: startValue,
  7240. end: endValue,
  7241. min,
  7242. max
  7243. };
  7244. }
  7245. function parseValue(entry, item, vScale, i) {
  7246. if (isArray(entry)) {
  7247. parseFloatBar(entry, item, vScale, i);
  7248. } else {
  7249. item[vScale.axis] = vScale.parse(entry, i);
  7250. }
  7251. return item;
  7252. }
  7253. function parseArrayOrPrimitive(meta, data, start, count) {
  7254. const iScale = meta.iScale;
  7255. const vScale = meta.vScale;
  7256. const labels = iScale.getLabels();
  7257. const singleScale = iScale === vScale;
  7258. const parsed = [];
  7259. let i, ilen, item, entry;
  7260. for (i = start, ilen = start + count; i < ilen; ++i) {
  7261. entry = data[i];
  7262. item = {};
  7263. item[iScale.axis] = singleScale || iScale.parse(labels[i], i);
  7264. parsed.push(parseValue(entry, item, vScale, i));
  7265. }
  7266. return parsed;
  7267. }
  7268. function isFloatBar(custom) {
  7269. return custom && custom.barStart !== undefined && custom.barEnd !== undefined;
  7270. }
  7271. class BarController extends DatasetController {
  7272. parsePrimitiveData(meta, data, start, count) {
  7273. return parseArrayOrPrimitive(meta, data, start, count);
  7274. }
  7275. parseArrayData(meta, data, start, count) {
  7276. return parseArrayOrPrimitive(meta, data, start, count);
  7277. }
  7278. parseObjectData(meta, data, start, count) {
  7279. const {iScale, vScale} = meta;
  7280. const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;
  7281. const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey;
  7282. const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey;
  7283. const parsed = [];
  7284. let i, ilen, item, obj;
  7285. for (i = start, ilen = start + count; i < ilen; ++i) {
  7286. obj = data[i];
  7287. item = {};
  7288. item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i);
  7289. parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i));
  7290. }
  7291. return parsed;
  7292. }
  7293. updateRangeFromParsed(range, scale, parsed, stack) {
  7294. super.updateRangeFromParsed(range, scale, parsed, stack);
  7295. const custom = parsed._custom;
  7296. if (custom && scale === this._cachedMeta.vScale) {
  7297. range.min = Math.min(range.min, custom.min);
  7298. range.max = Math.max(range.max, custom.max);
  7299. }
  7300. }
  7301. getLabelAndValue(index) {
  7302. const me = this;
  7303. const meta = me._cachedMeta;
  7304. const {iScale, vScale} = meta;
  7305. const parsed = me.getParsed(index);
  7306. const custom = parsed._custom;
  7307. const value = isFloatBar(custom)
  7308. ? '[' + custom.start + ', ' + custom.end + ']'
  7309. : '' + vScale.getLabelForValue(parsed[vScale.axis]);
  7310. return {
  7311. label: '' + iScale.getLabelForValue(parsed[iScale.axis]),
  7312. value
  7313. };
  7314. }
  7315. initialize() {
  7316. const me = this;
  7317. me.enableOptionSharing = true;
  7318. super.initialize();
  7319. const meta = me._cachedMeta;
  7320. meta.stack = me.getDataset().stack;
  7321. }
  7322. update(mode) {
  7323. const me = this;
  7324. const meta = me._cachedMeta;
  7325. me.updateElements(meta.data, 0, meta.data.length, mode);
  7326. }
  7327. updateElements(bars, start, count, mode) {
  7328. const me = this;
  7329. const reset = mode === 'reset';
  7330. const vScale = me._cachedMeta.vScale;
  7331. const base = vScale.getBasePixel();
  7332. const horizontal = vScale.isHorizontal();
  7333. const ruler = me._getRuler();
  7334. const firstOpts = me.resolveDataElementOptions(start, mode);
  7335. const sharedOptions = me.getSharedOptions(firstOpts);
  7336. const includeOptions = me.includeOptions(mode, sharedOptions);
  7337. me.updateSharedOptions(sharedOptions, mode, firstOpts);
  7338. for (let i = start; i < start + count; i++) {
  7339. const parsed = me.getParsed(i);
  7340. const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {base, head: base} : me._calculateBarValuePixels(i);
  7341. const ipixels = me._calculateBarIndexPixels(i, ruler);
  7342. const stack = (parsed._stacks || {})[vScale.axis];
  7343. const properties = {
  7344. horizontal,
  7345. base: vpixels.base,
  7346. enableBorderRadius: !stack || isFloatBar(parsed._custom) || (me.index === stack._top || me.index === stack._bottom),
  7347. x: horizontal ? vpixels.head : ipixels.center,
  7348. y: horizontal ? ipixels.center : vpixels.head,
  7349. height: horizontal ? ipixels.size : undefined,
  7350. width: horizontal ? undefined : ipixels.size
  7351. };
  7352. if (includeOptions) {
  7353. properties.options = sharedOptions || me.resolveDataElementOptions(i, mode);
  7354. }
  7355. me.updateElement(bars[i], i, properties, mode);
  7356. }
  7357. }
  7358. _getStacks(last, dataIndex) {
  7359. const me = this;
  7360. const meta = me._cachedMeta;
  7361. const iScale = meta.iScale;
  7362. const metasets = iScale.getMatchingVisibleMetas(me._type);
  7363. const stacked = iScale.options.stacked;
  7364. const ilen = metasets.length;
  7365. const stacks = [];
  7366. let i, item;
  7367. for (i = 0; i < ilen; ++i) {
  7368. item = metasets[i];
  7369. if (typeof dataIndex !== 'undefined') {
  7370. const val = item.controller.getParsed(dataIndex)[
  7371. item.controller._cachedMeta.vScale.axis
  7372. ];
  7373. if (isNullOrUndef(val) || isNaN(val)) {
  7374. continue;
  7375. }
  7376. }
  7377. if (stacked === false || stacks.indexOf(item.stack) === -1 ||
  7378. (stacked === undefined && item.stack === undefined)) {
  7379. stacks.push(item.stack);
  7380. }
  7381. if (item.index === last) {
  7382. break;
  7383. }
  7384. }
  7385. if (!stacks.length) {
  7386. stacks.push(undefined);
  7387. }
  7388. return stacks;
  7389. }
  7390. _getStackCount(index) {
  7391. return this._getStacks(undefined, index).length;
  7392. }
  7393. _getStackIndex(datasetIndex, name, dataIndex) {
  7394. const stacks = this._getStacks(datasetIndex, dataIndex);
  7395. const index = (name !== undefined)
  7396. ? stacks.indexOf(name)
  7397. : -1;
  7398. return (index === -1)
  7399. ? stacks.length - 1
  7400. : index;
  7401. }
  7402. _getRuler() {
  7403. const me = this;
  7404. const opts = me.options;
  7405. const meta = me._cachedMeta;
  7406. const iScale = meta.iScale;
  7407. const pixels = [];
  7408. let i, ilen;
  7409. for (i = 0, ilen = meta.data.length; i < ilen; ++i) {
  7410. pixels.push(iScale.getPixelForValue(me.getParsed(i)[iScale.axis], i));
  7411. }
  7412. const barThickness = opts.barThickness;
  7413. const min = barThickness || computeMinSampleSize(iScale);
  7414. return {
  7415. min,
  7416. pixels,
  7417. start: iScale._startPixel,
  7418. end: iScale._endPixel,
  7419. stackCount: me._getStackCount(),
  7420. scale: iScale,
  7421. grouped: opts.grouped,
  7422. ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage
  7423. };
  7424. }
  7425. _calculateBarValuePixels(index) {
  7426. const me = this;
  7427. const {vScale, _stacked} = me._cachedMeta;
  7428. const {base: baseValue, minBarLength} = me.options;
  7429. const parsed = me.getParsed(index);
  7430. const custom = parsed._custom;
  7431. const floating = isFloatBar(custom);
  7432. let value = parsed[vScale.axis];
  7433. let start = 0;
  7434. let length = _stacked ? me.applyStack(vScale, parsed, _stacked) : value;
  7435. let head, size;
  7436. if (length !== value) {
  7437. start = length - value;
  7438. length = value;
  7439. }
  7440. if (floating) {
  7441. value = custom.barStart;
  7442. length = custom.barEnd - custom.barStart;
  7443. if (value !== 0 && sign(value) !== sign(custom.barEnd)) {
  7444. start = 0;
  7445. }
  7446. start += value;
  7447. }
  7448. const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start;
  7449. let base = vScale.getPixelForValue(startValue);
  7450. if (this.chart.getDataVisibility(index)) {
  7451. head = vScale.getPixelForValue(start + length);
  7452. } else {
  7453. head = base;
  7454. }
  7455. size = head - base;
  7456. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  7457. size = size < 0 ? -minBarLength : minBarLength;
  7458. if (value === 0) {
  7459. base -= size / 2;
  7460. }
  7461. head = base + size;
  7462. }
  7463. const actualBase = baseValue || 0;
  7464. if (base === vScale.getPixelForValue(actualBase)) {
  7465. const halfGrid = vScale.getLineWidthForValue(actualBase) / 2;
  7466. if (size > 0) {
  7467. base += halfGrid;
  7468. size -= halfGrid;
  7469. } else if (size < 0) {
  7470. base -= halfGrid;
  7471. size += halfGrid;
  7472. }
  7473. }
  7474. return {
  7475. size,
  7476. base,
  7477. head,
  7478. center: head + size / 2
  7479. };
  7480. }
  7481. _calculateBarIndexPixels(index, ruler) {
  7482. const me = this;
  7483. const scale = ruler.scale;
  7484. const options = me.options;
  7485. const skipNull = options.skipNull;
  7486. const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity);
  7487. let center, size;
  7488. if (ruler.grouped) {
  7489. const stackCount = skipNull ? me._getStackCount(index) : ruler.stackCount;
  7490. const range = options.barThickness === 'flex'
  7491. ? computeFlexCategoryTraits(index, ruler, options, stackCount)
  7492. : computeFitCategoryTraits(index, ruler, options, stackCount);
  7493. const stackIndex = me._getStackIndex(me.index, me._cachedMeta.stack, skipNull ? index : undefined);
  7494. center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  7495. size = Math.min(maxBarThickness, range.chunk * range.ratio);
  7496. } else {
  7497. center = scale.getPixelForValue(me.getParsed(index)[scale.axis], index);
  7498. size = Math.min(maxBarThickness, ruler.min * ruler.ratio);
  7499. }
  7500. return {
  7501. base: center - size / 2,
  7502. head: center + size / 2,
  7503. center,
  7504. size
  7505. };
  7506. }
  7507. draw() {
  7508. const me = this;
  7509. const chart = me.chart;
  7510. const meta = me._cachedMeta;
  7511. const vScale = meta.vScale;
  7512. const rects = meta.data;
  7513. const ilen = rects.length;
  7514. let i = 0;
  7515. clipArea(chart.ctx, chart.chartArea);
  7516. for (; i < ilen; ++i) {
  7517. if (me.getParsed(i)[vScale.axis] !== null) {
  7518. rects[i].draw(me._ctx);
  7519. }
  7520. }
  7521. unclipArea(chart.ctx);
  7522. }
  7523. }
  7524. BarController.id = 'bar';
  7525. BarController.defaults = {
  7526. datasetElementType: false,
  7527. dataElementType: 'bar',
  7528. categoryPercentage: 0.8,
  7529. barPercentage: 0.9,
  7530. grouped: true,
  7531. animations: {
  7532. numbers: {
  7533. type: 'number',
  7534. properties: ['x', 'y', 'base', 'width', 'height']
  7535. }
  7536. }
  7537. };
  7538. BarController.overrides = {
  7539. interaction: {
  7540. mode: 'index'
  7541. },
  7542. scales: {
  7543. _index_: {
  7544. type: 'category',
  7545. offset: true,
  7546. grid: {
  7547. offset: true
  7548. }
  7549. },
  7550. _value_: {
  7551. type: 'linear',
  7552. beginAtZero: true,
  7553. }
  7554. }
  7555. };
  7556. class BubbleController extends DatasetController {
  7557. initialize() {
  7558. this.enableOptionSharing = true;
  7559. super.initialize();
  7560. }
  7561. parseObjectData(meta, data, start, count) {
  7562. const {xScale, yScale} = meta;
  7563. const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing;
  7564. const parsed = [];
  7565. let i, ilen, item;
  7566. for (i = start, ilen = start + count; i < ilen; ++i) {
  7567. item = data[i];
  7568. parsed.push({
  7569. x: xScale.parse(resolveObjectKey(item, xAxisKey), i),
  7570. y: yScale.parse(resolveObjectKey(item, yAxisKey), i),
  7571. _custom: item && item.r && +item.r
  7572. });
  7573. }
  7574. return parsed;
  7575. }
  7576. getMaxOverflow() {
  7577. const {data, _parsed} = this._cachedMeta;
  7578. let max = 0;
  7579. for (let i = data.length - 1; i >= 0; --i) {
  7580. max = Math.max(max, data[i].size() / 2, _parsed[i]._custom);
  7581. }
  7582. return max > 0 && max;
  7583. }
  7584. getLabelAndValue(index) {
  7585. const me = this;
  7586. const meta = me._cachedMeta;
  7587. const {xScale, yScale} = meta;
  7588. const parsed = me.getParsed(index);
  7589. const x = xScale.getLabelForValue(parsed.x);
  7590. const y = yScale.getLabelForValue(parsed.y);
  7591. const r = parsed._custom;
  7592. return {
  7593. label: meta.label,
  7594. value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')'
  7595. };
  7596. }
  7597. update(mode) {
  7598. const me = this;
  7599. const points = me._cachedMeta.data;
  7600. me.updateElements(points, 0, points.length, mode);
  7601. }
  7602. updateElements(points, start, count, mode) {
  7603. const me = this;
  7604. const reset = mode === 'reset';
  7605. const {xScale, yScale} = me._cachedMeta;
  7606. const firstOpts = me.resolveDataElementOptions(start, mode);
  7607. const sharedOptions = me.getSharedOptions(firstOpts);
  7608. const includeOptions = me.includeOptions(mode, sharedOptions);
  7609. for (let i = start; i < start + count; i++) {
  7610. const point = points[i];
  7611. const parsed = !reset && me.getParsed(i);
  7612. const x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(parsed.x);
  7613. const y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(parsed.y);
  7614. const properties = {
  7615. x,
  7616. y,
  7617. skip: isNaN(x) || isNaN(y)
  7618. };
  7619. if (includeOptions) {
  7620. properties.options = me.resolveDataElementOptions(i, mode);
  7621. if (reset) {
  7622. properties.options.radius = 0;
  7623. }
  7624. }
  7625. me.updateElement(point, i, properties, mode);
  7626. }
  7627. me.updateSharedOptions(sharedOptions, mode, firstOpts);
  7628. }
  7629. resolveDataElementOptions(index, mode) {
  7630. const parsed = this.getParsed(index);
  7631. let values = super.resolveDataElementOptions(index, mode);
  7632. if (values.$shared) {
  7633. values = Object.assign({}, values, {$shared: false});
  7634. }
  7635. const radius = values.radius;
  7636. if (mode !== 'active') {
  7637. values.radius = 0;
  7638. }
  7639. values.radius += valueOrDefault(parsed && parsed._custom, radius);
  7640. return values;
  7641. }
  7642. }
  7643. BubbleController.id = 'bubble';
  7644. BubbleController.defaults = {
  7645. datasetElementType: false,
  7646. dataElementType: 'point',
  7647. animations: {
  7648. numbers: {
  7649. type: 'number',
  7650. properties: ['x', 'y', 'borderWidth', 'radius']
  7651. }
  7652. }
  7653. };
  7654. BubbleController.overrides = {
  7655. scales: {
  7656. x: {
  7657. type: 'linear'
  7658. },
  7659. y: {
  7660. type: 'linear'
  7661. }
  7662. },
  7663. plugins: {
  7664. tooltip: {
  7665. callbacks: {
  7666. title() {
  7667. return '';
  7668. }
  7669. }
  7670. }
  7671. }
  7672. };
  7673. function getRatioAndOffset(rotation, circumference, cutout) {
  7674. let ratioX = 1;
  7675. let ratioY = 1;
  7676. let offsetX = 0;
  7677. let offsetY = 0;
  7678. if (circumference < TAU) {
  7679. const startAngle = rotation;
  7680. const endAngle = startAngle + circumference;
  7681. const startX = Math.cos(startAngle);
  7682. const startY = Math.sin(startAngle);
  7683. const endX = Math.cos(endAngle);
  7684. const endY = Math.sin(endAngle);
  7685. const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle) ? 1 : Math.max(a, a * cutout, b, b * cutout);
  7686. const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle) ? -1 : Math.min(a, a * cutout, b, b * cutout);
  7687. const maxX = calcMax(0, startX, endX);
  7688. const maxY = calcMax(HALF_PI, startY, endY);
  7689. const minX = calcMin(PI, startX, endX);
  7690. const minY = calcMin(PI + HALF_PI, startY, endY);
  7691. ratioX = (maxX - minX) / 2;
  7692. ratioY = (maxY - minY) / 2;
  7693. offsetX = -(maxX + minX) / 2;
  7694. offsetY = -(maxY + minY) / 2;
  7695. }
  7696. return {ratioX, ratioY, offsetX, offsetY};
  7697. }
  7698. class DoughnutController extends DatasetController {
  7699. constructor(chart, datasetIndex) {
  7700. super(chart, datasetIndex);
  7701. this.enableOptionSharing = true;
  7702. this.innerRadius = undefined;
  7703. this.outerRadius = undefined;
  7704. this.offsetX = undefined;
  7705. this.offsetY = undefined;
  7706. }
  7707. linkScales() {}
  7708. parse(start, count) {
  7709. const data = this.getDataset().data;
  7710. const meta = this._cachedMeta;
  7711. let i, ilen;
  7712. for (i = start, ilen = start + count; i < ilen; ++i) {
  7713. meta._parsed[i] = +data[i];
  7714. }
  7715. }
  7716. _getRotation() {
  7717. return toRadians(this.options.rotation - 90);
  7718. }
  7719. _getCircumference() {
  7720. return toRadians(this.options.circumference);
  7721. }
  7722. _getRotationExtents() {
  7723. let min = TAU;
  7724. let max = -TAU;
  7725. const me = this;
  7726. for (let i = 0; i < me.chart.data.datasets.length; ++i) {
  7727. if (me.chart.isDatasetVisible(i)) {
  7728. const controller = me.chart.getDatasetMeta(i).controller;
  7729. const rotation = controller._getRotation();
  7730. const circumference = controller._getCircumference();
  7731. min = Math.min(min, rotation);
  7732. max = Math.max(max, rotation + circumference);
  7733. }
  7734. }
  7735. return {
  7736. rotation: min,
  7737. circumference: max - min,
  7738. };
  7739. }
  7740. update(mode) {
  7741. const me = this;
  7742. const chart = me.chart;
  7743. const {chartArea} = chart;
  7744. const meta = me._cachedMeta;
  7745. const arcs = meta.data;
  7746. const spacing = me.getMaxBorderWidth() + me.getMaxOffset(arcs);
  7747. const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0);
  7748. const cutout = Math.min(toPercentage(me.options.cutout, maxSize), 1);
  7749. const chartWeight = me._getRingWeight(me.index);
  7750. const {circumference, rotation} = me._getRotationExtents();
  7751. const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout);
  7752. const maxWidth = (chartArea.width - spacing) / ratioX;
  7753. const maxHeight = (chartArea.height - spacing) / ratioY;
  7754. const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  7755. const outerRadius = toDimension(me.options.radius, maxRadius);
  7756. const innerRadius = Math.max(outerRadius * cutout, 0);
  7757. const radiusLength = (outerRadius - innerRadius) / me._getVisibleDatasetWeightTotal();
  7758. me.offsetX = offsetX * outerRadius;
  7759. me.offsetY = offsetY * outerRadius;
  7760. meta.total = me.calculateTotal();
  7761. me.outerRadius = outerRadius - radiusLength * me._getRingWeightOffset(me.index);
  7762. me.innerRadius = Math.max(me.outerRadius - radiusLength * chartWeight, 0);
  7763. me.updateElements(arcs, 0, arcs.length, mode);
  7764. }
  7765. _circumference(i, reset) {
  7766. const me = this;
  7767. const opts = me.options;
  7768. const meta = me._cachedMeta;
  7769. const circumference = me._getCircumference();
  7770. if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null) {
  7771. return 0;
  7772. }
  7773. return me.calculateCircumference(meta._parsed[i] * circumference / TAU);
  7774. }
  7775. updateElements(arcs, start, count, mode) {
  7776. const me = this;
  7777. const reset = mode === 'reset';
  7778. const chart = me.chart;
  7779. const chartArea = chart.chartArea;
  7780. const opts = chart.options;
  7781. const animationOpts = opts.animation;
  7782. const centerX = (chartArea.left + chartArea.right) / 2;
  7783. const centerY = (chartArea.top + chartArea.bottom) / 2;
  7784. const animateScale = reset && animationOpts.animateScale;
  7785. const innerRadius = animateScale ? 0 : me.innerRadius;
  7786. const outerRadius = animateScale ? 0 : me.outerRadius;
  7787. const firstOpts = me.resolveDataElementOptions(start, mode);
  7788. const sharedOptions = me.getSharedOptions(firstOpts);
  7789. const includeOptions = me.includeOptions(mode, sharedOptions);
  7790. let startAngle = me._getRotation();
  7791. let i;
  7792. for (i = 0; i < start; ++i) {
  7793. startAngle += me._circumference(i, reset);
  7794. }
  7795. for (i = start; i < start + count; ++i) {
  7796. const circumference = me._circumference(i, reset);
  7797. const arc = arcs[i];
  7798. const properties = {
  7799. x: centerX + me.offsetX,
  7800. y: centerY + me.offsetY,
  7801. startAngle,
  7802. endAngle: startAngle + circumference,
  7803. circumference,
  7804. outerRadius,
  7805. innerRadius
  7806. };
  7807. if (includeOptions) {
  7808. properties.options = sharedOptions || me.resolveDataElementOptions(i, mode);
  7809. }
  7810. startAngle += circumference;
  7811. me.updateElement(arc, i, properties, mode);
  7812. }
  7813. me.updateSharedOptions(sharedOptions, mode, firstOpts);
  7814. }
  7815. calculateTotal() {
  7816. const meta = this._cachedMeta;
  7817. const metaData = meta.data;
  7818. let total = 0;
  7819. let i;
  7820. for (i = 0; i < metaData.length; i++) {
  7821. const value = meta._parsed[i];
  7822. if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i)) {
  7823. total += Math.abs(value);
  7824. }
  7825. }
  7826. return total;
  7827. }
  7828. calculateCircumference(value) {
  7829. const total = this._cachedMeta.total;
  7830. if (total > 0 && !isNaN(value)) {
  7831. return TAU * (Math.abs(value) / total);
  7832. }
  7833. return 0;
  7834. }
  7835. getLabelAndValue(index) {
  7836. const me = this;
  7837. const meta = me._cachedMeta;
  7838. const chart = me.chart;
  7839. const labels = chart.data.labels || [];
  7840. const value = formatNumber(meta._parsed[index], chart.options.locale);
  7841. return {
  7842. label: labels[index] || '',
  7843. value,
  7844. };
  7845. }
  7846. getMaxBorderWidth(arcs) {
  7847. const me = this;
  7848. let max = 0;
  7849. const chart = me.chart;
  7850. let i, ilen, meta, controller, options;
  7851. if (!arcs) {
  7852. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  7853. if (chart.isDatasetVisible(i)) {
  7854. meta = chart.getDatasetMeta(i);
  7855. arcs = meta.data;
  7856. controller = meta.controller;
  7857. if (controller !== me) {
  7858. controller.configure();
  7859. }
  7860. break;
  7861. }
  7862. }
  7863. }
  7864. if (!arcs) {
  7865. return 0;
  7866. }
  7867. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  7868. options = controller.resolveDataElementOptions(i);
  7869. if (options.borderAlign !== 'inner') {
  7870. max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0);
  7871. }
  7872. }
  7873. return max;
  7874. }
  7875. getMaxOffset(arcs) {
  7876. let max = 0;
  7877. for (let i = 0, ilen = arcs.length; i < ilen; ++i) {
  7878. const options = this.resolveDataElementOptions(i);
  7879. max = Math.max(max, options.offset || 0, options.hoverOffset || 0);
  7880. }
  7881. return max;
  7882. }
  7883. _getRingWeightOffset(datasetIndex) {
  7884. let ringWeightOffset = 0;
  7885. for (let i = 0; i < datasetIndex; ++i) {
  7886. if (this.chart.isDatasetVisible(i)) {
  7887. ringWeightOffset += this._getRingWeight(i);
  7888. }
  7889. }
  7890. return ringWeightOffset;
  7891. }
  7892. _getRingWeight(datasetIndex) {
  7893. return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0);
  7894. }
  7895. _getVisibleDatasetWeightTotal() {
  7896. return this._getRingWeightOffset(this.chart.data.datasets.length) || 1;
  7897. }
  7898. }
  7899. DoughnutController.id = 'doughnut';
  7900. DoughnutController.defaults = {
  7901. datasetElementType: false,
  7902. dataElementType: 'arc',
  7903. animation: {
  7904. animateRotate: true,
  7905. animateScale: false
  7906. },
  7907. animations: {
  7908. numbers: {
  7909. type: 'number',
  7910. properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth']
  7911. },
  7912. },
  7913. cutout: '50%',
  7914. rotation: 0,
  7915. circumference: 360,
  7916. radius: '100%',
  7917. indexAxis: 'r',
  7918. };
  7919. DoughnutController.overrides = {
  7920. aspectRatio: 1,
  7921. plugins: {
  7922. legend: {
  7923. labels: {
  7924. generateLabels(chart) {
  7925. const data = chart.data;
  7926. if (data.labels.length && data.datasets.length) {
  7927. return data.labels.map((label, i) => {
  7928. const meta = chart.getDatasetMeta(0);
  7929. const style = meta.controller.getStyle(i);
  7930. return {
  7931. text: label,
  7932. fillStyle: style.backgroundColor,
  7933. strokeStyle: style.borderColor,
  7934. lineWidth: style.borderWidth,
  7935. hidden: !chart.getDataVisibility(i),
  7936. index: i
  7937. };
  7938. });
  7939. }
  7940. return [];
  7941. }
  7942. },
  7943. onClick(e, legendItem, legend) {
  7944. legend.chart.toggleDataVisibility(legendItem.index);
  7945. legend.chart.update();
  7946. }
  7947. },
  7948. tooltip: {
  7949. callbacks: {
  7950. title() {
  7951. return '';
  7952. },
  7953. label(tooltipItem) {
  7954. let dataLabel = tooltipItem.label;
  7955. const value = ': ' + tooltipItem.formattedValue;
  7956. if (isArray(dataLabel)) {
  7957. dataLabel = dataLabel.slice();
  7958. dataLabel[0] += value;
  7959. } else {
  7960. dataLabel += value;
  7961. }
  7962. return dataLabel;
  7963. }
  7964. }
  7965. }
  7966. }
  7967. };
  7968. class LineController extends DatasetController {
  7969. initialize() {
  7970. this.enableOptionSharing = true;
  7971. super.initialize();
  7972. }
  7973. update(mode) {
  7974. const me = this;
  7975. const meta = me._cachedMeta;
  7976. const {dataset: line, data: points = [], _dataset} = meta;
  7977. const animationsDisabled = me.chart._animationsDisabled;
  7978. let {start, count} = getStartAndCountOfVisiblePoints(meta, points, animationsDisabled);
  7979. me._drawStart = start;
  7980. me._drawCount = count;
  7981. if (scaleRangesChanged(meta)) {
  7982. start = 0;
  7983. count = points.length;
  7984. }
  7985. line._decimated = !!_dataset._decimated;
  7986. line.points = points;
  7987. const options = me.resolveDatasetElementOptions(mode);
  7988. if (!me.options.showLine) {
  7989. options.borderWidth = 0;
  7990. }
  7991. options.segment = me.options.segment;
  7992. me.updateElement(line, undefined, {
  7993. animated: !animationsDisabled,
  7994. options
  7995. }, mode);
  7996. me.updateElements(points, start, count, mode);
  7997. }
  7998. updateElements(points, start, count, mode) {
  7999. const me = this;
  8000. const reset = mode === 'reset';
  8001. const {xScale, yScale, _stacked} = me._cachedMeta;
  8002. const firstOpts = me.resolveDataElementOptions(start, mode);
  8003. const sharedOptions = me.getSharedOptions(firstOpts);
  8004. const includeOptions = me.includeOptions(mode, sharedOptions);
  8005. const spanGaps = me.options.spanGaps;
  8006. const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY;
  8007. const directUpdate = me.chart._animationsDisabled || reset || mode === 'none';
  8008. let prevParsed = start > 0 && me.getParsed(start - 1);
  8009. for (let i = start; i < start + count; ++i) {
  8010. const point = points[i];
  8011. const parsed = me.getParsed(i);
  8012. const properties = directUpdate ? point : {};
  8013. const nullData = isNullOrUndef(parsed.y);
  8014. const x = properties.x = xScale.getPixelForValue(parsed.x, i);
  8015. const y = properties.y = reset || nullData ? yScale.getBasePixel() : yScale.getPixelForValue(_stacked ? me.applyStack(yScale, parsed, _stacked) : parsed.y, i);
  8016. properties.skip = isNaN(x) || isNaN(y) || nullData;
  8017. properties.stop = i > 0 && (parsed.x - prevParsed.x) > maxGapLength;
  8018. properties.parsed = parsed;
  8019. if (includeOptions) {
  8020. properties.options = sharedOptions || me.resolveDataElementOptions(i, mode);
  8021. }
  8022. if (!directUpdate) {
  8023. me.updateElement(point, i, properties, mode);
  8024. }
  8025. prevParsed = parsed;
  8026. }
  8027. me.updateSharedOptions(sharedOptions, mode, firstOpts);
  8028. }
  8029. getMaxOverflow() {
  8030. const me = this;
  8031. const meta = me._cachedMeta;
  8032. const dataset = meta.dataset;
  8033. const border = dataset.options && dataset.options.borderWidth || 0;
  8034. const data = meta.data || [];
  8035. if (!data.length) {
  8036. return border;
  8037. }
  8038. const firstPoint = data[0].size(me.resolveDataElementOptions(0));
  8039. const lastPoint = data[data.length - 1].size(me.resolveDataElementOptions(data.length - 1));
  8040. return Math.max(border, firstPoint, lastPoint) / 2;
  8041. }
  8042. draw() {
  8043. this._cachedMeta.dataset.updateControlPoints(this.chart.chartArea);
  8044. super.draw();
  8045. }
  8046. }
  8047. LineController.id = 'line';
  8048. LineController.defaults = {
  8049. datasetElementType: 'line',
  8050. dataElementType: 'point',
  8051. showLine: true,
  8052. spanGaps: false,
  8053. };
  8054. LineController.overrides = {
  8055. scales: {
  8056. _index_: {
  8057. type: 'category',
  8058. },
  8059. _value_: {
  8060. type: 'linear',
  8061. },
  8062. }
  8063. };
  8064. function getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) {
  8065. const pointCount = points.length;
  8066. let start = 0;
  8067. let count = pointCount;
  8068. if (meta._sorted) {
  8069. const {iScale, _parsed} = meta;
  8070. const axis = iScale.axis;
  8071. const {min, max, minDefined, maxDefined} = iScale.getUserBounds();
  8072. if (minDefined) {
  8073. start = _limitValue(Math.min(
  8074. _lookupByKey(_parsed, iScale.axis, min).lo,
  8075. animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo),
  8076. 0, pointCount - 1);
  8077. }
  8078. if (maxDefined) {
  8079. count = _limitValue(Math.max(
  8080. _lookupByKey(_parsed, iScale.axis, max).hi + 1,
  8081. animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max)).hi + 1),
  8082. start, pointCount) - start;
  8083. } else {
  8084. count = pointCount - start;
  8085. }
  8086. }
  8087. return {start, count};
  8088. }
  8089. function scaleRangesChanged(meta) {
  8090. const {xScale, yScale, _scaleRanges} = meta;
  8091. const newRanges = {
  8092. xmin: xScale.min,
  8093. xmax: xScale.max,
  8094. ymin: yScale.min,
  8095. ymax: yScale.max
  8096. };
  8097. if (!_scaleRanges) {
  8098. meta._scaleRanges = newRanges;
  8099. return true;
  8100. }
  8101. const changed = _scaleRanges.xmin !== xScale.min
  8102. || _scaleRanges.xmax !== xScale.max
  8103. || _scaleRanges.ymin !== yScale.min
  8104. || _scaleRanges.ymax !== yScale.max;
  8105. Object.assign(_scaleRanges, newRanges);
  8106. return changed;
  8107. }
  8108. class PolarAreaController extends DatasetController {
  8109. constructor(chart, datasetIndex) {
  8110. super(chart, datasetIndex);
  8111. this.innerRadius = undefined;
  8112. this.outerRadius = undefined;
  8113. }
  8114. update(mode) {
  8115. const arcs = this._cachedMeta.data;
  8116. this._updateRadius();
  8117. this.updateElements(arcs, 0, arcs.length, mode);
  8118. }
  8119. _updateRadius() {
  8120. const me = this;
  8121. const chart = me.chart;
  8122. const chartArea = chart.chartArea;
  8123. const opts = chart.options;
  8124. const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  8125. const outerRadius = Math.max(minSize / 2, 0);
  8126. const innerRadius = Math.max(opts.cutoutPercentage ? (outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  8127. const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount();
  8128. me.outerRadius = outerRadius - (radiusLength * me.index);
  8129. me.innerRadius = me.outerRadius - radiusLength;
  8130. }
  8131. updateElements(arcs, start, count, mode) {
  8132. const me = this;
  8133. const reset = mode === 'reset';
  8134. const chart = me.chart;
  8135. const dataset = me.getDataset();
  8136. const opts = chart.options;
  8137. const animationOpts = opts.animation;
  8138. const scale = me._cachedMeta.rScale;
  8139. const centerX = scale.xCenter;
  8140. const centerY = scale.yCenter;
  8141. const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI;
  8142. let angle = datasetStartAngle;
  8143. let i;
  8144. const defaultAngle = 360 / me.countVisibleElements();
  8145. for (i = 0; i < start; ++i) {
  8146. angle += me._computeAngle(i, mode, defaultAngle);
  8147. }
  8148. for (i = start; i < start + count; i++) {
  8149. const arc = arcs[i];
  8150. let startAngle = angle;
  8151. let endAngle = angle + me._computeAngle(i, mode, defaultAngle);
  8152. let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(dataset.data[i]) : 0;
  8153. angle = endAngle;
  8154. if (reset) {
  8155. if (animationOpts.animateScale) {
  8156. outerRadius = 0;
  8157. }
  8158. if (animationOpts.animateRotate) {
  8159. startAngle = endAngle = datasetStartAngle;
  8160. }
  8161. }
  8162. const properties = {
  8163. x: centerX,
  8164. y: centerY,
  8165. innerRadius: 0,
  8166. outerRadius,
  8167. startAngle,
  8168. endAngle,
  8169. options: me.resolveDataElementOptions(i, mode)
  8170. };
  8171. me.updateElement(arc, i, properties, mode);
  8172. }
  8173. }
  8174. countVisibleElements() {
  8175. const dataset = this.getDataset();
  8176. const meta = this._cachedMeta;
  8177. let count = 0;
  8178. meta.data.forEach((element, index) => {
  8179. if (!isNaN(dataset.data[index]) && this.chart.getDataVisibility(index)) {
  8180. count++;
  8181. }
  8182. });
  8183. return count;
  8184. }
  8185. _computeAngle(index, mode, defaultAngle) {
  8186. return this.chart.getDataVisibility(index)
  8187. ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle)
  8188. : 0;
  8189. }
  8190. }
  8191. PolarAreaController.id = 'polarArea';
  8192. PolarAreaController.defaults = {
  8193. dataElementType: 'arc',
  8194. animation: {
  8195. animateRotate: true,
  8196. animateScale: true
  8197. },
  8198. animations: {
  8199. numbers: {
  8200. type: 'number',
  8201. properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius']
  8202. },
  8203. },
  8204. indexAxis: 'r',
  8205. startAngle: 0,
  8206. };
  8207. PolarAreaController.overrides = {
  8208. aspectRatio: 1,
  8209. plugins: {
  8210. legend: {
  8211. labels: {
  8212. generateLabels(chart) {
  8213. const data = chart.data;
  8214. if (data.labels.length && data.datasets.length) {
  8215. return data.labels.map((label, i) => {
  8216. const meta = chart.getDatasetMeta(0);
  8217. const style = meta.controller.getStyle(i);
  8218. return {
  8219. text: label,
  8220. fillStyle: style.backgroundColor,
  8221. strokeStyle: style.borderColor,
  8222. lineWidth: style.borderWidth,
  8223. hidden: !chart.getDataVisibility(i),
  8224. index: i
  8225. };
  8226. });
  8227. }
  8228. return [];
  8229. }
  8230. },
  8231. onClick(e, legendItem, legend) {
  8232. legend.chart.toggleDataVisibility(legendItem.index);
  8233. legend.chart.update();
  8234. }
  8235. },
  8236. tooltip: {
  8237. callbacks: {
  8238. title() {
  8239. return '';
  8240. },
  8241. label(context) {
  8242. return context.chart.data.labels[context.dataIndex] + ': ' + context.formattedValue;
  8243. }
  8244. }
  8245. }
  8246. },
  8247. scales: {
  8248. r: {
  8249. type: 'radialLinear',
  8250. angleLines: {
  8251. display: false
  8252. },
  8253. beginAtZero: true,
  8254. grid: {
  8255. circular: true
  8256. },
  8257. pointLabels: {
  8258. display: false
  8259. },
  8260. startAngle: 0
  8261. }
  8262. }
  8263. };
  8264. class PieController extends DoughnutController {
  8265. }
  8266. PieController.id = 'pie';
  8267. PieController.defaults = {
  8268. cutout: 0,
  8269. rotation: 0,
  8270. circumference: 360,
  8271. radius: '100%'
  8272. };
  8273. class RadarController extends DatasetController {
  8274. getLabelAndValue(index) {
  8275. const me = this;
  8276. const vScale = me._cachedMeta.vScale;
  8277. const parsed = me.getParsed(index);
  8278. return {
  8279. label: vScale.getLabels()[index],
  8280. value: '' + vScale.getLabelForValue(parsed[vScale.axis])
  8281. };
  8282. }
  8283. update(mode) {
  8284. const me = this;
  8285. const meta = me._cachedMeta;
  8286. const line = meta.dataset;
  8287. const points = meta.data || [];
  8288. const labels = meta.iScale.getLabels();
  8289. line.points = points;
  8290. if (mode !== 'resize') {
  8291. const options = me.resolveDatasetElementOptions(mode);
  8292. if (!me.options.showLine) {
  8293. options.borderWidth = 0;
  8294. }
  8295. const properties = {
  8296. _loop: true,
  8297. _fullLoop: labels.length === points.length,
  8298. options
  8299. };
  8300. me.updateElement(line, undefined, properties, mode);
  8301. }
  8302. me.updateElements(points, 0, points.length, mode);
  8303. }
  8304. updateElements(points, start, count, mode) {
  8305. const me = this;
  8306. const dataset = me.getDataset();
  8307. const scale = me._cachedMeta.rScale;
  8308. const reset = mode === 'reset';
  8309. for (let i = start; i < start + count; i++) {
  8310. const point = points[i];
  8311. const options = me.resolveDataElementOptions(i, mode);
  8312. const pointPosition = scale.getPointPositionForValue(i, dataset.data[i]);
  8313. const x = reset ? scale.xCenter : pointPosition.x;
  8314. const y = reset ? scale.yCenter : pointPosition.y;
  8315. const properties = {
  8316. x,
  8317. y,
  8318. angle: pointPosition.angle,
  8319. skip: isNaN(x) || isNaN(y),
  8320. options
  8321. };
  8322. me.updateElement(point, i, properties, mode);
  8323. }
  8324. }
  8325. }
  8326. RadarController.id = 'radar';
  8327. RadarController.defaults = {
  8328. datasetElementType: 'line',
  8329. dataElementType: 'point',
  8330. indexAxis: 'r',
  8331. showLine: true,
  8332. elements: {
  8333. line: {
  8334. fill: 'start'
  8335. }
  8336. },
  8337. };
  8338. RadarController.overrides = {
  8339. aspectRatio: 1,
  8340. scales: {
  8341. r: {
  8342. type: 'radialLinear',
  8343. }
  8344. }
  8345. };
  8346. class ScatterController extends LineController {
  8347. }
  8348. ScatterController.id = 'scatter';
  8349. ScatterController.defaults = {
  8350. showLine: false,
  8351. fill: false
  8352. };
  8353. ScatterController.overrides = {
  8354. interaction: {
  8355. mode: 'point'
  8356. },
  8357. plugins: {
  8358. tooltip: {
  8359. callbacks: {
  8360. title() {
  8361. return '';
  8362. },
  8363. label(item) {
  8364. return '(' + item.label + ', ' + item.formattedValue + ')';
  8365. }
  8366. }
  8367. }
  8368. },
  8369. scales: {
  8370. x: {
  8371. type: 'linear'
  8372. },
  8373. y: {
  8374. type: 'linear'
  8375. }
  8376. }
  8377. };
  8378. var controllers = /*#__PURE__*/Object.freeze({
  8379. __proto__: null,
  8380. BarController: BarController,
  8381. BubbleController: BubbleController,
  8382. DoughnutController: DoughnutController,
  8383. LineController: LineController,
  8384. PolarAreaController: PolarAreaController,
  8385. PieController: PieController,
  8386. RadarController: RadarController,
  8387. ScatterController: ScatterController
  8388. });
  8389. function clipArc(ctx, element) {
  8390. const {startAngle, endAngle, pixelMargin, x, y, outerRadius, innerRadius} = element;
  8391. let angleMargin = pixelMargin / outerRadius;
  8392. ctx.beginPath();
  8393. ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  8394. if (innerRadius > pixelMargin) {
  8395. angleMargin = pixelMargin / innerRadius;
  8396. ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true);
  8397. } else {
  8398. ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI);
  8399. }
  8400. ctx.closePath();
  8401. ctx.clip();
  8402. }
  8403. function toRadiusCorners(value) {
  8404. return _readValueToProps(value, ['outerStart', 'outerEnd', 'innerStart', 'innerEnd']);
  8405. }
  8406. function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) {
  8407. const o = toRadiusCorners(arc.options.borderRadius);
  8408. const halfThickness = (outerRadius - innerRadius) / 2;
  8409. const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2);
  8410. const computeOuterLimit = (val) => {
  8411. const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2;
  8412. return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit));
  8413. };
  8414. return {
  8415. outerStart: computeOuterLimit(o.outerStart),
  8416. outerEnd: computeOuterLimit(o.outerEnd),
  8417. innerStart: _limitValue(o.innerStart, 0, innerLimit),
  8418. innerEnd: _limitValue(o.innerEnd, 0, innerLimit),
  8419. };
  8420. }
  8421. function rThetaToXY(r, theta, x, y) {
  8422. return {
  8423. x: x + r * Math.cos(theta),
  8424. y: y + r * Math.sin(theta),
  8425. };
  8426. }
  8427. function pathArc(ctx, element) {
  8428. const {x, y, startAngle, endAngle, pixelMargin} = element;
  8429. const outerRadius = Math.max(element.outerRadius - pixelMargin, 0);
  8430. const innerRadius = element.innerRadius + pixelMargin;
  8431. const {outerStart, outerEnd, innerStart, innerEnd} = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle);
  8432. const outerStartAdjustedRadius = outerRadius - outerStart;
  8433. const outerEndAdjustedRadius = outerRadius - outerEnd;
  8434. const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius;
  8435. const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius;
  8436. const innerStartAdjustedRadius = innerRadius + innerStart;
  8437. const innerEndAdjustedRadius = innerRadius + innerEnd;
  8438. const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius;
  8439. const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius;
  8440. ctx.beginPath();
  8441. ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerEndAdjustedAngle);
  8442. if (outerEnd > 0) {
  8443. const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y);
  8444. ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI);
  8445. }
  8446. const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y);
  8447. ctx.lineTo(p4.x, p4.y);
  8448. if (innerEnd > 0) {
  8449. const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y);
  8450. ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI);
  8451. }
  8452. ctx.arc(x, y, innerRadius, endAngle - (innerEnd / innerRadius), startAngle + (innerStart / innerRadius), true);
  8453. if (innerStart > 0) {
  8454. const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y);
  8455. ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI);
  8456. }
  8457. const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y);
  8458. ctx.lineTo(p8.x, p8.y);
  8459. if (outerStart > 0) {
  8460. const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y);
  8461. ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle);
  8462. }
  8463. ctx.closePath();
  8464. }
  8465. function drawArc(ctx, element) {
  8466. if (element.fullCircles) {
  8467. element.endAngle = element.startAngle + TAU;
  8468. pathArc(ctx, element);
  8469. for (let i = 0; i < element.fullCircles; ++i) {
  8470. ctx.fill();
  8471. }
  8472. }
  8473. if (!isNaN(element.circumference)) {
  8474. element.endAngle = element.startAngle + element.circumference % TAU;
  8475. }
  8476. pathArc(ctx, element);
  8477. ctx.fill();
  8478. }
  8479. function drawFullCircleBorders(ctx, element, inner) {
  8480. const {x, y, startAngle, endAngle, pixelMargin} = element;
  8481. const outerRadius = Math.max(element.outerRadius - pixelMargin, 0);
  8482. const innerRadius = element.innerRadius + pixelMargin;
  8483. let i;
  8484. if (inner) {
  8485. element.endAngle = element.startAngle + TAU;
  8486. clipArc(ctx, element);
  8487. element.endAngle = endAngle;
  8488. if (element.endAngle === element.startAngle) {
  8489. element.endAngle += TAU;
  8490. element.fullCircles--;
  8491. }
  8492. }
  8493. ctx.beginPath();
  8494. ctx.arc(x, y, innerRadius, startAngle + TAU, startAngle, true);
  8495. for (i = 0; i < element.fullCircles; ++i) {
  8496. ctx.stroke();
  8497. }
  8498. ctx.beginPath();
  8499. ctx.arc(x, y, outerRadius, startAngle, startAngle + TAU);
  8500. for (i = 0; i < element.fullCircles; ++i) {
  8501. ctx.stroke();
  8502. }
  8503. }
  8504. function drawBorder(ctx, element) {
  8505. const {options} = element;
  8506. const inner = options.borderAlign === 'inner';
  8507. if (!options.borderWidth) {
  8508. return;
  8509. }
  8510. if (inner) {
  8511. ctx.lineWidth = options.borderWidth * 2;
  8512. ctx.lineJoin = 'round';
  8513. } else {
  8514. ctx.lineWidth = options.borderWidth;
  8515. ctx.lineJoin = 'bevel';
  8516. }
  8517. if (element.fullCircles) {
  8518. drawFullCircleBorders(ctx, element, inner);
  8519. }
  8520. if (inner) {
  8521. clipArc(ctx, element);
  8522. }
  8523. pathArc(ctx, element);
  8524. ctx.stroke();
  8525. }
  8526. class ArcElement extends Element {
  8527. constructor(cfg) {
  8528. super();
  8529. this.options = undefined;
  8530. this.circumference = undefined;
  8531. this.startAngle = undefined;
  8532. this.endAngle = undefined;
  8533. this.innerRadius = undefined;
  8534. this.outerRadius = undefined;
  8535. this.pixelMargin = 0;
  8536. this.fullCircles = 0;
  8537. if (cfg) {
  8538. Object.assign(this, cfg);
  8539. }
  8540. }
  8541. inRange(chartX, chartY, useFinalPosition) {
  8542. const point = this.getProps(['x', 'y'], useFinalPosition);
  8543. const {angle, distance} = getAngleFromPoint(point, {x: chartX, y: chartY});
  8544. const {startAngle, endAngle, innerRadius, outerRadius, circumference} = this.getProps([
  8545. 'startAngle',
  8546. 'endAngle',
  8547. 'innerRadius',
  8548. 'outerRadius',
  8549. 'circumference'
  8550. ], useFinalPosition);
  8551. const betweenAngles = circumference >= TAU || _angleBetween(angle, startAngle, endAngle);
  8552. const withinRadius = (distance >= innerRadius && distance <= outerRadius);
  8553. return (betweenAngles && withinRadius);
  8554. }
  8555. getCenterPoint(useFinalPosition) {
  8556. const {x, y, startAngle, endAngle, innerRadius, outerRadius} = this.getProps([
  8557. 'x',
  8558. 'y',
  8559. 'startAngle',
  8560. 'endAngle',
  8561. 'innerRadius',
  8562. 'outerRadius'
  8563. ], useFinalPosition);
  8564. const halfAngle = (startAngle + endAngle) / 2;
  8565. const halfRadius = (innerRadius + outerRadius) / 2;
  8566. return {
  8567. x: x + Math.cos(halfAngle) * halfRadius,
  8568. y: y + Math.sin(halfAngle) * halfRadius
  8569. };
  8570. }
  8571. tooltipPosition(useFinalPosition) {
  8572. return this.getCenterPoint(useFinalPosition);
  8573. }
  8574. draw(ctx) {
  8575. const me = this;
  8576. const options = me.options;
  8577. const offset = options.offset || 0;
  8578. me.pixelMargin = (options.borderAlign === 'inner') ? 0.33 : 0;
  8579. me.fullCircles = Math.floor(me.circumference / TAU);
  8580. if (me.circumference === 0 || me.innerRadius < 0 || me.outerRadius < 0) {
  8581. return;
  8582. }
  8583. ctx.save();
  8584. if (offset && me.circumference < TAU) {
  8585. const halfAngle = (me.startAngle + me.endAngle) / 2;
  8586. ctx.translate(Math.cos(halfAngle) * offset, Math.sin(halfAngle) * offset);
  8587. }
  8588. ctx.fillStyle = options.backgroundColor;
  8589. ctx.strokeStyle = options.borderColor;
  8590. drawArc(ctx, me);
  8591. drawBorder(ctx, me);
  8592. ctx.restore();
  8593. }
  8594. }
  8595. ArcElement.id = 'arc';
  8596. ArcElement.defaults = {
  8597. borderAlign: 'center',
  8598. borderColor: '#fff',
  8599. borderRadius: 0,
  8600. borderWidth: 2,
  8601. offset: 0,
  8602. angle: undefined,
  8603. };
  8604. ArcElement.defaultRoutes = {
  8605. backgroundColor: 'backgroundColor'
  8606. };
  8607. function setStyle(ctx, options, style = options) {
  8608. ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle);
  8609. ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash));
  8610. ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset);
  8611. ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle);
  8612. ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth);
  8613. ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor);
  8614. }
  8615. function lineTo(ctx, previous, target) {
  8616. ctx.lineTo(target.x, target.y);
  8617. }
  8618. function getLineMethod(options) {
  8619. if (options.stepped) {
  8620. return _steppedLineTo;
  8621. }
  8622. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  8623. return _bezierCurveTo;
  8624. }
  8625. return lineTo;
  8626. }
  8627. function pathVars(points, segment, params = {}) {
  8628. const count = points.length;
  8629. const {start: paramsStart = 0, end: paramsEnd = count - 1} = params;
  8630. const {start: segmentStart, end: segmentEnd} = segment;
  8631. const start = Math.max(paramsStart, segmentStart);
  8632. const end = Math.min(paramsEnd, segmentEnd);
  8633. const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd;
  8634. return {
  8635. count,
  8636. start,
  8637. loop: segment.loop,
  8638. ilen: end < start && !outside ? count + end - start : end - start
  8639. };
  8640. }
  8641. function pathSegment(ctx, line, segment, params) {
  8642. const {points, options} = line;
  8643. const {count, start, loop, ilen} = pathVars(points, segment, params);
  8644. const lineMethod = getLineMethod(options);
  8645. let {move = true, reverse} = params || {};
  8646. let i, point, prev;
  8647. for (i = 0; i <= ilen; ++i) {
  8648. point = points[(start + (reverse ? ilen - i : i)) % count];
  8649. if (point.skip) {
  8650. continue;
  8651. } else if (move) {
  8652. ctx.moveTo(point.x, point.y);
  8653. move = false;
  8654. } else {
  8655. lineMethod(ctx, prev, point, reverse, options.stepped);
  8656. }
  8657. prev = point;
  8658. }
  8659. if (loop) {
  8660. point = points[(start + (reverse ? ilen : 0)) % count];
  8661. lineMethod(ctx, prev, point, reverse, options.stepped);
  8662. }
  8663. return !!loop;
  8664. }
  8665. function fastPathSegment(ctx, line, segment, params) {
  8666. const points = line.points;
  8667. const {count, start, ilen} = pathVars(points, segment, params);
  8668. const {move = true, reverse} = params || {};
  8669. let avgX = 0;
  8670. let countX = 0;
  8671. let i, point, prevX, minY, maxY, lastY;
  8672. const pointIndex = (index) => (start + (reverse ? ilen - index : index)) % count;
  8673. const drawX = () => {
  8674. if (minY !== maxY) {
  8675. ctx.lineTo(avgX, maxY);
  8676. ctx.lineTo(avgX, minY);
  8677. ctx.lineTo(avgX, lastY);
  8678. }
  8679. };
  8680. if (move) {
  8681. point = points[pointIndex(0)];
  8682. ctx.moveTo(point.x, point.y);
  8683. }
  8684. for (i = 0; i <= ilen; ++i) {
  8685. point = points[pointIndex(i)];
  8686. if (point.skip) {
  8687. continue;
  8688. }
  8689. const x = point.x;
  8690. const y = point.y;
  8691. const truncX = x | 0;
  8692. if (truncX === prevX) {
  8693. if (y < minY) {
  8694. minY = y;
  8695. } else if (y > maxY) {
  8696. maxY = y;
  8697. }
  8698. avgX = (countX * avgX + x) / ++countX;
  8699. } else {
  8700. drawX();
  8701. ctx.lineTo(x, y);
  8702. prevX = truncX;
  8703. countX = 0;
  8704. minY = maxY = y;
  8705. }
  8706. lastY = y;
  8707. }
  8708. drawX();
  8709. }
  8710. function _getSegmentMethod(line) {
  8711. const opts = line.options;
  8712. const borderDash = opts.borderDash && opts.borderDash.length;
  8713. const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash;
  8714. return useFastPath ? fastPathSegment : pathSegment;
  8715. }
  8716. function _getInterpolationMethod(options) {
  8717. if (options.stepped) {
  8718. return _steppedInterpolation;
  8719. }
  8720. if (options.tension || options.cubicInterpolationMode === 'monotone') {
  8721. return _bezierInterpolation;
  8722. }
  8723. return _pointInLine;
  8724. }
  8725. function strokePathWithCache(ctx, line, start, count) {
  8726. let path = line._path;
  8727. if (!path) {
  8728. path = line._path = new Path2D();
  8729. if (line.path(path, start, count)) {
  8730. path.closePath();
  8731. }
  8732. }
  8733. setStyle(ctx, line.options);
  8734. ctx.stroke(path);
  8735. }
  8736. function strokePathDirect(ctx, line, start, count) {
  8737. const {segments, options} = line;
  8738. const segmentMethod = _getSegmentMethod(line);
  8739. for (const segment of segments) {
  8740. setStyle(ctx, options, segment.style);
  8741. ctx.beginPath();
  8742. if (segmentMethod(ctx, line, segment, {start, end: start + count - 1})) {
  8743. ctx.closePath();
  8744. }
  8745. ctx.stroke();
  8746. }
  8747. }
  8748. const usePath2D = typeof Path2D === 'function';
  8749. function draw(ctx, line, start, count) {
  8750. if (usePath2D && line.segments.length === 1) {
  8751. strokePathWithCache(ctx, line, start, count);
  8752. } else {
  8753. strokePathDirect(ctx, line, start, count);
  8754. }
  8755. }
  8756. class LineElement extends Element {
  8757. constructor(cfg) {
  8758. super();
  8759. this.animated = true;
  8760. this.options = undefined;
  8761. this._loop = undefined;
  8762. this._fullLoop = undefined;
  8763. this._path = undefined;
  8764. this._points = undefined;
  8765. this._segments = undefined;
  8766. this._decimated = false;
  8767. this._pointsUpdated = false;
  8768. if (cfg) {
  8769. Object.assign(this, cfg);
  8770. }
  8771. }
  8772. updateControlPoints(chartArea) {
  8773. const me = this;
  8774. const options = me.options;
  8775. if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !me._pointsUpdated) {
  8776. const loop = options.spanGaps ? me._loop : me._fullLoop;
  8777. _updateBezierControlPoints(me._points, options, chartArea, loop);
  8778. me._pointsUpdated = true;
  8779. }
  8780. }
  8781. set points(points) {
  8782. const me = this;
  8783. me._points = points;
  8784. delete me._segments;
  8785. delete me._path;
  8786. me._pointsUpdated = false;
  8787. }
  8788. get points() {
  8789. return this._points;
  8790. }
  8791. get segments() {
  8792. return this._segments || (this._segments = _computeSegments(this, this.options.segment));
  8793. }
  8794. first() {
  8795. const segments = this.segments;
  8796. const points = this.points;
  8797. return segments.length && points[segments[0].start];
  8798. }
  8799. last() {
  8800. const segments = this.segments;
  8801. const points = this.points;
  8802. const count = segments.length;
  8803. return count && points[segments[count - 1].end];
  8804. }
  8805. interpolate(point, property) {
  8806. const me = this;
  8807. const options = me.options;
  8808. const value = point[property];
  8809. const points = me.points;
  8810. const segments = _boundSegments(me, {property, start: value, end: value});
  8811. if (!segments.length) {
  8812. return;
  8813. }
  8814. const result = [];
  8815. const _interpolate = _getInterpolationMethod(options);
  8816. let i, ilen;
  8817. for (i = 0, ilen = segments.length; i < ilen; ++i) {
  8818. const {start, end} = segments[i];
  8819. const p1 = points[start];
  8820. const p2 = points[end];
  8821. if (p1 === p2) {
  8822. result.push(p1);
  8823. continue;
  8824. }
  8825. const t = Math.abs((value - p1[property]) / (p2[property] - p1[property]));
  8826. const interpolated = _interpolate(p1, p2, t, options.stepped);
  8827. interpolated[property] = point[property];
  8828. result.push(interpolated);
  8829. }
  8830. return result.length === 1 ? result[0] : result;
  8831. }
  8832. pathSegment(ctx, segment, params) {
  8833. const segmentMethod = _getSegmentMethod(this);
  8834. return segmentMethod(ctx, this, segment, params);
  8835. }
  8836. path(ctx, start, count) {
  8837. const me = this;
  8838. const segments = me.segments;
  8839. const segmentMethod = _getSegmentMethod(me);
  8840. let loop = me._loop;
  8841. start = start || 0;
  8842. count = count || (me.points.length - start);
  8843. for (const segment of segments) {
  8844. loop &= segmentMethod(ctx, me, segment, {start, end: start + count - 1});
  8845. }
  8846. return !!loop;
  8847. }
  8848. draw(ctx, chartArea, start, count) {
  8849. const me = this;
  8850. const options = me.options || {};
  8851. const points = me.points || [];
  8852. if (!points.length || !options.borderWidth) {
  8853. return;
  8854. }
  8855. ctx.save();
  8856. draw(ctx, me, start, count);
  8857. ctx.restore();
  8858. if (me.animated) {
  8859. me._pointsUpdated = false;
  8860. me._path = undefined;
  8861. }
  8862. }
  8863. }
  8864. LineElement.id = 'line';
  8865. LineElement.defaults = {
  8866. borderCapStyle: 'butt',
  8867. borderDash: [],
  8868. borderDashOffset: 0,
  8869. borderJoinStyle: 'miter',
  8870. borderWidth: 3,
  8871. capBezierPoints: true,
  8872. cubicInterpolationMode: 'default',
  8873. fill: false,
  8874. spanGaps: false,
  8875. stepped: false,
  8876. tension: 0,
  8877. };
  8878. LineElement.defaultRoutes = {
  8879. backgroundColor: 'backgroundColor',
  8880. borderColor: 'borderColor'
  8881. };
  8882. LineElement.descriptors = {
  8883. _scriptable: true,
  8884. _indexable: (name) => name !== 'borderDash' && name !== 'fill',
  8885. };
  8886. function inRange$1(el, pos, axis, useFinalPosition) {
  8887. const options = el.options;
  8888. const {[axis]: value} = el.getProps([axis], useFinalPosition);
  8889. return (Math.abs(pos - value) < options.radius + options.hitRadius);
  8890. }
  8891. class PointElement extends Element {
  8892. constructor(cfg) {
  8893. super();
  8894. this.options = undefined;
  8895. this.parsed = undefined;
  8896. this.skip = undefined;
  8897. this.stop = undefined;
  8898. if (cfg) {
  8899. Object.assign(this, cfg);
  8900. }
  8901. }
  8902. inRange(mouseX, mouseY, useFinalPosition) {
  8903. const options = this.options;
  8904. const {x, y} = this.getProps(['x', 'y'], useFinalPosition);
  8905. return ((Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2)) < Math.pow(options.hitRadius + options.radius, 2));
  8906. }
  8907. inXRange(mouseX, useFinalPosition) {
  8908. return inRange$1(this, mouseX, 'x', useFinalPosition);
  8909. }
  8910. inYRange(mouseY, useFinalPosition) {
  8911. return inRange$1(this, mouseY, 'y', useFinalPosition);
  8912. }
  8913. getCenterPoint(useFinalPosition) {
  8914. const {x, y} = this.getProps(['x', 'y'], useFinalPosition);
  8915. return {x, y};
  8916. }
  8917. size(options) {
  8918. options = options || this.options || {};
  8919. let radius = options.radius || 0;
  8920. radius = Math.max(radius, radius && options.hoverRadius || 0);
  8921. const borderWidth = radius && options.borderWidth || 0;
  8922. return (radius + borderWidth) * 2;
  8923. }
  8924. draw(ctx) {
  8925. const me = this;
  8926. const options = me.options;
  8927. if (me.skip || options.radius < 0.1) {
  8928. return;
  8929. }
  8930. ctx.strokeStyle = options.borderColor;
  8931. ctx.lineWidth = options.borderWidth;
  8932. ctx.fillStyle = options.backgroundColor;
  8933. drawPoint(ctx, options, me.x, me.y);
  8934. }
  8935. getRange() {
  8936. const options = this.options || {};
  8937. return options.radius + options.hitRadius;
  8938. }
  8939. }
  8940. PointElement.id = 'point';
  8941. PointElement.defaults = {
  8942. borderWidth: 1,
  8943. hitRadius: 1,
  8944. hoverBorderWidth: 1,
  8945. hoverRadius: 4,
  8946. pointStyle: 'circle',
  8947. radius: 3,
  8948. rotation: 0
  8949. };
  8950. PointElement.defaultRoutes = {
  8951. backgroundColor: 'backgroundColor',
  8952. borderColor: 'borderColor'
  8953. };
  8954. function getBarBounds(bar, useFinalPosition) {
  8955. const {x, y, base, width, height} = bar.getProps(['x', 'y', 'base', 'width', 'height'], useFinalPosition);
  8956. let left, right, top, bottom, half;
  8957. if (bar.horizontal) {
  8958. half = height / 2;
  8959. left = Math.min(x, base);
  8960. right = Math.max(x, base);
  8961. top = y - half;
  8962. bottom = y + half;
  8963. } else {
  8964. half = width / 2;
  8965. left = x - half;
  8966. right = x + half;
  8967. top = Math.min(y, base);
  8968. bottom = Math.max(y, base);
  8969. }
  8970. return {left, top, right, bottom};
  8971. }
  8972. function parseBorderSkipped(bar) {
  8973. let edge = bar.options.borderSkipped;
  8974. const res = {};
  8975. if (!edge) {
  8976. return res;
  8977. }
  8978. edge = bar.horizontal
  8979. ? parseEdge(edge, 'left', 'right', bar.base > bar.x)
  8980. : parseEdge(edge, 'bottom', 'top', bar.base < bar.y);
  8981. res[edge] = true;
  8982. return res;
  8983. }
  8984. function parseEdge(edge, a, b, reverse) {
  8985. if (reverse) {
  8986. edge = swap(edge, a, b);
  8987. edge = startEnd(edge, b, a);
  8988. } else {
  8989. edge = startEnd(edge, a, b);
  8990. }
  8991. return edge;
  8992. }
  8993. function swap(orig, v1, v2) {
  8994. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  8995. }
  8996. function startEnd(v, start, end) {
  8997. return v === 'start' ? start : v === 'end' ? end : v;
  8998. }
  8999. function skipOrLimit(skip, value, min, max) {
  9000. return skip ? 0 : Math.max(Math.min(value, max), min);
  9001. }
  9002. function parseBorderWidth(bar, maxW, maxH) {
  9003. const value = bar.options.borderWidth;
  9004. const skip = parseBorderSkipped(bar);
  9005. const o = toTRBL(value);
  9006. return {
  9007. t: skipOrLimit(skip.top, o.top, 0, maxH),
  9008. r: skipOrLimit(skip.right, o.right, 0, maxW),
  9009. b: skipOrLimit(skip.bottom, o.bottom, 0, maxH),
  9010. l: skipOrLimit(skip.left, o.left, 0, maxW)
  9011. };
  9012. }
  9013. function parseBorderRadius(bar, maxW, maxH) {
  9014. const {enableBorderRadius} = bar.getProps(['enableBorderRadius']);
  9015. const value = bar.options.borderRadius;
  9016. const o = toTRBLCorners(value);
  9017. const maxR = Math.min(maxW, maxH);
  9018. const skip = parseBorderSkipped(bar);
  9019. const enableBorder = enableBorderRadius || isObject(value);
  9020. return {
  9021. topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR),
  9022. topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR),
  9023. bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR),
  9024. bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR)
  9025. };
  9026. }
  9027. function boundingRects(bar) {
  9028. const bounds = getBarBounds(bar);
  9029. const width = bounds.right - bounds.left;
  9030. const height = bounds.bottom - bounds.top;
  9031. const border = parseBorderWidth(bar, width / 2, height / 2);
  9032. const radius = parseBorderRadius(bar, width / 2, height / 2);
  9033. return {
  9034. outer: {
  9035. x: bounds.left,
  9036. y: bounds.top,
  9037. w: width,
  9038. h: height,
  9039. radius
  9040. },
  9041. inner: {
  9042. x: bounds.left + border.l,
  9043. y: bounds.top + border.t,
  9044. w: width - border.l - border.r,
  9045. h: height - border.t - border.b,
  9046. radius: {
  9047. topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)),
  9048. topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)),
  9049. bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)),
  9050. bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r)),
  9051. }
  9052. }
  9053. };
  9054. }
  9055. function inRange(bar, x, y, useFinalPosition) {
  9056. const skipX = x === null;
  9057. const skipY = y === null;
  9058. const skipBoth = skipX && skipY;
  9059. const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition);
  9060. return bounds
  9061. && (skipX || x >= bounds.left && x <= bounds.right)
  9062. && (skipY || y >= bounds.top && y <= bounds.bottom);
  9063. }
  9064. function hasRadius(radius) {
  9065. return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight;
  9066. }
  9067. function addNormalRectPath(ctx, rect) {
  9068. ctx.rect(rect.x, rect.y, rect.w, rect.h);
  9069. }
  9070. class BarElement extends Element {
  9071. constructor(cfg) {
  9072. super();
  9073. this.options = undefined;
  9074. this.horizontal = undefined;
  9075. this.base = undefined;
  9076. this.width = undefined;
  9077. this.height = undefined;
  9078. if (cfg) {
  9079. Object.assign(this, cfg);
  9080. }
  9081. }
  9082. draw(ctx) {
  9083. const options = this.options;
  9084. const {inner, outer} = boundingRects(this);
  9085. const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath;
  9086. ctx.save();
  9087. if (outer.w !== inner.w || outer.h !== inner.h) {
  9088. ctx.beginPath();
  9089. addRectPath(ctx, outer);
  9090. ctx.clip();
  9091. addRectPath(ctx, inner);
  9092. ctx.fillStyle = options.borderColor;
  9093. ctx.fill('evenodd');
  9094. }
  9095. ctx.beginPath();
  9096. addRectPath(ctx, inner);
  9097. ctx.fillStyle = options.backgroundColor;
  9098. ctx.fill();
  9099. ctx.restore();
  9100. }
  9101. inRange(mouseX, mouseY, useFinalPosition) {
  9102. return inRange(this, mouseX, mouseY, useFinalPosition);
  9103. }
  9104. inXRange(mouseX, useFinalPosition) {
  9105. return inRange(this, mouseX, null, useFinalPosition);
  9106. }
  9107. inYRange(mouseY, useFinalPosition) {
  9108. return inRange(this, null, mouseY, useFinalPosition);
  9109. }
  9110. getCenterPoint(useFinalPosition) {
  9111. const {x, y, base, horizontal} = this.getProps(['x', 'y', 'base', 'horizontal'], useFinalPosition);
  9112. return {
  9113. x: horizontal ? (x + base) / 2 : x,
  9114. y: horizontal ? y : (y + base) / 2
  9115. };
  9116. }
  9117. getRange(axis) {
  9118. return axis === 'x' ? this.width / 2 : this.height / 2;
  9119. }
  9120. }
  9121. BarElement.id = 'bar';
  9122. BarElement.defaults = {
  9123. borderSkipped: 'start',
  9124. borderWidth: 0,
  9125. borderRadius: 0,
  9126. enableBorderRadius: true,
  9127. pointStyle: undefined
  9128. };
  9129. BarElement.defaultRoutes = {
  9130. backgroundColor: 'backgroundColor',
  9131. borderColor: 'borderColor'
  9132. };
  9133. var elements = /*#__PURE__*/Object.freeze({
  9134. __proto__: null,
  9135. ArcElement: ArcElement,
  9136. LineElement: LineElement,
  9137. PointElement: PointElement,
  9138. BarElement: BarElement
  9139. });
  9140. function lttbDecimation(data, start, count, availableWidth, options) {
  9141. const samples = options.samples || availableWidth;
  9142. if (samples >= count) {
  9143. return data.slice(start, start + count);
  9144. }
  9145. const decimated = [];
  9146. const bucketWidth = (count - 2) / (samples - 2);
  9147. let sampledIndex = 0;
  9148. const endIndex = start + count - 1;
  9149. let a = start;
  9150. let i, maxAreaPoint, maxArea, area, nextA;
  9151. decimated[sampledIndex++] = data[a];
  9152. for (i = 0; i < samples - 2; i++) {
  9153. let avgX = 0;
  9154. let avgY = 0;
  9155. let j;
  9156. const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start;
  9157. const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start;
  9158. const avgRangeLength = avgRangeEnd - avgRangeStart;
  9159. for (j = avgRangeStart; j < avgRangeEnd; j++) {
  9160. avgX += data[j].x;
  9161. avgY += data[j].y;
  9162. }
  9163. avgX /= avgRangeLength;
  9164. avgY /= avgRangeLength;
  9165. const rangeOffs = Math.floor(i * bucketWidth) + 1 + start;
  9166. const rangeTo = Math.floor((i + 1) * bucketWidth) + 1 + start;
  9167. const {x: pointAx, y: pointAy} = data[a];
  9168. maxArea = area = -1;
  9169. for (j = rangeOffs; j < rangeTo; j++) {
  9170. area = 0.5 * Math.abs(
  9171. (pointAx - avgX) * (data[j].y - pointAy) -
  9172. (pointAx - data[j].x) * (avgY - pointAy)
  9173. );
  9174. if (area > maxArea) {
  9175. maxArea = area;
  9176. maxAreaPoint = data[j];
  9177. nextA = j;
  9178. }
  9179. }
  9180. decimated[sampledIndex++] = maxAreaPoint;
  9181. a = nextA;
  9182. }
  9183. decimated[sampledIndex++] = data[endIndex];
  9184. return decimated;
  9185. }
  9186. function minMaxDecimation(data, start, count, availableWidth) {
  9187. let avgX = 0;
  9188. let countX = 0;
  9189. let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY;
  9190. const decimated = [];
  9191. const endIndex = start + count - 1;
  9192. const xMin = data[start].x;
  9193. const xMax = data[endIndex].x;
  9194. const dx = xMax - xMin;
  9195. for (i = start; i < start + count; ++i) {
  9196. point = data[i];
  9197. x = (point.x - xMin) / dx * availableWidth;
  9198. y = point.y;
  9199. const truncX = x | 0;
  9200. if (truncX === prevX) {
  9201. if (y < minY) {
  9202. minY = y;
  9203. minIndex = i;
  9204. } else if (y > maxY) {
  9205. maxY = y;
  9206. maxIndex = i;
  9207. }
  9208. avgX = (countX * avgX + point.x) / ++countX;
  9209. } else {
  9210. const lastIndex = i - 1;
  9211. if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) {
  9212. const intermediateIndex1 = Math.min(minIndex, maxIndex);
  9213. const intermediateIndex2 = Math.max(minIndex, maxIndex);
  9214. if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) {
  9215. decimated.push({
  9216. ...data[intermediateIndex1],
  9217. x: avgX,
  9218. });
  9219. }
  9220. if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) {
  9221. decimated.push({
  9222. ...data[intermediateIndex2],
  9223. x: avgX
  9224. });
  9225. }
  9226. }
  9227. if (i > 0 && lastIndex !== startIndex) {
  9228. decimated.push(data[lastIndex]);
  9229. }
  9230. decimated.push(point);
  9231. prevX = truncX;
  9232. countX = 0;
  9233. minY = maxY = y;
  9234. minIndex = maxIndex = startIndex = i;
  9235. }
  9236. }
  9237. return decimated;
  9238. }
  9239. function cleanDecimatedDataset(dataset) {
  9240. if (dataset._decimated) {
  9241. const data = dataset._data;
  9242. delete dataset._decimated;
  9243. delete dataset._data;
  9244. Object.defineProperty(dataset, 'data', {value: data});
  9245. }
  9246. }
  9247. function cleanDecimatedData(chart) {
  9248. chart.data.datasets.forEach((dataset) => {
  9249. cleanDecimatedDataset(dataset);
  9250. });
  9251. }
  9252. function getStartAndCountOfVisiblePointsSimplified(meta, points) {
  9253. const pointCount = points.length;
  9254. let start = 0;
  9255. let count;
  9256. const {iScale} = meta;
  9257. const {min, max, minDefined, maxDefined} = iScale.getUserBounds();
  9258. if (minDefined) {
  9259. start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1);
  9260. }
  9261. if (maxDefined) {
  9262. count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start;
  9263. } else {
  9264. count = pointCount - start;
  9265. }
  9266. return {start, count};
  9267. }
  9268. var plugin_decimation = {
  9269. id: 'decimation',
  9270. defaults: {
  9271. algorithm: 'min-max',
  9272. enabled: false,
  9273. },
  9274. beforeElementsUpdate: (chart, args, options) => {
  9275. if (!options.enabled) {
  9276. cleanDecimatedData(chart);
  9277. return;
  9278. }
  9279. const availableWidth = chart.width;
  9280. chart.data.datasets.forEach((dataset, datasetIndex) => {
  9281. const {_data, indexAxis} = dataset;
  9282. const meta = chart.getDatasetMeta(datasetIndex);
  9283. const data = _data || dataset.data;
  9284. if (resolve([indexAxis, chart.options.indexAxis]) === 'y') {
  9285. return;
  9286. }
  9287. if (meta.type !== 'line') {
  9288. return;
  9289. }
  9290. const xAxis = chart.scales[meta.xAxisID];
  9291. if (xAxis.type !== 'linear' && xAxis.type !== 'time') {
  9292. return;
  9293. }
  9294. if (chart.options.parsing) {
  9295. return;
  9296. }
  9297. let {start, count} = getStartAndCountOfVisiblePointsSimplified(meta, data);
  9298. if (count <= 4 * availableWidth) {
  9299. cleanDecimatedDataset(dataset);
  9300. return;
  9301. }
  9302. if (isNullOrUndef(_data)) {
  9303. dataset._data = data;
  9304. delete dataset.data;
  9305. Object.defineProperty(dataset, 'data', {
  9306. configurable: true,
  9307. enumerable: true,
  9308. get: function() {
  9309. return this._decimated;
  9310. },
  9311. set: function(d) {
  9312. this._data = d;
  9313. }
  9314. });
  9315. }
  9316. let decimated;
  9317. switch (options.algorithm) {
  9318. case 'lttb':
  9319. decimated = lttbDecimation(data, start, count, availableWidth, options);
  9320. break;
  9321. case 'min-max':
  9322. decimated = minMaxDecimation(data, start, count, availableWidth);
  9323. break;
  9324. default:
  9325. throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`);
  9326. }
  9327. dataset._decimated = decimated;
  9328. });
  9329. },
  9330. destroy(chart) {
  9331. cleanDecimatedData(chart);
  9332. }
  9333. };
  9334. function getLineByIndex(chart, index) {
  9335. const meta = chart.getDatasetMeta(index);
  9336. const visible = meta && chart.isDatasetVisible(index);
  9337. return visible ? meta.dataset : null;
  9338. }
  9339. function parseFillOption(line) {
  9340. const options = line.options;
  9341. const fillOption = options.fill;
  9342. let fill = valueOrDefault(fillOption && fillOption.target, fillOption);
  9343. if (fill === undefined) {
  9344. fill = !!options.backgroundColor;
  9345. }
  9346. if (fill === false || fill === null) {
  9347. return false;
  9348. }
  9349. if (fill === true) {
  9350. return 'origin';
  9351. }
  9352. return fill;
  9353. }
  9354. function decodeFill(line, index, count) {
  9355. const fill = parseFillOption(line);
  9356. if (isObject(fill)) {
  9357. return isNaN(fill.value) ? false : fill;
  9358. }
  9359. let target = parseFloat(fill);
  9360. if (isNumberFinite(target) && Math.floor(target) === target) {
  9361. if (fill[0] === '-' || fill[0] === '+') {
  9362. target = index + target;
  9363. }
  9364. if (target === index || target < 0 || target >= count) {
  9365. return false;
  9366. }
  9367. return target;
  9368. }
  9369. return ['origin', 'start', 'end', 'stack'].indexOf(fill) >= 0 && fill;
  9370. }
  9371. function computeLinearBoundary(source) {
  9372. const {scale = {}, fill} = source;
  9373. let target = null;
  9374. let horizontal;
  9375. if (fill === 'start') {
  9376. target = scale.bottom;
  9377. } else if (fill === 'end') {
  9378. target = scale.top;
  9379. } else if (isObject(fill)) {
  9380. target = scale.getPixelForValue(fill.value);
  9381. } else if (scale.getBasePixel) {
  9382. target = scale.getBasePixel();
  9383. }
  9384. if (isNumberFinite(target)) {
  9385. horizontal = scale.isHorizontal();
  9386. return {
  9387. x: horizontal ? target : null,
  9388. y: horizontal ? null : target
  9389. };
  9390. }
  9391. return null;
  9392. }
  9393. class simpleArc {
  9394. constructor(opts) {
  9395. this.x = opts.x;
  9396. this.y = opts.y;
  9397. this.radius = opts.radius;
  9398. }
  9399. pathSegment(ctx, bounds, opts) {
  9400. const {x, y, radius} = this;
  9401. bounds = bounds || {start: 0, end: TAU};
  9402. ctx.arc(x, y, radius, bounds.end, bounds.start, true);
  9403. return !opts.bounds;
  9404. }
  9405. interpolate(point) {
  9406. const {x, y, radius} = this;
  9407. const angle = point.angle;
  9408. return {
  9409. x: x + Math.cos(angle) * radius,
  9410. y: y + Math.sin(angle) * radius,
  9411. angle
  9412. };
  9413. }
  9414. }
  9415. function computeCircularBoundary(source) {
  9416. const {scale, fill} = source;
  9417. const options = scale.options;
  9418. const length = scale.getLabels().length;
  9419. const target = [];
  9420. const start = options.reverse ? scale.max : scale.min;
  9421. const end = options.reverse ? scale.min : scale.max;
  9422. let i, center, value;
  9423. if (fill === 'start') {
  9424. value = start;
  9425. } else if (fill === 'end') {
  9426. value = end;
  9427. } else if (isObject(fill)) {
  9428. value = fill.value;
  9429. } else {
  9430. value = scale.getBaseValue();
  9431. }
  9432. if (options.grid.circular) {
  9433. center = scale.getPointPositionForValue(0, start);
  9434. return new simpleArc({
  9435. x: center.x,
  9436. y: center.y,
  9437. radius: scale.getDistanceFromCenterForValue(value)
  9438. });
  9439. }
  9440. for (i = 0; i < length; ++i) {
  9441. target.push(scale.getPointPositionForValue(i, value));
  9442. }
  9443. return target;
  9444. }
  9445. function computeBoundary(source) {
  9446. const scale = source.scale || {};
  9447. if (scale.getPointPositionForValue) {
  9448. return computeCircularBoundary(source);
  9449. }
  9450. return computeLinearBoundary(source);
  9451. }
  9452. function pointsFromSegments(boundary, line) {
  9453. const {x = null, y = null} = boundary || {};
  9454. const linePoints = line.points;
  9455. const points = [];
  9456. line.segments.forEach((segment) => {
  9457. const first = linePoints[segment.start];
  9458. const last = linePoints[segment.end];
  9459. if (y !== null) {
  9460. points.push({x: first.x, y});
  9461. points.push({x: last.x, y});
  9462. } else if (x !== null) {
  9463. points.push({x, y: first.y});
  9464. points.push({x, y: last.y});
  9465. }
  9466. });
  9467. return points;
  9468. }
  9469. function buildStackLine(source) {
  9470. const {chart, scale, index, line} = source;
  9471. const points = [];
  9472. const segments = line.segments;
  9473. const sourcePoints = line.points;
  9474. const linesBelow = getLinesBelow(chart, index);
  9475. linesBelow.push(createBoundaryLine({x: null, y: scale.bottom}, line));
  9476. for (let i = 0; i < segments.length; i++) {
  9477. const segment = segments[i];
  9478. for (let j = segment.start; j <= segment.end; j++) {
  9479. addPointsBelow(points, sourcePoints[j], linesBelow);
  9480. }
  9481. }
  9482. return new LineElement({points, options: {}});
  9483. }
  9484. const isLineAndNotInHideAnimation = (meta) => meta.type === 'line' && !meta.hidden;
  9485. function getLinesBelow(chart, index) {
  9486. const below = [];
  9487. const metas = chart.getSortedVisibleDatasetMetas();
  9488. for (let i = 0; i < metas.length; i++) {
  9489. const meta = metas[i];
  9490. if (meta.index === index) {
  9491. break;
  9492. }
  9493. if (isLineAndNotInHideAnimation(meta)) {
  9494. below.unshift(meta.dataset);
  9495. }
  9496. }
  9497. return below;
  9498. }
  9499. function addPointsBelow(points, sourcePoint, linesBelow) {
  9500. const postponed = [];
  9501. for (let j = 0; j < linesBelow.length; j++) {
  9502. const line = linesBelow[j];
  9503. const {first, last, point} = findPoint(line, sourcePoint, 'x');
  9504. if (!point || (first && last)) {
  9505. continue;
  9506. }
  9507. if (first) {
  9508. postponed.unshift(point);
  9509. } else {
  9510. points.push(point);
  9511. if (!last) {
  9512. break;
  9513. }
  9514. }
  9515. }
  9516. points.push(...postponed);
  9517. }
  9518. function findPoint(line, sourcePoint, property) {
  9519. const point = line.interpolate(sourcePoint, property);
  9520. if (!point) {
  9521. return {};
  9522. }
  9523. const pointValue = point[property];
  9524. const segments = line.segments;
  9525. const linePoints = line.points;
  9526. let first = false;
  9527. let last = false;
  9528. for (let i = 0; i < segments.length; i++) {
  9529. const segment = segments[i];
  9530. const firstValue = linePoints[segment.start][property];
  9531. const lastValue = linePoints[segment.end][property];
  9532. if (pointValue >= firstValue && pointValue <= lastValue) {
  9533. first = pointValue === firstValue;
  9534. last = pointValue === lastValue;
  9535. break;
  9536. }
  9537. }
  9538. return {first, last, point};
  9539. }
  9540. function getTarget(source) {
  9541. const {chart, fill, line} = source;
  9542. if (isNumberFinite(fill)) {
  9543. return getLineByIndex(chart, fill);
  9544. }
  9545. if (fill === 'stack') {
  9546. return buildStackLine(source);
  9547. }
  9548. const boundary = computeBoundary(source);
  9549. if (boundary instanceof simpleArc) {
  9550. return boundary;
  9551. }
  9552. return createBoundaryLine(boundary, line);
  9553. }
  9554. function createBoundaryLine(boundary, line) {
  9555. let points = [];
  9556. let _loop = false;
  9557. if (isArray(boundary)) {
  9558. _loop = true;
  9559. points = boundary;
  9560. } else {
  9561. points = pointsFromSegments(boundary, line);
  9562. }
  9563. return points.length ? new LineElement({
  9564. points,
  9565. options: {tension: 0},
  9566. _loop,
  9567. _fullLoop: _loop
  9568. }) : null;
  9569. }
  9570. function resolveTarget(sources, index, propagate) {
  9571. const source = sources[index];
  9572. let fill = source.fill;
  9573. const visited = [index];
  9574. let target;
  9575. if (!propagate) {
  9576. return fill;
  9577. }
  9578. while (fill !== false && visited.indexOf(fill) === -1) {
  9579. if (!isNumberFinite(fill)) {
  9580. return fill;
  9581. }
  9582. target = sources[fill];
  9583. if (!target) {
  9584. return false;
  9585. }
  9586. if (target.visible) {
  9587. return fill;
  9588. }
  9589. visited.push(fill);
  9590. fill = target.fill;
  9591. }
  9592. return false;
  9593. }
  9594. function _clip(ctx, target, clipY) {
  9595. ctx.beginPath();
  9596. target.path(ctx);
  9597. ctx.lineTo(target.last().x, clipY);
  9598. ctx.lineTo(target.first().x, clipY);
  9599. ctx.closePath();
  9600. ctx.clip();
  9601. }
  9602. function getBounds(property, first, last, loop) {
  9603. if (loop) {
  9604. return;
  9605. }
  9606. let start = first[property];
  9607. let end = last[property];
  9608. if (property === 'angle') {
  9609. start = _normalizeAngle(start);
  9610. end = _normalizeAngle(end);
  9611. }
  9612. return {property, start, end};
  9613. }
  9614. function _getEdge(a, b, prop, fn) {
  9615. if (a && b) {
  9616. return fn(a[prop], b[prop]);
  9617. }
  9618. return a ? a[prop] : b ? b[prop] : 0;
  9619. }
  9620. function _segments(line, target, property) {
  9621. const segments = line.segments;
  9622. const points = line.points;
  9623. const tpoints = target.points;
  9624. const parts = [];
  9625. for (const segment of segments) {
  9626. const bounds = getBounds(property, points[segment.start], points[segment.end], segment.loop);
  9627. if (!target.segments) {
  9628. parts.push({
  9629. source: segment,
  9630. target: bounds,
  9631. start: points[segment.start],
  9632. end: points[segment.end]
  9633. });
  9634. continue;
  9635. }
  9636. const targetSegments = _boundSegments(target, bounds);
  9637. for (const tgt of targetSegments) {
  9638. const subBounds = getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop);
  9639. const fillSources = _boundSegment(segment, points, subBounds);
  9640. for (const fillSource of fillSources) {
  9641. parts.push({
  9642. source: fillSource,
  9643. target: tgt,
  9644. start: {
  9645. [property]: _getEdge(bounds, subBounds, 'start', Math.max)
  9646. },
  9647. end: {
  9648. [property]: _getEdge(bounds, subBounds, 'end', Math.min)
  9649. }
  9650. });
  9651. }
  9652. }
  9653. }
  9654. return parts;
  9655. }
  9656. function clipBounds(ctx, scale, bounds) {
  9657. const {top, bottom} = scale.chart.chartArea;
  9658. const {property, start, end} = bounds || {};
  9659. if (property === 'x') {
  9660. ctx.beginPath();
  9661. ctx.rect(start, top, end - start, bottom - top);
  9662. ctx.clip();
  9663. }
  9664. }
  9665. function interpolatedLineTo(ctx, target, point, property) {
  9666. const interpolatedPoint = target.interpolate(point, property);
  9667. if (interpolatedPoint) {
  9668. ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y);
  9669. }
  9670. }
  9671. function _fill(ctx, cfg) {
  9672. const {line, target, property, color, scale} = cfg;
  9673. const segments = _segments(line, target, property);
  9674. for (const {source: src, target: tgt, start, end} of segments) {
  9675. const {style: {backgroundColor = color} = {}} = src;
  9676. ctx.save();
  9677. ctx.fillStyle = backgroundColor;
  9678. clipBounds(ctx, scale, getBounds(property, start, end));
  9679. ctx.beginPath();
  9680. const lineLoop = !!line.pathSegment(ctx, src);
  9681. if (lineLoop) {
  9682. ctx.closePath();
  9683. } else {
  9684. interpolatedLineTo(ctx, target, end, property);
  9685. }
  9686. const targetLoop = !!target.pathSegment(ctx, tgt, {move: lineLoop, reverse: true});
  9687. const loop = lineLoop && targetLoop;
  9688. if (!loop) {
  9689. interpolatedLineTo(ctx, target, start, property);
  9690. }
  9691. ctx.closePath();
  9692. ctx.fill(loop ? 'evenodd' : 'nonzero');
  9693. ctx.restore();
  9694. }
  9695. }
  9696. function doFill(ctx, cfg) {
  9697. const {line, target, above, below, area, scale} = cfg;
  9698. const property = line._loop ? 'angle' : cfg.axis;
  9699. ctx.save();
  9700. if (property === 'x' && below !== above) {
  9701. _clip(ctx, target, area.top);
  9702. _fill(ctx, {line, target, color: above, scale, property});
  9703. ctx.restore();
  9704. ctx.save();
  9705. _clip(ctx, target, area.bottom);
  9706. }
  9707. _fill(ctx, {line, target, color: below, scale, property});
  9708. ctx.restore();
  9709. }
  9710. function drawfill(ctx, source, area) {
  9711. const target = getTarget(source);
  9712. const {line, scale, axis} = source;
  9713. const lineOpts = line.options;
  9714. const fillOption = lineOpts.fill;
  9715. const color = lineOpts.backgroundColor;
  9716. const {above = color, below = color} = fillOption || {};
  9717. if (target && line.points.length) {
  9718. clipArea(ctx, area);
  9719. doFill(ctx, {line, target, above, below, area, scale, axis});
  9720. unclipArea(ctx);
  9721. }
  9722. }
  9723. var plugin_filler = {
  9724. id: 'filler',
  9725. afterDatasetsUpdate(chart, _args, options) {
  9726. const count = (chart.data.datasets || []).length;
  9727. const sources = [];
  9728. let meta, i, line, source;
  9729. for (i = 0; i < count; ++i) {
  9730. meta = chart.getDatasetMeta(i);
  9731. line = meta.dataset;
  9732. source = null;
  9733. if (line && line.options && line instanceof LineElement) {
  9734. source = {
  9735. visible: chart.isDatasetVisible(i),
  9736. index: i,
  9737. fill: decodeFill(line, i, count),
  9738. chart,
  9739. axis: meta.controller.options.indexAxis,
  9740. scale: meta.vScale,
  9741. line,
  9742. };
  9743. }
  9744. meta.$filler = source;
  9745. sources.push(source);
  9746. }
  9747. for (i = 0; i < count; ++i) {
  9748. source = sources[i];
  9749. if (!source || source.fill === false) {
  9750. continue;
  9751. }
  9752. source.fill = resolveTarget(sources, i, options.propagate);
  9753. }
  9754. },
  9755. beforeDraw(chart, _args, options) {
  9756. const draw = options.drawTime === 'beforeDraw';
  9757. const metasets = chart.getSortedVisibleDatasetMetas();
  9758. const area = chart.chartArea;
  9759. for (let i = metasets.length - 1; i >= 0; --i) {
  9760. const source = metasets[i].$filler;
  9761. if (!source) {
  9762. continue;
  9763. }
  9764. source.line.updateControlPoints(area);
  9765. if (draw) {
  9766. drawfill(chart.ctx, source, area);
  9767. }
  9768. }
  9769. },
  9770. beforeDatasetsDraw(chart, _args, options) {
  9771. if (options.drawTime !== 'beforeDatasetsDraw') {
  9772. return;
  9773. }
  9774. const metasets = chart.getSortedVisibleDatasetMetas();
  9775. for (let i = metasets.length - 1; i >= 0; --i) {
  9776. const source = metasets[i].$filler;
  9777. if (source) {
  9778. drawfill(chart.ctx, source, chart.chartArea);
  9779. }
  9780. }
  9781. },
  9782. beforeDatasetDraw(chart, args, options) {
  9783. const source = args.meta.$filler;
  9784. if (!source || source.fill === false || options.drawTime !== 'beforeDatasetDraw') {
  9785. return;
  9786. }
  9787. drawfill(chart.ctx, source, chart.chartArea);
  9788. },
  9789. defaults: {
  9790. propagate: true,
  9791. drawTime: 'beforeDatasetDraw'
  9792. }
  9793. };
  9794. const getBoxSize = (labelOpts, fontSize) => {
  9795. let {boxHeight = fontSize, boxWidth = fontSize} = labelOpts;
  9796. if (labelOpts.usePointStyle) {
  9797. boxHeight = Math.min(boxHeight, fontSize);
  9798. boxWidth = Math.min(boxWidth, fontSize);
  9799. }
  9800. return {
  9801. boxWidth,
  9802. boxHeight,
  9803. itemHeight: Math.max(fontSize, boxHeight)
  9804. };
  9805. };
  9806. const itemsEqual = (a, b) => a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index;
  9807. class Legend extends Element {
  9808. constructor(config) {
  9809. super();
  9810. this._added = false;
  9811. this.legendHitBoxes = [];
  9812. this._hoveredItem = null;
  9813. this.doughnutMode = false;
  9814. this.chart = config.chart;
  9815. this.options = config.options;
  9816. this.ctx = config.ctx;
  9817. this.legendItems = undefined;
  9818. this.columnSizes = undefined;
  9819. this.lineWidths = undefined;
  9820. this.maxHeight = undefined;
  9821. this.maxWidth = undefined;
  9822. this.top = undefined;
  9823. this.bottom = undefined;
  9824. this.left = undefined;
  9825. this.right = undefined;
  9826. this.height = undefined;
  9827. this.width = undefined;
  9828. this._margins = undefined;
  9829. this.position = undefined;
  9830. this.weight = undefined;
  9831. this.fullSize = undefined;
  9832. }
  9833. update(maxWidth, maxHeight, margins) {
  9834. const me = this;
  9835. me.maxWidth = maxWidth;
  9836. me.maxHeight = maxHeight;
  9837. me._margins = margins;
  9838. me.setDimensions();
  9839. me.buildLabels();
  9840. me.fit();
  9841. }
  9842. setDimensions() {
  9843. const me = this;
  9844. if (me.isHorizontal()) {
  9845. me.width = me.maxWidth;
  9846. me.left = 0;
  9847. me.right = me.width;
  9848. } else {
  9849. me.height = me.maxHeight;
  9850. me.top = 0;
  9851. me.bottom = me.height;
  9852. }
  9853. }
  9854. buildLabels() {
  9855. const me = this;
  9856. const labelOpts = me.options.labels || {};
  9857. let legendItems = callback(labelOpts.generateLabels, [me.chart], me) || [];
  9858. if (labelOpts.filter) {
  9859. legendItems = legendItems.filter((item) => labelOpts.filter(item, me.chart.data));
  9860. }
  9861. if (labelOpts.sort) {
  9862. legendItems = legendItems.sort((a, b) => labelOpts.sort(a, b, me.chart.data));
  9863. }
  9864. if (me.options.reverse) {
  9865. legendItems.reverse();
  9866. }
  9867. me.legendItems = legendItems;
  9868. }
  9869. fit() {
  9870. const me = this;
  9871. const {options, ctx} = me;
  9872. if (!options.display) {
  9873. me.width = me.height = 0;
  9874. return;
  9875. }
  9876. const labelOpts = options.labels;
  9877. const labelFont = toFont(labelOpts.font);
  9878. const fontSize = labelFont.size;
  9879. const titleHeight = me._computeTitleHeight();
  9880. const {boxWidth, itemHeight} = getBoxSize(labelOpts, fontSize);
  9881. let width, height;
  9882. ctx.font = labelFont.string;
  9883. if (me.isHorizontal()) {
  9884. width = me.maxWidth;
  9885. height = me._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10;
  9886. } else {
  9887. height = me.maxHeight;
  9888. width = me._fitCols(titleHeight, fontSize, boxWidth, itemHeight) + 10;
  9889. }
  9890. me.width = Math.min(width, options.maxWidth || me.maxWidth);
  9891. me.height = Math.min(height, options.maxHeight || me.maxHeight);
  9892. }
  9893. _fitRows(titleHeight, fontSize, boxWidth, itemHeight) {
  9894. const me = this;
  9895. const {ctx, maxWidth, options: {labels: {padding}}} = me;
  9896. const hitboxes = me.legendHitBoxes = [];
  9897. const lineWidths = me.lineWidths = [0];
  9898. const lineHeight = itemHeight + padding;
  9899. let totalHeight = titleHeight;
  9900. ctx.textAlign = 'left';
  9901. ctx.textBaseline = 'middle';
  9902. let row = -1;
  9903. let top = -lineHeight;
  9904. me.legendItems.forEach((legendItem, i) => {
  9905. const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  9906. if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) {
  9907. totalHeight += lineHeight;
  9908. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  9909. top += lineHeight;
  9910. row++;
  9911. }
  9912. hitboxes[i] = {left: 0, top, row, width: itemWidth, height: itemHeight};
  9913. lineWidths[lineWidths.length - 1] += itemWidth + padding;
  9914. });
  9915. return totalHeight;
  9916. }
  9917. _fitCols(titleHeight, fontSize, boxWidth, itemHeight) {
  9918. const me = this;
  9919. const {ctx, maxHeight, options: {labels: {padding}}} = me;
  9920. const hitboxes = me.legendHitBoxes = [];
  9921. const columnSizes = me.columnSizes = [];
  9922. const heightLimit = maxHeight - titleHeight;
  9923. let totalWidth = padding;
  9924. let currentColWidth = 0;
  9925. let currentColHeight = 0;
  9926. let left = 0;
  9927. let top = 0;
  9928. let col = 0;
  9929. me.legendItems.forEach((legendItem, i) => {
  9930. const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  9931. if (i > 0 && currentColHeight + fontSize + 2 * padding > heightLimit) {
  9932. totalWidth += currentColWidth + padding;
  9933. columnSizes.push({width: currentColWidth, height: currentColHeight});
  9934. left += currentColWidth + padding;
  9935. col++;
  9936. top = 0;
  9937. currentColWidth = currentColHeight = 0;
  9938. }
  9939. currentColWidth = Math.max(currentColWidth, itemWidth);
  9940. currentColHeight += fontSize + padding;
  9941. hitboxes[i] = {left, top, col, width: itemWidth, height: itemHeight};
  9942. top += itemHeight + padding;
  9943. });
  9944. totalWidth += currentColWidth;
  9945. columnSizes.push({width: currentColWidth, height: currentColHeight});
  9946. return totalWidth;
  9947. }
  9948. adjustHitBoxes() {
  9949. const me = this;
  9950. if (!me.options.display) {
  9951. return;
  9952. }
  9953. const titleHeight = me._computeTitleHeight();
  9954. const {legendHitBoxes: hitboxes, options: {align, labels: {padding}}} = me;
  9955. if (this.isHorizontal()) {
  9956. let row = 0;
  9957. let left = _alignStartEnd(align, me.left + padding, me.right - me.lineWidths[row]);
  9958. for (const hitbox of hitboxes) {
  9959. if (row !== hitbox.row) {
  9960. row = hitbox.row;
  9961. left = _alignStartEnd(align, me.left + padding, me.right - me.lineWidths[row]);
  9962. }
  9963. hitbox.top += me.top + titleHeight + padding;
  9964. hitbox.left = left;
  9965. left += hitbox.width + padding;
  9966. }
  9967. } else {
  9968. let col = 0;
  9969. let top = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - me.columnSizes[col].height);
  9970. for (const hitbox of hitboxes) {
  9971. if (hitbox.col !== col) {
  9972. col = hitbox.col;
  9973. top = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - me.columnSizes[col].height);
  9974. }
  9975. hitbox.top = top;
  9976. hitbox.left += me.left + padding;
  9977. top += hitbox.height + padding;
  9978. }
  9979. }
  9980. }
  9981. isHorizontal() {
  9982. return this.options.position === 'top' || this.options.position === 'bottom';
  9983. }
  9984. draw() {
  9985. const me = this;
  9986. if (me.options.display) {
  9987. const ctx = me.ctx;
  9988. clipArea(ctx, me);
  9989. me._draw();
  9990. unclipArea(ctx);
  9991. }
  9992. }
  9993. _draw() {
  9994. const me = this;
  9995. const {options: opts, columnSizes, lineWidths, ctx} = me;
  9996. const {align, labels: labelOpts} = opts;
  9997. const defaultColor = defaults.color;
  9998. const rtlHelper = getRtlAdapter(opts.rtl, me.left, me.width);
  9999. const labelFont = toFont(labelOpts.font);
  10000. const {color: fontColor, padding} = labelOpts;
  10001. const fontSize = labelFont.size;
  10002. const halfFontSize = fontSize / 2;
  10003. let cursor;
  10004. me.drawTitle();
  10005. ctx.textAlign = rtlHelper.textAlign('left');
  10006. ctx.textBaseline = 'middle';
  10007. ctx.lineWidth = 0.5;
  10008. ctx.font = labelFont.string;
  10009. const {boxWidth, boxHeight, itemHeight} = getBoxSize(labelOpts, fontSize);
  10010. const drawLegendBox = function(x, y, legendItem) {
  10011. if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) {
  10012. return;
  10013. }
  10014. ctx.save();
  10015. const lineWidth = valueOrDefault(legendItem.lineWidth, 1);
  10016. ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor);
  10017. ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt');
  10018. ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0);
  10019. ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter');
  10020. ctx.lineWidth = lineWidth;
  10021. ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor);
  10022. ctx.setLineDash(valueOrDefault(legendItem.lineDash, []));
  10023. if (labelOpts.usePointStyle) {
  10024. const drawOptions = {
  10025. radius: boxWidth * Math.SQRT2 / 2,
  10026. pointStyle: legendItem.pointStyle,
  10027. rotation: legendItem.rotation,
  10028. borderWidth: lineWidth
  10029. };
  10030. const centerX = rtlHelper.xPlus(x, boxWidth / 2);
  10031. const centerY = y + halfFontSize;
  10032. drawPoint(ctx, drawOptions, centerX, centerY);
  10033. } else {
  10034. const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0);
  10035. const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth);
  10036. const borderRadius = toTRBLCorners(legendItem.borderRadius);
  10037. ctx.beginPath();
  10038. if (Object.values(borderRadius).some(v => v !== 0)) {
  10039. addRoundedRectPath(ctx, {
  10040. x: xBoxLeft,
  10041. y: yBoxTop,
  10042. w: boxWidth,
  10043. h: boxHeight,
  10044. radius: borderRadius,
  10045. });
  10046. } else {
  10047. ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight);
  10048. }
  10049. ctx.fill();
  10050. if (lineWidth !== 0) {
  10051. ctx.stroke();
  10052. }
  10053. }
  10054. ctx.restore();
  10055. };
  10056. const fillText = function(x, y, legendItem) {
  10057. renderText(ctx, legendItem.text, x, y + (itemHeight / 2), labelFont, {
  10058. strikethrough: legendItem.hidden,
  10059. textAlign: legendItem.textAlign
  10060. });
  10061. };
  10062. const isHorizontal = me.isHorizontal();
  10063. const titleHeight = this._computeTitleHeight();
  10064. if (isHorizontal) {
  10065. cursor = {
  10066. x: _alignStartEnd(align, me.left + padding, me.right - lineWidths[0]),
  10067. y: me.top + padding + titleHeight,
  10068. line: 0
  10069. };
  10070. } else {
  10071. cursor = {
  10072. x: me.left + padding,
  10073. y: _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - columnSizes[0].height),
  10074. line: 0
  10075. };
  10076. }
  10077. overrideTextDirection(me.ctx, opts.textDirection);
  10078. const lineHeight = itemHeight + padding;
  10079. me.legendItems.forEach((legendItem, i) => {
  10080. ctx.strokeStyle = legendItem.fontColor || fontColor;
  10081. ctx.fillStyle = legendItem.fontColor || fontColor;
  10082. const textWidth = ctx.measureText(legendItem.text).width;
  10083. const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign));
  10084. const width = boxWidth + (fontSize / 2) + textWidth;
  10085. let x = cursor.x;
  10086. let y = cursor.y;
  10087. rtlHelper.setWidth(me.width);
  10088. if (isHorizontal) {
  10089. if (i > 0 && x + width + padding > me.right) {
  10090. y = cursor.y += lineHeight;
  10091. cursor.line++;
  10092. x = cursor.x = _alignStartEnd(align, me.left + padding, me.right - lineWidths[cursor.line]);
  10093. }
  10094. } else if (i > 0 && y + lineHeight > me.bottom) {
  10095. x = cursor.x = x + columnSizes[cursor.line].width + padding;
  10096. cursor.line++;
  10097. y = cursor.y = _alignStartEnd(align, me.top + titleHeight + padding, me.bottom - columnSizes[cursor.line].height);
  10098. }
  10099. const realX = rtlHelper.x(x);
  10100. drawLegendBox(realX, y, legendItem);
  10101. x = _textX(textAlign, x + boxWidth + halfFontSize, me.right);
  10102. fillText(rtlHelper.x(x), y, legendItem);
  10103. if (isHorizontal) {
  10104. cursor.x += width + padding;
  10105. } else {
  10106. cursor.y += lineHeight;
  10107. }
  10108. });
  10109. restoreTextDirection(me.ctx, opts.textDirection);
  10110. }
  10111. drawTitle() {
  10112. const me = this;
  10113. const opts = me.options;
  10114. const titleOpts = opts.title;
  10115. const titleFont = toFont(titleOpts.font);
  10116. const titlePadding = toPadding(titleOpts.padding);
  10117. if (!titleOpts.display) {
  10118. return;
  10119. }
  10120. const rtlHelper = getRtlAdapter(opts.rtl, me.left, me.width);
  10121. const ctx = me.ctx;
  10122. const position = titleOpts.position;
  10123. const halfFontSize = titleFont.size / 2;
  10124. const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize;
  10125. let y;
  10126. let left = me.left;
  10127. let maxWidth = me.width;
  10128. if (this.isHorizontal()) {
  10129. maxWidth = Math.max(...me.lineWidths);
  10130. y = me.top + topPaddingPlusHalfFontSize;
  10131. left = _alignStartEnd(opts.align, left, me.right - maxWidth);
  10132. } else {
  10133. const maxHeight = me.columnSizes.reduce((acc, size) => Math.max(acc, size.height), 0);
  10134. y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, me.top, me.bottom - maxHeight - opts.labels.padding - me._computeTitleHeight());
  10135. }
  10136. const x = _alignStartEnd(position, left, left + maxWidth);
  10137. ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position));
  10138. ctx.textBaseline = 'middle';
  10139. ctx.strokeStyle = titleOpts.color;
  10140. ctx.fillStyle = titleOpts.color;
  10141. ctx.font = titleFont.string;
  10142. renderText(ctx, titleOpts.text, x, y, titleFont);
  10143. }
  10144. _computeTitleHeight() {
  10145. const titleOpts = this.options.title;
  10146. const titleFont = toFont(titleOpts.font);
  10147. const titlePadding = toPadding(titleOpts.padding);
  10148. return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0;
  10149. }
  10150. _getLegendItemAt(x, y) {
  10151. const me = this;
  10152. let i, hitBox, lh;
  10153. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  10154. lh = me.legendHitBoxes;
  10155. for (i = 0; i < lh.length; ++i) {
  10156. hitBox = lh[i];
  10157. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  10158. return me.legendItems[i];
  10159. }
  10160. }
  10161. }
  10162. return null;
  10163. }
  10164. handleEvent(e) {
  10165. const me = this;
  10166. const opts = me.options;
  10167. if (!isListened(e.type, opts)) {
  10168. return;
  10169. }
  10170. const hoveredItem = me._getLegendItemAt(e.x, e.y);
  10171. if (e.type === 'mousemove') {
  10172. const previous = me._hoveredItem;
  10173. const sameItem = itemsEqual(previous, hoveredItem);
  10174. if (previous && !sameItem) {
  10175. callback(opts.onLeave, [e, previous, me], me);
  10176. }
  10177. me._hoveredItem = hoveredItem;
  10178. if (hoveredItem && !sameItem) {
  10179. callback(opts.onHover, [e, hoveredItem, me], me);
  10180. }
  10181. } else if (hoveredItem) {
  10182. callback(opts.onClick, [e, hoveredItem, me], me);
  10183. }
  10184. }
  10185. }
  10186. function isListened(type, opts) {
  10187. if (type === 'mousemove' && (opts.onHover || opts.onLeave)) {
  10188. return true;
  10189. }
  10190. if (opts.onClick && (type === 'click' || type === 'mouseup')) {
  10191. return true;
  10192. }
  10193. return false;
  10194. }
  10195. var plugin_legend = {
  10196. id: 'legend',
  10197. _element: Legend,
  10198. start(chart, _args, options) {
  10199. const legend = chart.legend = new Legend({ctx: chart.ctx, options, chart});
  10200. layouts.configure(chart, legend, options);
  10201. layouts.addBox(chart, legend);
  10202. },
  10203. stop(chart) {
  10204. layouts.removeBox(chart, chart.legend);
  10205. delete chart.legend;
  10206. },
  10207. beforeUpdate(chart, _args, options) {
  10208. const legend = chart.legend;
  10209. layouts.configure(chart, legend, options);
  10210. legend.options = options;
  10211. },
  10212. afterUpdate(chart) {
  10213. const legend = chart.legend;
  10214. legend.buildLabels();
  10215. legend.adjustHitBoxes();
  10216. },
  10217. afterEvent(chart, args) {
  10218. if (!args.replay) {
  10219. chart.legend.handleEvent(args.event);
  10220. }
  10221. },
  10222. defaults: {
  10223. display: true,
  10224. position: 'top',
  10225. align: 'center',
  10226. fullSize: true,
  10227. reverse: false,
  10228. weight: 1000,
  10229. onClick(e, legendItem, legend) {
  10230. const index = legendItem.datasetIndex;
  10231. const ci = legend.chart;
  10232. if (ci.isDatasetVisible(index)) {
  10233. ci.hide(index);
  10234. legendItem.hidden = true;
  10235. } else {
  10236. ci.show(index);
  10237. legendItem.hidden = false;
  10238. }
  10239. },
  10240. onHover: null,
  10241. onLeave: null,
  10242. labels: {
  10243. color: (ctx) => ctx.chart.options.color,
  10244. boxWidth: 40,
  10245. padding: 10,
  10246. generateLabels(chart) {
  10247. const datasets = chart.data.datasets;
  10248. const {labels: {usePointStyle, pointStyle, textAlign, color}} = chart.legend.options;
  10249. return chart._getSortedDatasetMetas().map((meta) => {
  10250. const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  10251. const borderWidth = toPadding(style.borderWidth);
  10252. return {
  10253. text: datasets[meta.index].label,
  10254. fillStyle: style.backgroundColor,
  10255. fontColor: color,
  10256. hidden: !meta.visible,
  10257. lineCap: style.borderCapStyle,
  10258. lineDash: style.borderDash,
  10259. lineDashOffset: style.borderDashOffset,
  10260. lineJoin: style.borderJoinStyle,
  10261. lineWidth: (borderWidth.width + borderWidth.height) / 4,
  10262. strokeStyle: style.borderColor,
  10263. pointStyle: pointStyle || style.pointStyle,
  10264. rotation: style.rotation,
  10265. textAlign: textAlign || style.textAlign,
  10266. borderRadius: 0,
  10267. datasetIndex: meta.index
  10268. };
  10269. }, this);
  10270. }
  10271. },
  10272. title: {
  10273. color: (ctx) => ctx.chart.options.color,
  10274. display: false,
  10275. position: 'center',
  10276. text: '',
  10277. }
  10278. },
  10279. descriptors: {
  10280. _scriptable: (name) => !name.startsWith('on'),
  10281. labels: {
  10282. _scriptable: (name) => !['generateLabels', 'filter', 'sort'].includes(name),
  10283. }
  10284. },
  10285. };
  10286. class Title extends Element {
  10287. constructor(config) {
  10288. super();
  10289. this.chart = config.chart;
  10290. this.options = config.options;
  10291. this.ctx = config.ctx;
  10292. this._padding = undefined;
  10293. this.top = undefined;
  10294. this.bottom = undefined;
  10295. this.left = undefined;
  10296. this.right = undefined;
  10297. this.width = undefined;
  10298. this.height = undefined;
  10299. this.position = undefined;
  10300. this.weight = undefined;
  10301. this.fullSize = undefined;
  10302. }
  10303. update(maxWidth, maxHeight) {
  10304. const me = this;
  10305. const opts = me.options;
  10306. me.left = 0;
  10307. me.top = 0;
  10308. if (!opts.display) {
  10309. me.width = me.height = me.right = me.bottom = 0;
  10310. return;
  10311. }
  10312. me.width = me.right = maxWidth;
  10313. me.height = me.bottom = maxHeight;
  10314. const lineCount = isArray(opts.text) ? opts.text.length : 1;
  10315. me._padding = toPadding(opts.padding);
  10316. const textSize = lineCount * toFont(opts.font).lineHeight + me._padding.height;
  10317. if (me.isHorizontal()) {
  10318. me.height = textSize;
  10319. } else {
  10320. me.width = textSize;
  10321. }
  10322. }
  10323. isHorizontal() {
  10324. const pos = this.options.position;
  10325. return pos === 'top' || pos === 'bottom';
  10326. }
  10327. _drawArgs(offset) {
  10328. const {top, left, bottom, right, options} = this;
  10329. const align = options.align;
  10330. let rotation = 0;
  10331. let maxWidth, titleX, titleY;
  10332. if (this.isHorizontal()) {
  10333. titleX = _alignStartEnd(align, left, right);
  10334. titleY = top + offset;
  10335. maxWidth = right - left;
  10336. } else {
  10337. if (options.position === 'left') {
  10338. titleX = left + offset;
  10339. titleY = _alignStartEnd(align, bottom, top);
  10340. rotation = PI * -0.5;
  10341. } else {
  10342. titleX = right - offset;
  10343. titleY = _alignStartEnd(align, top, bottom);
  10344. rotation = PI * 0.5;
  10345. }
  10346. maxWidth = bottom - top;
  10347. }
  10348. return {titleX, titleY, maxWidth, rotation};
  10349. }
  10350. draw() {
  10351. const me = this;
  10352. const ctx = me.ctx;
  10353. const opts = me.options;
  10354. if (!opts.display) {
  10355. return;
  10356. }
  10357. const fontOpts = toFont(opts.font);
  10358. const lineHeight = fontOpts.lineHeight;
  10359. const offset = lineHeight / 2 + me._padding.top;
  10360. const {titleX, titleY, maxWidth, rotation} = me._drawArgs(offset);
  10361. renderText(ctx, opts.text, 0, 0, fontOpts, {
  10362. color: opts.color,
  10363. maxWidth,
  10364. rotation,
  10365. textAlign: _toLeftRightCenter(opts.align),
  10366. textBaseline: 'middle',
  10367. translation: [titleX, titleY],
  10368. });
  10369. }
  10370. }
  10371. function createTitle(chart, titleOpts) {
  10372. const title = new Title({
  10373. ctx: chart.ctx,
  10374. options: titleOpts,
  10375. chart
  10376. });
  10377. layouts.configure(chart, title, titleOpts);
  10378. layouts.addBox(chart, title);
  10379. chart.titleBlock = title;
  10380. }
  10381. var plugin_title = {
  10382. id: 'title',
  10383. _element: Title,
  10384. start(chart, _args, options) {
  10385. createTitle(chart, options);
  10386. },
  10387. stop(chart) {
  10388. const titleBlock = chart.titleBlock;
  10389. layouts.removeBox(chart, titleBlock);
  10390. delete chart.titleBlock;
  10391. },
  10392. beforeUpdate(chart, _args, options) {
  10393. const title = chart.titleBlock;
  10394. layouts.configure(chart, title, options);
  10395. title.options = options;
  10396. },
  10397. defaults: {
  10398. align: 'center',
  10399. display: false,
  10400. font: {
  10401. weight: 'bold',
  10402. },
  10403. fullSize: true,
  10404. padding: 10,
  10405. position: 'top',
  10406. text: '',
  10407. weight: 2000
  10408. },
  10409. defaultRoutes: {
  10410. color: 'color'
  10411. },
  10412. descriptors: {
  10413. _scriptable: true,
  10414. _indexable: false,
  10415. },
  10416. };
  10417. const positioners = {
  10418. average(items) {
  10419. if (!items.length) {
  10420. return false;
  10421. }
  10422. let i, len;
  10423. let x = 0;
  10424. let y = 0;
  10425. let count = 0;
  10426. for (i = 0, len = items.length; i < len; ++i) {
  10427. const el = items[i].element;
  10428. if (el && el.hasValue()) {
  10429. const pos = el.tooltipPosition();
  10430. x += pos.x;
  10431. y += pos.y;
  10432. ++count;
  10433. }
  10434. }
  10435. return {
  10436. x: x / count,
  10437. y: y / count
  10438. };
  10439. },
  10440. nearest(items, eventPosition) {
  10441. if (!items.length) {
  10442. return false;
  10443. }
  10444. let x = eventPosition.x;
  10445. let y = eventPosition.y;
  10446. let minDistance = Number.POSITIVE_INFINITY;
  10447. let i, len, nearestElement;
  10448. for (i = 0, len = items.length; i < len; ++i) {
  10449. const el = items[i].element;
  10450. if (el && el.hasValue()) {
  10451. const center = el.getCenterPoint();
  10452. const d = distanceBetweenPoints(eventPosition, center);
  10453. if (d < minDistance) {
  10454. minDistance = d;
  10455. nearestElement = el;
  10456. }
  10457. }
  10458. }
  10459. if (nearestElement) {
  10460. const tp = nearestElement.tooltipPosition();
  10461. x = tp.x;
  10462. y = tp.y;
  10463. }
  10464. return {
  10465. x,
  10466. y
  10467. };
  10468. }
  10469. };
  10470. function pushOrConcat(base, toPush) {
  10471. if (toPush) {
  10472. if (isArray(toPush)) {
  10473. Array.prototype.push.apply(base, toPush);
  10474. } else {
  10475. base.push(toPush);
  10476. }
  10477. }
  10478. return base;
  10479. }
  10480. function splitNewlines(str) {
  10481. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  10482. return str.split('\n');
  10483. }
  10484. return str;
  10485. }
  10486. function createTooltipItem(chart, item) {
  10487. const {element, datasetIndex, index} = item;
  10488. const controller = chart.getDatasetMeta(datasetIndex).controller;
  10489. const {label, value} = controller.getLabelAndValue(index);
  10490. return {
  10491. chart,
  10492. label,
  10493. parsed: controller.getParsed(index),
  10494. raw: chart.data.datasets[datasetIndex].data[index],
  10495. formattedValue: value,
  10496. dataset: controller.getDataset(),
  10497. dataIndex: index,
  10498. datasetIndex,
  10499. element
  10500. };
  10501. }
  10502. function getTooltipSize(tooltip, options) {
  10503. const ctx = tooltip._chart.ctx;
  10504. const {body, footer, title} = tooltip;
  10505. const {boxWidth, boxHeight} = options;
  10506. const bodyFont = toFont(options.bodyFont);
  10507. const titleFont = toFont(options.titleFont);
  10508. const footerFont = toFont(options.footerFont);
  10509. const titleLineCount = title.length;
  10510. const footerLineCount = footer.length;
  10511. const bodyLineItemCount = body.length;
  10512. const padding = toPadding(options.padding);
  10513. let height = padding.height;
  10514. let width = 0;
  10515. let combinedBodyLength = body.reduce((count, bodyItem) => count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0);
  10516. combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length;
  10517. if (titleLineCount) {
  10518. height += titleLineCount * titleFont.lineHeight
  10519. + (titleLineCount - 1) * options.titleSpacing
  10520. + options.titleMarginBottom;
  10521. }
  10522. if (combinedBodyLength) {
  10523. const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight;
  10524. height += bodyLineItemCount * bodyLineHeight
  10525. + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight
  10526. + (combinedBodyLength - 1) * options.bodySpacing;
  10527. }
  10528. if (footerLineCount) {
  10529. height += options.footerMarginTop
  10530. + footerLineCount * footerFont.lineHeight
  10531. + (footerLineCount - 1) * options.footerSpacing;
  10532. }
  10533. let widthPadding = 0;
  10534. const maxLineWidth = function(line) {
  10535. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  10536. };
  10537. ctx.save();
  10538. ctx.font = titleFont.string;
  10539. each(tooltip.title, maxLineWidth);
  10540. ctx.font = bodyFont.string;
  10541. each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth);
  10542. widthPadding = options.displayColors ? (boxWidth + 2) : 0;
  10543. each(body, (bodyItem) => {
  10544. each(bodyItem.before, maxLineWidth);
  10545. each(bodyItem.lines, maxLineWidth);
  10546. each(bodyItem.after, maxLineWidth);
  10547. });
  10548. widthPadding = 0;
  10549. ctx.font = footerFont.string;
  10550. each(tooltip.footer, maxLineWidth);
  10551. ctx.restore();
  10552. width += padding.width;
  10553. return {width, height};
  10554. }
  10555. function determineYAlign(chart, size) {
  10556. const {y, height} = size;
  10557. if (y < height / 2) {
  10558. return 'top';
  10559. } else if (y > (chart.height - height / 2)) {
  10560. return 'bottom';
  10561. }
  10562. return 'center';
  10563. }
  10564. function doesNotFitWithAlign(xAlign, chart, options, size) {
  10565. const {x, width} = size;
  10566. const caret = options.caretSize + options.caretPadding;
  10567. if (xAlign === 'left' && x + width + caret > chart.width) {
  10568. return true;
  10569. }
  10570. if (xAlign === 'right' && x - width - caret < 0) {
  10571. return true;
  10572. }
  10573. }
  10574. function determineXAlign(chart, options, size, yAlign) {
  10575. const {x, width} = size;
  10576. const {width: chartWidth, chartArea: {left, right}} = chart;
  10577. let xAlign = 'center';
  10578. if (yAlign === 'center') {
  10579. xAlign = x <= (left + right) / 2 ? 'left' : 'right';
  10580. } else if (x <= width / 2) {
  10581. xAlign = 'left';
  10582. } else if (x >= chartWidth - width / 2) {
  10583. xAlign = 'right';
  10584. }
  10585. if (doesNotFitWithAlign(xAlign, chart, options, size)) {
  10586. xAlign = 'center';
  10587. }
  10588. return xAlign;
  10589. }
  10590. function determineAlignment(chart, options, size) {
  10591. const yAlign = options.yAlign || determineYAlign(chart, size);
  10592. return {
  10593. xAlign: options.xAlign || determineXAlign(chart, options, size, yAlign),
  10594. yAlign
  10595. };
  10596. }
  10597. function alignX(size, xAlign) {
  10598. let {x, width} = size;
  10599. if (xAlign === 'right') {
  10600. x -= width;
  10601. } else if (xAlign === 'center') {
  10602. x -= (width / 2);
  10603. }
  10604. return x;
  10605. }
  10606. function alignY(size, yAlign, paddingAndSize) {
  10607. let {y, height} = size;
  10608. if (yAlign === 'top') {
  10609. y += paddingAndSize;
  10610. } else if (yAlign === 'bottom') {
  10611. y -= height + paddingAndSize;
  10612. } else {
  10613. y -= (height / 2);
  10614. }
  10615. return y;
  10616. }
  10617. function getBackgroundPoint(options, size, alignment, chart) {
  10618. const {caretSize, caretPadding, cornerRadius} = options;
  10619. const {xAlign, yAlign} = alignment;
  10620. const paddingAndSize = caretSize + caretPadding;
  10621. const radiusAndPadding = cornerRadius + caretPadding;
  10622. let x = alignX(size, xAlign);
  10623. const y = alignY(size, yAlign, paddingAndSize);
  10624. if (yAlign === 'center') {
  10625. if (xAlign === 'left') {
  10626. x += paddingAndSize;
  10627. } else if (xAlign === 'right') {
  10628. x -= paddingAndSize;
  10629. }
  10630. } else if (xAlign === 'left') {
  10631. x -= radiusAndPadding;
  10632. } else if (xAlign === 'right') {
  10633. x += radiusAndPadding;
  10634. }
  10635. return {
  10636. x: _limitValue(x, 0, chart.width - size.width),
  10637. y: _limitValue(y, 0, chart.height - size.height)
  10638. };
  10639. }
  10640. function getAlignedX(tooltip, align, options) {
  10641. const padding = toPadding(options.padding);
  10642. return align === 'center'
  10643. ? tooltip.x + tooltip.width / 2
  10644. : align === 'right'
  10645. ? tooltip.x + tooltip.width - padding.right
  10646. : tooltip.x + padding.left;
  10647. }
  10648. function getBeforeAfterBodyLines(callback) {
  10649. return pushOrConcat([], splitNewlines(callback));
  10650. }
  10651. function createTooltipContext(parent, tooltip, tooltipItems) {
  10652. return Object.assign(Object.create(parent), {
  10653. tooltip,
  10654. tooltipItems,
  10655. type: 'tooltip'
  10656. });
  10657. }
  10658. function overrideCallbacks(callbacks, context) {
  10659. const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks;
  10660. return override ? callbacks.override(override) : callbacks;
  10661. }
  10662. class Tooltip extends Element {
  10663. constructor(config) {
  10664. super();
  10665. this.opacity = 0;
  10666. this._active = [];
  10667. this._chart = config._chart;
  10668. this._eventPosition = undefined;
  10669. this._size = undefined;
  10670. this._cachedAnimations = undefined;
  10671. this._tooltipItems = [];
  10672. this.$animations = undefined;
  10673. this.$context = undefined;
  10674. this.options = config.options;
  10675. this.dataPoints = undefined;
  10676. this.title = undefined;
  10677. this.beforeBody = undefined;
  10678. this.body = undefined;
  10679. this.afterBody = undefined;
  10680. this.footer = undefined;
  10681. this.xAlign = undefined;
  10682. this.yAlign = undefined;
  10683. this.x = undefined;
  10684. this.y = undefined;
  10685. this.height = undefined;
  10686. this.width = undefined;
  10687. this.caretX = undefined;
  10688. this.caretY = undefined;
  10689. this.labelColors = undefined;
  10690. this.labelPointStyles = undefined;
  10691. this.labelTextColors = undefined;
  10692. }
  10693. initialize(options) {
  10694. this.options = options;
  10695. this._cachedAnimations = undefined;
  10696. this.$context = undefined;
  10697. }
  10698. _resolveAnimations() {
  10699. const me = this;
  10700. const cached = me._cachedAnimations;
  10701. if (cached) {
  10702. return cached;
  10703. }
  10704. const chart = me._chart;
  10705. const options = me.options.setContext(me.getContext());
  10706. const opts = options.enabled && chart.options.animation && options.animations;
  10707. const animations = new Animations(me._chart, opts);
  10708. if (opts._cacheable) {
  10709. me._cachedAnimations = Object.freeze(animations);
  10710. }
  10711. return animations;
  10712. }
  10713. getContext() {
  10714. const me = this;
  10715. return me.$context ||
  10716. (me.$context = createTooltipContext(me._chart.getContext(), me, me._tooltipItems));
  10717. }
  10718. getTitle(context, options) {
  10719. const me = this;
  10720. const {callbacks} = options;
  10721. const beforeTitle = callbacks.beforeTitle.apply(me, [context]);
  10722. const title = callbacks.title.apply(me, [context]);
  10723. const afterTitle = callbacks.afterTitle.apply(me, [context]);
  10724. let lines = [];
  10725. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  10726. lines = pushOrConcat(lines, splitNewlines(title));
  10727. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  10728. return lines;
  10729. }
  10730. getBeforeBody(tooltipItems, options) {
  10731. return getBeforeAfterBodyLines(options.callbacks.beforeBody.apply(this, [tooltipItems]));
  10732. }
  10733. getBody(tooltipItems, options) {
  10734. const me = this;
  10735. const {callbacks} = options;
  10736. const bodyItems = [];
  10737. each(tooltipItems, (context) => {
  10738. const bodyItem = {
  10739. before: [],
  10740. lines: [],
  10741. after: []
  10742. };
  10743. const scoped = overrideCallbacks(callbacks, context);
  10744. pushOrConcat(bodyItem.before, splitNewlines(scoped.beforeLabel.call(me, context)));
  10745. pushOrConcat(bodyItem.lines, scoped.label.call(me, context));
  10746. pushOrConcat(bodyItem.after, splitNewlines(scoped.afterLabel.call(me, context)));
  10747. bodyItems.push(bodyItem);
  10748. });
  10749. return bodyItems;
  10750. }
  10751. getAfterBody(tooltipItems, options) {
  10752. return getBeforeAfterBodyLines(options.callbacks.afterBody.apply(this, [tooltipItems]));
  10753. }
  10754. getFooter(tooltipItems, options) {
  10755. const me = this;
  10756. const {callbacks} = options;
  10757. const beforeFooter = callbacks.beforeFooter.apply(me, [tooltipItems]);
  10758. const footer = callbacks.footer.apply(me, [tooltipItems]);
  10759. const afterFooter = callbacks.afterFooter.apply(me, [tooltipItems]);
  10760. let lines = [];
  10761. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  10762. lines = pushOrConcat(lines, splitNewlines(footer));
  10763. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  10764. return lines;
  10765. }
  10766. _createItems(options) {
  10767. const me = this;
  10768. const active = me._active;
  10769. const data = me._chart.data;
  10770. const labelColors = [];
  10771. const labelPointStyles = [];
  10772. const labelTextColors = [];
  10773. let tooltipItems = [];
  10774. let i, len;
  10775. for (i = 0, len = active.length; i < len; ++i) {
  10776. tooltipItems.push(createTooltipItem(me._chart, active[i]));
  10777. }
  10778. if (options.filter) {
  10779. tooltipItems = tooltipItems.filter((element, index, array) => options.filter(element, index, array, data));
  10780. }
  10781. if (options.itemSort) {
  10782. tooltipItems = tooltipItems.sort((a, b) => options.itemSort(a, b, data));
  10783. }
  10784. each(tooltipItems, (context) => {
  10785. const scoped = overrideCallbacks(options.callbacks, context);
  10786. labelColors.push(scoped.labelColor.call(me, context));
  10787. labelPointStyles.push(scoped.labelPointStyle.call(me, context));
  10788. labelTextColors.push(scoped.labelTextColor.call(me, context));
  10789. });
  10790. me.labelColors = labelColors;
  10791. me.labelPointStyles = labelPointStyles;
  10792. me.labelTextColors = labelTextColors;
  10793. me.dataPoints = tooltipItems;
  10794. return tooltipItems;
  10795. }
  10796. update(changed, replay) {
  10797. const me = this;
  10798. const options = me.options.setContext(me.getContext());
  10799. const active = me._active;
  10800. let properties;
  10801. let tooltipItems = [];
  10802. if (!active.length) {
  10803. if (me.opacity !== 0) {
  10804. properties = {
  10805. opacity: 0
  10806. };
  10807. }
  10808. } else {
  10809. const position = positioners[options.position].call(me, active, me._eventPosition);
  10810. tooltipItems = me._createItems(options);
  10811. me.title = me.getTitle(tooltipItems, options);
  10812. me.beforeBody = me.getBeforeBody(tooltipItems, options);
  10813. me.body = me.getBody(tooltipItems, options);
  10814. me.afterBody = me.getAfterBody(tooltipItems, options);
  10815. me.footer = me.getFooter(tooltipItems, options);
  10816. const size = me._size = getTooltipSize(me, options);
  10817. const positionAndSize = Object.assign({}, position, size);
  10818. const alignment = determineAlignment(me._chart, options, positionAndSize);
  10819. const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, me._chart);
  10820. me.xAlign = alignment.xAlign;
  10821. me.yAlign = alignment.yAlign;
  10822. properties = {
  10823. opacity: 1,
  10824. x: backgroundPoint.x,
  10825. y: backgroundPoint.y,
  10826. width: size.width,
  10827. height: size.height,
  10828. caretX: position.x,
  10829. caretY: position.y
  10830. };
  10831. }
  10832. me._tooltipItems = tooltipItems;
  10833. me.$context = undefined;
  10834. if (properties) {
  10835. me._resolveAnimations().update(me, properties);
  10836. }
  10837. if (changed && options.external) {
  10838. options.external.call(me, {chart: me._chart, tooltip: me, replay});
  10839. }
  10840. }
  10841. drawCaret(tooltipPoint, ctx, size, options) {
  10842. const caretPosition = this.getCaretPosition(tooltipPoint, size, options);
  10843. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  10844. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  10845. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  10846. }
  10847. getCaretPosition(tooltipPoint, size, options) {
  10848. const {xAlign, yAlign} = this;
  10849. const {cornerRadius, caretSize} = options;
  10850. const {x: ptX, y: ptY} = tooltipPoint;
  10851. const {width, height} = size;
  10852. let x1, x2, x3, y1, y2, y3;
  10853. if (yAlign === 'center') {
  10854. y2 = ptY + (height / 2);
  10855. if (xAlign === 'left') {
  10856. x1 = ptX;
  10857. x2 = x1 - caretSize;
  10858. y1 = y2 + caretSize;
  10859. y3 = y2 - caretSize;
  10860. } else {
  10861. x1 = ptX + width;
  10862. x2 = x1 + caretSize;
  10863. y1 = y2 - caretSize;
  10864. y3 = y2 + caretSize;
  10865. }
  10866. x3 = x1;
  10867. } else {
  10868. if (xAlign === 'left') {
  10869. x2 = ptX + cornerRadius + (caretSize);
  10870. } else if (xAlign === 'right') {
  10871. x2 = ptX + width - cornerRadius - caretSize;
  10872. } else {
  10873. x2 = this.caretX;
  10874. }
  10875. if (yAlign === 'top') {
  10876. y1 = ptY;
  10877. y2 = y1 - caretSize;
  10878. x1 = x2 - caretSize;
  10879. x3 = x2 + caretSize;
  10880. } else {
  10881. y1 = ptY + height;
  10882. y2 = y1 + caretSize;
  10883. x1 = x2 + caretSize;
  10884. x3 = x2 - caretSize;
  10885. }
  10886. y3 = y1;
  10887. }
  10888. return {x1, x2, x3, y1, y2, y3};
  10889. }
  10890. drawTitle(pt, ctx, options) {
  10891. const me = this;
  10892. const title = me.title;
  10893. const length = title.length;
  10894. let titleFont, titleSpacing, i;
  10895. if (length) {
  10896. const rtlHelper = getRtlAdapter(options.rtl, me.x, me.width);
  10897. pt.x = getAlignedX(me, options.titleAlign, options);
  10898. ctx.textAlign = rtlHelper.textAlign(options.titleAlign);
  10899. ctx.textBaseline = 'middle';
  10900. titleFont = toFont(options.titleFont);
  10901. titleSpacing = options.titleSpacing;
  10902. ctx.fillStyle = options.titleColor;
  10903. ctx.font = titleFont.string;
  10904. for (i = 0; i < length; ++i) {
  10905. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2);
  10906. pt.y += titleFont.lineHeight + titleSpacing;
  10907. if (i + 1 === length) {
  10908. pt.y += options.titleMarginBottom - titleSpacing;
  10909. }
  10910. }
  10911. }
  10912. }
  10913. _drawColorBox(ctx, pt, i, rtlHelper, options) {
  10914. const me = this;
  10915. const labelColors = me.labelColors[i];
  10916. const labelPointStyle = me.labelPointStyles[i];
  10917. const {boxHeight, boxWidth} = options;
  10918. const bodyFont = toFont(options.bodyFont);
  10919. const colorX = getAlignedX(me, 'left', options);
  10920. const rtlColorX = rtlHelper.x(colorX);
  10921. const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0;
  10922. const colorY = pt.y + yOffSet;
  10923. if (options.usePointStyle) {
  10924. const drawOptions = {
  10925. radius: Math.min(boxWidth, boxHeight) / 2,
  10926. pointStyle: labelPointStyle.pointStyle,
  10927. rotation: labelPointStyle.rotation,
  10928. borderWidth: 1
  10929. };
  10930. const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2;
  10931. const centerY = colorY + boxHeight / 2;
  10932. ctx.strokeStyle = options.multiKeyBackground;
  10933. ctx.fillStyle = options.multiKeyBackground;
  10934. drawPoint(ctx, drawOptions, centerX, centerY);
  10935. ctx.strokeStyle = labelColors.borderColor;
  10936. ctx.fillStyle = labelColors.backgroundColor;
  10937. drawPoint(ctx, drawOptions, centerX, centerY);
  10938. } else {
  10939. ctx.lineWidth = labelColors.borderWidth || 1;
  10940. ctx.strokeStyle = labelColors.borderColor;
  10941. ctx.setLineDash(labelColors.borderDash || []);
  10942. ctx.lineDashOffset = labelColors.borderDashOffset || 0;
  10943. const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth);
  10944. const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - 2);
  10945. const borderRadius = toTRBLCorners(labelColors.borderRadius);
  10946. if (Object.values(borderRadius).some(v => v !== 0)) {
  10947. ctx.beginPath();
  10948. ctx.fillStyle = options.multiKeyBackground;
  10949. addRoundedRectPath(ctx, {
  10950. x: outerX,
  10951. y: colorY,
  10952. w: boxWidth,
  10953. h: boxHeight,
  10954. radius: borderRadius,
  10955. });
  10956. ctx.fill();
  10957. ctx.stroke();
  10958. ctx.fillStyle = labelColors.backgroundColor;
  10959. ctx.beginPath();
  10960. addRoundedRectPath(ctx, {
  10961. x: innerX,
  10962. y: colorY + 1,
  10963. w: boxWidth - 2,
  10964. h: boxHeight - 2,
  10965. radius: borderRadius,
  10966. });
  10967. ctx.fill();
  10968. } else {
  10969. ctx.fillStyle = options.multiKeyBackground;
  10970. ctx.fillRect(outerX, colorY, boxWidth, boxHeight);
  10971. ctx.strokeRect(outerX, colorY, boxWidth, boxHeight);
  10972. ctx.fillStyle = labelColors.backgroundColor;
  10973. ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2);
  10974. }
  10975. }
  10976. ctx.fillStyle = me.labelTextColors[i];
  10977. }
  10978. drawBody(pt, ctx, options) {
  10979. const me = this;
  10980. const {body} = me;
  10981. const {bodySpacing, bodyAlign, displayColors, boxHeight, boxWidth} = options;
  10982. const bodyFont = toFont(options.bodyFont);
  10983. let bodyLineHeight = bodyFont.lineHeight;
  10984. let xLinePadding = 0;
  10985. const rtlHelper = getRtlAdapter(options.rtl, me.x, me.width);
  10986. const fillLineOfText = function(line) {
  10987. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2);
  10988. pt.y += bodyLineHeight + bodySpacing;
  10989. };
  10990. const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  10991. let bodyItem, textColor, lines, i, j, ilen, jlen;
  10992. ctx.textAlign = bodyAlign;
  10993. ctx.textBaseline = 'middle';
  10994. ctx.font = bodyFont.string;
  10995. pt.x = getAlignedX(me, bodyAlignForCalculation, options);
  10996. ctx.fillStyle = options.bodyColor;
  10997. each(me.beforeBody, fillLineOfText);
  10998. xLinePadding = displayColors && bodyAlignForCalculation !== 'right'
  10999. ? bodyAlign === 'center' ? (boxWidth / 2 + 1) : (boxWidth + 2)
  11000. : 0;
  11001. for (i = 0, ilen = body.length; i < ilen; ++i) {
  11002. bodyItem = body[i];
  11003. textColor = me.labelTextColors[i];
  11004. ctx.fillStyle = textColor;
  11005. each(bodyItem.before, fillLineOfText);
  11006. lines = bodyItem.lines;
  11007. if (displayColors && lines.length) {
  11008. me._drawColorBox(ctx, pt, i, rtlHelper, options);
  11009. bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight);
  11010. }
  11011. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  11012. fillLineOfText(lines[j]);
  11013. bodyLineHeight = bodyFont.lineHeight;
  11014. }
  11015. each(bodyItem.after, fillLineOfText);
  11016. }
  11017. xLinePadding = 0;
  11018. bodyLineHeight = bodyFont.lineHeight;
  11019. each(me.afterBody, fillLineOfText);
  11020. pt.y -= bodySpacing;
  11021. }
  11022. drawFooter(pt, ctx, options) {
  11023. const me = this;
  11024. const footer = me.footer;
  11025. const length = footer.length;
  11026. let footerFont, i;
  11027. if (length) {
  11028. const rtlHelper = getRtlAdapter(options.rtl, me.x, me.width);
  11029. pt.x = getAlignedX(me, options.footerAlign, options);
  11030. pt.y += options.footerMarginTop;
  11031. ctx.textAlign = rtlHelper.textAlign(options.footerAlign);
  11032. ctx.textBaseline = 'middle';
  11033. footerFont = toFont(options.footerFont);
  11034. ctx.fillStyle = options.footerColor;
  11035. ctx.font = footerFont.string;
  11036. for (i = 0; i < length; ++i) {
  11037. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2);
  11038. pt.y += footerFont.lineHeight + options.footerSpacing;
  11039. }
  11040. }
  11041. }
  11042. drawBackground(pt, ctx, tooltipSize, options) {
  11043. const {xAlign, yAlign} = this;
  11044. const {x, y} = pt;
  11045. const {width, height} = tooltipSize;
  11046. const radius = options.cornerRadius;
  11047. ctx.fillStyle = options.backgroundColor;
  11048. ctx.strokeStyle = options.borderColor;
  11049. ctx.lineWidth = options.borderWidth;
  11050. ctx.beginPath();
  11051. ctx.moveTo(x + radius, y);
  11052. if (yAlign === 'top') {
  11053. this.drawCaret(pt, ctx, tooltipSize, options);
  11054. }
  11055. ctx.lineTo(x + width - radius, y);
  11056. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  11057. if (yAlign === 'center' && xAlign === 'right') {
  11058. this.drawCaret(pt, ctx, tooltipSize, options);
  11059. }
  11060. ctx.lineTo(x + width, y + height - radius);
  11061. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  11062. if (yAlign === 'bottom') {
  11063. this.drawCaret(pt, ctx, tooltipSize, options);
  11064. }
  11065. ctx.lineTo(x + radius, y + height);
  11066. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  11067. if (yAlign === 'center' && xAlign === 'left') {
  11068. this.drawCaret(pt, ctx, tooltipSize, options);
  11069. }
  11070. ctx.lineTo(x, y + radius);
  11071. ctx.quadraticCurveTo(x, y, x + radius, y);
  11072. ctx.closePath();
  11073. ctx.fill();
  11074. if (options.borderWidth > 0) {
  11075. ctx.stroke();
  11076. }
  11077. }
  11078. _updateAnimationTarget(options) {
  11079. const me = this;
  11080. const chart = me._chart;
  11081. const anims = me.$animations;
  11082. const animX = anims && anims.x;
  11083. const animY = anims && anims.y;
  11084. if (animX || animY) {
  11085. const position = positioners[options.position].call(me, me._active, me._eventPosition);
  11086. if (!position) {
  11087. return;
  11088. }
  11089. const size = me._size = getTooltipSize(me, options);
  11090. const positionAndSize = Object.assign({}, position, me._size);
  11091. const alignment = determineAlignment(chart, options, positionAndSize);
  11092. const point = getBackgroundPoint(options, positionAndSize, alignment, chart);
  11093. if (animX._to !== point.x || animY._to !== point.y) {
  11094. me.xAlign = alignment.xAlign;
  11095. me.yAlign = alignment.yAlign;
  11096. me.width = size.width;
  11097. me.height = size.height;
  11098. me.caretX = position.x;
  11099. me.caretY = position.y;
  11100. me._resolveAnimations().update(me, point);
  11101. }
  11102. }
  11103. }
  11104. draw(ctx) {
  11105. const me = this;
  11106. const options = me.options.setContext(me.getContext());
  11107. let opacity = me.opacity;
  11108. if (!opacity) {
  11109. return;
  11110. }
  11111. me._updateAnimationTarget(options);
  11112. const tooltipSize = {
  11113. width: me.width,
  11114. height: me.height
  11115. };
  11116. const pt = {
  11117. x: me.x,
  11118. y: me.y
  11119. };
  11120. opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity;
  11121. const padding = toPadding(options.padding);
  11122. const hasTooltipContent = me.title.length || me.beforeBody.length || me.body.length || me.afterBody.length || me.footer.length;
  11123. if (options.enabled && hasTooltipContent) {
  11124. ctx.save();
  11125. ctx.globalAlpha = opacity;
  11126. me.drawBackground(pt, ctx, tooltipSize, options);
  11127. overrideTextDirection(ctx, options.textDirection);
  11128. pt.y += padding.top;
  11129. me.drawTitle(pt, ctx, options);
  11130. me.drawBody(pt, ctx, options);
  11131. me.drawFooter(pt, ctx, options);
  11132. restoreTextDirection(ctx, options.textDirection);
  11133. ctx.restore();
  11134. }
  11135. }
  11136. getActiveElements() {
  11137. return this._active || [];
  11138. }
  11139. setActiveElements(activeElements, eventPosition) {
  11140. const me = this;
  11141. const lastActive = me._active;
  11142. const active = activeElements.map(({datasetIndex, index}) => {
  11143. const meta = me._chart.getDatasetMeta(datasetIndex);
  11144. if (!meta) {
  11145. throw new Error('Cannot find a dataset at index ' + datasetIndex);
  11146. }
  11147. return {
  11148. datasetIndex,
  11149. element: meta.data[index],
  11150. index,
  11151. };
  11152. });
  11153. const changed = !_elementsEqual(lastActive, active);
  11154. const positionChanged = me._positionChanged(active, eventPosition);
  11155. if (changed || positionChanged) {
  11156. me._active = active;
  11157. me._eventPosition = eventPosition;
  11158. me.update(true);
  11159. }
  11160. }
  11161. handleEvent(e, replay) {
  11162. const me = this;
  11163. const options = me.options;
  11164. const lastActive = me._active || [];
  11165. let changed = false;
  11166. let active = [];
  11167. if (e.type !== 'mouseout') {
  11168. active = me._chart.getElementsAtEventForMode(e, options.mode, options, replay);
  11169. if (options.reverse) {
  11170. active.reverse();
  11171. }
  11172. }
  11173. const positionChanged = me._positionChanged(active, e);
  11174. changed = replay || !_elementsEqual(active, lastActive) || positionChanged;
  11175. if (changed) {
  11176. me._active = active;
  11177. if (options.enabled || options.external) {
  11178. me._eventPosition = {
  11179. x: e.x,
  11180. y: e.y
  11181. };
  11182. me.update(true, replay);
  11183. }
  11184. }
  11185. return changed;
  11186. }
  11187. _positionChanged(active, e) {
  11188. const {caretX, caretY, options} = this;
  11189. const position = positioners[options.position].call(this, active, e);
  11190. return position !== false && (caretX !== position.x || caretY !== position.y);
  11191. }
  11192. }
  11193. Tooltip.positioners = positioners;
  11194. var plugin_tooltip = {
  11195. id: 'tooltip',
  11196. _element: Tooltip,
  11197. positioners,
  11198. afterInit(chart, _args, options) {
  11199. if (options) {
  11200. chart.tooltip = new Tooltip({_chart: chart, options});
  11201. }
  11202. },
  11203. beforeUpdate(chart, _args, options) {
  11204. if (chart.tooltip) {
  11205. chart.tooltip.initialize(options);
  11206. }
  11207. },
  11208. reset(chart, _args, options) {
  11209. if (chart.tooltip) {
  11210. chart.tooltip.initialize(options);
  11211. }
  11212. },
  11213. afterDraw(chart) {
  11214. const tooltip = chart.tooltip;
  11215. const args = {
  11216. tooltip
  11217. };
  11218. if (chart.notifyPlugins('beforeTooltipDraw', args) === false) {
  11219. return;
  11220. }
  11221. if (tooltip) {
  11222. tooltip.draw(chart.ctx);
  11223. }
  11224. chart.notifyPlugins('afterTooltipDraw', args);
  11225. },
  11226. afterEvent(chart, args) {
  11227. if (chart.tooltip) {
  11228. const useFinalPosition = args.replay;
  11229. if (chart.tooltip.handleEvent(args.event, useFinalPosition)) {
  11230. args.changed = true;
  11231. }
  11232. }
  11233. },
  11234. defaults: {
  11235. enabled: true,
  11236. external: null,
  11237. position: 'average',
  11238. backgroundColor: 'rgba(0,0,0,0.8)',
  11239. titleColor: '#fff',
  11240. titleFont: {
  11241. weight: 'bold',
  11242. },
  11243. titleSpacing: 2,
  11244. titleMarginBottom: 6,
  11245. titleAlign: 'left',
  11246. bodyColor: '#fff',
  11247. bodySpacing: 2,
  11248. bodyFont: {
  11249. },
  11250. bodyAlign: 'left',
  11251. footerColor: '#fff',
  11252. footerSpacing: 2,
  11253. footerMarginTop: 6,
  11254. footerFont: {
  11255. weight: 'bold',
  11256. },
  11257. footerAlign: 'left',
  11258. padding: 6,
  11259. caretPadding: 2,
  11260. caretSize: 5,
  11261. cornerRadius: 6,
  11262. boxHeight: (ctx, opts) => opts.bodyFont.size,
  11263. boxWidth: (ctx, opts) => opts.bodyFont.size,
  11264. multiKeyBackground: '#fff',
  11265. displayColors: true,
  11266. borderColor: 'rgba(0,0,0,0)',
  11267. borderWidth: 0,
  11268. animation: {
  11269. duration: 400,
  11270. easing: 'easeOutQuart',
  11271. },
  11272. animations: {
  11273. numbers: {
  11274. type: 'number',
  11275. properties: ['x', 'y', 'width', 'height', 'caretX', 'caretY'],
  11276. },
  11277. opacity: {
  11278. easing: 'linear',
  11279. duration: 200
  11280. }
  11281. },
  11282. callbacks: {
  11283. beforeTitle: noop,
  11284. title(tooltipItems) {
  11285. if (tooltipItems.length > 0) {
  11286. const item = tooltipItems[0];
  11287. const labels = item.chart.data.labels;
  11288. const labelCount = labels ? labels.length : 0;
  11289. if (this && this.options && this.options.mode === 'dataset') {
  11290. return item.dataset.label || '';
  11291. } else if (item.label) {
  11292. return item.label;
  11293. } else if (labelCount > 0 && item.dataIndex < labelCount) {
  11294. return labels[item.dataIndex];
  11295. }
  11296. }
  11297. return '';
  11298. },
  11299. afterTitle: noop,
  11300. beforeBody: noop,
  11301. beforeLabel: noop,
  11302. label(tooltipItem) {
  11303. if (this && this.options && this.options.mode === 'dataset') {
  11304. return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue;
  11305. }
  11306. let label = tooltipItem.dataset.label || '';
  11307. if (label) {
  11308. label += ': ';
  11309. }
  11310. const value = tooltipItem.formattedValue;
  11311. if (!isNullOrUndef(value)) {
  11312. label += value;
  11313. }
  11314. return label;
  11315. },
  11316. labelColor(tooltipItem) {
  11317. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  11318. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  11319. return {
  11320. borderColor: options.borderColor,
  11321. backgroundColor: options.backgroundColor,
  11322. borderWidth: options.borderWidth,
  11323. borderDash: options.borderDash,
  11324. borderDashOffset: options.borderDashOffset,
  11325. borderRadius: 0,
  11326. };
  11327. },
  11328. labelTextColor() {
  11329. return this.options.bodyColor;
  11330. },
  11331. labelPointStyle(tooltipItem) {
  11332. const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex);
  11333. const options = meta.controller.getStyle(tooltipItem.dataIndex);
  11334. return {
  11335. pointStyle: options.pointStyle,
  11336. rotation: options.rotation,
  11337. };
  11338. },
  11339. afterLabel: noop,
  11340. afterBody: noop,
  11341. beforeFooter: noop,
  11342. footer: noop,
  11343. afterFooter: noop
  11344. }
  11345. },
  11346. defaultRoutes: {
  11347. bodyFont: 'font',
  11348. footerFont: 'font',
  11349. titleFont: 'font'
  11350. },
  11351. descriptors: {
  11352. _scriptable: (name) => name !== 'filter' && name !== 'itemSort' && name !== 'external',
  11353. _indexable: false,
  11354. callbacks: {
  11355. _scriptable: false,
  11356. _indexable: false,
  11357. },
  11358. animation: {
  11359. _fallback: false
  11360. },
  11361. animations: {
  11362. _fallback: 'animation'
  11363. }
  11364. },
  11365. additionalOptionScopes: ['interaction']
  11366. };
  11367. var plugins = /*#__PURE__*/Object.freeze({
  11368. __proto__: null,
  11369. Decimation: plugin_decimation,
  11370. Filler: plugin_filler,
  11371. Legend: plugin_legend,
  11372. Title: plugin_title,
  11373. Tooltip: plugin_tooltip
  11374. });
  11375. const addIfString = (labels, raw, index) => typeof raw === 'string'
  11376. ? labels.push(raw) - 1
  11377. : isNaN(raw) ? null : index;
  11378. function findOrAddLabel(labels, raw, index) {
  11379. const first = labels.indexOf(raw);
  11380. if (first === -1) {
  11381. return addIfString(labels, raw, index);
  11382. }
  11383. const last = labels.lastIndexOf(raw);
  11384. return first !== last ? index : first;
  11385. }
  11386. const validIndex = (index, max) => index === null ? null : _limitValue(Math.round(index), 0, max);
  11387. class CategoryScale extends Scale {
  11388. constructor(cfg) {
  11389. super(cfg);
  11390. this._startValue = undefined;
  11391. this._valueRange = 0;
  11392. }
  11393. parse(raw, index) {
  11394. if (isNullOrUndef(raw)) {
  11395. return null;
  11396. }
  11397. const labels = this.getLabels();
  11398. index = isFinite(index) && labels[index] === raw ? index
  11399. : findOrAddLabel(labels, raw, valueOrDefault(index, raw));
  11400. return validIndex(index, labels.length - 1);
  11401. }
  11402. determineDataLimits() {
  11403. const me = this;
  11404. const {minDefined, maxDefined} = me.getUserBounds();
  11405. let {min, max} = me.getMinMax(true);
  11406. if (me.options.bounds === 'ticks') {
  11407. if (!minDefined) {
  11408. min = 0;
  11409. }
  11410. if (!maxDefined) {
  11411. max = me.getLabels().length - 1;
  11412. }
  11413. }
  11414. me.min = min;
  11415. me.max = max;
  11416. }
  11417. buildTicks() {
  11418. const me = this;
  11419. const min = me.min;
  11420. const max = me.max;
  11421. const offset = me.options.offset;
  11422. const ticks = [];
  11423. let labels = me.getLabels();
  11424. labels = (min === 0 && max === labels.length - 1) ? labels : labels.slice(min, max + 1);
  11425. me._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1);
  11426. me._startValue = me.min - (offset ? 0.5 : 0);
  11427. for (let value = min; value <= max; value++) {
  11428. ticks.push({value});
  11429. }
  11430. return ticks;
  11431. }
  11432. getLabelForValue(value) {
  11433. const me = this;
  11434. const labels = me.getLabels();
  11435. if (value >= 0 && value < labels.length) {
  11436. return labels[value];
  11437. }
  11438. return value;
  11439. }
  11440. configure() {
  11441. const me = this;
  11442. super.configure();
  11443. if (!me.isHorizontal()) {
  11444. me._reversePixels = !me._reversePixels;
  11445. }
  11446. }
  11447. getPixelForValue(value) {
  11448. const me = this;
  11449. if (typeof value !== 'number') {
  11450. value = me.parse(value);
  11451. }
  11452. return value === null ? NaN : me.getPixelForDecimal((value - me._startValue) / me._valueRange);
  11453. }
  11454. getPixelForTick(index) {
  11455. const me = this;
  11456. const ticks = me.ticks;
  11457. if (index < 0 || index > ticks.length - 1) {
  11458. return null;
  11459. }
  11460. return me.getPixelForValue(ticks[index].value);
  11461. }
  11462. getValueForPixel(pixel) {
  11463. const me = this;
  11464. return Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
  11465. }
  11466. getBasePixel() {
  11467. return this.bottom;
  11468. }
  11469. }
  11470. CategoryScale.id = 'category';
  11471. CategoryScale.defaults = {
  11472. ticks: {
  11473. callback: CategoryScale.prototype.getLabelForValue
  11474. }
  11475. };
  11476. function generateTicks$1(generationOptions, dataRange) {
  11477. const ticks = [];
  11478. const MIN_SPACING = 1e-14;
  11479. const {step, min, max, precision, count, maxTicks, maxDigits, horizontal} = generationOptions;
  11480. const unit = step || 1;
  11481. const maxSpaces = maxTicks - 1;
  11482. const {min: rmin, max: rmax} = dataRange;
  11483. const minDefined = !isNullOrUndef(min);
  11484. const maxDefined = !isNullOrUndef(max);
  11485. const countDefined = !isNullOrUndef(count);
  11486. const minSpacing = (rmax - rmin) / maxDigits;
  11487. let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit;
  11488. let factor, niceMin, niceMax, numSpaces;
  11489. if (spacing < MIN_SPACING && !minDefined && !maxDefined) {
  11490. return [{value: rmin}, {value: rmax}];
  11491. }
  11492. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  11493. if (numSpaces > maxSpaces) {
  11494. spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit;
  11495. }
  11496. if (!isNullOrUndef(precision)) {
  11497. factor = Math.pow(10, precision);
  11498. spacing = Math.ceil(spacing * factor) / factor;
  11499. }
  11500. niceMin = Math.floor(rmin / spacing) * spacing;
  11501. niceMax = Math.ceil(rmax / spacing) * spacing;
  11502. if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) {
  11503. numSpaces = Math.min((max - min) / spacing, maxTicks);
  11504. spacing = (max - min) / numSpaces;
  11505. niceMin = min;
  11506. niceMax = max;
  11507. } else if (countDefined) {
  11508. niceMin = minDefined ? min : niceMin;
  11509. niceMax = maxDefined ? max : niceMax;
  11510. numSpaces = count - 1;
  11511. spacing = (niceMax - niceMin) / numSpaces;
  11512. } else {
  11513. numSpaces = (niceMax - niceMin) / spacing;
  11514. if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  11515. numSpaces = Math.round(numSpaces);
  11516. } else {
  11517. numSpaces = Math.ceil(numSpaces);
  11518. }
  11519. }
  11520. factor = Math.pow(10, isNullOrUndef(precision) ? _decimalPlaces(spacing) : precision);
  11521. niceMin = Math.round(niceMin * factor) / factor;
  11522. niceMax = Math.round(niceMax * factor) / factor;
  11523. let j = 0;
  11524. if (minDefined) {
  11525. ticks.push({value: min});
  11526. if (niceMin <= min) {
  11527. j++;
  11528. }
  11529. if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, minSpacing * (horizontal ? ('' + min).length : 1))) {
  11530. j++;
  11531. }
  11532. }
  11533. for (; j < numSpaces; ++j) {
  11534. ticks.push({value: Math.round((niceMin + j * spacing) * factor) / factor});
  11535. }
  11536. if (maxDefined) {
  11537. if (almostEquals(ticks[ticks.length - 1].value, max, minSpacing * (horizontal ? ('' + max).length : 1))) {
  11538. ticks[ticks.length - 1].value = max;
  11539. } else {
  11540. ticks.push({value: max});
  11541. }
  11542. } else {
  11543. ticks.push({value: niceMax});
  11544. }
  11545. return ticks;
  11546. }
  11547. class LinearScaleBase extends Scale {
  11548. constructor(cfg) {
  11549. super(cfg);
  11550. this.start = undefined;
  11551. this.end = undefined;
  11552. this._startValue = undefined;
  11553. this._endValue = undefined;
  11554. this._valueRange = 0;
  11555. }
  11556. parse(raw, index) {
  11557. if (isNullOrUndef(raw)) {
  11558. return null;
  11559. }
  11560. if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) {
  11561. return null;
  11562. }
  11563. return +raw;
  11564. }
  11565. handleTickRangeOptions() {
  11566. const me = this;
  11567. const {beginAtZero, stacked} = me.options;
  11568. const {minDefined, maxDefined} = me.getUserBounds();
  11569. let {min, max} = me;
  11570. const setMin = v => (min = minDefined ? min : v);
  11571. const setMax = v => (max = maxDefined ? max : v);
  11572. if (beginAtZero || stacked) {
  11573. const minSign = sign(min);
  11574. const maxSign = sign(max);
  11575. if (minSign < 0 && maxSign < 0) {
  11576. setMax(0);
  11577. } else if (minSign > 0 && maxSign > 0) {
  11578. setMin(0);
  11579. }
  11580. }
  11581. if (min === max) {
  11582. setMax(max + 1);
  11583. if (!beginAtZero) {
  11584. setMin(min - 1);
  11585. }
  11586. }
  11587. me.min = min;
  11588. me.max = max;
  11589. }
  11590. getTickLimit() {
  11591. const me = this;
  11592. const tickOpts = me.options.ticks;
  11593. let {maxTicksLimit, stepSize} = tickOpts;
  11594. let maxTicks;
  11595. if (stepSize) {
  11596. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  11597. } else {
  11598. maxTicks = me.computeTickLimit();
  11599. maxTicksLimit = maxTicksLimit || 11;
  11600. }
  11601. if (maxTicksLimit) {
  11602. maxTicks = Math.min(maxTicksLimit, maxTicks);
  11603. }
  11604. return maxTicks;
  11605. }
  11606. computeTickLimit() {
  11607. return Number.POSITIVE_INFINITY;
  11608. }
  11609. buildTicks() {
  11610. const me = this;
  11611. const opts = me.options;
  11612. const tickOpts = opts.ticks;
  11613. let maxTicks = me.getTickLimit();
  11614. maxTicks = Math.max(2, maxTicks);
  11615. const numericGeneratorOptions = {
  11616. maxTicks,
  11617. min: opts.min,
  11618. max: opts.max,
  11619. precision: tickOpts.precision,
  11620. step: tickOpts.stepSize,
  11621. count: tickOpts.count,
  11622. maxDigits: me._maxDigits(),
  11623. horizontal: me.isHorizontal()
  11624. };
  11625. const dataRange = me._range || me;
  11626. const ticks = generateTicks$1(numericGeneratorOptions, dataRange);
  11627. if (opts.bounds === 'ticks') {
  11628. _setMinAndMaxByKey(ticks, me, 'value');
  11629. }
  11630. if (opts.reverse) {
  11631. ticks.reverse();
  11632. me.start = me.max;
  11633. me.end = me.min;
  11634. } else {
  11635. me.start = me.min;
  11636. me.end = me.max;
  11637. }
  11638. return ticks;
  11639. }
  11640. configure() {
  11641. const me = this;
  11642. const ticks = me.ticks;
  11643. let start = me.min;
  11644. let end = me.max;
  11645. super.configure();
  11646. if (me.options.offset && ticks.length) {
  11647. const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  11648. start -= offset;
  11649. end += offset;
  11650. }
  11651. me._startValue = start;
  11652. me._endValue = end;
  11653. me._valueRange = end - start;
  11654. }
  11655. getLabelForValue(value) {
  11656. return formatNumber(value, this.chart.options.locale);
  11657. }
  11658. }
  11659. class LinearScale extends LinearScaleBase {
  11660. determineDataLimits() {
  11661. const me = this;
  11662. const {min, max} = me.getMinMax(true);
  11663. me.min = isNumberFinite(min) ? min : 0;
  11664. me.max = isNumberFinite(max) ? max : 1;
  11665. me.handleTickRangeOptions();
  11666. }
  11667. computeTickLimit() {
  11668. const me = this;
  11669. if (me.isHorizontal()) {
  11670. return Math.ceil(me.width / 40);
  11671. }
  11672. const tickFont = me._resolveTickFontOptions(0);
  11673. return Math.ceil(me.height / tickFont.lineHeight);
  11674. }
  11675. getPixelForValue(value) {
  11676. return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange);
  11677. }
  11678. getValueForPixel(pixel) {
  11679. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  11680. }
  11681. }
  11682. LinearScale.id = 'linear';
  11683. LinearScale.defaults = {
  11684. ticks: {
  11685. callback: Ticks.formatters.numeric
  11686. }
  11687. };
  11688. function isMajor(tickVal) {
  11689. const remain = tickVal / (Math.pow(10, Math.floor(log10(tickVal))));
  11690. return remain === 1;
  11691. }
  11692. function generateTicks(generationOptions, dataRange) {
  11693. const endExp = Math.floor(log10(dataRange.max));
  11694. const endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  11695. const ticks = [];
  11696. let tickVal = finiteOrDefault(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  11697. let exp = Math.floor(log10(tickVal));
  11698. let significand = Math.floor(tickVal / Math.pow(10, exp));
  11699. let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  11700. do {
  11701. ticks.push({value: tickVal, major: isMajor(tickVal)});
  11702. ++significand;
  11703. if (significand === 10) {
  11704. significand = 1;
  11705. ++exp;
  11706. precision = exp >= 0 ? 1 : precision;
  11707. }
  11708. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  11709. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  11710. const lastTick = finiteOrDefault(generationOptions.max, tickVal);
  11711. ticks.push({value: lastTick, major: isMajor(tickVal)});
  11712. return ticks;
  11713. }
  11714. class LogarithmicScale extends Scale {
  11715. constructor(cfg) {
  11716. super(cfg);
  11717. this.start = undefined;
  11718. this.end = undefined;
  11719. this._startValue = undefined;
  11720. this._valueRange = 0;
  11721. }
  11722. parse(raw, index) {
  11723. const value = LinearScaleBase.prototype.parse.apply(this, [raw, index]);
  11724. if (value === 0) {
  11725. this._zero = true;
  11726. return undefined;
  11727. }
  11728. return isNumberFinite(value) && value > 0 ? value : null;
  11729. }
  11730. determineDataLimits() {
  11731. const me = this;
  11732. const {min, max} = me.getMinMax(true);
  11733. me.min = isNumberFinite(min) ? Math.max(0, min) : null;
  11734. me.max = isNumberFinite(max) ? Math.max(0, max) : null;
  11735. if (me.options.beginAtZero) {
  11736. me._zero = true;
  11737. }
  11738. me.handleTickRangeOptions();
  11739. }
  11740. handleTickRangeOptions() {
  11741. const me = this;
  11742. const {minDefined, maxDefined} = me.getUserBounds();
  11743. let min = me.min;
  11744. let max = me.max;
  11745. const setMin = v => (min = minDefined ? min : v);
  11746. const setMax = v => (max = maxDefined ? max : v);
  11747. const exp = (v, m) => Math.pow(10, Math.floor(log10(v)) + m);
  11748. if (min === max) {
  11749. if (min <= 0) {
  11750. setMin(1);
  11751. setMax(10);
  11752. } else {
  11753. setMin(exp(min, -1));
  11754. setMax(exp(max, +1));
  11755. }
  11756. }
  11757. if (min <= 0) {
  11758. setMin(exp(max, -1));
  11759. }
  11760. if (max <= 0) {
  11761. setMax(exp(min, +1));
  11762. }
  11763. if (me._zero && me.min !== me._suggestedMin && min === exp(me.min, 0)) {
  11764. setMin(exp(min, -1));
  11765. }
  11766. me.min = min;
  11767. me.max = max;
  11768. }
  11769. buildTicks() {
  11770. const me = this;
  11771. const opts = me.options;
  11772. const generationOptions = {
  11773. min: me._userMin,
  11774. max: me._userMax
  11775. };
  11776. const ticks = generateTicks(generationOptions, me);
  11777. if (opts.bounds === 'ticks') {
  11778. _setMinAndMaxByKey(ticks, me, 'value');
  11779. }
  11780. if (opts.reverse) {
  11781. ticks.reverse();
  11782. me.start = me.max;
  11783. me.end = me.min;
  11784. } else {
  11785. me.start = me.min;
  11786. me.end = me.max;
  11787. }
  11788. return ticks;
  11789. }
  11790. getLabelForValue(value) {
  11791. return value === undefined ? '0' : formatNumber(value, this.chart.options.locale);
  11792. }
  11793. configure() {
  11794. const me = this;
  11795. const start = me.min;
  11796. super.configure();
  11797. me._startValue = log10(start);
  11798. me._valueRange = log10(me.max) - log10(start);
  11799. }
  11800. getPixelForValue(value) {
  11801. const me = this;
  11802. if (value === undefined || value === 0) {
  11803. value = me.min;
  11804. }
  11805. if (value === null || isNaN(value)) {
  11806. return NaN;
  11807. }
  11808. return me.getPixelForDecimal(value === me.min
  11809. ? 0
  11810. : (log10(value) - me._startValue) / me._valueRange);
  11811. }
  11812. getValueForPixel(pixel) {
  11813. const me = this;
  11814. const decimal = me.getDecimalForPixel(pixel);
  11815. return Math.pow(10, me._startValue + decimal * me._valueRange);
  11816. }
  11817. }
  11818. LogarithmicScale.id = 'logarithmic';
  11819. LogarithmicScale.defaults = {
  11820. ticks: {
  11821. callback: Ticks.formatters.logarithmic,
  11822. major: {
  11823. enabled: true
  11824. }
  11825. }
  11826. };
  11827. function getTickBackdropHeight(opts) {
  11828. const tickOpts = opts.ticks;
  11829. if (tickOpts.display && opts.display) {
  11830. const padding = toPadding(tickOpts.backdropPadding);
  11831. return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height;
  11832. }
  11833. return 0;
  11834. }
  11835. function measureLabelSize(ctx, lineHeight, label) {
  11836. if (isArray(label)) {
  11837. return {
  11838. w: _longestText(ctx, ctx.font, label),
  11839. h: label.length * lineHeight
  11840. };
  11841. }
  11842. return {
  11843. w: ctx.measureText(label).width,
  11844. h: lineHeight
  11845. };
  11846. }
  11847. function determineLimits(angle, pos, size, min, max) {
  11848. if (angle === min || angle === max) {
  11849. return {
  11850. start: pos - (size / 2),
  11851. end: pos + (size / 2)
  11852. };
  11853. } else if (angle < min || angle > max) {
  11854. return {
  11855. start: pos - size,
  11856. end: pos
  11857. };
  11858. }
  11859. return {
  11860. start: pos,
  11861. end: pos + size
  11862. };
  11863. }
  11864. function fitWithPointLabels(scale) {
  11865. const furthestLimits = {
  11866. l: 0,
  11867. r: scale.width,
  11868. t: 0,
  11869. b: scale.height - scale.paddingTop
  11870. };
  11871. const furthestAngles = {};
  11872. let i, textSize, pointPosition;
  11873. const labelSizes = [];
  11874. const padding = [];
  11875. const valueCount = scale.getLabels().length;
  11876. for (i = 0; i < valueCount; i++) {
  11877. const opts = scale.options.pointLabels.setContext(scale.getContext(i));
  11878. padding[i] = opts.padding;
  11879. pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i]);
  11880. const plFont = toFont(opts.font);
  11881. scale.ctx.font = plFont.string;
  11882. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale._pointLabels[i]);
  11883. labelSizes[i] = textSize;
  11884. const angleRadians = scale.getIndexAngle(i);
  11885. const angle = toDegrees(angleRadians);
  11886. const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  11887. const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  11888. if (hLimits.start < furthestLimits.l) {
  11889. furthestLimits.l = hLimits.start;
  11890. furthestAngles.l = angleRadians;
  11891. }
  11892. if (hLimits.end > furthestLimits.r) {
  11893. furthestLimits.r = hLimits.end;
  11894. furthestAngles.r = angleRadians;
  11895. }
  11896. if (vLimits.start < furthestLimits.t) {
  11897. furthestLimits.t = vLimits.start;
  11898. furthestAngles.t = angleRadians;
  11899. }
  11900. if (vLimits.end > furthestLimits.b) {
  11901. furthestLimits.b = vLimits.end;
  11902. furthestAngles.b = angleRadians;
  11903. }
  11904. }
  11905. scale._setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  11906. scale._pointLabelItems = [];
  11907. const opts = scale.options;
  11908. const tickBackdropHeight = getTickBackdropHeight(opts);
  11909. const outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  11910. for (i = 0; i < valueCount; i++) {
  11911. const extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  11912. const pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + padding[i]);
  11913. const angle = toDegrees(scale.getIndexAngle(i));
  11914. const size = labelSizes[i];
  11915. adjustPointPositionForLabelHeight(angle, size, pointLabelPosition);
  11916. const textAlign = getTextAlignForAngle(angle);
  11917. let left;
  11918. if (textAlign === 'left') {
  11919. left = pointLabelPosition.x;
  11920. } else if (textAlign === 'center') {
  11921. left = pointLabelPosition.x - (size.w / 2);
  11922. } else {
  11923. left = pointLabelPosition.x - size.w;
  11924. }
  11925. const right = left + size.w;
  11926. scale._pointLabelItems[i] = {
  11927. x: pointLabelPosition.x,
  11928. y: pointLabelPosition.y,
  11929. textAlign,
  11930. left,
  11931. top: pointLabelPosition.y,
  11932. right,
  11933. bottom: pointLabelPosition.y + size.h,
  11934. };
  11935. }
  11936. }
  11937. function getTextAlignForAngle(angle) {
  11938. if (angle === 0 || angle === 180) {
  11939. return 'center';
  11940. } else if (angle < 180) {
  11941. return 'left';
  11942. }
  11943. return 'right';
  11944. }
  11945. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  11946. if (angle === 90 || angle === 270) {
  11947. position.y -= (textSize.h / 2);
  11948. } else if (angle > 270 || angle < 90) {
  11949. position.y -= textSize.h;
  11950. }
  11951. }
  11952. function drawPointLabels(scale, labelCount) {
  11953. const {ctx, options: {pointLabels}} = scale;
  11954. for (let i = labelCount - 1; i >= 0; i--) {
  11955. const optsAtIndex = pointLabels.setContext(scale.getContext(i));
  11956. const plFont = toFont(optsAtIndex.font);
  11957. const {x, y, textAlign, left, top, right, bottom} = scale._pointLabelItems[i];
  11958. const {backdropColor} = optsAtIndex;
  11959. if (!isNullOrUndef(backdropColor)) {
  11960. const padding = toPadding(optsAtIndex.backdropPadding);
  11961. ctx.fillStyle = backdropColor;
  11962. ctx.fillRect(left - padding.left, top - padding.top, right - left + padding.width, bottom - top + padding.height);
  11963. }
  11964. renderText(
  11965. ctx,
  11966. scale._pointLabels[i],
  11967. x,
  11968. y + (plFont.lineHeight / 2),
  11969. plFont,
  11970. {
  11971. color: optsAtIndex.color,
  11972. textAlign: textAlign,
  11973. textBaseline: 'middle'
  11974. }
  11975. );
  11976. }
  11977. }
  11978. function pathRadiusLine(scale, radius, circular, labelCount) {
  11979. const {ctx} = scale;
  11980. if (circular) {
  11981. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU);
  11982. } else {
  11983. let pointPosition = scale.getPointPosition(0, radius);
  11984. ctx.moveTo(pointPosition.x, pointPosition.y);
  11985. for (let i = 1; i < labelCount; i++) {
  11986. pointPosition = scale.getPointPosition(i, radius);
  11987. ctx.lineTo(pointPosition.x, pointPosition.y);
  11988. }
  11989. }
  11990. }
  11991. function drawRadiusLine(scale, gridLineOpts, radius, labelCount) {
  11992. const ctx = scale.ctx;
  11993. const circular = gridLineOpts.circular;
  11994. const {color, lineWidth} = gridLineOpts;
  11995. if ((!circular && !labelCount) || !color || !lineWidth || radius < 0) {
  11996. return;
  11997. }
  11998. ctx.save();
  11999. ctx.strokeStyle = color;
  12000. ctx.lineWidth = lineWidth;
  12001. ctx.setLineDash(gridLineOpts.borderDash);
  12002. ctx.lineDashOffset = gridLineOpts.borderDashOffset;
  12003. ctx.beginPath();
  12004. pathRadiusLine(scale, radius, circular, labelCount);
  12005. ctx.closePath();
  12006. ctx.stroke();
  12007. ctx.restore();
  12008. }
  12009. function numberOrZero(param) {
  12010. return isNumber(param) ? param : 0;
  12011. }
  12012. class RadialLinearScale extends LinearScaleBase {
  12013. constructor(cfg) {
  12014. super(cfg);
  12015. this.xCenter = undefined;
  12016. this.yCenter = undefined;
  12017. this.drawingArea = undefined;
  12018. this._pointLabels = [];
  12019. this._pointLabelItems = [];
  12020. }
  12021. setDimensions() {
  12022. const me = this;
  12023. me.width = me.maxWidth;
  12024. me.height = me.maxHeight;
  12025. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  12026. me.xCenter = Math.floor(me.width / 2);
  12027. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  12028. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  12029. }
  12030. determineDataLimits() {
  12031. const me = this;
  12032. const {min, max} = me.getMinMax(false);
  12033. me.min = isNumberFinite(min) && !isNaN(min) ? min : 0;
  12034. me.max = isNumberFinite(max) && !isNaN(max) ? max : 0;
  12035. me.handleTickRangeOptions();
  12036. }
  12037. computeTickLimit() {
  12038. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  12039. }
  12040. generateTickLabels(ticks) {
  12041. const me = this;
  12042. LinearScaleBase.prototype.generateTickLabels.call(me, ticks);
  12043. me._pointLabels = me.getLabels().map((value, index) => {
  12044. const label = callback(me.options.pointLabels.callback, [value, index], me);
  12045. return label || label === 0 ? label : '';
  12046. });
  12047. }
  12048. fit() {
  12049. const me = this;
  12050. const opts = me.options;
  12051. if (opts.display && opts.pointLabels.display) {
  12052. fitWithPointLabels(me);
  12053. } else {
  12054. me.setCenterPoint(0, 0, 0, 0);
  12055. }
  12056. }
  12057. _setReductions(largestPossibleRadius, furthestLimits, furthestAngles) {
  12058. const me = this;
  12059. let radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  12060. let radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  12061. let radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  12062. let radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  12063. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  12064. radiusReductionRight = numberOrZero(radiusReductionRight);
  12065. radiusReductionTop = numberOrZero(radiusReductionTop);
  12066. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  12067. me.drawingArea = Math.max(largestPossibleRadius / 2, Math.min(
  12068. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  12069. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2)));
  12070. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  12071. }
  12072. setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) {
  12073. const me = this;
  12074. const maxRight = me.width - rightMovement - me.drawingArea;
  12075. const maxLeft = leftMovement + me.drawingArea;
  12076. const maxTop = topMovement + me.drawingArea;
  12077. const maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  12078. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  12079. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  12080. }
  12081. getIndexAngle(index) {
  12082. const angleMultiplier = TAU / this.getLabels().length;
  12083. const startAngle = this.options.startAngle || 0;
  12084. return _normalizeAngle(index * angleMultiplier + toRadians(startAngle));
  12085. }
  12086. getDistanceFromCenterForValue(value) {
  12087. const me = this;
  12088. if (isNullOrUndef(value)) {
  12089. return NaN;
  12090. }
  12091. const scalingFactor = me.drawingArea / (me.max - me.min);
  12092. if (me.options.reverse) {
  12093. return (me.max - value) * scalingFactor;
  12094. }
  12095. return (value - me.min) * scalingFactor;
  12096. }
  12097. getValueForDistanceFromCenter(distance) {
  12098. if (isNullOrUndef(distance)) {
  12099. return NaN;
  12100. }
  12101. const me = this;
  12102. const scaledDistance = distance / (me.drawingArea / (me.max - me.min));
  12103. return me.options.reverse ? me.max - scaledDistance : me.min + scaledDistance;
  12104. }
  12105. getPointPosition(index, distanceFromCenter) {
  12106. const me = this;
  12107. const angle = me.getIndexAngle(index) - HALF_PI;
  12108. return {
  12109. x: Math.cos(angle) * distanceFromCenter + me.xCenter,
  12110. y: Math.sin(angle) * distanceFromCenter + me.yCenter,
  12111. angle
  12112. };
  12113. }
  12114. getPointPositionForValue(index, value) {
  12115. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  12116. }
  12117. getBasePosition(index) {
  12118. return this.getPointPositionForValue(index || 0, this.getBaseValue());
  12119. }
  12120. getPointLabelPosition(index) {
  12121. const {left, top, right, bottom} = this._pointLabelItems[index];
  12122. return {
  12123. left,
  12124. top,
  12125. right,
  12126. bottom,
  12127. };
  12128. }
  12129. drawBackground() {
  12130. const me = this;
  12131. const {backgroundColor, grid: {circular}} = me.options;
  12132. if (backgroundColor) {
  12133. const ctx = me.ctx;
  12134. ctx.save();
  12135. ctx.beginPath();
  12136. pathRadiusLine(me, me.getDistanceFromCenterForValue(me._endValue), circular, me.getLabels().length);
  12137. ctx.closePath();
  12138. ctx.fillStyle = backgroundColor;
  12139. ctx.fill();
  12140. ctx.restore();
  12141. }
  12142. }
  12143. drawGrid() {
  12144. const me = this;
  12145. const ctx = me.ctx;
  12146. const opts = me.options;
  12147. const {angleLines, grid} = opts;
  12148. const labelCount = me.getLabels().length;
  12149. let i, offset, position;
  12150. if (opts.pointLabels.display) {
  12151. drawPointLabels(me, labelCount);
  12152. }
  12153. if (grid.display) {
  12154. me.ticks.forEach((tick, index) => {
  12155. if (index !== 0) {
  12156. offset = me.getDistanceFromCenterForValue(tick.value);
  12157. const optsAtIndex = grid.setContext(me.getContext(index - 1));
  12158. drawRadiusLine(me, optsAtIndex, offset, labelCount);
  12159. }
  12160. });
  12161. }
  12162. if (angleLines.display) {
  12163. ctx.save();
  12164. for (i = me.getLabels().length - 1; i >= 0; i--) {
  12165. const optsAtIndex = angleLines.setContext(me.getContext(i));
  12166. const {color, lineWidth} = optsAtIndex;
  12167. if (!lineWidth || !color) {
  12168. continue;
  12169. }
  12170. ctx.lineWidth = lineWidth;
  12171. ctx.strokeStyle = color;
  12172. ctx.setLineDash(optsAtIndex.borderDash);
  12173. ctx.lineDashOffset = optsAtIndex.borderDashOffset;
  12174. offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
  12175. position = me.getPointPosition(i, offset);
  12176. ctx.beginPath();
  12177. ctx.moveTo(me.xCenter, me.yCenter);
  12178. ctx.lineTo(position.x, position.y);
  12179. ctx.stroke();
  12180. }
  12181. ctx.restore();
  12182. }
  12183. }
  12184. drawBorder() {}
  12185. drawLabels() {
  12186. const me = this;
  12187. const ctx = me.ctx;
  12188. const opts = me.options;
  12189. const tickOpts = opts.ticks;
  12190. if (!tickOpts.display) {
  12191. return;
  12192. }
  12193. const startAngle = me.getIndexAngle(0);
  12194. let offset, width;
  12195. ctx.save();
  12196. ctx.translate(me.xCenter, me.yCenter);
  12197. ctx.rotate(startAngle);
  12198. ctx.textAlign = 'center';
  12199. ctx.textBaseline = 'middle';
  12200. me.ticks.forEach((tick, index) => {
  12201. if (index === 0 && !opts.reverse) {
  12202. return;
  12203. }
  12204. const optsAtIndex = tickOpts.setContext(me.getContext(index));
  12205. const tickFont = toFont(optsAtIndex.font);
  12206. offset = me.getDistanceFromCenterForValue(me.ticks[index].value);
  12207. if (optsAtIndex.showLabelBackdrop) {
  12208. width = ctx.measureText(tick.label).width;
  12209. ctx.fillStyle = optsAtIndex.backdropColor;
  12210. const padding = toPadding(optsAtIndex.backdropPadding);
  12211. ctx.fillRect(
  12212. -width / 2 - padding.left,
  12213. -offset - tickFont.size / 2 - padding.top,
  12214. width + padding.width,
  12215. tickFont.size + padding.height
  12216. );
  12217. }
  12218. renderText(ctx, tick.label, 0, -offset, tickFont, {
  12219. color: optsAtIndex.color,
  12220. });
  12221. });
  12222. ctx.restore();
  12223. }
  12224. drawTitle() {}
  12225. }
  12226. RadialLinearScale.id = 'radialLinear';
  12227. RadialLinearScale.defaults = {
  12228. display: true,
  12229. animate: true,
  12230. position: 'chartArea',
  12231. angleLines: {
  12232. display: true,
  12233. lineWidth: 1,
  12234. borderDash: [],
  12235. borderDashOffset: 0.0
  12236. },
  12237. grid: {
  12238. circular: false
  12239. },
  12240. startAngle: 0,
  12241. ticks: {
  12242. showLabelBackdrop: true,
  12243. callback: Ticks.formatters.numeric
  12244. },
  12245. pointLabels: {
  12246. backdropColor: undefined,
  12247. backdropPadding: 2,
  12248. display: true,
  12249. font: {
  12250. size: 10
  12251. },
  12252. callback(label) {
  12253. return label;
  12254. },
  12255. padding: 5
  12256. }
  12257. };
  12258. RadialLinearScale.defaultRoutes = {
  12259. 'angleLines.color': 'borderColor',
  12260. 'pointLabels.color': 'color',
  12261. 'ticks.color': 'color'
  12262. };
  12263. RadialLinearScale.descriptors = {
  12264. angleLines: {
  12265. _fallback: 'grid'
  12266. }
  12267. };
  12268. const INTERVALS = {
  12269. millisecond: {common: true, size: 1, steps: 1000},
  12270. second: {common: true, size: 1000, steps: 60},
  12271. minute: {common: true, size: 60000, steps: 60},
  12272. hour: {common: true, size: 3600000, steps: 24},
  12273. day: {common: true, size: 86400000, steps: 30},
  12274. week: {common: false, size: 604800000, steps: 4},
  12275. month: {common: true, size: 2.628e9, steps: 12},
  12276. quarter: {common: false, size: 7.884e9, steps: 4},
  12277. year: {common: true, size: 3.154e10}
  12278. };
  12279. const UNITS = (Object.keys(INTERVALS));
  12280. function sorter(a, b) {
  12281. return a - b;
  12282. }
  12283. function parse(scale, input) {
  12284. if (isNullOrUndef(input)) {
  12285. return null;
  12286. }
  12287. const adapter = scale._adapter;
  12288. const {parser, round, isoWeekday} = scale._parseOpts;
  12289. let value = input;
  12290. if (typeof parser === 'function') {
  12291. value = parser(value);
  12292. }
  12293. if (!isNumberFinite(value)) {
  12294. value = typeof parser === 'string'
  12295. ? adapter.parse(value, parser)
  12296. : adapter.parse(value);
  12297. }
  12298. if (value === null) {
  12299. return null;
  12300. }
  12301. if (round) {
  12302. value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true)
  12303. ? adapter.startOf(value, 'isoWeek', isoWeekday)
  12304. : adapter.startOf(value, round);
  12305. }
  12306. return +value;
  12307. }
  12308. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  12309. const ilen = UNITS.length;
  12310. for (let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  12311. const interval = INTERVALS[UNITS[i]];
  12312. const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER;
  12313. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  12314. return UNITS[i];
  12315. }
  12316. }
  12317. return UNITS[ilen - 1];
  12318. }
  12319. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  12320. for (let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  12321. const unit = UNITS[i];
  12322. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  12323. return unit;
  12324. }
  12325. }
  12326. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  12327. }
  12328. function determineMajorUnit(unit) {
  12329. for (let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  12330. if (INTERVALS[UNITS[i]].common) {
  12331. return UNITS[i];
  12332. }
  12333. }
  12334. }
  12335. function addTick(ticks, time, timestamps) {
  12336. if (!timestamps) {
  12337. ticks[time] = true;
  12338. } else if (timestamps.length) {
  12339. const {lo, hi} = _lookup(timestamps, time);
  12340. const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi];
  12341. ticks[timestamp] = true;
  12342. }
  12343. }
  12344. function setMajorTicks(scale, ticks, map, majorUnit) {
  12345. const adapter = scale._adapter;
  12346. const first = +adapter.startOf(ticks[0].value, majorUnit);
  12347. const last = ticks[ticks.length - 1].value;
  12348. let major, index;
  12349. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  12350. index = map[major];
  12351. if (index >= 0) {
  12352. ticks[index].major = true;
  12353. }
  12354. }
  12355. return ticks;
  12356. }
  12357. function ticksFromTimestamps(scale, values, majorUnit) {
  12358. const ticks = [];
  12359. const map = {};
  12360. const ilen = values.length;
  12361. let i, value;
  12362. for (i = 0; i < ilen; ++i) {
  12363. value = values[i];
  12364. map[value] = i;
  12365. ticks.push({
  12366. value,
  12367. major: false
  12368. });
  12369. }
  12370. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  12371. }
  12372. class TimeScale extends Scale {
  12373. constructor(props) {
  12374. super(props);
  12375. this._cache = {
  12376. data: [],
  12377. labels: [],
  12378. all: []
  12379. };
  12380. this._unit = 'day';
  12381. this._majorUnit = undefined;
  12382. this._offsets = {};
  12383. this._normalized = false;
  12384. this._parseOpts = undefined;
  12385. }
  12386. init(scaleOpts, opts) {
  12387. const time = scaleOpts.time || (scaleOpts.time = {});
  12388. const adapter = this._adapter = new _adapters._date(scaleOpts.adapters.date);
  12389. mergeIf(time.displayFormats, adapter.formats());
  12390. this._parseOpts = {
  12391. parser: time.parser,
  12392. round: time.round,
  12393. isoWeekday: time.isoWeekday
  12394. };
  12395. super.init(scaleOpts);
  12396. this._normalized = opts.normalized;
  12397. }
  12398. parse(raw, index) {
  12399. if (raw === undefined) {
  12400. return null;
  12401. }
  12402. return parse(this, raw);
  12403. }
  12404. beforeLayout() {
  12405. super.beforeLayout();
  12406. this._cache = {
  12407. data: [],
  12408. labels: [],
  12409. all: []
  12410. };
  12411. }
  12412. determineDataLimits() {
  12413. const me = this;
  12414. const options = me.options;
  12415. const adapter = me._adapter;
  12416. const unit = options.time.unit || 'day';
  12417. let {min, max, minDefined, maxDefined} = me.getUserBounds();
  12418. function _applyBounds(bounds) {
  12419. if (!minDefined && !isNaN(bounds.min)) {
  12420. min = Math.min(min, bounds.min);
  12421. }
  12422. if (!maxDefined && !isNaN(bounds.max)) {
  12423. max = Math.max(max, bounds.max);
  12424. }
  12425. }
  12426. if (!minDefined || !maxDefined) {
  12427. _applyBounds(me._getLabelBounds());
  12428. if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') {
  12429. _applyBounds(me.getMinMax(false));
  12430. }
  12431. }
  12432. min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit);
  12433. max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1;
  12434. me.min = Math.min(min, max - 1);
  12435. me.max = Math.max(min + 1, max);
  12436. }
  12437. _getLabelBounds() {
  12438. const arr = this.getLabelTimestamps();
  12439. let min = Number.POSITIVE_INFINITY;
  12440. let max = Number.NEGATIVE_INFINITY;
  12441. if (arr.length) {
  12442. min = arr[0];
  12443. max = arr[arr.length - 1];
  12444. }
  12445. return {min, max};
  12446. }
  12447. buildTicks() {
  12448. const me = this;
  12449. const options = me.options;
  12450. const timeOpts = options.time;
  12451. const tickOpts = options.ticks;
  12452. const timestamps = tickOpts.source === 'labels' ? me.getLabelTimestamps() : me._generate();
  12453. if (options.bounds === 'ticks' && timestamps.length) {
  12454. me.min = me._userMin || timestamps[0];
  12455. me.max = me._userMax || timestamps[timestamps.length - 1];
  12456. }
  12457. const min = me.min;
  12458. const max = me.max;
  12459. const ticks = _filterBetween(timestamps, min, max);
  12460. me._unit = timeOpts.unit || (tickOpts.autoSkip
  12461. ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, me._getLabelCapacity(min))
  12462. : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
  12463. me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
  12464. : determineMajorUnit(me._unit);
  12465. me.initOffsets(timestamps);
  12466. if (options.reverse) {
  12467. ticks.reverse();
  12468. }
  12469. return ticksFromTimestamps(me, ticks, me._majorUnit);
  12470. }
  12471. initOffsets(timestamps) {
  12472. const me = this;
  12473. let start = 0;
  12474. let end = 0;
  12475. let first, last;
  12476. if (me.options.offset && timestamps.length) {
  12477. first = me.getDecimalForValue(timestamps[0]);
  12478. if (timestamps.length === 1) {
  12479. start = 1 - first;
  12480. } else {
  12481. start = (me.getDecimalForValue(timestamps[1]) - first) / 2;
  12482. }
  12483. last = me.getDecimalForValue(timestamps[timestamps.length - 1]);
  12484. if (timestamps.length === 1) {
  12485. end = last;
  12486. } else {
  12487. end = (last - me.getDecimalForValue(timestamps[timestamps.length - 2])) / 2;
  12488. }
  12489. }
  12490. const limit = timestamps.length < 3 ? 0.5 : 0.25;
  12491. start = _limitValue(start, 0, limit);
  12492. end = _limitValue(end, 0, limit);
  12493. me._offsets = {start, end, factor: 1 / (start + 1 + end)};
  12494. }
  12495. _generate() {
  12496. const me = this;
  12497. const adapter = me._adapter;
  12498. const min = me.min;
  12499. const max = me.max;
  12500. const options = me.options;
  12501. const timeOpts = options.time;
  12502. const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, me._getLabelCapacity(min));
  12503. const stepSize = valueOrDefault(timeOpts.stepSize, 1);
  12504. const weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  12505. const hasWeekday = isNumber(weekday) || weekday === true;
  12506. const ticks = {};
  12507. let first = min;
  12508. let time, count;
  12509. if (hasWeekday) {
  12510. first = +adapter.startOf(first, 'isoWeek', weekday);
  12511. }
  12512. first = +adapter.startOf(first, hasWeekday ? 'day' : minor);
  12513. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  12514. throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor);
  12515. }
  12516. const timestamps = options.ticks.source === 'data' && me.getDataTimestamps();
  12517. for (time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++) {
  12518. addTick(ticks, time, timestamps);
  12519. }
  12520. if (time === max || options.bounds === 'ticks' || count === 1) {
  12521. addTick(ticks, time, timestamps);
  12522. }
  12523. return Object.keys(ticks).sort((a, b) => a - b).map(x => +x);
  12524. }
  12525. getLabelForValue(value) {
  12526. const me = this;
  12527. const adapter = me._adapter;
  12528. const timeOpts = me.options.time;
  12529. if (timeOpts.tooltipFormat) {
  12530. return adapter.format(value, timeOpts.tooltipFormat);
  12531. }
  12532. return adapter.format(value, timeOpts.displayFormats.datetime);
  12533. }
  12534. _tickFormatFunction(time, index, ticks, format) {
  12535. const me = this;
  12536. const options = me.options;
  12537. const formats = options.time.displayFormats;
  12538. const unit = me._unit;
  12539. const majorUnit = me._majorUnit;
  12540. const minorFormat = unit && formats[unit];
  12541. const majorFormat = majorUnit && formats[majorUnit];
  12542. const tick = ticks[index];
  12543. const major = majorUnit && majorFormat && tick && tick.major;
  12544. const label = me._adapter.format(time, format || (major ? majorFormat : minorFormat));
  12545. const formatter = options.ticks.callback;
  12546. return formatter ? callback(formatter, [label, index, ticks], me) : label;
  12547. }
  12548. generateTickLabels(ticks) {
  12549. let i, ilen, tick;
  12550. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  12551. tick = ticks[i];
  12552. tick.label = this._tickFormatFunction(tick.value, i, ticks);
  12553. }
  12554. }
  12555. getDecimalForValue(value) {
  12556. const me = this;
  12557. return value === null ? NaN : (value - me.min) / (me.max - me.min);
  12558. }
  12559. getPixelForValue(value) {
  12560. const me = this;
  12561. const offsets = me._offsets;
  12562. const pos = me.getDecimalForValue(value);
  12563. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  12564. }
  12565. getValueForPixel(pixel) {
  12566. const me = this;
  12567. const offsets = me._offsets;
  12568. const pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  12569. return me.min + pos * (me.max - me.min);
  12570. }
  12571. _getLabelSize(label) {
  12572. const me = this;
  12573. const ticksOpts = me.options.ticks;
  12574. const tickLabelWidth = me.ctx.measureText(label).width;
  12575. const angle = toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  12576. const cosRotation = Math.cos(angle);
  12577. const sinRotation = Math.sin(angle);
  12578. const tickFontSize = me._resolveTickFontOptions(0).size;
  12579. return {
  12580. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  12581. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  12582. };
  12583. }
  12584. _getLabelCapacity(exampleTime) {
  12585. const me = this;
  12586. const timeOpts = me.options.time;
  12587. const displayFormats = timeOpts.displayFormats;
  12588. const format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  12589. const exampleLabel = me._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
  12590. const size = me._getLabelSize(exampleLabel);
  12591. const capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h) - 1;
  12592. return capacity > 0 ? capacity : 1;
  12593. }
  12594. getDataTimestamps() {
  12595. const me = this;
  12596. let timestamps = me._cache.data || [];
  12597. let i, ilen;
  12598. if (timestamps.length) {
  12599. return timestamps;
  12600. }
  12601. const metas = me.getMatchingVisibleMetas();
  12602. if (me._normalized && metas.length) {
  12603. return (me._cache.data = metas[0].controller.getAllParsedValues(me));
  12604. }
  12605. for (i = 0, ilen = metas.length; i < ilen; ++i) {
  12606. timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(me));
  12607. }
  12608. return (me._cache.data = me.normalize(timestamps));
  12609. }
  12610. getLabelTimestamps() {
  12611. const me = this;
  12612. const timestamps = me._cache.labels || [];
  12613. let i, ilen;
  12614. if (timestamps.length) {
  12615. return timestamps;
  12616. }
  12617. const labels = me.getLabels();
  12618. for (i = 0, ilen = labels.length; i < ilen; ++i) {
  12619. timestamps.push(parse(me, labels[i]));
  12620. }
  12621. return (me._cache.labels = me._normalized ? timestamps : me.normalize(timestamps));
  12622. }
  12623. normalize(values) {
  12624. return _arrayUnique(values.sort(sorter));
  12625. }
  12626. }
  12627. TimeScale.id = 'time';
  12628. TimeScale.defaults = {
  12629. bounds: 'data',
  12630. adapters: {},
  12631. time: {
  12632. parser: false,
  12633. unit: false,
  12634. round: false,
  12635. isoWeekday: false,
  12636. minUnit: 'millisecond',
  12637. displayFormats: {}
  12638. },
  12639. ticks: {
  12640. source: 'auto',
  12641. major: {
  12642. enabled: false
  12643. }
  12644. }
  12645. };
  12646. function interpolate(table, val, reverse) {
  12647. let prevSource, nextSource, prevTarget, nextTarget;
  12648. if (reverse) {
  12649. prevSource = Math.floor(val);
  12650. nextSource = Math.ceil(val);
  12651. prevTarget = table[prevSource];
  12652. nextTarget = table[nextSource];
  12653. } else {
  12654. const result = _lookup(table, val);
  12655. prevTarget = result.lo;
  12656. nextTarget = result.hi;
  12657. prevSource = table[prevTarget];
  12658. nextSource = table[nextTarget];
  12659. }
  12660. const span = nextSource - prevSource;
  12661. return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget;
  12662. }
  12663. class TimeSeriesScale extends TimeScale {
  12664. constructor(props) {
  12665. super(props);
  12666. this._table = [];
  12667. this._maxIndex = undefined;
  12668. }
  12669. initOffsets() {
  12670. const me = this;
  12671. const timestamps = me._getTimestampsForTable();
  12672. me._table = me.buildLookupTable(timestamps);
  12673. me._maxIndex = me._table.length - 1;
  12674. super.initOffsets(timestamps);
  12675. }
  12676. buildLookupTable(timestamps) {
  12677. const me = this;
  12678. const {min, max} = me;
  12679. if (!timestamps.length) {
  12680. return [
  12681. {time: min, pos: 0},
  12682. {time: max, pos: 1}
  12683. ];
  12684. }
  12685. const items = [min];
  12686. let i, ilen, curr;
  12687. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12688. curr = timestamps[i];
  12689. if (curr > min && curr < max) {
  12690. items.push(curr);
  12691. }
  12692. }
  12693. items.push(max);
  12694. return items;
  12695. }
  12696. _getTimestampsForTable() {
  12697. const me = this;
  12698. let timestamps = me._cache.all || [];
  12699. if (timestamps.length) {
  12700. return timestamps;
  12701. }
  12702. const data = me.getDataTimestamps();
  12703. const label = me.getLabelTimestamps();
  12704. if (data.length && label.length) {
  12705. timestamps = me.normalize(data.concat(label));
  12706. } else {
  12707. timestamps = data.length ? data : label;
  12708. }
  12709. timestamps = me._cache.all = timestamps;
  12710. return timestamps;
  12711. }
  12712. getPixelForValue(value, index) {
  12713. const me = this;
  12714. const offsets = me._offsets;
  12715. const pos = me._normalized && me._maxIndex > 0 && !isNullOrUndef(index)
  12716. ? index / me._maxIndex : me.getDecimalForValue(value);
  12717. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  12718. }
  12719. getDecimalForValue(value) {
  12720. return interpolate(this._table, value) / this._maxIndex;
  12721. }
  12722. getValueForPixel(pixel) {
  12723. const me = this;
  12724. const offsets = me._offsets;
  12725. const decimal = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  12726. return interpolate(me._table, decimal * this._maxIndex, true);
  12727. }
  12728. }
  12729. TimeSeriesScale.id = 'timeseries';
  12730. TimeSeriesScale.defaults = TimeScale.defaults;
  12731. var scales = /*#__PURE__*/Object.freeze({
  12732. __proto__: null,
  12733. CategoryScale: CategoryScale,
  12734. LinearScale: LinearScale,
  12735. LogarithmicScale: LogarithmicScale,
  12736. RadialLinearScale: RadialLinearScale,
  12737. TimeScale: TimeScale,
  12738. TimeSeriesScale: TimeSeriesScale
  12739. });
  12740. Chart.register(controllers, scales, elements, plugins);
  12741. Chart.helpers = {...helpers};
  12742. Chart._adapters = _adapters;
  12743. Chart.Animation = Animation;
  12744. Chart.Animations = Animations;
  12745. Chart.animator = animator;
  12746. Chart.controllers = registry.controllers.items;
  12747. Chart.DatasetController = DatasetController;
  12748. Chart.Element = Element;
  12749. Chart.elements = elements;
  12750. Chart.Interaction = Interaction;
  12751. Chart.layouts = layouts;
  12752. Chart.platforms = platforms;
  12753. Chart.Scale = Scale;
  12754. Chart.Ticks = Ticks;
  12755. Object.assign(Chart, controllers, scales, elements, plugins, platforms);
  12756. Chart.Chart = Chart;
  12757. if (typeof window !== 'undefined') {
  12758. window.Chart = Chart;
  12759. }
  12760. return Chart;
  12761. })));