Chart.js 418 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151
  1. /*!
  2. * Chart.js v2.9.3
  3. * https://www.chartjs.org
  4. * (c) 2019 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(function() { try { return require('moment'); } catch(e) { } }()) :
  9. typeof define === 'function' && define.amd ? define(['require'], function(require) { return factory(function() { try { return require('moment'); } catch(e) { } }()); }) :
  10. (global = global || self, global.Chart = factory(global.moment));
  11. }(this, (function (moment) { 'use strict';
  12. moment = moment && moment.hasOwnProperty('default') ? moment['default'] : moment;
  13. function createCommonjsModule(fn, module) {
  14. return module = { exports: {} }, fn(module, module.exports), module.exports;
  15. }
  16. function getCjsExportFromNamespace (n) {
  17. return n && n['default'] || n;
  18. }
  19. var colorName = {
  20. "aliceblue": [240, 248, 255],
  21. "antiquewhite": [250, 235, 215],
  22. "aqua": [0, 255, 255],
  23. "aquamarine": [127, 255, 212],
  24. "azure": [240, 255, 255],
  25. "beige": [245, 245, 220],
  26. "bisque": [255, 228, 196],
  27. "black": [0, 0, 0],
  28. "blanchedalmond": [255, 235, 205],
  29. "blue": [0, 0, 255],
  30. "blueviolet": [138, 43, 226],
  31. "brown": [165, 42, 42],
  32. "burlywood": [222, 184, 135],
  33. "cadetblue": [95, 158, 160],
  34. "chartreuse": [127, 255, 0],
  35. "chocolate": [210, 105, 30],
  36. "coral": [255, 127, 80],
  37. "cornflowerblue": [100, 149, 237],
  38. "cornsilk": [255, 248, 220],
  39. "crimson": [220, 20, 60],
  40. "cyan": [0, 255, 255],
  41. "darkblue": [0, 0, 139],
  42. "darkcyan": [0, 139, 139],
  43. "darkgoldenrod": [184, 134, 11],
  44. "darkgray": [169, 169, 169],
  45. "darkgreen": [0, 100, 0],
  46. "darkgrey": [169, 169, 169],
  47. "darkkhaki": [189, 183, 107],
  48. "darkmagenta": [139, 0, 139],
  49. "darkolivegreen": [85, 107, 47],
  50. "darkorange": [255, 140, 0],
  51. "darkorchid": [153, 50, 204],
  52. "darkred": [139, 0, 0],
  53. "darksalmon": [233, 150, 122],
  54. "darkseagreen": [143, 188, 143],
  55. "darkslateblue": [72, 61, 139],
  56. "darkslategray": [47, 79, 79],
  57. "darkslategrey": [47, 79, 79],
  58. "darkturquoise": [0, 206, 209],
  59. "darkviolet": [148, 0, 211],
  60. "deeppink": [255, 20, 147],
  61. "deepskyblue": [0, 191, 255],
  62. "dimgray": [105, 105, 105],
  63. "dimgrey": [105, 105, 105],
  64. "dodgerblue": [30, 144, 255],
  65. "firebrick": [178, 34, 34],
  66. "floralwhite": [255, 250, 240],
  67. "forestgreen": [34, 139, 34],
  68. "fuchsia": [255, 0, 255],
  69. "gainsboro": [220, 220, 220],
  70. "ghostwhite": [248, 248, 255],
  71. "gold": [255, 215, 0],
  72. "goldenrod": [218, 165, 32],
  73. "gray": [128, 128, 128],
  74. "green": [0, 128, 0],
  75. "greenyellow": [173, 255, 47],
  76. "grey": [128, 128, 128],
  77. "honeydew": [240, 255, 240],
  78. "hotpink": [255, 105, 180],
  79. "indianred": [205, 92, 92],
  80. "indigo": [75, 0, 130],
  81. "ivory": [255, 255, 240],
  82. "khaki": [240, 230, 140],
  83. "lavender": [230, 230, 250],
  84. "lavenderblush": [255, 240, 245],
  85. "lawngreen": [124, 252, 0],
  86. "lemonchiffon": [255, 250, 205],
  87. "lightblue": [173, 216, 230],
  88. "lightcoral": [240, 128, 128],
  89. "lightcyan": [224, 255, 255],
  90. "lightgoldenrodyellow": [250, 250, 210],
  91. "lightgray": [211, 211, 211],
  92. "lightgreen": [144, 238, 144],
  93. "lightgrey": [211, 211, 211],
  94. "lightpink": [255, 182, 193],
  95. "lightsalmon": [255, 160, 122],
  96. "lightseagreen": [32, 178, 170],
  97. "lightskyblue": [135, 206, 250],
  98. "lightslategray": [119, 136, 153],
  99. "lightslategrey": [119, 136, 153],
  100. "lightsteelblue": [176, 196, 222],
  101. "lightyellow": [255, 255, 224],
  102. "lime": [0, 255, 0],
  103. "limegreen": [50, 205, 50],
  104. "linen": [250, 240, 230],
  105. "magenta": [255, 0, 255],
  106. "maroon": [128, 0, 0],
  107. "mediumaquamarine": [102, 205, 170],
  108. "mediumblue": [0, 0, 205],
  109. "mediumorchid": [186, 85, 211],
  110. "mediumpurple": [147, 112, 219],
  111. "mediumseagreen": [60, 179, 113],
  112. "mediumslateblue": [123, 104, 238],
  113. "mediumspringgreen": [0, 250, 154],
  114. "mediumturquoise": [72, 209, 204],
  115. "mediumvioletred": [199, 21, 133],
  116. "midnightblue": [25, 25, 112],
  117. "mintcream": [245, 255, 250],
  118. "mistyrose": [255, 228, 225],
  119. "moccasin": [255, 228, 181],
  120. "navajowhite": [255, 222, 173],
  121. "navy": [0, 0, 128],
  122. "oldlace": [253, 245, 230],
  123. "olive": [128, 128, 0],
  124. "olivedrab": [107, 142, 35],
  125. "orange": [255, 165, 0],
  126. "orangered": [255, 69, 0],
  127. "orchid": [218, 112, 214],
  128. "palegoldenrod": [238, 232, 170],
  129. "palegreen": [152, 251, 152],
  130. "paleturquoise": [175, 238, 238],
  131. "palevioletred": [219, 112, 147],
  132. "papayawhip": [255, 239, 213],
  133. "peachpuff": [255, 218, 185],
  134. "peru": [205, 133, 63],
  135. "pink": [255, 192, 203],
  136. "plum": [221, 160, 221],
  137. "powderblue": [176, 224, 230],
  138. "purple": [128, 0, 128],
  139. "rebeccapurple": [102, 51, 153],
  140. "red": [255, 0, 0],
  141. "rosybrown": [188, 143, 143],
  142. "royalblue": [65, 105, 225],
  143. "saddlebrown": [139, 69, 19],
  144. "salmon": [250, 128, 114],
  145. "sandybrown": [244, 164, 96],
  146. "seagreen": [46, 139, 87],
  147. "seashell": [255, 245, 238],
  148. "sienna": [160, 82, 45],
  149. "silver": [192, 192, 192],
  150. "skyblue": [135, 206, 235],
  151. "slateblue": [106, 90, 205],
  152. "slategray": [112, 128, 144],
  153. "slategrey": [112, 128, 144],
  154. "snow": [255, 250, 250],
  155. "springgreen": [0, 255, 127],
  156. "steelblue": [70, 130, 180],
  157. "tan": [210, 180, 140],
  158. "teal": [0, 128, 128],
  159. "thistle": [216, 191, 216],
  160. "tomato": [255, 99, 71],
  161. "turquoise": [64, 224, 208],
  162. "violet": [238, 130, 238],
  163. "wheat": [245, 222, 179],
  164. "white": [255, 255, 255],
  165. "whitesmoke": [245, 245, 245],
  166. "yellow": [255, 255, 0],
  167. "yellowgreen": [154, 205, 50]
  168. };
  169. var conversions = createCommonjsModule(function (module) {
  170. /* MIT license */
  171. // NOTE: conversions should only return primitive values (i.e. arrays, or
  172. // values that give correct `typeof` results).
  173. // do not use box values types (i.e. Number(), String(), etc.)
  174. var reverseKeywords = {};
  175. for (var key in colorName) {
  176. if (colorName.hasOwnProperty(key)) {
  177. reverseKeywords[colorName[key]] = key;
  178. }
  179. }
  180. var convert = module.exports = {
  181. rgb: {channels: 3, labels: 'rgb'},
  182. hsl: {channels: 3, labels: 'hsl'},
  183. hsv: {channels: 3, labels: 'hsv'},
  184. hwb: {channels: 3, labels: 'hwb'},
  185. cmyk: {channels: 4, labels: 'cmyk'},
  186. xyz: {channels: 3, labels: 'xyz'},
  187. lab: {channels: 3, labels: 'lab'},
  188. lch: {channels: 3, labels: 'lch'},
  189. hex: {channels: 1, labels: ['hex']},
  190. keyword: {channels: 1, labels: ['keyword']},
  191. ansi16: {channels: 1, labels: ['ansi16']},
  192. ansi256: {channels: 1, labels: ['ansi256']},
  193. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  194. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  195. gray: {channels: 1, labels: ['gray']}
  196. };
  197. // hide .channels and .labels properties
  198. for (var model in convert) {
  199. if (convert.hasOwnProperty(model)) {
  200. if (!('channels' in convert[model])) {
  201. throw new Error('missing channels property: ' + model);
  202. }
  203. if (!('labels' in convert[model])) {
  204. throw new Error('missing channel labels property: ' + model);
  205. }
  206. if (convert[model].labels.length !== convert[model].channels) {
  207. throw new Error('channel and label counts mismatch: ' + model);
  208. }
  209. var channels = convert[model].channels;
  210. var labels = convert[model].labels;
  211. delete convert[model].channels;
  212. delete convert[model].labels;
  213. Object.defineProperty(convert[model], 'channels', {value: channels});
  214. Object.defineProperty(convert[model], 'labels', {value: labels});
  215. }
  216. }
  217. convert.rgb.hsl = function (rgb) {
  218. var r = rgb[0] / 255;
  219. var g = rgb[1] / 255;
  220. var b = rgb[2] / 255;
  221. var min = Math.min(r, g, b);
  222. var max = Math.max(r, g, b);
  223. var delta = max - min;
  224. var h;
  225. var s;
  226. var l;
  227. if (max === min) {
  228. h = 0;
  229. } else if (r === max) {
  230. h = (g - b) / delta;
  231. } else if (g === max) {
  232. h = 2 + (b - r) / delta;
  233. } else if (b === max) {
  234. h = 4 + (r - g) / delta;
  235. }
  236. h = Math.min(h * 60, 360);
  237. if (h < 0) {
  238. h += 360;
  239. }
  240. l = (min + max) / 2;
  241. if (max === min) {
  242. s = 0;
  243. } else if (l <= 0.5) {
  244. s = delta / (max + min);
  245. } else {
  246. s = delta / (2 - max - min);
  247. }
  248. return [h, s * 100, l * 100];
  249. };
  250. convert.rgb.hsv = function (rgb) {
  251. var rdif;
  252. var gdif;
  253. var bdif;
  254. var h;
  255. var s;
  256. var r = rgb[0] / 255;
  257. var g = rgb[1] / 255;
  258. var b = rgb[2] / 255;
  259. var v = Math.max(r, g, b);
  260. var diff = v - Math.min(r, g, b);
  261. var diffc = function (c) {
  262. return (v - c) / 6 / diff + 1 / 2;
  263. };
  264. if (diff === 0) {
  265. h = s = 0;
  266. } else {
  267. s = diff / v;
  268. rdif = diffc(r);
  269. gdif = diffc(g);
  270. bdif = diffc(b);
  271. if (r === v) {
  272. h = bdif - gdif;
  273. } else if (g === v) {
  274. h = (1 / 3) + rdif - bdif;
  275. } else if (b === v) {
  276. h = (2 / 3) + gdif - rdif;
  277. }
  278. if (h < 0) {
  279. h += 1;
  280. } else if (h > 1) {
  281. h -= 1;
  282. }
  283. }
  284. return [
  285. h * 360,
  286. s * 100,
  287. v * 100
  288. ];
  289. };
  290. convert.rgb.hwb = function (rgb) {
  291. var r = rgb[0];
  292. var g = rgb[1];
  293. var b = rgb[2];
  294. var h = convert.rgb.hsl(rgb)[0];
  295. var w = 1 / 255 * Math.min(r, Math.min(g, b));
  296. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  297. return [h, w * 100, b * 100];
  298. };
  299. convert.rgb.cmyk = function (rgb) {
  300. var r = rgb[0] / 255;
  301. var g = rgb[1] / 255;
  302. var b = rgb[2] / 255;
  303. var c;
  304. var m;
  305. var y;
  306. var k;
  307. k = Math.min(1 - r, 1 - g, 1 - b);
  308. c = (1 - r - k) / (1 - k) || 0;
  309. m = (1 - g - k) / (1 - k) || 0;
  310. y = (1 - b - k) / (1 - k) || 0;
  311. return [c * 100, m * 100, y * 100, k * 100];
  312. };
  313. /**
  314. * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  315. * */
  316. function comparativeDistance(x, y) {
  317. return (
  318. Math.pow(x[0] - y[0], 2) +
  319. Math.pow(x[1] - y[1], 2) +
  320. Math.pow(x[2] - y[2], 2)
  321. );
  322. }
  323. convert.rgb.keyword = function (rgb) {
  324. var reversed = reverseKeywords[rgb];
  325. if (reversed) {
  326. return reversed;
  327. }
  328. var currentClosestDistance = Infinity;
  329. var currentClosestKeyword;
  330. for (var keyword in colorName) {
  331. if (colorName.hasOwnProperty(keyword)) {
  332. var value = colorName[keyword];
  333. // Compute comparative distance
  334. var distance = comparativeDistance(rgb, value);
  335. // Check if its less, if so set as closest
  336. if (distance < currentClosestDistance) {
  337. currentClosestDistance = distance;
  338. currentClosestKeyword = keyword;
  339. }
  340. }
  341. }
  342. return currentClosestKeyword;
  343. };
  344. convert.keyword.rgb = function (keyword) {
  345. return colorName[keyword];
  346. };
  347. convert.rgb.xyz = function (rgb) {
  348. var r = rgb[0] / 255;
  349. var g = rgb[1] / 255;
  350. var b = rgb[2] / 255;
  351. // assume sRGB
  352. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  353. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  354. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  355. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  356. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  357. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  358. return [x * 100, y * 100, z * 100];
  359. };
  360. convert.rgb.lab = function (rgb) {
  361. var xyz = convert.rgb.xyz(rgb);
  362. var x = xyz[0];
  363. var y = xyz[1];
  364. var z = xyz[2];
  365. var l;
  366. var a;
  367. var b;
  368. x /= 95.047;
  369. y /= 100;
  370. z /= 108.883;
  371. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  372. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  373. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  374. l = (116 * y) - 16;
  375. a = 500 * (x - y);
  376. b = 200 * (y - z);
  377. return [l, a, b];
  378. };
  379. convert.hsl.rgb = function (hsl) {
  380. var h = hsl[0] / 360;
  381. var s = hsl[1] / 100;
  382. var l = hsl[2] / 100;
  383. var t1;
  384. var t2;
  385. var t3;
  386. var rgb;
  387. var val;
  388. if (s === 0) {
  389. val = l * 255;
  390. return [val, val, val];
  391. }
  392. if (l < 0.5) {
  393. t2 = l * (1 + s);
  394. } else {
  395. t2 = l + s - l * s;
  396. }
  397. t1 = 2 * l - t2;
  398. rgb = [0, 0, 0];
  399. for (var i = 0; i < 3; i++) {
  400. t3 = h + 1 / 3 * -(i - 1);
  401. if (t3 < 0) {
  402. t3++;
  403. }
  404. if (t3 > 1) {
  405. t3--;
  406. }
  407. if (6 * t3 < 1) {
  408. val = t1 + (t2 - t1) * 6 * t3;
  409. } else if (2 * t3 < 1) {
  410. val = t2;
  411. } else if (3 * t3 < 2) {
  412. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  413. } else {
  414. val = t1;
  415. }
  416. rgb[i] = val * 255;
  417. }
  418. return rgb;
  419. };
  420. convert.hsl.hsv = function (hsl) {
  421. var h = hsl[0];
  422. var s = hsl[1] / 100;
  423. var l = hsl[2] / 100;
  424. var smin = s;
  425. var lmin = Math.max(l, 0.01);
  426. var sv;
  427. var v;
  428. l *= 2;
  429. s *= (l <= 1) ? l : 2 - l;
  430. smin *= lmin <= 1 ? lmin : 2 - lmin;
  431. v = (l + s) / 2;
  432. sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  433. return [h, sv * 100, v * 100];
  434. };
  435. convert.hsv.rgb = function (hsv) {
  436. var h = hsv[0] / 60;
  437. var s = hsv[1] / 100;
  438. var v = hsv[2] / 100;
  439. var hi = Math.floor(h) % 6;
  440. var f = h - Math.floor(h);
  441. var p = 255 * v * (1 - s);
  442. var q = 255 * v * (1 - (s * f));
  443. var t = 255 * v * (1 - (s * (1 - f)));
  444. v *= 255;
  445. switch (hi) {
  446. case 0:
  447. return [v, t, p];
  448. case 1:
  449. return [q, v, p];
  450. case 2:
  451. return [p, v, t];
  452. case 3:
  453. return [p, q, v];
  454. case 4:
  455. return [t, p, v];
  456. case 5:
  457. return [v, p, q];
  458. }
  459. };
  460. convert.hsv.hsl = function (hsv) {
  461. var h = hsv[0];
  462. var s = hsv[1] / 100;
  463. var v = hsv[2] / 100;
  464. var vmin = Math.max(v, 0.01);
  465. var lmin;
  466. var sl;
  467. var l;
  468. l = (2 - s) * v;
  469. lmin = (2 - s) * vmin;
  470. sl = s * vmin;
  471. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  472. sl = sl || 0;
  473. l /= 2;
  474. return [h, sl * 100, l * 100];
  475. };
  476. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  477. convert.hwb.rgb = function (hwb) {
  478. var h = hwb[0] / 360;
  479. var wh = hwb[1] / 100;
  480. var bl = hwb[2] / 100;
  481. var ratio = wh + bl;
  482. var i;
  483. var v;
  484. var f;
  485. var n;
  486. // wh + bl cant be > 1
  487. if (ratio > 1) {
  488. wh /= ratio;
  489. bl /= ratio;
  490. }
  491. i = Math.floor(6 * h);
  492. v = 1 - bl;
  493. f = 6 * h - i;
  494. if ((i & 0x01) !== 0) {
  495. f = 1 - f;
  496. }
  497. n = wh + f * (v - wh); // linear interpolation
  498. var r;
  499. var g;
  500. var b;
  501. switch (i) {
  502. default:
  503. case 6:
  504. case 0: r = v; g = n; b = wh; break;
  505. case 1: r = n; g = v; b = wh; break;
  506. case 2: r = wh; g = v; b = n; break;
  507. case 3: r = wh; g = n; b = v; break;
  508. case 4: r = n; g = wh; b = v; break;
  509. case 5: r = v; g = wh; b = n; break;
  510. }
  511. return [r * 255, g * 255, b * 255];
  512. };
  513. convert.cmyk.rgb = function (cmyk) {
  514. var c = cmyk[0] / 100;
  515. var m = cmyk[1] / 100;
  516. var y = cmyk[2] / 100;
  517. var k = cmyk[3] / 100;
  518. var r;
  519. var g;
  520. var b;
  521. r = 1 - Math.min(1, c * (1 - k) + k);
  522. g = 1 - Math.min(1, m * (1 - k) + k);
  523. b = 1 - Math.min(1, y * (1 - k) + k);
  524. return [r * 255, g * 255, b * 255];
  525. };
  526. convert.xyz.rgb = function (xyz) {
  527. var x = xyz[0] / 100;
  528. var y = xyz[1] / 100;
  529. var z = xyz[2] / 100;
  530. var r;
  531. var g;
  532. var b;
  533. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  534. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  535. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  536. // assume sRGB
  537. r = r > 0.0031308
  538. ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  539. : r * 12.92;
  540. g = g > 0.0031308
  541. ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  542. : g * 12.92;
  543. b = b > 0.0031308
  544. ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  545. : b * 12.92;
  546. r = Math.min(Math.max(0, r), 1);
  547. g = Math.min(Math.max(0, g), 1);
  548. b = Math.min(Math.max(0, b), 1);
  549. return [r * 255, g * 255, b * 255];
  550. };
  551. convert.xyz.lab = function (xyz) {
  552. var x = xyz[0];
  553. var y = xyz[1];
  554. var z = xyz[2];
  555. var l;
  556. var a;
  557. var b;
  558. x /= 95.047;
  559. y /= 100;
  560. z /= 108.883;
  561. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  562. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  563. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  564. l = (116 * y) - 16;
  565. a = 500 * (x - y);
  566. b = 200 * (y - z);
  567. return [l, a, b];
  568. };
  569. convert.lab.xyz = function (lab) {
  570. var l = lab[0];
  571. var a = lab[1];
  572. var b = lab[2];
  573. var x;
  574. var y;
  575. var z;
  576. y = (l + 16) / 116;
  577. x = a / 500 + y;
  578. z = y - b / 200;
  579. var y2 = Math.pow(y, 3);
  580. var x2 = Math.pow(x, 3);
  581. var z2 = Math.pow(z, 3);
  582. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  583. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  584. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  585. x *= 95.047;
  586. y *= 100;
  587. z *= 108.883;
  588. return [x, y, z];
  589. };
  590. convert.lab.lch = function (lab) {
  591. var l = lab[0];
  592. var a = lab[1];
  593. var b = lab[2];
  594. var hr;
  595. var h;
  596. var c;
  597. hr = Math.atan2(b, a);
  598. h = hr * 360 / 2 / Math.PI;
  599. if (h < 0) {
  600. h += 360;
  601. }
  602. c = Math.sqrt(a * a + b * b);
  603. return [l, c, h];
  604. };
  605. convert.lch.lab = function (lch) {
  606. var l = lch[0];
  607. var c = lch[1];
  608. var h = lch[2];
  609. var a;
  610. var b;
  611. var hr;
  612. hr = h / 360 * 2 * Math.PI;
  613. a = c * Math.cos(hr);
  614. b = c * Math.sin(hr);
  615. return [l, a, b];
  616. };
  617. convert.rgb.ansi16 = function (args) {
  618. var r = args[0];
  619. var g = args[1];
  620. var b = args[2];
  621. var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
  622. value = Math.round(value / 50);
  623. if (value === 0) {
  624. return 30;
  625. }
  626. var ansi = 30
  627. + ((Math.round(b / 255) << 2)
  628. | (Math.round(g / 255) << 1)
  629. | Math.round(r / 255));
  630. if (value === 2) {
  631. ansi += 60;
  632. }
  633. return ansi;
  634. };
  635. convert.hsv.ansi16 = function (args) {
  636. // optimization here; we already know the value and don't need to get
  637. // it converted for us.
  638. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
  639. };
  640. convert.rgb.ansi256 = function (args) {
  641. var r = args[0];
  642. var g = args[1];
  643. var b = args[2];
  644. // we use the extended greyscale palette here, with the exception of
  645. // black and white. normal palette only has 4 greyscale shades.
  646. if (r === g && g === b) {
  647. if (r < 8) {
  648. return 16;
  649. }
  650. if (r > 248) {
  651. return 231;
  652. }
  653. return Math.round(((r - 8) / 247) * 24) + 232;
  654. }
  655. var ansi = 16
  656. + (36 * Math.round(r / 255 * 5))
  657. + (6 * Math.round(g / 255 * 5))
  658. + Math.round(b / 255 * 5);
  659. return ansi;
  660. };
  661. convert.ansi16.rgb = function (args) {
  662. var color = args % 10;
  663. // handle greyscale
  664. if (color === 0 || color === 7) {
  665. if (args > 50) {
  666. color += 3.5;
  667. }
  668. color = color / 10.5 * 255;
  669. return [color, color, color];
  670. }
  671. var mult = (~~(args > 50) + 1) * 0.5;
  672. var r = ((color & 1) * mult) * 255;
  673. var g = (((color >> 1) & 1) * mult) * 255;
  674. var b = (((color >> 2) & 1) * mult) * 255;
  675. return [r, g, b];
  676. };
  677. convert.ansi256.rgb = function (args) {
  678. // handle greyscale
  679. if (args >= 232) {
  680. var c = (args - 232) * 10 + 8;
  681. return [c, c, c];
  682. }
  683. args -= 16;
  684. var rem;
  685. var r = Math.floor(args / 36) / 5 * 255;
  686. var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  687. var b = (rem % 6) / 5 * 255;
  688. return [r, g, b];
  689. };
  690. convert.rgb.hex = function (args) {
  691. var integer = ((Math.round(args[0]) & 0xFF) << 16)
  692. + ((Math.round(args[1]) & 0xFF) << 8)
  693. + (Math.round(args[2]) & 0xFF);
  694. var string = integer.toString(16).toUpperCase();
  695. return '000000'.substring(string.length) + string;
  696. };
  697. convert.hex.rgb = function (args) {
  698. var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  699. if (!match) {
  700. return [0, 0, 0];
  701. }
  702. var colorString = match[0];
  703. if (match[0].length === 3) {
  704. colorString = colorString.split('').map(function (char) {
  705. return char + char;
  706. }).join('');
  707. }
  708. var integer = parseInt(colorString, 16);
  709. var r = (integer >> 16) & 0xFF;
  710. var g = (integer >> 8) & 0xFF;
  711. var b = integer & 0xFF;
  712. return [r, g, b];
  713. };
  714. convert.rgb.hcg = function (rgb) {
  715. var r = rgb[0] / 255;
  716. var g = rgb[1] / 255;
  717. var b = rgb[2] / 255;
  718. var max = Math.max(Math.max(r, g), b);
  719. var min = Math.min(Math.min(r, g), b);
  720. var chroma = (max - min);
  721. var grayscale;
  722. var hue;
  723. if (chroma < 1) {
  724. grayscale = min / (1 - chroma);
  725. } else {
  726. grayscale = 0;
  727. }
  728. if (chroma <= 0) {
  729. hue = 0;
  730. } else
  731. if (max === r) {
  732. hue = ((g - b) / chroma) % 6;
  733. } else
  734. if (max === g) {
  735. hue = 2 + (b - r) / chroma;
  736. } else {
  737. hue = 4 + (r - g) / chroma + 4;
  738. }
  739. hue /= 6;
  740. hue %= 1;
  741. return [hue * 360, chroma * 100, grayscale * 100];
  742. };
  743. convert.hsl.hcg = function (hsl) {
  744. var s = hsl[1] / 100;
  745. var l = hsl[2] / 100;
  746. var c = 1;
  747. var f = 0;
  748. if (l < 0.5) {
  749. c = 2.0 * s * l;
  750. } else {
  751. c = 2.0 * s * (1.0 - l);
  752. }
  753. if (c < 1.0) {
  754. f = (l - 0.5 * c) / (1.0 - c);
  755. }
  756. return [hsl[0], c * 100, f * 100];
  757. };
  758. convert.hsv.hcg = function (hsv) {
  759. var s = hsv[1] / 100;
  760. var v = hsv[2] / 100;
  761. var c = s * v;
  762. var f = 0;
  763. if (c < 1.0) {
  764. f = (v - c) / (1 - c);
  765. }
  766. return [hsv[0], c * 100, f * 100];
  767. };
  768. convert.hcg.rgb = function (hcg) {
  769. var h = hcg[0] / 360;
  770. var c = hcg[1] / 100;
  771. var g = hcg[2] / 100;
  772. if (c === 0.0) {
  773. return [g * 255, g * 255, g * 255];
  774. }
  775. var pure = [0, 0, 0];
  776. var hi = (h % 1) * 6;
  777. var v = hi % 1;
  778. var w = 1 - v;
  779. var mg = 0;
  780. switch (Math.floor(hi)) {
  781. case 0:
  782. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  783. case 1:
  784. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  785. case 2:
  786. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  787. case 3:
  788. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  789. case 4:
  790. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  791. default:
  792. pure[0] = 1; pure[1] = 0; pure[2] = w;
  793. }
  794. mg = (1.0 - c) * g;
  795. return [
  796. (c * pure[0] + mg) * 255,
  797. (c * pure[1] + mg) * 255,
  798. (c * pure[2] + mg) * 255
  799. ];
  800. };
  801. convert.hcg.hsv = function (hcg) {
  802. var c = hcg[1] / 100;
  803. var g = hcg[2] / 100;
  804. var v = c + g * (1.0 - c);
  805. var f = 0;
  806. if (v > 0.0) {
  807. f = c / v;
  808. }
  809. return [hcg[0], f * 100, v * 100];
  810. };
  811. convert.hcg.hsl = function (hcg) {
  812. var c = hcg[1] / 100;
  813. var g = hcg[2] / 100;
  814. var l = g * (1.0 - c) + 0.5 * c;
  815. var s = 0;
  816. if (l > 0.0 && l < 0.5) {
  817. s = c / (2 * l);
  818. } else
  819. if (l >= 0.5 && l < 1.0) {
  820. s = c / (2 * (1 - l));
  821. }
  822. return [hcg[0], s * 100, l * 100];
  823. };
  824. convert.hcg.hwb = function (hcg) {
  825. var c = hcg[1] / 100;
  826. var g = hcg[2] / 100;
  827. var v = c + g * (1.0 - c);
  828. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  829. };
  830. convert.hwb.hcg = function (hwb) {
  831. var w = hwb[1] / 100;
  832. var b = hwb[2] / 100;
  833. var v = 1 - b;
  834. var c = v - w;
  835. var g = 0;
  836. if (c < 1) {
  837. g = (v - c) / (1 - c);
  838. }
  839. return [hwb[0], c * 100, g * 100];
  840. };
  841. convert.apple.rgb = function (apple) {
  842. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  843. };
  844. convert.rgb.apple = function (rgb) {
  845. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  846. };
  847. convert.gray.rgb = function (args) {
  848. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  849. };
  850. convert.gray.hsl = convert.gray.hsv = function (args) {
  851. return [0, 0, args[0]];
  852. };
  853. convert.gray.hwb = function (gray) {
  854. return [0, 100, gray[0]];
  855. };
  856. convert.gray.cmyk = function (gray) {
  857. return [0, 0, 0, gray[0]];
  858. };
  859. convert.gray.lab = function (gray) {
  860. return [gray[0], 0, 0];
  861. };
  862. convert.gray.hex = function (gray) {
  863. var val = Math.round(gray[0] / 100 * 255) & 0xFF;
  864. var integer = (val << 16) + (val << 8) + val;
  865. var string = integer.toString(16).toUpperCase();
  866. return '000000'.substring(string.length) + string;
  867. };
  868. convert.rgb.gray = function (rgb) {
  869. var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  870. return [val / 255 * 100];
  871. };
  872. });
  873. var conversions_1 = conversions.rgb;
  874. var conversions_2 = conversions.hsl;
  875. var conversions_3 = conversions.hsv;
  876. var conversions_4 = conversions.hwb;
  877. var conversions_5 = conversions.cmyk;
  878. var conversions_6 = conversions.xyz;
  879. var conversions_7 = conversions.lab;
  880. var conversions_8 = conversions.lch;
  881. var conversions_9 = conversions.hex;
  882. var conversions_10 = conversions.keyword;
  883. var conversions_11 = conversions.ansi16;
  884. var conversions_12 = conversions.ansi256;
  885. var conversions_13 = conversions.hcg;
  886. var conversions_14 = conversions.apple;
  887. var conversions_15 = conversions.gray;
  888. /*
  889. this function routes a model to all other models.
  890. all functions that are routed have a property `.conversion` attached
  891. to the returned synthetic function. This property is an array
  892. of strings, each with the steps in between the 'from' and 'to'
  893. color models (inclusive).
  894. conversions that are not possible simply are not included.
  895. */
  896. function buildGraph() {
  897. var graph = {};
  898. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  899. var models = Object.keys(conversions);
  900. for (var len = models.length, i = 0; i < len; i++) {
  901. graph[models[i]] = {
  902. // http://jsperf.com/1-vs-infinity
  903. // micro-opt, but this is simple.
  904. distance: -1,
  905. parent: null
  906. };
  907. }
  908. return graph;
  909. }
  910. // https://en.wikipedia.org/wiki/Breadth-first_search
  911. function deriveBFS(fromModel) {
  912. var graph = buildGraph();
  913. var queue = [fromModel]; // unshift -> queue -> pop
  914. graph[fromModel].distance = 0;
  915. while (queue.length) {
  916. var current = queue.pop();
  917. var adjacents = Object.keys(conversions[current]);
  918. for (var len = adjacents.length, i = 0; i < len; i++) {
  919. var adjacent = adjacents[i];
  920. var node = graph[adjacent];
  921. if (node.distance === -1) {
  922. node.distance = graph[current].distance + 1;
  923. node.parent = current;
  924. queue.unshift(adjacent);
  925. }
  926. }
  927. }
  928. return graph;
  929. }
  930. function link(from, to) {
  931. return function (args) {
  932. return to(from(args));
  933. };
  934. }
  935. function wrapConversion(toModel, graph) {
  936. var path = [graph[toModel].parent, toModel];
  937. var fn = conversions[graph[toModel].parent][toModel];
  938. var cur = graph[toModel].parent;
  939. while (graph[cur].parent) {
  940. path.unshift(graph[cur].parent);
  941. fn = link(conversions[graph[cur].parent][cur], fn);
  942. cur = graph[cur].parent;
  943. }
  944. fn.conversion = path;
  945. return fn;
  946. }
  947. var route = function (fromModel) {
  948. var graph = deriveBFS(fromModel);
  949. var conversion = {};
  950. var models = Object.keys(graph);
  951. for (var len = models.length, i = 0; i < len; i++) {
  952. var toModel = models[i];
  953. var node = graph[toModel];
  954. if (node.parent === null) {
  955. // no possible conversion, or this node is the source model.
  956. continue;
  957. }
  958. conversion[toModel] = wrapConversion(toModel, graph);
  959. }
  960. return conversion;
  961. };
  962. var convert = {};
  963. var models = Object.keys(conversions);
  964. function wrapRaw(fn) {
  965. var wrappedFn = function (args) {
  966. if (args === undefined || args === null) {
  967. return args;
  968. }
  969. if (arguments.length > 1) {
  970. args = Array.prototype.slice.call(arguments);
  971. }
  972. return fn(args);
  973. };
  974. // preserve .conversion property if there is one
  975. if ('conversion' in fn) {
  976. wrappedFn.conversion = fn.conversion;
  977. }
  978. return wrappedFn;
  979. }
  980. function wrapRounded(fn) {
  981. var wrappedFn = function (args) {
  982. if (args === undefined || args === null) {
  983. return args;
  984. }
  985. if (arguments.length > 1) {
  986. args = Array.prototype.slice.call(arguments);
  987. }
  988. var result = fn(args);
  989. // we're assuming the result is an array here.
  990. // see notice in conversions.js; don't use box types
  991. // in conversion functions.
  992. if (typeof result === 'object') {
  993. for (var len = result.length, i = 0; i < len; i++) {
  994. result[i] = Math.round(result[i]);
  995. }
  996. }
  997. return result;
  998. };
  999. // preserve .conversion property if there is one
  1000. if ('conversion' in fn) {
  1001. wrappedFn.conversion = fn.conversion;
  1002. }
  1003. return wrappedFn;
  1004. }
  1005. models.forEach(function (fromModel) {
  1006. convert[fromModel] = {};
  1007. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  1008. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  1009. var routes = route(fromModel);
  1010. var routeModels = Object.keys(routes);
  1011. routeModels.forEach(function (toModel) {
  1012. var fn = routes[toModel];
  1013. convert[fromModel][toModel] = wrapRounded(fn);
  1014. convert[fromModel][toModel].raw = wrapRaw(fn);
  1015. });
  1016. });
  1017. var colorConvert = convert;
  1018. var colorName$1 = {
  1019. "aliceblue": [240, 248, 255],
  1020. "antiquewhite": [250, 235, 215],
  1021. "aqua": [0, 255, 255],
  1022. "aquamarine": [127, 255, 212],
  1023. "azure": [240, 255, 255],
  1024. "beige": [245, 245, 220],
  1025. "bisque": [255, 228, 196],
  1026. "black": [0, 0, 0],
  1027. "blanchedalmond": [255, 235, 205],
  1028. "blue": [0, 0, 255],
  1029. "blueviolet": [138, 43, 226],
  1030. "brown": [165, 42, 42],
  1031. "burlywood": [222, 184, 135],
  1032. "cadetblue": [95, 158, 160],
  1033. "chartreuse": [127, 255, 0],
  1034. "chocolate": [210, 105, 30],
  1035. "coral": [255, 127, 80],
  1036. "cornflowerblue": [100, 149, 237],
  1037. "cornsilk": [255, 248, 220],
  1038. "crimson": [220, 20, 60],
  1039. "cyan": [0, 255, 255],
  1040. "darkblue": [0, 0, 139],
  1041. "darkcyan": [0, 139, 139],
  1042. "darkgoldenrod": [184, 134, 11],
  1043. "darkgray": [169, 169, 169],
  1044. "darkgreen": [0, 100, 0],
  1045. "darkgrey": [169, 169, 169],
  1046. "darkkhaki": [189, 183, 107],
  1047. "darkmagenta": [139, 0, 139],
  1048. "darkolivegreen": [85, 107, 47],
  1049. "darkorange": [255, 140, 0],
  1050. "darkorchid": [153, 50, 204],
  1051. "darkred": [139, 0, 0],
  1052. "darksalmon": [233, 150, 122],
  1053. "darkseagreen": [143, 188, 143],
  1054. "darkslateblue": [72, 61, 139],
  1055. "darkslategray": [47, 79, 79],
  1056. "darkslategrey": [47, 79, 79],
  1057. "darkturquoise": [0, 206, 209],
  1058. "darkviolet": [148, 0, 211],
  1059. "deeppink": [255, 20, 147],
  1060. "deepskyblue": [0, 191, 255],
  1061. "dimgray": [105, 105, 105],
  1062. "dimgrey": [105, 105, 105],
  1063. "dodgerblue": [30, 144, 255],
  1064. "firebrick": [178, 34, 34],
  1065. "floralwhite": [255, 250, 240],
  1066. "forestgreen": [34, 139, 34],
  1067. "fuchsia": [255, 0, 255],
  1068. "gainsboro": [220, 220, 220],
  1069. "ghostwhite": [248, 248, 255],
  1070. "gold": [255, 215, 0],
  1071. "goldenrod": [218, 165, 32],
  1072. "gray": [128, 128, 128],
  1073. "green": [0, 128, 0],
  1074. "greenyellow": [173, 255, 47],
  1075. "grey": [128, 128, 128],
  1076. "honeydew": [240, 255, 240],
  1077. "hotpink": [255, 105, 180],
  1078. "indianred": [205, 92, 92],
  1079. "indigo": [75, 0, 130],
  1080. "ivory": [255, 255, 240],
  1081. "khaki": [240, 230, 140],
  1082. "lavender": [230, 230, 250],
  1083. "lavenderblush": [255, 240, 245],
  1084. "lawngreen": [124, 252, 0],
  1085. "lemonchiffon": [255, 250, 205],
  1086. "lightblue": [173, 216, 230],
  1087. "lightcoral": [240, 128, 128],
  1088. "lightcyan": [224, 255, 255],
  1089. "lightgoldenrodyellow": [250, 250, 210],
  1090. "lightgray": [211, 211, 211],
  1091. "lightgreen": [144, 238, 144],
  1092. "lightgrey": [211, 211, 211],
  1093. "lightpink": [255, 182, 193],
  1094. "lightsalmon": [255, 160, 122],
  1095. "lightseagreen": [32, 178, 170],
  1096. "lightskyblue": [135, 206, 250],
  1097. "lightslategray": [119, 136, 153],
  1098. "lightslategrey": [119, 136, 153],
  1099. "lightsteelblue": [176, 196, 222],
  1100. "lightyellow": [255, 255, 224],
  1101. "lime": [0, 255, 0],
  1102. "limegreen": [50, 205, 50],
  1103. "linen": [250, 240, 230],
  1104. "magenta": [255, 0, 255],
  1105. "maroon": [128, 0, 0],
  1106. "mediumaquamarine": [102, 205, 170],
  1107. "mediumblue": [0, 0, 205],
  1108. "mediumorchid": [186, 85, 211],
  1109. "mediumpurple": [147, 112, 219],
  1110. "mediumseagreen": [60, 179, 113],
  1111. "mediumslateblue": [123, 104, 238],
  1112. "mediumspringgreen": [0, 250, 154],
  1113. "mediumturquoise": [72, 209, 204],
  1114. "mediumvioletred": [199, 21, 133],
  1115. "midnightblue": [25, 25, 112],
  1116. "mintcream": [245, 255, 250],
  1117. "mistyrose": [255, 228, 225],
  1118. "moccasin": [255, 228, 181],
  1119. "navajowhite": [255, 222, 173],
  1120. "navy": [0, 0, 128],
  1121. "oldlace": [253, 245, 230],
  1122. "olive": [128, 128, 0],
  1123. "olivedrab": [107, 142, 35],
  1124. "orange": [255, 165, 0],
  1125. "orangered": [255, 69, 0],
  1126. "orchid": [218, 112, 214],
  1127. "palegoldenrod": [238, 232, 170],
  1128. "palegreen": [152, 251, 152],
  1129. "paleturquoise": [175, 238, 238],
  1130. "palevioletred": [219, 112, 147],
  1131. "papayawhip": [255, 239, 213],
  1132. "peachpuff": [255, 218, 185],
  1133. "peru": [205, 133, 63],
  1134. "pink": [255, 192, 203],
  1135. "plum": [221, 160, 221],
  1136. "powderblue": [176, 224, 230],
  1137. "purple": [128, 0, 128],
  1138. "rebeccapurple": [102, 51, 153],
  1139. "red": [255, 0, 0],
  1140. "rosybrown": [188, 143, 143],
  1141. "royalblue": [65, 105, 225],
  1142. "saddlebrown": [139, 69, 19],
  1143. "salmon": [250, 128, 114],
  1144. "sandybrown": [244, 164, 96],
  1145. "seagreen": [46, 139, 87],
  1146. "seashell": [255, 245, 238],
  1147. "sienna": [160, 82, 45],
  1148. "silver": [192, 192, 192],
  1149. "skyblue": [135, 206, 235],
  1150. "slateblue": [106, 90, 205],
  1151. "slategray": [112, 128, 144],
  1152. "slategrey": [112, 128, 144],
  1153. "snow": [255, 250, 250],
  1154. "springgreen": [0, 255, 127],
  1155. "steelblue": [70, 130, 180],
  1156. "tan": [210, 180, 140],
  1157. "teal": [0, 128, 128],
  1158. "thistle": [216, 191, 216],
  1159. "tomato": [255, 99, 71],
  1160. "turquoise": [64, 224, 208],
  1161. "violet": [238, 130, 238],
  1162. "wheat": [245, 222, 179],
  1163. "white": [255, 255, 255],
  1164. "whitesmoke": [245, 245, 245],
  1165. "yellow": [255, 255, 0],
  1166. "yellowgreen": [154, 205, 50]
  1167. };
  1168. /* MIT license */
  1169. var colorString = {
  1170. getRgba: getRgba,
  1171. getHsla: getHsla,
  1172. getRgb: getRgb,
  1173. getHsl: getHsl,
  1174. getHwb: getHwb,
  1175. getAlpha: getAlpha,
  1176. hexString: hexString,
  1177. rgbString: rgbString,
  1178. rgbaString: rgbaString,
  1179. percentString: percentString,
  1180. percentaString: percentaString,
  1181. hslString: hslString,
  1182. hslaString: hslaString,
  1183. hwbString: hwbString,
  1184. keyword: keyword
  1185. };
  1186. function getRgba(string) {
  1187. if (!string) {
  1188. return;
  1189. }
  1190. var abbr = /^#([a-fA-F0-9]{3,4})$/i,
  1191. hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
  1192. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1193. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1194. keyword = /(\w+)/;
  1195. var rgb = [0, 0, 0],
  1196. a = 1,
  1197. match = string.match(abbr),
  1198. hexAlpha = "";
  1199. if (match) {
  1200. match = match[1];
  1201. hexAlpha = match[3];
  1202. for (var i = 0; i < rgb.length; i++) {
  1203. rgb[i] = parseInt(match[i] + match[i], 16);
  1204. }
  1205. if (hexAlpha) {
  1206. a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
  1207. }
  1208. }
  1209. else if (match = string.match(hex)) {
  1210. hexAlpha = match[2];
  1211. match = match[1];
  1212. for (var i = 0; i < rgb.length; i++) {
  1213. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  1214. }
  1215. if (hexAlpha) {
  1216. a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
  1217. }
  1218. }
  1219. else if (match = string.match(rgba)) {
  1220. for (var i = 0; i < rgb.length; i++) {
  1221. rgb[i] = parseInt(match[i + 1]);
  1222. }
  1223. a = parseFloat(match[4]);
  1224. }
  1225. else if (match = string.match(per)) {
  1226. for (var i = 0; i < rgb.length; i++) {
  1227. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  1228. }
  1229. a = parseFloat(match[4]);
  1230. }
  1231. else if (match = string.match(keyword)) {
  1232. if (match[1] == "transparent") {
  1233. return [0, 0, 0, 0];
  1234. }
  1235. rgb = colorName$1[match[1]];
  1236. if (!rgb) {
  1237. return;
  1238. }
  1239. }
  1240. for (var i = 0; i < rgb.length; i++) {
  1241. rgb[i] = scale(rgb[i], 0, 255);
  1242. }
  1243. if (!a && a != 0) {
  1244. a = 1;
  1245. }
  1246. else {
  1247. a = scale(a, 0, 1);
  1248. }
  1249. rgb[3] = a;
  1250. return rgb;
  1251. }
  1252. function getHsla(string) {
  1253. if (!string) {
  1254. return;
  1255. }
  1256. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1257. var match = string.match(hsl);
  1258. if (match) {
  1259. var alpha = parseFloat(match[4]);
  1260. var h = scale(parseInt(match[1]), 0, 360),
  1261. s = scale(parseFloat(match[2]), 0, 100),
  1262. l = scale(parseFloat(match[3]), 0, 100),
  1263. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1264. return [h, s, l, a];
  1265. }
  1266. }
  1267. function getHwb(string) {
  1268. if (!string) {
  1269. return;
  1270. }
  1271. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1272. var match = string.match(hwb);
  1273. if (match) {
  1274. var alpha = parseFloat(match[4]);
  1275. var h = scale(parseInt(match[1]), 0, 360),
  1276. w = scale(parseFloat(match[2]), 0, 100),
  1277. b = scale(parseFloat(match[3]), 0, 100),
  1278. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1279. return [h, w, b, a];
  1280. }
  1281. }
  1282. function getRgb(string) {
  1283. var rgba = getRgba(string);
  1284. return rgba && rgba.slice(0, 3);
  1285. }
  1286. function getHsl(string) {
  1287. var hsla = getHsla(string);
  1288. return hsla && hsla.slice(0, 3);
  1289. }
  1290. function getAlpha(string) {
  1291. var vals = getRgba(string);
  1292. if (vals) {
  1293. return vals[3];
  1294. }
  1295. else if (vals = getHsla(string)) {
  1296. return vals[3];
  1297. }
  1298. else if (vals = getHwb(string)) {
  1299. return vals[3];
  1300. }
  1301. }
  1302. // generators
  1303. function hexString(rgba, a) {
  1304. var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
  1305. return "#" + hexDouble(rgba[0])
  1306. + hexDouble(rgba[1])
  1307. + hexDouble(rgba[2])
  1308. + (
  1309. (a >= 0 && a < 1)
  1310. ? hexDouble(Math.round(a * 255))
  1311. : ""
  1312. );
  1313. }
  1314. function rgbString(rgba, alpha) {
  1315. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1316. return rgbaString(rgba, alpha);
  1317. }
  1318. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  1319. }
  1320. function rgbaString(rgba, alpha) {
  1321. if (alpha === undefined) {
  1322. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  1323. }
  1324. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  1325. + ", " + alpha + ")";
  1326. }
  1327. function percentString(rgba, alpha) {
  1328. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1329. return percentaString(rgba, alpha);
  1330. }
  1331. var r = Math.round(rgba[0]/255 * 100),
  1332. g = Math.round(rgba[1]/255 * 100),
  1333. b = Math.round(rgba[2]/255 * 100);
  1334. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  1335. }
  1336. function percentaString(rgba, alpha) {
  1337. var r = Math.round(rgba[0]/255 * 100),
  1338. g = Math.round(rgba[1]/255 * 100),
  1339. b = Math.round(rgba[2]/255 * 100);
  1340. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  1341. }
  1342. function hslString(hsla, alpha) {
  1343. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  1344. return hslaString(hsla, alpha);
  1345. }
  1346. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  1347. }
  1348. function hslaString(hsla, alpha) {
  1349. if (alpha === undefined) {
  1350. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  1351. }
  1352. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  1353. + alpha + ")";
  1354. }
  1355. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  1356. // (hwb have alpha optional & 1 is default value)
  1357. function hwbString(hwb, alpha) {
  1358. if (alpha === undefined) {
  1359. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  1360. }
  1361. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  1362. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  1363. }
  1364. function keyword(rgb) {
  1365. return reverseNames[rgb.slice(0, 3)];
  1366. }
  1367. // helpers
  1368. function scale(num, min, max) {
  1369. return Math.min(Math.max(min, num), max);
  1370. }
  1371. function hexDouble(num) {
  1372. var str = num.toString(16).toUpperCase();
  1373. return (str.length < 2) ? "0" + str : str;
  1374. }
  1375. //create a list of reverse color names
  1376. var reverseNames = {};
  1377. for (var name in colorName$1) {
  1378. reverseNames[colorName$1[name]] = name;
  1379. }
  1380. /* MIT license */
  1381. var Color = function (obj) {
  1382. if (obj instanceof Color) {
  1383. return obj;
  1384. }
  1385. if (!(this instanceof Color)) {
  1386. return new Color(obj);
  1387. }
  1388. this.valid = false;
  1389. this.values = {
  1390. rgb: [0, 0, 0],
  1391. hsl: [0, 0, 0],
  1392. hsv: [0, 0, 0],
  1393. hwb: [0, 0, 0],
  1394. cmyk: [0, 0, 0, 0],
  1395. alpha: 1
  1396. };
  1397. // parse Color() argument
  1398. var vals;
  1399. if (typeof obj === 'string') {
  1400. vals = colorString.getRgba(obj);
  1401. if (vals) {
  1402. this.setValues('rgb', vals);
  1403. } else if (vals = colorString.getHsla(obj)) {
  1404. this.setValues('hsl', vals);
  1405. } else if (vals = colorString.getHwb(obj)) {
  1406. this.setValues('hwb', vals);
  1407. }
  1408. } else if (typeof obj === 'object') {
  1409. vals = obj;
  1410. if (vals.r !== undefined || vals.red !== undefined) {
  1411. this.setValues('rgb', vals);
  1412. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  1413. this.setValues('hsl', vals);
  1414. } else if (vals.v !== undefined || vals.value !== undefined) {
  1415. this.setValues('hsv', vals);
  1416. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  1417. this.setValues('hwb', vals);
  1418. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  1419. this.setValues('cmyk', vals);
  1420. }
  1421. }
  1422. };
  1423. Color.prototype = {
  1424. isValid: function () {
  1425. return this.valid;
  1426. },
  1427. rgb: function () {
  1428. return this.setSpace('rgb', arguments);
  1429. },
  1430. hsl: function () {
  1431. return this.setSpace('hsl', arguments);
  1432. },
  1433. hsv: function () {
  1434. return this.setSpace('hsv', arguments);
  1435. },
  1436. hwb: function () {
  1437. return this.setSpace('hwb', arguments);
  1438. },
  1439. cmyk: function () {
  1440. return this.setSpace('cmyk', arguments);
  1441. },
  1442. rgbArray: function () {
  1443. return this.values.rgb;
  1444. },
  1445. hslArray: function () {
  1446. return this.values.hsl;
  1447. },
  1448. hsvArray: function () {
  1449. return this.values.hsv;
  1450. },
  1451. hwbArray: function () {
  1452. var values = this.values;
  1453. if (values.alpha !== 1) {
  1454. return values.hwb.concat([values.alpha]);
  1455. }
  1456. return values.hwb;
  1457. },
  1458. cmykArray: function () {
  1459. return this.values.cmyk;
  1460. },
  1461. rgbaArray: function () {
  1462. var values = this.values;
  1463. return values.rgb.concat([values.alpha]);
  1464. },
  1465. hslaArray: function () {
  1466. var values = this.values;
  1467. return values.hsl.concat([values.alpha]);
  1468. },
  1469. alpha: function (val) {
  1470. if (val === undefined) {
  1471. return this.values.alpha;
  1472. }
  1473. this.setValues('alpha', val);
  1474. return this;
  1475. },
  1476. red: function (val) {
  1477. return this.setChannel('rgb', 0, val);
  1478. },
  1479. green: function (val) {
  1480. return this.setChannel('rgb', 1, val);
  1481. },
  1482. blue: function (val) {
  1483. return this.setChannel('rgb', 2, val);
  1484. },
  1485. hue: function (val) {
  1486. if (val) {
  1487. val %= 360;
  1488. val = val < 0 ? 360 + val : val;
  1489. }
  1490. return this.setChannel('hsl', 0, val);
  1491. },
  1492. saturation: function (val) {
  1493. return this.setChannel('hsl', 1, val);
  1494. },
  1495. lightness: function (val) {
  1496. return this.setChannel('hsl', 2, val);
  1497. },
  1498. saturationv: function (val) {
  1499. return this.setChannel('hsv', 1, val);
  1500. },
  1501. whiteness: function (val) {
  1502. return this.setChannel('hwb', 1, val);
  1503. },
  1504. blackness: function (val) {
  1505. return this.setChannel('hwb', 2, val);
  1506. },
  1507. value: function (val) {
  1508. return this.setChannel('hsv', 2, val);
  1509. },
  1510. cyan: function (val) {
  1511. return this.setChannel('cmyk', 0, val);
  1512. },
  1513. magenta: function (val) {
  1514. return this.setChannel('cmyk', 1, val);
  1515. },
  1516. yellow: function (val) {
  1517. return this.setChannel('cmyk', 2, val);
  1518. },
  1519. black: function (val) {
  1520. return this.setChannel('cmyk', 3, val);
  1521. },
  1522. hexString: function () {
  1523. return colorString.hexString(this.values.rgb);
  1524. },
  1525. rgbString: function () {
  1526. return colorString.rgbString(this.values.rgb, this.values.alpha);
  1527. },
  1528. rgbaString: function () {
  1529. return colorString.rgbaString(this.values.rgb, this.values.alpha);
  1530. },
  1531. percentString: function () {
  1532. return colorString.percentString(this.values.rgb, this.values.alpha);
  1533. },
  1534. hslString: function () {
  1535. return colorString.hslString(this.values.hsl, this.values.alpha);
  1536. },
  1537. hslaString: function () {
  1538. return colorString.hslaString(this.values.hsl, this.values.alpha);
  1539. },
  1540. hwbString: function () {
  1541. return colorString.hwbString(this.values.hwb, this.values.alpha);
  1542. },
  1543. keyword: function () {
  1544. return colorString.keyword(this.values.rgb, this.values.alpha);
  1545. },
  1546. rgbNumber: function () {
  1547. var rgb = this.values.rgb;
  1548. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  1549. },
  1550. luminosity: function () {
  1551. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  1552. var rgb = this.values.rgb;
  1553. var lum = [];
  1554. for (var i = 0; i < rgb.length; i++) {
  1555. var chan = rgb[i] / 255;
  1556. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  1557. }
  1558. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  1559. },
  1560. contrast: function (color2) {
  1561. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  1562. var lum1 = this.luminosity();
  1563. var lum2 = color2.luminosity();
  1564. if (lum1 > lum2) {
  1565. return (lum1 + 0.05) / (lum2 + 0.05);
  1566. }
  1567. return (lum2 + 0.05) / (lum1 + 0.05);
  1568. },
  1569. level: function (color2) {
  1570. var contrastRatio = this.contrast(color2);
  1571. if (contrastRatio >= 7.1) {
  1572. return 'AAA';
  1573. }
  1574. return (contrastRatio >= 4.5) ? 'AA' : '';
  1575. },
  1576. dark: function () {
  1577. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  1578. var rgb = this.values.rgb;
  1579. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  1580. return yiq < 128;
  1581. },
  1582. light: function () {
  1583. return !this.dark();
  1584. },
  1585. negate: function () {
  1586. var rgb = [];
  1587. for (var i = 0; i < 3; i++) {
  1588. rgb[i] = 255 - this.values.rgb[i];
  1589. }
  1590. this.setValues('rgb', rgb);
  1591. return this;
  1592. },
  1593. lighten: function (ratio) {
  1594. var hsl = this.values.hsl;
  1595. hsl[2] += hsl[2] * ratio;
  1596. this.setValues('hsl', hsl);
  1597. return this;
  1598. },
  1599. darken: function (ratio) {
  1600. var hsl = this.values.hsl;
  1601. hsl[2] -= hsl[2] * ratio;
  1602. this.setValues('hsl', hsl);
  1603. return this;
  1604. },
  1605. saturate: function (ratio) {
  1606. var hsl = this.values.hsl;
  1607. hsl[1] += hsl[1] * ratio;
  1608. this.setValues('hsl', hsl);
  1609. return this;
  1610. },
  1611. desaturate: function (ratio) {
  1612. var hsl = this.values.hsl;
  1613. hsl[1] -= hsl[1] * ratio;
  1614. this.setValues('hsl', hsl);
  1615. return this;
  1616. },
  1617. whiten: function (ratio) {
  1618. var hwb = this.values.hwb;
  1619. hwb[1] += hwb[1] * ratio;
  1620. this.setValues('hwb', hwb);
  1621. return this;
  1622. },
  1623. blacken: function (ratio) {
  1624. var hwb = this.values.hwb;
  1625. hwb[2] += hwb[2] * ratio;
  1626. this.setValues('hwb', hwb);
  1627. return this;
  1628. },
  1629. greyscale: function () {
  1630. var rgb = this.values.rgb;
  1631. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  1632. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  1633. this.setValues('rgb', [val, val, val]);
  1634. return this;
  1635. },
  1636. clearer: function (ratio) {
  1637. var alpha = this.values.alpha;
  1638. this.setValues('alpha', alpha - (alpha * ratio));
  1639. return this;
  1640. },
  1641. opaquer: function (ratio) {
  1642. var alpha = this.values.alpha;
  1643. this.setValues('alpha', alpha + (alpha * ratio));
  1644. return this;
  1645. },
  1646. rotate: function (degrees) {
  1647. var hsl = this.values.hsl;
  1648. var hue = (hsl[0] + degrees) % 360;
  1649. hsl[0] = hue < 0 ? 360 + hue : hue;
  1650. this.setValues('hsl', hsl);
  1651. return this;
  1652. },
  1653. /**
  1654. * Ported from sass implementation in C
  1655. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  1656. */
  1657. mix: function (mixinColor, weight) {
  1658. var color1 = this;
  1659. var color2 = mixinColor;
  1660. var p = weight === undefined ? 0.5 : weight;
  1661. var w = 2 * p - 1;
  1662. var a = color1.alpha() - color2.alpha();
  1663. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  1664. var w2 = 1 - w1;
  1665. return this
  1666. .rgb(
  1667. w1 * color1.red() + w2 * color2.red(),
  1668. w1 * color1.green() + w2 * color2.green(),
  1669. w1 * color1.blue() + w2 * color2.blue()
  1670. )
  1671. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  1672. },
  1673. toJSON: function () {
  1674. return this.rgb();
  1675. },
  1676. clone: function () {
  1677. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  1678. // making the final build way to big to embed in Chart.js. So let's do it manually,
  1679. // assuming that values to clone are 1 dimension arrays containing only numbers,
  1680. // except 'alpha' which is a number.
  1681. var result = new Color();
  1682. var source = this.values;
  1683. var target = result.values;
  1684. var value, type;
  1685. for (var prop in source) {
  1686. if (source.hasOwnProperty(prop)) {
  1687. value = source[prop];
  1688. type = ({}).toString.call(value);
  1689. if (type === '[object Array]') {
  1690. target[prop] = value.slice(0);
  1691. } else if (type === '[object Number]') {
  1692. target[prop] = value;
  1693. } else {
  1694. console.error('unexpected color value:', value);
  1695. }
  1696. }
  1697. }
  1698. return result;
  1699. }
  1700. };
  1701. Color.prototype.spaces = {
  1702. rgb: ['red', 'green', 'blue'],
  1703. hsl: ['hue', 'saturation', 'lightness'],
  1704. hsv: ['hue', 'saturation', 'value'],
  1705. hwb: ['hue', 'whiteness', 'blackness'],
  1706. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  1707. };
  1708. Color.prototype.maxes = {
  1709. rgb: [255, 255, 255],
  1710. hsl: [360, 100, 100],
  1711. hsv: [360, 100, 100],
  1712. hwb: [360, 100, 100],
  1713. cmyk: [100, 100, 100, 100]
  1714. };
  1715. Color.prototype.getValues = function (space) {
  1716. var values = this.values;
  1717. var vals = {};
  1718. for (var i = 0; i < space.length; i++) {
  1719. vals[space.charAt(i)] = values[space][i];
  1720. }
  1721. if (values.alpha !== 1) {
  1722. vals.a = values.alpha;
  1723. }
  1724. // {r: 255, g: 255, b: 255, a: 0.4}
  1725. return vals;
  1726. };
  1727. Color.prototype.setValues = function (space, vals) {
  1728. var values = this.values;
  1729. var spaces = this.spaces;
  1730. var maxes = this.maxes;
  1731. var alpha = 1;
  1732. var i;
  1733. this.valid = true;
  1734. if (space === 'alpha') {
  1735. alpha = vals;
  1736. } else if (vals.length) {
  1737. // [10, 10, 10]
  1738. values[space] = vals.slice(0, space.length);
  1739. alpha = vals[space.length];
  1740. } else if (vals[space.charAt(0)] !== undefined) {
  1741. // {r: 10, g: 10, b: 10}
  1742. for (i = 0; i < space.length; i++) {
  1743. values[space][i] = vals[space.charAt(i)];
  1744. }
  1745. alpha = vals.a;
  1746. } else if (vals[spaces[space][0]] !== undefined) {
  1747. // {red: 10, green: 10, blue: 10}
  1748. var chans = spaces[space];
  1749. for (i = 0; i < space.length; i++) {
  1750. values[space][i] = vals[chans[i]];
  1751. }
  1752. alpha = vals.alpha;
  1753. }
  1754. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  1755. if (space === 'alpha') {
  1756. return false;
  1757. }
  1758. var capped;
  1759. // cap values of the space prior converting all values
  1760. for (i = 0; i < space.length; i++) {
  1761. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  1762. values[space][i] = Math.round(capped);
  1763. }
  1764. // convert to all the other color spaces
  1765. for (var sname in spaces) {
  1766. if (sname !== space) {
  1767. values[sname] = colorConvert[space][sname](values[space]);
  1768. }
  1769. }
  1770. return true;
  1771. };
  1772. Color.prototype.setSpace = function (space, args) {
  1773. var vals = args[0];
  1774. if (vals === undefined) {
  1775. // color.rgb()
  1776. return this.getValues(space);
  1777. }
  1778. // color.rgb(10, 10, 10)
  1779. if (typeof vals === 'number') {
  1780. vals = Array.prototype.slice.call(args);
  1781. }
  1782. this.setValues(space, vals);
  1783. return this;
  1784. };
  1785. Color.prototype.setChannel = function (space, index, val) {
  1786. var svalues = this.values[space];
  1787. if (val === undefined) {
  1788. // color.red()
  1789. return svalues[index];
  1790. } else if (val === svalues[index]) {
  1791. // color.red(color.red())
  1792. return this;
  1793. }
  1794. // color.red(100)
  1795. svalues[index] = val;
  1796. this.setValues(space, svalues);
  1797. return this;
  1798. };
  1799. if (typeof window !== 'undefined') {
  1800. window.Color = Color;
  1801. }
  1802. var chartjsColor = Color;
  1803. /**
  1804. * @namespace Chart.helpers
  1805. */
  1806. var helpers = {
  1807. /**
  1808. * An empty function that can be used, for example, for optional callback.
  1809. */
  1810. noop: function() {},
  1811. /**
  1812. * Returns a unique id, sequentially generated from a global variable.
  1813. * @returns {number}
  1814. * @function
  1815. */
  1816. uid: (function() {
  1817. var id = 0;
  1818. return function() {
  1819. return id++;
  1820. };
  1821. }()),
  1822. /**
  1823. * Returns true if `value` is neither null nor undefined, else returns false.
  1824. * @param {*} value - The value to test.
  1825. * @returns {boolean}
  1826. * @since 2.7.0
  1827. */
  1828. isNullOrUndef: function(value) {
  1829. return value === null || typeof value === 'undefined';
  1830. },
  1831. /**
  1832. * Returns true if `value` is an array (including typed arrays), else returns false.
  1833. * @param {*} value - The value to test.
  1834. * @returns {boolean}
  1835. * @function
  1836. */
  1837. isArray: function(value) {
  1838. if (Array.isArray && Array.isArray(value)) {
  1839. return true;
  1840. }
  1841. var type = Object.prototype.toString.call(value);
  1842. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  1843. return true;
  1844. }
  1845. return false;
  1846. },
  1847. /**
  1848. * Returns true if `value` is an object (excluding null), else returns false.
  1849. * @param {*} value - The value to test.
  1850. * @returns {boolean}
  1851. * @since 2.7.0
  1852. */
  1853. isObject: function(value) {
  1854. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  1855. },
  1856. /**
  1857. * Returns true if `value` is a finite number, else returns false
  1858. * @param {*} value - The value to test.
  1859. * @returns {boolean}
  1860. */
  1861. isFinite: function(value) {
  1862. return (typeof value === 'number' || value instanceof Number) && isFinite(value);
  1863. },
  1864. /**
  1865. * Returns `value` if defined, else returns `defaultValue`.
  1866. * @param {*} value - The value to return if defined.
  1867. * @param {*} defaultValue - The value to return if `value` is undefined.
  1868. * @returns {*}
  1869. */
  1870. valueOrDefault: function(value, defaultValue) {
  1871. return typeof value === 'undefined' ? defaultValue : value;
  1872. },
  1873. /**
  1874. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  1875. * @param {Array} value - The array to lookup for value at `index`.
  1876. * @param {number} index - The index in `value` to lookup for value.
  1877. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  1878. * @returns {*}
  1879. */
  1880. valueAtIndexOrDefault: function(value, index, defaultValue) {
  1881. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  1882. },
  1883. /**
  1884. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  1885. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  1886. * @param {function} fn - The function to call.
  1887. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  1888. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1889. * @returns {*}
  1890. */
  1891. callback: function(fn, args, thisArg) {
  1892. if (fn && typeof fn.call === 'function') {
  1893. return fn.apply(thisArg, args);
  1894. }
  1895. },
  1896. /**
  1897. * Note(SB) for performance sake, this method should only be used when loopable type
  1898. * is unknown or in none intensive code (not called often and small loopable). Else
  1899. * it's preferable to use a regular for() loop and save extra function calls.
  1900. * @param {object|Array} loopable - The object or array to be iterated.
  1901. * @param {function} fn - The function to call for each item.
  1902. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1903. * @param {boolean} [reverse] - If true, iterates backward on the loopable.
  1904. */
  1905. each: function(loopable, fn, thisArg, reverse) {
  1906. var i, len, keys;
  1907. if (helpers.isArray(loopable)) {
  1908. len = loopable.length;
  1909. if (reverse) {
  1910. for (i = len - 1; i >= 0; i--) {
  1911. fn.call(thisArg, loopable[i], i);
  1912. }
  1913. } else {
  1914. for (i = 0; i < len; i++) {
  1915. fn.call(thisArg, loopable[i], i);
  1916. }
  1917. }
  1918. } else if (helpers.isObject(loopable)) {
  1919. keys = Object.keys(loopable);
  1920. len = keys.length;
  1921. for (i = 0; i < len; i++) {
  1922. fn.call(thisArg, loopable[keys[i]], keys[i]);
  1923. }
  1924. }
  1925. },
  1926. /**
  1927. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  1928. * @see https://stackoverflow.com/a/14853974
  1929. * @param {Array} a0 - The array to compare
  1930. * @param {Array} a1 - The array to compare
  1931. * @returns {boolean}
  1932. */
  1933. arrayEquals: function(a0, a1) {
  1934. var i, ilen, v0, v1;
  1935. if (!a0 || !a1 || a0.length !== a1.length) {
  1936. return false;
  1937. }
  1938. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  1939. v0 = a0[i];
  1940. v1 = a1[i];
  1941. if (v0 instanceof Array && v1 instanceof Array) {
  1942. if (!helpers.arrayEquals(v0, v1)) {
  1943. return false;
  1944. }
  1945. } else if (v0 !== v1) {
  1946. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  1947. return false;
  1948. }
  1949. }
  1950. return true;
  1951. },
  1952. /**
  1953. * Returns a deep copy of `source` without keeping references on objects and arrays.
  1954. * @param {*} source - The value to clone.
  1955. * @returns {*}
  1956. */
  1957. clone: function(source) {
  1958. if (helpers.isArray(source)) {
  1959. return source.map(helpers.clone);
  1960. }
  1961. if (helpers.isObject(source)) {
  1962. var target = {};
  1963. var keys = Object.keys(source);
  1964. var klen = keys.length;
  1965. var k = 0;
  1966. for (; k < klen; ++k) {
  1967. target[keys[k]] = helpers.clone(source[keys[k]]);
  1968. }
  1969. return target;
  1970. }
  1971. return source;
  1972. },
  1973. /**
  1974. * The default merger when Chart.helpers.merge is called without merger option.
  1975. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
  1976. * @private
  1977. */
  1978. _merger: function(key, target, source, options) {
  1979. var tval = target[key];
  1980. var sval = source[key];
  1981. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1982. helpers.merge(tval, sval, options);
  1983. } else {
  1984. target[key] = helpers.clone(sval);
  1985. }
  1986. },
  1987. /**
  1988. * Merges source[key] in target[key] only if target[key] is undefined.
  1989. * @private
  1990. */
  1991. _mergerIf: function(key, target, source) {
  1992. var tval = target[key];
  1993. var sval = source[key];
  1994. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1995. helpers.mergeIf(tval, sval);
  1996. } else if (!target.hasOwnProperty(key)) {
  1997. target[key] = helpers.clone(sval);
  1998. }
  1999. },
  2000. /**
  2001. * Recursively deep copies `source` properties into `target` with the given `options`.
  2002. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2003. * @param {object} target - The target object in which all sources are merged into.
  2004. * @param {object|object[]} source - Object(s) to merge into `target`.
  2005. * @param {object} [options] - Merging options:
  2006. * @param {function} [options.merger] - The merge method (key, target, source, options)
  2007. * @returns {object} The `target` object.
  2008. */
  2009. merge: function(target, source, options) {
  2010. var sources = helpers.isArray(source) ? source : [source];
  2011. var ilen = sources.length;
  2012. var merge, i, keys, klen, k;
  2013. if (!helpers.isObject(target)) {
  2014. return target;
  2015. }
  2016. options = options || {};
  2017. merge = options.merger || helpers._merger;
  2018. for (i = 0; i < ilen; ++i) {
  2019. source = sources[i];
  2020. if (!helpers.isObject(source)) {
  2021. continue;
  2022. }
  2023. keys = Object.keys(source);
  2024. for (k = 0, klen = keys.length; k < klen; ++k) {
  2025. merge(keys[k], target, source, options);
  2026. }
  2027. }
  2028. return target;
  2029. },
  2030. /**
  2031. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  2032. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2033. * @param {object} target - The target object in which all sources are merged into.
  2034. * @param {object|object[]} source - Object(s) to merge into `target`.
  2035. * @returns {object} The `target` object.
  2036. */
  2037. mergeIf: function(target, source) {
  2038. return helpers.merge(target, source, {merger: helpers._mergerIf});
  2039. },
  2040. /**
  2041. * Applies the contents of two or more objects together into the first object.
  2042. * @param {object} target - The target object in which all objects are merged into.
  2043. * @param {object} arg1 - Object containing additional properties to merge in target.
  2044. * @param {object} argN - Additional objects containing properties to merge in target.
  2045. * @returns {object} The `target` object.
  2046. */
  2047. extend: Object.assign || function(target) {
  2048. return helpers.merge(target, [].slice.call(arguments, 1), {
  2049. merger: function(key, dst, src) {
  2050. dst[key] = src[key];
  2051. }
  2052. });
  2053. },
  2054. /**
  2055. * Basic javascript inheritance based on the model created in Backbone.js
  2056. */
  2057. inherits: function(extensions) {
  2058. var me = this;
  2059. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
  2060. return me.apply(this, arguments);
  2061. };
  2062. var Surrogate = function() {
  2063. this.constructor = ChartElement;
  2064. };
  2065. Surrogate.prototype = me.prototype;
  2066. ChartElement.prototype = new Surrogate();
  2067. ChartElement.extend = helpers.inherits;
  2068. if (extensions) {
  2069. helpers.extend(ChartElement.prototype, extensions);
  2070. }
  2071. ChartElement.__super__ = me.prototype;
  2072. return ChartElement;
  2073. },
  2074. _deprecated: function(scope, value, previous, current) {
  2075. if (value !== undefined) {
  2076. console.warn(scope + ': "' + previous +
  2077. '" is deprecated. Please use "' + current + '" instead');
  2078. }
  2079. }
  2080. };
  2081. var helpers_core = helpers;
  2082. // DEPRECATIONS
  2083. /**
  2084. * Provided for backward compatibility, use Chart.helpers.callback instead.
  2085. * @function Chart.helpers.callCallback
  2086. * @deprecated since version 2.6.0
  2087. * @todo remove at version 3
  2088. * @private
  2089. */
  2090. helpers.callCallback = helpers.callback;
  2091. /**
  2092. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  2093. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  2094. * @function Chart.helpers.indexOf
  2095. * @deprecated since version 2.7.0
  2096. * @todo remove at version 3
  2097. * @private
  2098. */
  2099. helpers.indexOf = function(array, item, fromIndex) {
  2100. return Array.prototype.indexOf.call(array, item, fromIndex);
  2101. };
  2102. /**
  2103. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  2104. * @function Chart.helpers.getValueOrDefault
  2105. * @deprecated since version 2.7.0
  2106. * @todo remove at version 3
  2107. * @private
  2108. */
  2109. helpers.getValueOrDefault = helpers.valueOrDefault;
  2110. /**
  2111. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  2112. * @function Chart.helpers.getValueAtIndexOrDefault
  2113. * @deprecated since version 2.7.0
  2114. * @todo remove at version 3
  2115. * @private
  2116. */
  2117. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  2118. /**
  2119. * Easing functions adapted from Robert Penner's easing equations.
  2120. * @namespace Chart.helpers.easingEffects
  2121. * @see http://www.robertpenner.com/easing/
  2122. */
  2123. var effects = {
  2124. linear: function(t) {
  2125. return t;
  2126. },
  2127. easeInQuad: function(t) {
  2128. return t * t;
  2129. },
  2130. easeOutQuad: function(t) {
  2131. return -t * (t - 2);
  2132. },
  2133. easeInOutQuad: function(t) {
  2134. if ((t /= 0.5) < 1) {
  2135. return 0.5 * t * t;
  2136. }
  2137. return -0.5 * ((--t) * (t - 2) - 1);
  2138. },
  2139. easeInCubic: function(t) {
  2140. return t * t * t;
  2141. },
  2142. easeOutCubic: function(t) {
  2143. return (t = t - 1) * t * t + 1;
  2144. },
  2145. easeInOutCubic: function(t) {
  2146. if ((t /= 0.5) < 1) {
  2147. return 0.5 * t * t * t;
  2148. }
  2149. return 0.5 * ((t -= 2) * t * t + 2);
  2150. },
  2151. easeInQuart: function(t) {
  2152. return t * t * t * t;
  2153. },
  2154. easeOutQuart: function(t) {
  2155. return -((t = t - 1) * t * t * t - 1);
  2156. },
  2157. easeInOutQuart: function(t) {
  2158. if ((t /= 0.5) < 1) {
  2159. return 0.5 * t * t * t * t;
  2160. }
  2161. return -0.5 * ((t -= 2) * t * t * t - 2);
  2162. },
  2163. easeInQuint: function(t) {
  2164. return t * t * t * t * t;
  2165. },
  2166. easeOutQuint: function(t) {
  2167. return (t = t - 1) * t * t * t * t + 1;
  2168. },
  2169. easeInOutQuint: function(t) {
  2170. if ((t /= 0.5) < 1) {
  2171. return 0.5 * t * t * t * t * t;
  2172. }
  2173. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  2174. },
  2175. easeInSine: function(t) {
  2176. return -Math.cos(t * (Math.PI / 2)) + 1;
  2177. },
  2178. easeOutSine: function(t) {
  2179. return Math.sin(t * (Math.PI / 2));
  2180. },
  2181. easeInOutSine: function(t) {
  2182. return -0.5 * (Math.cos(Math.PI * t) - 1);
  2183. },
  2184. easeInExpo: function(t) {
  2185. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  2186. },
  2187. easeOutExpo: function(t) {
  2188. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  2189. },
  2190. easeInOutExpo: function(t) {
  2191. if (t === 0) {
  2192. return 0;
  2193. }
  2194. if (t === 1) {
  2195. return 1;
  2196. }
  2197. if ((t /= 0.5) < 1) {
  2198. return 0.5 * Math.pow(2, 10 * (t - 1));
  2199. }
  2200. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  2201. },
  2202. easeInCirc: function(t) {
  2203. if (t >= 1) {
  2204. return t;
  2205. }
  2206. return -(Math.sqrt(1 - t * t) - 1);
  2207. },
  2208. easeOutCirc: function(t) {
  2209. return Math.sqrt(1 - (t = t - 1) * t);
  2210. },
  2211. easeInOutCirc: function(t) {
  2212. if ((t /= 0.5) < 1) {
  2213. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  2214. }
  2215. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  2216. },
  2217. easeInElastic: function(t) {
  2218. var s = 1.70158;
  2219. var p = 0;
  2220. var a = 1;
  2221. if (t === 0) {
  2222. return 0;
  2223. }
  2224. if (t === 1) {
  2225. return 1;
  2226. }
  2227. if (!p) {
  2228. p = 0.3;
  2229. }
  2230. if (a < 1) {
  2231. a = 1;
  2232. s = p / 4;
  2233. } else {
  2234. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2235. }
  2236. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2237. },
  2238. easeOutElastic: function(t) {
  2239. var s = 1.70158;
  2240. var p = 0;
  2241. var a = 1;
  2242. if (t === 0) {
  2243. return 0;
  2244. }
  2245. if (t === 1) {
  2246. return 1;
  2247. }
  2248. if (!p) {
  2249. p = 0.3;
  2250. }
  2251. if (a < 1) {
  2252. a = 1;
  2253. s = p / 4;
  2254. } else {
  2255. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2256. }
  2257. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  2258. },
  2259. easeInOutElastic: function(t) {
  2260. var s = 1.70158;
  2261. var p = 0;
  2262. var a = 1;
  2263. if (t === 0) {
  2264. return 0;
  2265. }
  2266. if ((t /= 0.5) === 2) {
  2267. return 1;
  2268. }
  2269. if (!p) {
  2270. p = 0.45;
  2271. }
  2272. if (a < 1) {
  2273. a = 1;
  2274. s = p / 4;
  2275. } else {
  2276. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2277. }
  2278. if (t < 1) {
  2279. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2280. }
  2281. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2282. },
  2283. easeInBack: function(t) {
  2284. var s = 1.70158;
  2285. return t * t * ((s + 1) * t - s);
  2286. },
  2287. easeOutBack: function(t) {
  2288. var s = 1.70158;
  2289. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  2290. },
  2291. easeInOutBack: function(t) {
  2292. var s = 1.70158;
  2293. if ((t /= 0.5) < 1) {
  2294. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  2295. }
  2296. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  2297. },
  2298. easeInBounce: function(t) {
  2299. return 1 - effects.easeOutBounce(1 - t);
  2300. },
  2301. easeOutBounce: function(t) {
  2302. if (t < (1 / 2.75)) {
  2303. return 7.5625 * t * t;
  2304. }
  2305. if (t < (2 / 2.75)) {
  2306. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  2307. }
  2308. if (t < (2.5 / 2.75)) {
  2309. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  2310. }
  2311. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  2312. },
  2313. easeInOutBounce: function(t) {
  2314. if (t < 0.5) {
  2315. return effects.easeInBounce(t * 2) * 0.5;
  2316. }
  2317. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  2318. }
  2319. };
  2320. var helpers_easing = {
  2321. effects: effects
  2322. };
  2323. // DEPRECATIONS
  2324. /**
  2325. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  2326. * @function Chart.helpers.easingEffects
  2327. * @deprecated since version 2.7.0
  2328. * @todo remove at version 3
  2329. * @private
  2330. */
  2331. helpers_core.easingEffects = effects;
  2332. var PI = Math.PI;
  2333. var RAD_PER_DEG = PI / 180;
  2334. var DOUBLE_PI = PI * 2;
  2335. var HALF_PI = PI / 2;
  2336. var QUARTER_PI = PI / 4;
  2337. var TWO_THIRDS_PI = PI * 2 / 3;
  2338. /**
  2339. * @namespace Chart.helpers.canvas
  2340. */
  2341. var exports$1 = {
  2342. /**
  2343. * Clears the entire canvas associated to the given `chart`.
  2344. * @param {Chart} chart - The chart for which to clear the canvas.
  2345. */
  2346. clear: function(chart) {
  2347. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  2348. },
  2349. /**
  2350. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  2351. * given size (width, height) and the same `radius` for all corners.
  2352. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  2353. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  2354. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  2355. * @param {number} width - The rectangle's width.
  2356. * @param {number} height - The rectangle's height.
  2357. * @param {number} radius - The rounded amount (in pixels) for the four corners.
  2358. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  2359. */
  2360. roundedRect: function(ctx, x, y, width, height, radius) {
  2361. if (radius) {
  2362. var r = Math.min(radius, height / 2, width / 2);
  2363. var left = x + r;
  2364. var top = y + r;
  2365. var right = x + width - r;
  2366. var bottom = y + height - r;
  2367. ctx.moveTo(x, top);
  2368. if (left < right && top < bottom) {
  2369. ctx.arc(left, top, r, -PI, -HALF_PI);
  2370. ctx.arc(right, top, r, -HALF_PI, 0);
  2371. ctx.arc(right, bottom, r, 0, HALF_PI);
  2372. ctx.arc(left, bottom, r, HALF_PI, PI);
  2373. } else if (left < right) {
  2374. ctx.moveTo(left, y);
  2375. ctx.arc(right, top, r, -HALF_PI, HALF_PI);
  2376. ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
  2377. } else if (top < bottom) {
  2378. ctx.arc(left, top, r, -PI, 0);
  2379. ctx.arc(left, bottom, r, 0, PI);
  2380. } else {
  2381. ctx.arc(left, top, r, -PI, PI);
  2382. }
  2383. ctx.closePath();
  2384. ctx.moveTo(x, y);
  2385. } else {
  2386. ctx.rect(x, y, width, height);
  2387. }
  2388. },
  2389. drawPoint: function(ctx, style, radius, x, y, rotation) {
  2390. var type, xOffset, yOffset, size, cornerRadius;
  2391. var rad = (rotation || 0) * RAD_PER_DEG;
  2392. if (style && typeof style === 'object') {
  2393. type = style.toString();
  2394. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  2395. ctx.save();
  2396. ctx.translate(x, y);
  2397. ctx.rotate(rad);
  2398. ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
  2399. ctx.restore();
  2400. return;
  2401. }
  2402. }
  2403. if (isNaN(radius) || radius <= 0) {
  2404. return;
  2405. }
  2406. ctx.beginPath();
  2407. switch (style) {
  2408. // Default includes circle
  2409. default:
  2410. ctx.arc(x, y, radius, 0, DOUBLE_PI);
  2411. ctx.closePath();
  2412. break;
  2413. case 'triangle':
  2414. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2415. rad += TWO_THIRDS_PI;
  2416. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2417. rad += TWO_THIRDS_PI;
  2418. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2419. ctx.closePath();
  2420. break;
  2421. case 'rectRounded':
  2422. // NOTE: the rounded rect implementation changed to use `arc` instead of
  2423. // `quadraticCurveTo` since it generates better results when rect is
  2424. // almost a circle. 0.516 (instead of 0.5) produces results with visually
  2425. // closer proportion to the previous impl and it is inscribed in the
  2426. // circle with `radius`. For more details, see the following PRs:
  2427. // https://github.com/chartjs/Chart.js/issues/5597
  2428. // https://github.com/chartjs/Chart.js/issues/5858
  2429. cornerRadius = radius * 0.516;
  2430. size = radius - cornerRadius;
  2431. xOffset = Math.cos(rad + QUARTER_PI) * size;
  2432. yOffset = Math.sin(rad + QUARTER_PI) * size;
  2433. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  2434. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  2435. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  2436. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  2437. ctx.closePath();
  2438. break;
  2439. case 'rect':
  2440. if (!rotation) {
  2441. size = Math.SQRT1_2 * radius;
  2442. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  2443. break;
  2444. }
  2445. rad += QUARTER_PI;
  2446. /* falls through */
  2447. case 'rectRot':
  2448. xOffset = Math.cos(rad) * radius;
  2449. yOffset = Math.sin(rad) * radius;
  2450. ctx.moveTo(x - xOffset, y - yOffset);
  2451. ctx.lineTo(x + yOffset, y - xOffset);
  2452. ctx.lineTo(x + xOffset, y + yOffset);
  2453. ctx.lineTo(x - yOffset, y + xOffset);
  2454. ctx.closePath();
  2455. break;
  2456. case 'crossRot':
  2457. rad += QUARTER_PI;
  2458. /* falls through */
  2459. case 'cross':
  2460. xOffset = Math.cos(rad) * radius;
  2461. yOffset = Math.sin(rad) * radius;
  2462. ctx.moveTo(x - xOffset, y - yOffset);
  2463. ctx.lineTo(x + xOffset, y + yOffset);
  2464. ctx.moveTo(x + yOffset, y - xOffset);
  2465. ctx.lineTo(x - yOffset, y + xOffset);
  2466. break;
  2467. case 'star':
  2468. xOffset = Math.cos(rad) * radius;
  2469. yOffset = Math.sin(rad) * radius;
  2470. ctx.moveTo(x - xOffset, y - yOffset);
  2471. ctx.lineTo(x + xOffset, y + yOffset);
  2472. ctx.moveTo(x + yOffset, y - xOffset);
  2473. ctx.lineTo(x - yOffset, y + xOffset);
  2474. rad += QUARTER_PI;
  2475. xOffset = Math.cos(rad) * radius;
  2476. yOffset = Math.sin(rad) * radius;
  2477. ctx.moveTo(x - xOffset, y - yOffset);
  2478. ctx.lineTo(x + xOffset, y + yOffset);
  2479. ctx.moveTo(x + yOffset, y - xOffset);
  2480. ctx.lineTo(x - yOffset, y + xOffset);
  2481. break;
  2482. case 'line':
  2483. xOffset = Math.cos(rad) * radius;
  2484. yOffset = Math.sin(rad) * radius;
  2485. ctx.moveTo(x - xOffset, y - yOffset);
  2486. ctx.lineTo(x + xOffset, y + yOffset);
  2487. break;
  2488. case 'dash':
  2489. ctx.moveTo(x, y);
  2490. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  2491. break;
  2492. }
  2493. ctx.fill();
  2494. ctx.stroke();
  2495. },
  2496. /**
  2497. * Returns true if the point is inside the rectangle
  2498. * @param {object} point - The point to test
  2499. * @param {object} area - The rectangle
  2500. * @returns {boolean}
  2501. * @private
  2502. */
  2503. _isPointInArea: function(point, area) {
  2504. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  2505. return point.x > area.left - epsilon && point.x < area.right + epsilon &&
  2506. point.y > area.top - epsilon && point.y < area.bottom + epsilon;
  2507. },
  2508. clipArea: function(ctx, area) {
  2509. ctx.save();
  2510. ctx.beginPath();
  2511. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  2512. ctx.clip();
  2513. },
  2514. unclipArea: function(ctx) {
  2515. ctx.restore();
  2516. },
  2517. lineTo: function(ctx, previous, target, flip) {
  2518. var stepped = target.steppedLine;
  2519. if (stepped) {
  2520. if (stepped === 'middle') {
  2521. var midpoint = (previous.x + target.x) / 2.0;
  2522. ctx.lineTo(midpoint, flip ? target.y : previous.y);
  2523. ctx.lineTo(midpoint, flip ? previous.y : target.y);
  2524. } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
  2525. ctx.lineTo(previous.x, target.y);
  2526. } else {
  2527. ctx.lineTo(target.x, previous.y);
  2528. }
  2529. ctx.lineTo(target.x, target.y);
  2530. return;
  2531. }
  2532. if (!target.tension) {
  2533. ctx.lineTo(target.x, target.y);
  2534. return;
  2535. }
  2536. ctx.bezierCurveTo(
  2537. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  2538. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  2539. flip ? target.controlPointNextX : target.controlPointPreviousX,
  2540. flip ? target.controlPointNextY : target.controlPointPreviousY,
  2541. target.x,
  2542. target.y);
  2543. }
  2544. };
  2545. var helpers_canvas = exports$1;
  2546. // DEPRECATIONS
  2547. /**
  2548. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  2549. * @namespace Chart.helpers.clear
  2550. * @deprecated since version 2.7.0
  2551. * @todo remove at version 3
  2552. * @private
  2553. */
  2554. helpers_core.clear = exports$1.clear;
  2555. /**
  2556. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  2557. * @namespace Chart.helpers.drawRoundedRectangle
  2558. * @deprecated since version 2.7.0
  2559. * @todo remove at version 3
  2560. * @private
  2561. */
  2562. helpers_core.drawRoundedRectangle = function(ctx) {
  2563. ctx.beginPath();
  2564. exports$1.roundedRect.apply(exports$1, arguments);
  2565. };
  2566. var defaults = {
  2567. /**
  2568. * @private
  2569. */
  2570. _set: function(scope, values) {
  2571. return helpers_core.merge(this[scope] || (this[scope] = {}), values);
  2572. }
  2573. };
  2574. // TODO(v3): remove 'global' from namespace. all default are global and
  2575. // there's inconsistency around which options are under 'global'
  2576. defaults._set('global', {
  2577. defaultColor: 'rgba(0,0,0,0.1)',
  2578. defaultFontColor: '#666',
  2579. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  2580. defaultFontSize: 12,
  2581. defaultFontStyle: 'normal',
  2582. defaultLineHeight: 1.2,
  2583. showLines: true
  2584. });
  2585. var core_defaults = defaults;
  2586. var valueOrDefault = helpers_core.valueOrDefault;
  2587. /**
  2588. * Converts the given font object into a CSS font string.
  2589. * @param {object} font - A font object.
  2590. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
  2591. * @private
  2592. */
  2593. function toFontString(font) {
  2594. if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
  2595. return null;
  2596. }
  2597. return (font.style ? font.style + ' ' : '')
  2598. + (font.weight ? font.weight + ' ' : '')
  2599. + font.size + 'px '
  2600. + font.family;
  2601. }
  2602. /**
  2603. * @alias Chart.helpers.options
  2604. * @namespace
  2605. */
  2606. var helpers_options = {
  2607. /**
  2608. * Converts the given line height `value` in pixels for a specific font `size`.
  2609. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  2610. * @param {number} size - The font size (in pixels) used to resolve relative `value`.
  2611. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
  2612. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  2613. * @since 2.7.0
  2614. */
  2615. toLineHeight: function(value, size) {
  2616. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  2617. if (!matches || matches[1] === 'normal') {
  2618. return size * 1.2;
  2619. }
  2620. value = +matches[2];
  2621. switch (matches[3]) {
  2622. case 'px':
  2623. return value;
  2624. case '%':
  2625. value /= 100;
  2626. break;
  2627. }
  2628. return size * value;
  2629. },
  2630. /**
  2631. * Converts the given value into a padding object with pre-computed width/height.
  2632. * @param {number|object} value - If a number, set the value to all TRBL component,
  2633. * else, if and object, use defined properties and sets undefined ones to 0.
  2634. * @returns {object} The padding values (top, right, bottom, left, width, height)
  2635. * @since 2.7.0
  2636. */
  2637. toPadding: function(value) {
  2638. var t, r, b, l;
  2639. if (helpers_core.isObject(value)) {
  2640. t = +value.top || 0;
  2641. r = +value.right || 0;
  2642. b = +value.bottom || 0;
  2643. l = +value.left || 0;
  2644. } else {
  2645. t = r = b = l = +value || 0;
  2646. }
  2647. return {
  2648. top: t,
  2649. right: r,
  2650. bottom: b,
  2651. left: l,
  2652. height: t + b,
  2653. width: l + r
  2654. };
  2655. },
  2656. /**
  2657. * Parses font options and returns the font object.
  2658. * @param {object} options - A object that contains font options to be parsed.
  2659. * @return {object} The font object.
  2660. * @todo Support font.* options and renamed to toFont().
  2661. * @private
  2662. */
  2663. _parseFont: function(options) {
  2664. var globalDefaults = core_defaults.global;
  2665. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  2666. var font = {
  2667. family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
  2668. lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
  2669. size: size,
  2670. style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
  2671. weight: null,
  2672. string: ''
  2673. };
  2674. font.string = toFontString(font);
  2675. return font;
  2676. },
  2677. /**
  2678. * Evaluates the given `inputs` sequentially and returns the first defined value.
  2679. * @param {Array} inputs - An array of values, falling back to the last value.
  2680. * @param {object} [context] - If defined and the current value is a function, the value
  2681. * is called with `context` as first argument and the result becomes the new input.
  2682. * @param {number} [index] - If defined and the current value is an array, the value
  2683. * at `index` become the new input.
  2684. * @param {object} [info] - object to return information about resolution in
  2685. * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable.
  2686. * @since 2.7.0
  2687. */
  2688. resolve: function(inputs, context, index, info) {
  2689. var cacheable = true;
  2690. var i, ilen, value;
  2691. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  2692. value = inputs[i];
  2693. if (value === undefined) {
  2694. continue;
  2695. }
  2696. if (context !== undefined && typeof value === 'function') {
  2697. value = value(context);
  2698. cacheable = false;
  2699. }
  2700. if (index !== undefined && helpers_core.isArray(value)) {
  2701. value = value[index];
  2702. cacheable = false;
  2703. }
  2704. if (value !== undefined) {
  2705. if (info && !cacheable) {
  2706. info.cacheable = false;
  2707. }
  2708. return value;
  2709. }
  2710. }
  2711. }
  2712. };
  2713. /**
  2714. * @alias Chart.helpers.math
  2715. * @namespace
  2716. */
  2717. var exports$2 = {
  2718. /**
  2719. * Returns an array of factors sorted from 1 to sqrt(value)
  2720. * @private
  2721. */
  2722. _factorize: function(value) {
  2723. var result = [];
  2724. var sqrt = Math.sqrt(value);
  2725. var i;
  2726. for (i = 1; i < sqrt; i++) {
  2727. if (value % i === 0) {
  2728. result.push(i);
  2729. result.push(value / i);
  2730. }
  2731. }
  2732. if (sqrt === (sqrt | 0)) { // if value is a square number
  2733. result.push(sqrt);
  2734. }
  2735. result.sort(function(a, b) {
  2736. return a - b;
  2737. }).pop();
  2738. return result;
  2739. },
  2740. log10: Math.log10 || function(x) {
  2741. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  2742. // Check for whole powers of 10,
  2743. // which due to floating point rounding error should be corrected.
  2744. var powerOf10 = Math.round(exponent);
  2745. var isPowerOf10 = x === Math.pow(10, powerOf10);
  2746. return isPowerOf10 ? powerOf10 : exponent;
  2747. }
  2748. };
  2749. var helpers_math = exports$2;
  2750. // DEPRECATIONS
  2751. /**
  2752. * Provided for backward compatibility, use Chart.helpers.math.log10 instead.
  2753. * @namespace Chart.helpers.log10
  2754. * @deprecated since version 2.9.0
  2755. * @todo remove at version 3
  2756. * @private
  2757. */
  2758. helpers_core.log10 = exports$2.log10;
  2759. var getRtlAdapter = function(rectX, width) {
  2760. return {
  2761. x: function(x) {
  2762. return rectX + rectX + width - x;
  2763. },
  2764. setWidth: function(w) {
  2765. width = w;
  2766. },
  2767. textAlign: function(align) {
  2768. if (align === 'center') {
  2769. return align;
  2770. }
  2771. return align === 'right' ? 'left' : 'right';
  2772. },
  2773. xPlus: function(x, value) {
  2774. return x - value;
  2775. },
  2776. leftForLtr: function(x, itemWidth) {
  2777. return x - itemWidth;
  2778. },
  2779. };
  2780. };
  2781. var getLtrAdapter = function() {
  2782. return {
  2783. x: function(x) {
  2784. return x;
  2785. },
  2786. setWidth: function(w) { // eslint-disable-line no-unused-vars
  2787. },
  2788. textAlign: function(align) {
  2789. return align;
  2790. },
  2791. xPlus: function(x, value) {
  2792. return x + value;
  2793. },
  2794. leftForLtr: function(x, _itemWidth) { // eslint-disable-line no-unused-vars
  2795. return x;
  2796. },
  2797. };
  2798. };
  2799. var getAdapter = function(rtl, rectX, width) {
  2800. return rtl ? getRtlAdapter(rectX, width) : getLtrAdapter();
  2801. };
  2802. var overrideTextDirection = function(ctx, direction) {
  2803. var style, original;
  2804. if (direction === 'ltr' || direction === 'rtl') {
  2805. style = ctx.canvas.style;
  2806. original = [
  2807. style.getPropertyValue('direction'),
  2808. style.getPropertyPriority('direction'),
  2809. ];
  2810. style.setProperty('direction', direction, 'important');
  2811. ctx.prevTextDirection = original;
  2812. }
  2813. };
  2814. var restoreTextDirection = function(ctx) {
  2815. var original = ctx.prevTextDirection;
  2816. if (original !== undefined) {
  2817. delete ctx.prevTextDirection;
  2818. ctx.canvas.style.setProperty('direction', original[0], original[1]);
  2819. }
  2820. };
  2821. var helpers_rtl = {
  2822. getRtlAdapter: getAdapter,
  2823. overrideTextDirection: overrideTextDirection,
  2824. restoreTextDirection: restoreTextDirection,
  2825. };
  2826. var helpers$1 = helpers_core;
  2827. var easing = helpers_easing;
  2828. var canvas = helpers_canvas;
  2829. var options = helpers_options;
  2830. var math = helpers_math;
  2831. var rtl = helpers_rtl;
  2832. helpers$1.easing = easing;
  2833. helpers$1.canvas = canvas;
  2834. helpers$1.options = options;
  2835. helpers$1.math = math;
  2836. helpers$1.rtl = rtl;
  2837. function interpolate(start, view, model, ease) {
  2838. var keys = Object.keys(model);
  2839. var i, ilen, key, actual, origin, target, type, c0, c1;
  2840. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  2841. key = keys[i];
  2842. target = model[key];
  2843. // if a value is added to the model after pivot() has been called, the view
  2844. // doesn't contain it, so let's initialize the view to the target value.
  2845. if (!view.hasOwnProperty(key)) {
  2846. view[key] = target;
  2847. }
  2848. actual = view[key];
  2849. if (actual === target || key[0] === '_') {
  2850. continue;
  2851. }
  2852. if (!start.hasOwnProperty(key)) {
  2853. start[key] = actual;
  2854. }
  2855. origin = start[key];
  2856. type = typeof target;
  2857. if (type === typeof origin) {
  2858. if (type === 'string') {
  2859. c0 = chartjsColor(origin);
  2860. if (c0.valid) {
  2861. c1 = chartjsColor(target);
  2862. if (c1.valid) {
  2863. view[key] = c1.mix(c0, ease).rgbString();
  2864. continue;
  2865. }
  2866. }
  2867. } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
  2868. view[key] = origin + (target - origin) * ease;
  2869. continue;
  2870. }
  2871. }
  2872. view[key] = target;
  2873. }
  2874. }
  2875. var Element = function(configuration) {
  2876. helpers$1.extend(this, configuration);
  2877. this.initialize.apply(this, arguments);
  2878. };
  2879. helpers$1.extend(Element.prototype, {
  2880. _type: undefined,
  2881. initialize: function() {
  2882. this.hidden = false;
  2883. },
  2884. pivot: function() {
  2885. var me = this;
  2886. if (!me._view) {
  2887. me._view = helpers$1.extend({}, me._model);
  2888. }
  2889. me._start = {};
  2890. return me;
  2891. },
  2892. transition: function(ease) {
  2893. var me = this;
  2894. var model = me._model;
  2895. var start = me._start;
  2896. var view = me._view;
  2897. // No animation -> No Transition
  2898. if (!model || ease === 1) {
  2899. me._view = helpers$1.extend({}, model);
  2900. me._start = null;
  2901. return me;
  2902. }
  2903. if (!view) {
  2904. view = me._view = {};
  2905. }
  2906. if (!start) {
  2907. start = me._start = {};
  2908. }
  2909. interpolate(start, view, model, ease);
  2910. return me;
  2911. },
  2912. tooltipPosition: function() {
  2913. return {
  2914. x: this._model.x,
  2915. y: this._model.y
  2916. };
  2917. },
  2918. hasValue: function() {
  2919. return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
  2920. }
  2921. });
  2922. Element.extend = helpers$1.inherits;
  2923. var core_element = Element;
  2924. var exports$3 = core_element.extend({
  2925. chart: null, // the animation associated chart instance
  2926. currentStep: 0, // the current animation step
  2927. numSteps: 60, // default number of steps
  2928. easing: '', // the easing to use for this animation
  2929. render: null, // render function used by the animation service
  2930. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  2931. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  2932. });
  2933. var core_animation = exports$3;
  2934. // DEPRECATIONS
  2935. /**
  2936. * Provided for backward compatibility, use Chart.Animation instead
  2937. * @prop Chart.Animation#animationObject
  2938. * @deprecated since version 2.6.0
  2939. * @todo remove at version 3
  2940. */
  2941. Object.defineProperty(exports$3.prototype, 'animationObject', {
  2942. get: function() {
  2943. return this;
  2944. }
  2945. });
  2946. /**
  2947. * Provided for backward compatibility, use Chart.Animation#chart instead
  2948. * @prop Chart.Animation#chartInstance
  2949. * @deprecated since version 2.6.0
  2950. * @todo remove at version 3
  2951. */
  2952. Object.defineProperty(exports$3.prototype, 'chartInstance', {
  2953. get: function() {
  2954. return this.chart;
  2955. },
  2956. set: function(value) {
  2957. this.chart = value;
  2958. }
  2959. });
  2960. core_defaults._set('global', {
  2961. animation: {
  2962. duration: 1000,
  2963. easing: 'easeOutQuart',
  2964. onProgress: helpers$1.noop,
  2965. onComplete: helpers$1.noop
  2966. }
  2967. });
  2968. var core_animations = {
  2969. animations: [],
  2970. request: null,
  2971. /**
  2972. * @param {Chart} chart - The chart to animate.
  2973. * @param {Chart.Animation} animation - The animation that we will animate.
  2974. * @param {number} duration - The animation duration in ms.
  2975. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  2976. */
  2977. addAnimation: function(chart, animation, duration, lazy) {
  2978. var animations = this.animations;
  2979. var i, ilen;
  2980. animation.chart = chart;
  2981. animation.startTime = Date.now();
  2982. animation.duration = duration;
  2983. if (!lazy) {
  2984. chart.animating = true;
  2985. }
  2986. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  2987. if (animations[i].chart === chart) {
  2988. animations[i] = animation;
  2989. return;
  2990. }
  2991. }
  2992. animations.push(animation);
  2993. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  2994. if (animations.length === 1) {
  2995. this.requestAnimationFrame();
  2996. }
  2997. },
  2998. cancelAnimation: function(chart) {
  2999. var index = helpers$1.findIndex(this.animations, function(animation) {
  3000. return animation.chart === chart;
  3001. });
  3002. if (index !== -1) {
  3003. this.animations.splice(index, 1);
  3004. chart.animating = false;
  3005. }
  3006. },
  3007. requestAnimationFrame: function() {
  3008. var me = this;
  3009. if (me.request === null) {
  3010. // Skip animation frame requests until the active one is executed.
  3011. // This can happen when processing mouse events, e.g. 'mousemove'
  3012. // and 'mouseout' events will trigger multiple renders.
  3013. me.request = helpers$1.requestAnimFrame.call(window, function() {
  3014. me.request = null;
  3015. me.startDigest();
  3016. });
  3017. }
  3018. },
  3019. /**
  3020. * @private
  3021. */
  3022. startDigest: function() {
  3023. var me = this;
  3024. me.advance();
  3025. // Do we have more stuff to animate?
  3026. if (me.animations.length > 0) {
  3027. me.requestAnimationFrame();
  3028. }
  3029. },
  3030. /**
  3031. * @private
  3032. */
  3033. advance: function() {
  3034. var animations = this.animations;
  3035. var animation, chart, numSteps, nextStep;
  3036. var i = 0;
  3037. // 1 animation per chart, so we are looping charts here
  3038. while (i < animations.length) {
  3039. animation = animations[i];
  3040. chart = animation.chart;
  3041. numSteps = animation.numSteps;
  3042. // Make sure that currentStep starts at 1
  3043. // https://github.com/chartjs/Chart.js/issues/6104
  3044. nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
  3045. animation.currentStep = Math.min(nextStep, numSteps);
  3046. helpers$1.callback(animation.render, [chart, animation], chart);
  3047. helpers$1.callback(animation.onAnimationProgress, [animation], chart);
  3048. if (animation.currentStep >= numSteps) {
  3049. helpers$1.callback(animation.onAnimationComplete, [animation], chart);
  3050. chart.animating = false;
  3051. animations.splice(i, 1);
  3052. } else {
  3053. ++i;
  3054. }
  3055. }
  3056. }
  3057. };
  3058. var resolve = helpers$1.options.resolve;
  3059. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  3060. /**
  3061. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  3062. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  3063. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  3064. */
  3065. function listenArrayEvents(array, listener) {
  3066. if (array._chartjs) {
  3067. array._chartjs.listeners.push(listener);
  3068. return;
  3069. }
  3070. Object.defineProperty(array, '_chartjs', {
  3071. configurable: true,
  3072. enumerable: false,
  3073. value: {
  3074. listeners: [listener]
  3075. }
  3076. });
  3077. arrayEvents.forEach(function(key) {
  3078. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  3079. var base = array[key];
  3080. Object.defineProperty(array, key, {
  3081. configurable: true,
  3082. enumerable: false,
  3083. value: function() {
  3084. var args = Array.prototype.slice.call(arguments);
  3085. var res = base.apply(this, args);
  3086. helpers$1.each(array._chartjs.listeners, function(object) {
  3087. if (typeof object[method] === 'function') {
  3088. object[method].apply(object, args);
  3089. }
  3090. });
  3091. return res;
  3092. }
  3093. });
  3094. });
  3095. }
  3096. /**
  3097. * Removes the given array event listener and cleanup extra attached properties (such as
  3098. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  3099. */
  3100. function unlistenArrayEvents(array, listener) {
  3101. var stub = array._chartjs;
  3102. if (!stub) {
  3103. return;
  3104. }
  3105. var listeners = stub.listeners;
  3106. var index = listeners.indexOf(listener);
  3107. if (index !== -1) {
  3108. listeners.splice(index, 1);
  3109. }
  3110. if (listeners.length > 0) {
  3111. return;
  3112. }
  3113. arrayEvents.forEach(function(key) {
  3114. delete array[key];
  3115. });
  3116. delete array._chartjs;
  3117. }
  3118. // Base class for all dataset controllers (line, bar, etc)
  3119. var DatasetController = function(chart, datasetIndex) {
  3120. this.initialize(chart, datasetIndex);
  3121. };
  3122. helpers$1.extend(DatasetController.prototype, {
  3123. /**
  3124. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  3125. * @type {Chart.core.element}
  3126. */
  3127. datasetElementType: null,
  3128. /**
  3129. * Element type used to generate a meta data (e.g. Chart.element.Point).
  3130. * @type {Chart.core.element}
  3131. */
  3132. dataElementType: null,
  3133. /**
  3134. * Dataset element option keys to be resolved in _resolveDatasetElementOptions.
  3135. * A derived controller may override this to resolve controller-specific options.
  3136. * The keys defined here are for backward compatibility for legend styles.
  3137. * @private
  3138. */
  3139. _datasetElementOptions: [
  3140. 'backgroundColor',
  3141. 'borderCapStyle',
  3142. 'borderColor',
  3143. 'borderDash',
  3144. 'borderDashOffset',
  3145. 'borderJoinStyle',
  3146. 'borderWidth'
  3147. ],
  3148. /**
  3149. * Data element option keys to be resolved in _resolveDataElementOptions.
  3150. * A derived controller may override this to resolve controller-specific options.
  3151. * The keys defined here are for backward compatibility for legend styles.
  3152. * @private
  3153. */
  3154. _dataElementOptions: [
  3155. 'backgroundColor',
  3156. 'borderColor',
  3157. 'borderWidth',
  3158. 'pointStyle'
  3159. ],
  3160. initialize: function(chart, datasetIndex) {
  3161. var me = this;
  3162. me.chart = chart;
  3163. me.index = datasetIndex;
  3164. me.linkScales();
  3165. me.addElements();
  3166. me._type = me.getMeta().type;
  3167. },
  3168. updateIndex: function(datasetIndex) {
  3169. this.index = datasetIndex;
  3170. },
  3171. linkScales: function() {
  3172. var me = this;
  3173. var meta = me.getMeta();
  3174. var chart = me.chart;
  3175. var scales = chart.scales;
  3176. var dataset = me.getDataset();
  3177. var scalesOpts = chart.options.scales;
  3178. if (meta.xAxisID === null || !(meta.xAxisID in scales) || dataset.xAxisID) {
  3179. meta.xAxisID = dataset.xAxisID || scalesOpts.xAxes[0].id;
  3180. }
  3181. if (meta.yAxisID === null || !(meta.yAxisID in scales) || dataset.yAxisID) {
  3182. meta.yAxisID = dataset.yAxisID || scalesOpts.yAxes[0].id;
  3183. }
  3184. },
  3185. getDataset: function() {
  3186. return this.chart.data.datasets[this.index];
  3187. },
  3188. getMeta: function() {
  3189. return this.chart.getDatasetMeta(this.index);
  3190. },
  3191. getScaleForId: function(scaleID) {
  3192. return this.chart.scales[scaleID];
  3193. },
  3194. /**
  3195. * @private
  3196. */
  3197. _getValueScaleId: function() {
  3198. return this.getMeta().yAxisID;
  3199. },
  3200. /**
  3201. * @private
  3202. */
  3203. _getIndexScaleId: function() {
  3204. return this.getMeta().xAxisID;
  3205. },
  3206. /**
  3207. * @private
  3208. */
  3209. _getValueScale: function() {
  3210. return this.getScaleForId(this._getValueScaleId());
  3211. },
  3212. /**
  3213. * @private
  3214. */
  3215. _getIndexScale: function() {
  3216. return this.getScaleForId(this._getIndexScaleId());
  3217. },
  3218. reset: function() {
  3219. this._update(true);
  3220. },
  3221. /**
  3222. * @private
  3223. */
  3224. destroy: function() {
  3225. if (this._data) {
  3226. unlistenArrayEvents(this._data, this);
  3227. }
  3228. },
  3229. createMetaDataset: function() {
  3230. var me = this;
  3231. var type = me.datasetElementType;
  3232. return type && new type({
  3233. _chart: me.chart,
  3234. _datasetIndex: me.index
  3235. });
  3236. },
  3237. createMetaData: function(index) {
  3238. var me = this;
  3239. var type = me.dataElementType;
  3240. return type && new type({
  3241. _chart: me.chart,
  3242. _datasetIndex: me.index,
  3243. _index: index
  3244. });
  3245. },
  3246. addElements: function() {
  3247. var me = this;
  3248. var meta = me.getMeta();
  3249. var data = me.getDataset().data || [];
  3250. var metaData = meta.data;
  3251. var i, ilen;
  3252. for (i = 0, ilen = data.length; i < ilen; ++i) {
  3253. metaData[i] = metaData[i] || me.createMetaData(i);
  3254. }
  3255. meta.dataset = meta.dataset || me.createMetaDataset();
  3256. },
  3257. addElementAndReset: function(index) {
  3258. var element = this.createMetaData(index);
  3259. this.getMeta().data.splice(index, 0, element);
  3260. this.updateElement(element, index, true);
  3261. },
  3262. buildOrUpdateElements: function() {
  3263. var me = this;
  3264. var dataset = me.getDataset();
  3265. var data = dataset.data || (dataset.data = []);
  3266. // In order to correctly handle data addition/deletion animation (an thus simulate
  3267. // real-time charts), we need to monitor these data modifications and synchronize
  3268. // the internal meta data accordingly.
  3269. if (me._data !== data) {
  3270. if (me._data) {
  3271. // This case happens when the user replaced the data array instance.
  3272. unlistenArrayEvents(me._data, me);
  3273. }
  3274. if (data && Object.isExtensible(data)) {
  3275. listenArrayEvents(data, me);
  3276. }
  3277. me._data = data;
  3278. }
  3279. // Re-sync meta data in case the user replaced the data array or if we missed
  3280. // any updates and so make sure that we handle number of datapoints changing.
  3281. me.resyncElements();
  3282. },
  3283. /**
  3284. * Returns the merged user-supplied and default dataset-level options
  3285. * @private
  3286. */
  3287. _configure: function() {
  3288. var me = this;
  3289. me._config = helpers$1.merge({}, [
  3290. me.chart.options.datasets[me._type],
  3291. me.getDataset(),
  3292. ], {
  3293. merger: function(key, target, source) {
  3294. if (key !== '_meta' && key !== 'data') {
  3295. helpers$1._merger(key, target, source);
  3296. }
  3297. }
  3298. });
  3299. },
  3300. _update: function(reset) {
  3301. var me = this;
  3302. me._configure();
  3303. me._cachedDataOpts = null;
  3304. me.update(reset);
  3305. },
  3306. update: helpers$1.noop,
  3307. transition: function(easingValue) {
  3308. var meta = this.getMeta();
  3309. var elements = meta.data || [];
  3310. var ilen = elements.length;
  3311. var i = 0;
  3312. for (; i < ilen; ++i) {
  3313. elements[i].transition(easingValue);
  3314. }
  3315. if (meta.dataset) {
  3316. meta.dataset.transition(easingValue);
  3317. }
  3318. },
  3319. draw: function() {
  3320. var meta = this.getMeta();
  3321. var elements = meta.data || [];
  3322. var ilen = elements.length;
  3323. var i = 0;
  3324. if (meta.dataset) {
  3325. meta.dataset.draw();
  3326. }
  3327. for (; i < ilen; ++i) {
  3328. elements[i].draw();
  3329. }
  3330. },
  3331. /**
  3332. * Returns a set of predefined style properties that should be used to represent the dataset
  3333. * or the data if the index is specified
  3334. * @param {number} index - data index
  3335. * @return {IStyleInterface} style object
  3336. */
  3337. getStyle: function(index) {
  3338. var me = this;
  3339. var meta = me.getMeta();
  3340. var dataset = meta.dataset;
  3341. var style;
  3342. me._configure();
  3343. if (dataset && index === undefined) {
  3344. style = me._resolveDatasetElementOptions(dataset || {});
  3345. } else {
  3346. index = index || 0;
  3347. style = me._resolveDataElementOptions(meta.data[index] || {}, index);
  3348. }
  3349. if (style.fill === false || style.fill === null) {
  3350. style.backgroundColor = style.borderColor;
  3351. }
  3352. return style;
  3353. },
  3354. /**
  3355. * @private
  3356. */
  3357. _resolveDatasetElementOptions: function(element, hover) {
  3358. var me = this;
  3359. var chart = me.chart;
  3360. var datasetOpts = me._config;
  3361. var custom = element.custom || {};
  3362. var options = chart.options.elements[me.datasetElementType.prototype._type] || {};
  3363. var elementOptions = me._datasetElementOptions;
  3364. var values = {};
  3365. var i, ilen, key, readKey;
  3366. // Scriptable options
  3367. var context = {
  3368. chart: chart,
  3369. dataset: me.getDataset(),
  3370. datasetIndex: me.index,
  3371. hover: hover
  3372. };
  3373. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3374. key = elementOptions[i];
  3375. readKey = hover ? 'hover' + key.charAt(0).toUpperCase() + key.slice(1) : key;
  3376. values[key] = resolve([
  3377. custom[readKey],
  3378. datasetOpts[readKey],
  3379. options[readKey]
  3380. ], context);
  3381. }
  3382. return values;
  3383. },
  3384. /**
  3385. * @private
  3386. */
  3387. _resolveDataElementOptions: function(element, index) {
  3388. var me = this;
  3389. var custom = element && element.custom;
  3390. var cached = me._cachedDataOpts;
  3391. if (cached && !custom) {
  3392. return cached;
  3393. }
  3394. var chart = me.chart;
  3395. var datasetOpts = me._config;
  3396. var options = chart.options.elements[me.dataElementType.prototype._type] || {};
  3397. var elementOptions = me._dataElementOptions;
  3398. var values = {};
  3399. // Scriptable options
  3400. var context = {
  3401. chart: chart,
  3402. dataIndex: index,
  3403. dataset: me.getDataset(),
  3404. datasetIndex: me.index
  3405. };
  3406. // `resolve` sets cacheable to `false` if any option is indexed or scripted
  3407. var info = {cacheable: !custom};
  3408. var keys, i, ilen, key;
  3409. custom = custom || {};
  3410. if (helpers$1.isArray(elementOptions)) {
  3411. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3412. key = elementOptions[i];
  3413. values[key] = resolve([
  3414. custom[key],
  3415. datasetOpts[key],
  3416. options[key]
  3417. ], context, index, info);
  3418. }
  3419. } else {
  3420. keys = Object.keys(elementOptions);
  3421. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3422. key = keys[i];
  3423. values[key] = resolve([
  3424. custom[key],
  3425. datasetOpts[elementOptions[key]],
  3426. datasetOpts[key],
  3427. options[key]
  3428. ], context, index, info);
  3429. }
  3430. }
  3431. if (info.cacheable) {
  3432. me._cachedDataOpts = Object.freeze(values);
  3433. }
  3434. return values;
  3435. },
  3436. removeHoverStyle: function(element) {
  3437. helpers$1.merge(element._model, element.$previousStyle || {});
  3438. delete element.$previousStyle;
  3439. },
  3440. setHoverStyle: function(element) {
  3441. var dataset = this.chart.data.datasets[element._datasetIndex];
  3442. var index = element._index;
  3443. var custom = element.custom || {};
  3444. var model = element._model;
  3445. var getHoverColor = helpers$1.getHoverColor;
  3446. element.$previousStyle = {
  3447. backgroundColor: model.backgroundColor,
  3448. borderColor: model.borderColor,
  3449. borderWidth: model.borderWidth
  3450. };
  3451. model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
  3452. model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
  3453. model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
  3454. },
  3455. /**
  3456. * @private
  3457. */
  3458. _removeDatasetHoverStyle: function() {
  3459. var element = this.getMeta().dataset;
  3460. if (element) {
  3461. this.removeHoverStyle(element);
  3462. }
  3463. },
  3464. /**
  3465. * @private
  3466. */
  3467. _setDatasetHoverStyle: function() {
  3468. var element = this.getMeta().dataset;
  3469. var prev = {};
  3470. var i, ilen, key, keys, hoverOptions, model;
  3471. if (!element) {
  3472. return;
  3473. }
  3474. model = element._model;
  3475. hoverOptions = this._resolveDatasetElementOptions(element, true);
  3476. keys = Object.keys(hoverOptions);
  3477. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3478. key = keys[i];
  3479. prev[key] = model[key];
  3480. model[key] = hoverOptions[key];
  3481. }
  3482. element.$previousStyle = prev;
  3483. },
  3484. /**
  3485. * @private
  3486. */
  3487. resyncElements: function() {
  3488. var me = this;
  3489. var meta = me.getMeta();
  3490. var data = me.getDataset().data;
  3491. var numMeta = meta.data.length;
  3492. var numData = data.length;
  3493. if (numData < numMeta) {
  3494. meta.data.splice(numData, numMeta - numData);
  3495. } else if (numData > numMeta) {
  3496. me.insertElements(numMeta, numData - numMeta);
  3497. }
  3498. },
  3499. /**
  3500. * @private
  3501. */
  3502. insertElements: function(start, count) {
  3503. for (var i = 0; i < count; ++i) {
  3504. this.addElementAndReset(start + i);
  3505. }
  3506. },
  3507. /**
  3508. * @private
  3509. */
  3510. onDataPush: function() {
  3511. var count = arguments.length;
  3512. this.insertElements(this.getDataset().data.length - count, count);
  3513. },
  3514. /**
  3515. * @private
  3516. */
  3517. onDataPop: function() {
  3518. this.getMeta().data.pop();
  3519. },
  3520. /**
  3521. * @private
  3522. */
  3523. onDataShift: function() {
  3524. this.getMeta().data.shift();
  3525. },
  3526. /**
  3527. * @private
  3528. */
  3529. onDataSplice: function(start, count) {
  3530. this.getMeta().data.splice(start, count);
  3531. this.insertElements(start, arguments.length - 2);
  3532. },
  3533. /**
  3534. * @private
  3535. */
  3536. onDataUnshift: function() {
  3537. this.insertElements(0, arguments.length);
  3538. }
  3539. });
  3540. DatasetController.extend = helpers$1.inherits;
  3541. var core_datasetController = DatasetController;
  3542. var TAU = Math.PI * 2;
  3543. core_defaults._set('global', {
  3544. elements: {
  3545. arc: {
  3546. backgroundColor: core_defaults.global.defaultColor,
  3547. borderColor: '#fff',
  3548. borderWidth: 2,
  3549. borderAlign: 'center'
  3550. }
  3551. }
  3552. });
  3553. function clipArc(ctx, arc) {
  3554. var startAngle = arc.startAngle;
  3555. var endAngle = arc.endAngle;
  3556. var pixelMargin = arc.pixelMargin;
  3557. var angleMargin = pixelMargin / arc.outerRadius;
  3558. var x = arc.x;
  3559. var y = arc.y;
  3560. // Draw an inner border by cliping the arc and drawing a double-width border
  3561. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  3562. ctx.beginPath();
  3563. ctx.arc(x, y, arc.outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  3564. if (arc.innerRadius > pixelMargin) {
  3565. angleMargin = pixelMargin / arc.innerRadius;
  3566. ctx.arc(x, y, arc.innerRadius - pixelMargin, endAngle + angleMargin, startAngle - angleMargin, true);
  3567. } else {
  3568. ctx.arc(x, y, pixelMargin, endAngle + Math.PI / 2, startAngle - Math.PI / 2);
  3569. }
  3570. ctx.closePath();
  3571. ctx.clip();
  3572. }
  3573. function drawFullCircleBorders(ctx, vm, arc, inner) {
  3574. var endAngle = arc.endAngle;
  3575. var i;
  3576. if (inner) {
  3577. arc.endAngle = arc.startAngle + TAU;
  3578. clipArc(ctx, arc);
  3579. arc.endAngle = endAngle;
  3580. if (arc.endAngle === arc.startAngle && arc.fullCircles) {
  3581. arc.endAngle += TAU;
  3582. arc.fullCircles--;
  3583. }
  3584. }
  3585. ctx.beginPath();
  3586. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.startAngle + TAU, arc.startAngle, true);
  3587. for (i = 0; i < arc.fullCircles; ++i) {
  3588. ctx.stroke();
  3589. }
  3590. ctx.beginPath();
  3591. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.startAngle + TAU);
  3592. for (i = 0; i < arc.fullCircles; ++i) {
  3593. ctx.stroke();
  3594. }
  3595. }
  3596. function drawBorder(ctx, vm, arc) {
  3597. var inner = vm.borderAlign === 'inner';
  3598. if (inner) {
  3599. ctx.lineWidth = vm.borderWidth * 2;
  3600. ctx.lineJoin = 'round';
  3601. } else {
  3602. ctx.lineWidth = vm.borderWidth;
  3603. ctx.lineJoin = 'bevel';
  3604. }
  3605. if (arc.fullCircles) {
  3606. drawFullCircleBorders(ctx, vm, arc, inner);
  3607. }
  3608. if (inner) {
  3609. clipArc(ctx, arc);
  3610. }
  3611. ctx.beginPath();
  3612. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.endAngle);
  3613. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3614. ctx.closePath();
  3615. ctx.stroke();
  3616. }
  3617. var element_arc = core_element.extend({
  3618. _type: 'arc',
  3619. inLabelRange: function(mouseX) {
  3620. var vm = this._view;
  3621. if (vm) {
  3622. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  3623. }
  3624. return false;
  3625. },
  3626. inRange: function(chartX, chartY) {
  3627. var vm = this._view;
  3628. if (vm) {
  3629. var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
  3630. var angle = pointRelativePosition.angle;
  3631. var distance = pointRelativePosition.distance;
  3632. // Sanitise angle range
  3633. var startAngle = vm.startAngle;
  3634. var endAngle = vm.endAngle;
  3635. while (endAngle < startAngle) {
  3636. endAngle += TAU;
  3637. }
  3638. while (angle > endAngle) {
  3639. angle -= TAU;
  3640. }
  3641. while (angle < startAngle) {
  3642. angle += TAU;
  3643. }
  3644. // Check if within the range of the open/close angle
  3645. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  3646. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  3647. return (betweenAngles && withinRadius);
  3648. }
  3649. return false;
  3650. },
  3651. getCenterPoint: function() {
  3652. var vm = this._view;
  3653. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  3654. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  3655. return {
  3656. x: vm.x + Math.cos(halfAngle) * halfRadius,
  3657. y: vm.y + Math.sin(halfAngle) * halfRadius
  3658. };
  3659. },
  3660. getArea: function() {
  3661. var vm = this._view;
  3662. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  3663. },
  3664. tooltipPosition: function() {
  3665. var vm = this._view;
  3666. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  3667. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  3668. return {
  3669. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  3670. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  3671. };
  3672. },
  3673. draw: function() {
  3674. var ctx = this._chart.ctx;
  3675. var vm = this._view;
  3676. var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
  3677. var arc = {
  3678. x: vm.x,
  3679. y: vm.y,
  3680. innerRadius: vm.innerRadius,
  3681. outerRadius: Math.max(vm.outerRadius - pixelMargin, 0),
  3682. pixelMargin: pixelMargin,
  3683. startAngle: vm.startAngle,
  3684. endAngle: vm.endAngle,
  3685. fullCircles: Math.floor(vm.circumference / TAU)
  3686. };
  3687. var i;
  3688. ctx.save();
  3689. ctx.fillStyle = vm.backgroundColor;
  3690. ctx.strokeStyle = vm.borderColor;
  3691. if (arc.fullCircles) {
  3692. arc.endAngle = arc.startAngle + TAU;
  3693. ctx.beginPath();
  3694. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3695. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3696. ctx.closePath();
  3697. for (i = 0; i < arc.fullCircles; ++i) {
  3698. ctx.fill();
  3699. }
  3700. arc.endAngle = arc.startAngle + vm.circumference % TAU;
  3701. }
  3702. ctx.beginPath();
  3703. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3704. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3705. ctx.closePath();
  3706. ctx.fill();
  3707. if (vm.borderWidth) {
  3708. drawBorder(ctx, vm, arc);
  3709. }
  3710. ctx.restore();
  3711. }
  3712. });
  3713. var valueOrDefault$1 = helpers$1.valueOrDefault;
  3714. var defaultColor = core_defaults.global.defaultColor;
  3715. core_defaults._set('global', {
  3716. elements: {
  3717. line: {
  3718. tension: 0.4,
  3719. backgroundColor: defaultColor,
  3720. borderWidth: 3,
  3721. borderColor: defaultColor,
  3722. borderCapStyle: 'butt',
  3723. borderDash: [],
  3724. borderDashOffset: 0.0,
  3725. borderJoinStyle: 'miter',
  3726. capBezierPoints: true,
  3727. fill: true, // do we fill in the area between the line and its base axis
  3728. }
  3729. }
  3730. });
  3731. var element_line = core_element.extend({
  3732. _type: 'line',
  3733. draw: function() {
  3734. var me = this;
  3735. var vm = me._view;
  3736. var ctx = me._chart.ctx;
  3737. var spanGaps = vm.spanGaps;
  3738. var points = me._children.slice(); // clone array
  3739. var globalDefaults = core_defaults.global;
  3740. var globalOptionLineElements = globalDefaults.elements.line;
  3741. var lastDrawnIndex = -1;
  3742. var closePath = me._loop;
  3743. var index, previous, currentVM;
  3744. if (!points.length) {
  3745. return;
  3746. }
  3747. if (me._loop) {
  3748. for (index = 0; index < points.length; ++index) {
  3749. previous = helpers$1.previousItem(points, index);
  3750. // If the line has an open path, shift the point array
  3751. if (!points[index]._view.skip && previous._view.skip) {
  3752. points = points.slice(index).concat(points.slice(0, index));
  3753. closePath = spanGaps;
  3754. break;
  3755. }
  3756. }
  3757. // If the line has a close path, add the first point again
  3758. if (closePath) {
  3759. points.push(points[0]);
  3760. }
  3761. }
  3762. ctx.save();
  3763. // Stroke Line Options
  3764. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  3765. // IE 9 and 10 do not support line dash
  3766. if (ctx.setLineDash) {
  3767. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  3768. }
  3769. ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
  3770. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  3771. ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
  3772. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  3773. // Stroke Line
  3774. ctx.beginPath();
  3775. // First point moves to it's starting position no matter what
  3776. currentVM = points[0]._view;
  3777. if (!currentVM.skip) {
  3778. ctx.moveTo(currentVM.x, currentVM.y);
  3779. lastDrawnIndex = 0;
  3780. }
  3781. for (index = 1; index < points.length; ++index) {
  3782. currentVM = points[index]._view;
  3783. previous = lastDrawnIndex === -1 ? helpers$1.previousItem(points, index) : points[lastDrawnIndex];
  3784. if (!currentVM.skip) {
  3785. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  3786. // There was a gap and this is the first point after the gap
  3787. ctx.moveTo(currentVM.x, currentVM.y);
  3788. } else {
  3789. // Line to next point
  3790. helpers$1.canvas.lineTo(ctx, previous._view, currentVM);
  3791. }
  3792. lastDrawnIndex = index;
  3793. }
  3794. }
  3795. if (closePath) {
  3796. ctx.closePath();
  3797. }
  3798. ctx.stroke();
  3799. ctx.restore();
  3800. }
  3801. });
  3802. var valueOrDefault$2 = helpers$1.valueOrDefault;
  3803. var defaultColor$1 = core_defaults.global.defaultColor;
  3804. core_defaults._set('global', {
  3805. elements: {
  3806. point: {
  3807. radius: 3,
  3808. pointStyle: 'circle',
  3809. backgroundColor: defaultColor$1,
  3810. borderColor: defaultColor$1,
  3811. borderWidth: 1,
  3812. // Hover
  3813. hitRadius: 1,
  3814. hoverRadius: 4,
  3815. hoverBorderWidth: 1
  3816. }
  3817. }
  3818. });
  3819. function xRange(mouseX) {
  3820. var vm = this._view;
  3821. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  3822. }
  3823. function yRange(mouseY) {
  3824. var vm = this._view;
  3825. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  3826. }
  3827. var element_point = core_element.extend({
  3828. _type: 'point',
  3829. inRange: function(mouseX, mouseY) {
  3830. var vm = this._view;
  3831. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  3832. },
  3833. inLabelRange: xRange,
  3834. inXRange: xRange,
  3835. inYRange: yRange,
  3836. getCenterPoint: function() {
  3837. var vm = this._view;
  3838. return {
  3839. x: vm.x,
  3840. y: vm.y
  3841. };
  3842. },
  3843. getArea: function() {
  3844. return Math.PI * Math.pow(this._view.radius, 2);
  3845. },
  3846. tooltipPosition: function() {
  3847. var vm = this._view;
  3848. return {
  3849. x: vm.x,
  3850. y: vm.y,
  3851. padding: vm.radius + vm.borderWidth
  3852. };
  3853. },
  3854. draw: function(chartArea) {
  3855. var vm = this._view;
  3856. var ctx = this._chart.ctx;
  3857. var pointStyle = vm.pointStyle;
  3858. var rotation = vm.rotation;
  3859. var radius = vm.radius;
  3860. var x = vm.x;
  3861. var y = vm.y;
  3862. var globalDefaults = core_defaults.global;
  3863. var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
  3864. if (vm.skip) {
  3865. return;
  3866. }
  3867. // Clipping for Points.
  3868. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
  3869. ctx.strokeStyle = vm.borderColor || defaultColor;
  3870. ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
  3871. ctx.fillStyle = vm.backgroundColor || defaultColor;
  3872. helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  3873. }
  3874. }
  3875. });
  3876. var defaultColor$2 = core_defaults.global.defaultColor;
  3877. core_defaults._set('global', {
  3878. elements: {
  3879. rectangle: {
  3880. backgroundColor: defaultColor$2,
  3881. borderColor: defaultColor$2,
  3882. borderSkipped: 'bottom',
  3883. borderWidth: 0
  3884. }
  3885. }
  3886. });
  3887. function isVertical(vm) {
  3888. return vm && vm.width !== undefined;
  3889. }
  3890. /**
  3891. * Helper function to get the bounds of the bar regardless of the orientation
  3892. * @param bar {Chart.Element.Rectangle} the bar
  3893. * @return {Bounds} bounds of the bar
  3894. * @private
  3895. */
  3896. function getBarBounds(vm) {
  3897. var x1, x2, y1, y2, half;
  3898. if (isVertical(vm)) {
  3899. half = vm.width / 2;
  3900. x1 = vm.x - half;
  3901. x2 = vm.x + half;
  3902. y1 = Math.min(vm.y, vm.base);
  3903. y2 = Math.max(vm.y, vm.base);
  3904. } else {
  3905. half = vm.height / 2;
  3906. x1 = Math.min(vm.x, vm.base);
  3907. x2 = Math.max(vm.x, vm.base);
  3908. y1 = vm.y - half;
  3909. y2 = vm.y + half;
  3910. }
  3911. return {
  3912. left: x1,
  3913. top: y1,
  3914. right: x2,
  3915. bottom: y2
  3916. };
  3917. }
  3918. function swap(orig, v1, v2) {
  3919. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  3920. }
  3921. function parseBorderSkipped(vm) {
  3922. var edge = vm.borderSkipped;
  3923. var res = {};
  3924. if (!edge) {
  3925. return res;
  3926. }
  3927. if (vm.horizontal) {
  3928. if (vm.base > vm.x) {
  3929. edge = swap(edge, 'left', 'right');
  3930. }
  3931. } else if (vm.base < vm.y) {
  3932. edge = swap(edge, 'bottom', 'top');
  3933. }
  3934. res[edge] = true;
  3935. return res;
  3936. }
  3937. function parseBorderWidth(vm, maxW, maxH) {
  3938. var value = vm.borderWidth;
  3939. var skip = parseBorderSkipped(vm);
  3940. var t, r, b, l;
  3941. if (helpers$1.isObject(value)) {
  3942. t = +value.top || 0;
  3943. r = +value.right || 0;
  3944. b = +value.bottom || 0;
  3945. l = +value.left || 0;
  3946. } else {
  3947. t = r = b = l = +value || 0;
  3948. }
  3949. return {
  3950. t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
  3951. r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
  3952. b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
  3953. l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
  3954. };
  3955. }
  3956. function boundingRects(vm) {
  3957. var bounds = getBarBounds(vm);
  3958. var width = bounds.right - bounds.left;
  3959. var height = bounds.bottom - bounds.top;
  3960. var border = parseBorderWidth(vm, width / 2, height / 2);
  3961. return {
  3962. outer: {
  3963. x: bounds.left,
  3964. y: bounds.top,
  3965. w: width,
  3966. h: height
  3967. },
  3968. inner: {
  3969. x: bounds.left + border.l,
  3970. y: bounds.top + border.t,
  3971. w: width - border.l - border.r,
  3972. h: height - border.t - border.b
  3973. }
  3974. };
  3975. }
  3976. function inRange(vm, x, y) {
  3977. var skipX = x === null;
  3978. var skipY = y === null;
  3979. var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
  3980. return bounds
  3981. && (skipX || x >= bounds.left && x <= bounds.right)
  3982. && (skipY || y >= bounds.top && y <= bounds.bottom);
  3983. }
  3984. var element_rectangle = core_element.extend({
  3985. _type: 'rectangle',
  3986. draw: function() {
  3987. var ctx = this._chart.ctx;
  3988. var vm = this._view;
  3989. var rects = boundingRects(vm);
  3990. var outer = rects.outer;
  3991. var inner = rects.inner;
  3992. ctx.fillStyle = vm.backgroundColor;
  3993. ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
  3994. if (outer.w === inner.w && outer.h === inner.h) {
  3995. return;
  3996. }
  3997. ctx.save();
  3998. ctx.beginPath();
  3999. ctx.rect(outer.x, outer.y, outer.w, outer.h);
  4000. ctx.clip();
  4001. ctx.fillStyle = vm.borderColor;
  4002. ctx.rect(inner.x, inner.y, inner.w, inner.h);
  4003. ctx.fill('evenodd');
  4004. ctx.restore();
  4005. },
  4006. height: function() {
  4007. var vm = this._view;
  4008. return vm.base - vm.y;
  4009. },
  4010. inRange: function(mouseX, mouseY) {
  4011. return inRange(this._view, mouseX, mouseY);
  4012. },
  4013. inLabelRange: function(mouseX, mouseY) {
  4014. var vm = this._view;
  4015. return isVertical(vm)
  4016. ? inRange(vm, mouseX, null)
  4017. : inRange(vm, null, mouseY);
  4018. },
  4019. inXRange: function(mouseX) {
  4020. return inRange(this._view, mouseX, null);
  4021. },
  4022. inYRange: function(mouseY) {
  4023. return inRange(this._view, null, mouseY);
  4024. },
  4025. getCenterPoint: function() {
  4026. var vm = this._view;
  4027. var x, y;
  4028. if (isVertical(vm)) {
  4029. x = vm.x;
  4030. y = (vm.y + vm.base) / 2;
  4031. } else {
  4032. x = (vm.x + vm.base) / 2;
  4033. y = vm.y;
  4034. }
  4035. return {x: x, y: y};
  4036. },
  4037. getArea: function() {
  4038. var vm = this._view;
  4039. return isVertical(vm)
  4040. ? vm.width * Math.abs(vm.y - vm.base)
  4041. : vm.height * Math.abs(vm.x - vm.base);
  4042. },
  4043. tooltipPosition: function() {
  4044. var vm = this._view;
  4045. return {
  4046. x: vm.x,
  4047. y: vm.y
  4048. };
  4049. }
  4050. });
  4051. var elements = {};
  4052. var Arc = element_arc;
  4053. var Line = element_line;
  4054. var Point = element_point;
  4055. var Rectangle = element_rectangle;
  4056. elements.Arc = Arc;
  4057. elements.Line = Line;
  4058. elements.Point = Point;
  4059. elements.Rectangle = Rectangle;
  4060. var deprecated = helpers$1._deprecated;
  4061. var valueOrDefault$3 = helpers$1.valueOrDefault;
  4062. core_defaults._set('bar', {
  4063. hover: {
  4064. mode: 'label'
  4065. },
  4066. scales: {
  4067. xAxes: [{
  4068. type: 'category',
  4069. offset: true,
  4070. gridLines: {
  4071. offsetGridLines: true
  4072. }
  4073. }],
  4074. yAxes: [{
  4075. type: 'linear'
  4076. }]
  4077. }
  4078. });
  4079. core_defaults._set('global', {
  4080. datasets: {
  4081. bar: {
  4082. categoryPercentage: 0.8,
  4083. barPercentage: 0.9
  4084. }
  4085. }
  4086. });
  4087. /**
  4088. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  4089. * @private
  4090. */
  4091. function computeMinSampleSize(scale, pixels) {
  4092. var min = scale._length;
  4093. var prev, curr, i, ilen;
  4094. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  4095. min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
  4096. }
  4097. for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) {
  4098. curr = scale.getPixelForTick(i);
  4099. min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;
  4100. prev = curr;
  4101. }
  4102. return min;
  4103. }
  4104. /**
  4105. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  4106. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  4107. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  4108. * @private
  4109. */
  4110. function computeFitCategoryTraits(index, ruler, options) {
  4111. var thickness = options.barThickness;
  4112. var count = ruler.stackCount;
  4113. var curr = ruler.pixels[index];
  4114. var min = helpers$1.isNullOrUndef(thickness)
  4115. ? computeMinSampleSize(ruler.scale, ruler.pixels)
  4116. : -1;
  4117. var size, ratio;
  4118. if (helpers$1.isNullOrUndef(thickness)) {
  4119. size = min * options.categoryPercentage;
  4120. ratio = options.barPercentage;
  4121. } else {
  4122. // When bar thickness is enforced, category and bar percentages are ignored.
  4123. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  4124. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  4125. size = thickness * count;
  4126. ratio = 1;
  4127. }
  4128. return {
  4129. chunk: size / count,
  4130. ratio: ratio,
  4131. start: curr - (size / 2)
  4132. };
  4133. }
  4134. /**
  4135. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  4136. * percentage options are 1), based on the previous and following categories. This mode
  4137. * generates bars with different widths when data are not evenly spaced.
  4138. * @private
  4139. */
  4140. function computeFlexCategoryTraits(index, ruler, options) {
  4141. var pixels = ruler.pixels;
  4142. var curr = pixels[index];
  4143. var prev = index > 0 ? pixels[index - 1] : null;
  4144. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  4145. var percent = options.categoryPercentage;
  4146. var start, size;
  4147. if (prev === null) {
  4148. // first data: its size is double based on the next point or,
  4149. // if it's also the last data, we use the scale size.
  4150. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  4151. }
  4152. if (next === null) {
  4153. // last data: its size is also double based on the previous point.
  4154. next = curr + curr - prev;
  4155. }
  4156. start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  4157. size = Math.abs(next - prev) / 2 * percent;
  4158. return {
  4159. chunk: size / ruler.stackCount,
  4160. ratio: options.barPercentage,
  4161. start: start
  4162. };
  4163. }
  4164. var controller_bar = core_datasetController.extend({
  4165. dataElementType: elements.Rectangle,
  4166. /**
  4167. * @private
  4168. */
  4169. _dataElementOptions: [
  4170. 'backgroundColor',
  4171. 'borderColor',
  4172. 'borderSkipped',
  4173. 'borderWidth',
  4174. 'barPercentage',
  4175. 'barThickness',
  4176. 'categoryPercentage',
  4177. 'maxBarThickness',
  4178. 'minBarLength'
  4179. ],
  4180. initialize: function() {
  4181. var me = this;
  4182. var meta, scaleOpts;
  4183. core_datasetController.prototype.initialize.apply(me, arguments);
  4184. meta = me.getMeta();
  4185. meta.stack = me.getDataset().stack;
  4186. meta.bar = true;
  4187. scaleOpts = me._getIndexScale().options;
  4188. deprecated('bar chart', scaleOpts.barPercentage, 'scales.[x/y]Axes.barPercentage', 'dataset.barPercentage');
  4189. deprecated('bar chart', scaleOpts.barThickness, 'scales.[x/y]Axes.barThickness', 'dataset.barThickness');
  4190. deprecated('bar chart', scaleOpts.categoryPercentage, 'scales.[x/y]Axes.categoryPercentage', 'dataset.categoryPercentage');
  4191. deprecated('bar chart', me._getValueScale().options.minBarLength, 'scales.[x/y]Axes.minBarLength', 'dataset.minBarLength');
  4192. deprecated('bar chart', scaleOpts.maxBarThickness, 'scales.[x/y]Axes.maxBarThickness', 'dataset.maxBarThickness');
  4193. },
  4194. update: function(reset) {
  4195. var me = this;
  4196. var rects = me.getMeta().data;
  4197. var i, ilen;
  4198. me._ruler = me.getRuler();
  4199. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  4200. me.updateElement(rects[i], i, reset);
  4201. }
  4202. },
  4203. updateElement: function(rectangle, index, reset) {
  4204. var me = this;
  4205. var meta = me.getMeta();
  4206. var dataset = me.getDataset();
  4207. var options = me._resolveDataElementOptions(rectangle, index);
  4208. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  4209. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  4210. rectangle._datasetIndex = me.index;
  4211. rectangle._index = index;
  4212. rectangle._model = {
  4213. backgroundColor: options.backgroundColor,
  4214. borderColor: options.borderColor,
  4215. borderSkipped: options.borderSkipped,
  4216. borderWidth: options.borderWidth,
  4217. datasetLabel: dataset.label,
  4218. label: me.chart.data.labels[index]
  4219. };
  4220. if (helpers$1.isArray(dataset.data[index])) {
  4221. rectangle._model.borderSkipped = null;
  4222. }
  4223. me._updateElementGeometry(rectangle, index, reset, options);
  4224. rectangle.pivot();
  4225. },
  4226. /**
  4227. * @private
  4228. */
  4229. _updateElementGeometry: function(rectangle, index, reset, options) {
  4230. var me = this;
  4231. var model = rectangle._model;
  4232. var vscale = me._getValueScale();
  4233. var base = vscale.getBasePixel();
  4234. var horizontal = vscale.isHorizontal();
  4235. var ruler = me._ruler || me.getRuler();
  4236. var vpixels = me.calculateBarValuePixels(me.index, index, options);
  4237. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler, options);
  4238. model.horizontal = horizontal;
  4239. model.base = reset ? base : vpixels.base;
  4240. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  4241. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  4242. model.height = horizontal ? ipixels.size : undefined;
  4243. model.width = horizontal ? undefined : ipixels.size;
  4244. },
  4245. /**
  4246. * Returns the stacks based on groups and bar visibility.
  4247. * @param {number} [last] - The dataset index
  4248. * @returns {string[]} The list of stack IDs
  4249. * @private
  4250. */
  4251. _getStacks: function(last) {
  4252. var me = this;
  4253. var scale = me._getIndexScale();
  4254. var metasets = scale._getMatchingVisibleMetas(me._type);
  4255. var stacked = scale.options.stacked;
  4256. var ilen = metasets.length;
  4257. var stacks = [];
  4258. var i, meta;
  4259. for (i = 0; i < ilen; ++i) {
  4260. meta = metasets[i];
  4261. // stacked | meta.stack
  4262. // | found | not found | undefined
  4263. // false | x | x | x
  4264. // true | | x |
  4265. // undefined | | x | x
  4266. if (stacked === false || stacks.indexOf(meta.stack) === -1 ||
  4267. (stacked === undefined && meta.stack === undefined)) {
  4268. stacks.push(meta.stack);
  4269. }
  4270. if (meta.index === last) {
  4271. break;
  4272. }
  4273. }
  4274. return stacks;
  4275. },
  4276. /**
  4277. * Returns the effective number of stacks based on groups and bar visibility.
  4278. * @private
  4279. */
  4280. getStackCount: function() {
  4281. return this._getStacks().length;
  4282. },
  4283. /**
  4284. * Returns the stack index for the given dataset based on groups and bar visibility.
  4285. * @param {number} [datasetIndex] - The dataset index
  4286. * @param {string} [name] - The stack name to find
  4287. * @returns {number} The stack index
  4288. * @private
  4289. */
  4290. getStackIndex: function(datasetIndex, name) {
  4291. var stacks = this._getStacks(datasetIndex);
  4292. var index = (name !== undefined)
  4293. ? stacks.indexOf(name)
  4294. : -1; // indexOf returns -1 if element is not present
  4295. return (index === -1)
  4296. ? stacks.length - 1
  4297. : index;
  4298. },
  4299. /**
  4300. * @private
  4301. */
  4302. getRuler: function() {
  4303. var me = this;
  4304. var scale = me._getIndexScale();
  4305. var pixels = [];
  4306. var i, ilen;
  4307. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  4308. pixels.push(scale.getPixelForValue(null, i, me.index));
  4309. }
  4310. return {
  4311. pixels: pixels,
  4312. start: scale._startPixel,
  4313. end: scale._endPixel,
  4314. stackCount: me.getStackCount(),
  4315. scale: scale
  4316. };
  4317. },
  4318. /**
  4319. * Note: pixel values are not clamped to the scale area.
  4320. * @private
  4321. */
  4322. calculateBarValuePixels: function(datasetIndex, index, options) {
  4323. var me = this;
  4324. var chart = me.chart;
  4325. var scale = me._getValueScale();
  4326. var isHorizontal = scale.isHorizontal();
  4327. var datasets = chart.data.datasets;
  4328. var metasets = scale._getMatchingVisibleMetas(me._type);
  4329. var value = scale._parseValue(datasets[datasetIndex].data[index]);
  4330. var minBarLength = options.minBarLength;
  4331. var stacked = scale.options.stacked;
  4332. var stack = me.getMeta().stack;
  4333. var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;
  4334. var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;
  4335. var ilen = metasets.length;
  4336. var i, imeta, ivalue, base, head, size, stackLength;
  4337. if (stacked || (stacked === undefined && stack !== undefined)) {
  4338. for (i = 0; i < ilen; ++i) {
  4339. imeta = metasets[i];
  4340. if (imeta.index === datasetIndex) {
  4341. break;
  4342. }
  4343. if (imeta.stack === stack) {
  4344. stackLength = scale._parseValue(datasets[imeta.index].data[index]);
  4345. ivalue = stackLength.start === undefined ? stackLength.end : stackLength.min >= 0 && stackLength.max >= 0 ? stackLength.max : stackLength.min;
  4346. if ((value.min < 0 && ivalue < 0) || (value.max >= 0 && ivalue > 0)) {
  4347. start += ivalue;
  4348. }
  4349. }
  4350. }
  4351. }
  4352. base = scale.getPixelForValue(start);
  4353. head = scale.getPixelForValue(start + length);
  4354. size = head - base;
  4355. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  4356. size = minBarLength;
  4357. if (length >= 0 && !isHorizontal || length < 0 && isHorizontal) {
  4358. head = base - minBarLength;
  4359. } else {
  4360. head = base + minBarLength;
  4361. }
  4362. }
  4363. return {
  4364. size: size,
  4365. base: base,
  4366. head: head,
  4367. center: head + size / 2
  4368. };
  4369. },
  4370. /**
  4371. * @private
  4372. */
  4373. calculateBarIndexPixels: function(datasetIndex, index, ruler, options) {
  4374. var me = this;
  4375. var range = options.barThickness === 'flex'
  4376. ? computeFlexCategoryTraits(index, ruler, options)
  4377. : computeFitCategoryTraits(index, ruler, options);
  4378. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  4379. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  4380. var size = Math.min(
  4381. valueOrDefault$3(options.maxBarThickness, Infinity),
  4382. range.chunk * range.ratio);
  4383. return {
  4384. base: center - size / 2,
  4385. head: center + size / 2,
  4386. center: center,
  4387. size: size
  4388. };
  4389. },
  4390. draw: function() {
  4391. var me = this;
  4392. var chart = me.chart;
  4393. var scale = me._getValueScale();
  4394. var rects = me.getMeta().data;
  4395. var dataset = me.getDataset();
  4396. var ilen = rects.length;
  4397. var i = 0;
  4398. helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
  4399. for (; i < ilen; ++i) {
  4400. var val = scale._parseValue(dataset.data[i]);
  4401. if (!isNaN(val.min) && !isNaN(val.max)) {
  4402. rects[i].draw();
  4403. }
  4404. }
  4405. helpers$1.canvas.unclipArea(chart.ctx);
  4406. },
  4407. /**
  4408. * @private
  4409. */
  4410. _resolveDataElementOptions: function() {
  4411. var me = this;
  4412. var values = helpers$1.extend({}, core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments));
  4413. var indexOpts = me._getIndexScale().options;
  4414. var valueOpts = me._getValueScale().options;
  4415. values.barPercentage = valueOrDefault$3(indexOpts.barPercentage, values.barPercentage);
  4416. values.barThickness = valueOrDefault$3(indexOpts.barThickness, values.barThickness);
  4417. values.categoryPercentage = valueOrDefault$3(indexOpts.categoryPercentage, values.categoryPercentage);
  4418. values.maxBarThickness = valueOrDefault$3(indexOpts.maxBarThickness, values.maxBarThickness);
  4419. values.minBarLength = valueOrDefault$3(valueOpts.minBarLength, values.minBarLength);
  4420. return values;
  4421. }
  4422. });
  4423. var valueOrDefault$4 = helpers$1.valueOrDefault;
  4424. var resolve$1 = helpers$1.options.resolve;
  4425. core_defaults._set('bubble', {
  4426. hover: {
  4427. mode: 'single'
  4428. },
  4429. scales: {
  4430. xAxes: [{
  4431. type: 'linear', // bubble should probably use a linear scale by default
  4432. position: 'bottom',
  4433. id: 'x-axis-0' // need an ID so datasets can reference the scale
  4434. }],
  4435. yAxes: [{
  4436. type: 'linear',
  4437. position: 'left',
  4438. id: 'y-axis-0'
  4439. }]
  4440. },
  4441. tooltips: {
  4442. callbacks: {
  4443. title: function() {
  4444. // Title doesn't make sense for scatter since we format the data as a point
  4445. return '';
  4446. },
  4447. label: function(item, data) {
  4448. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  4449. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  4450. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  4451. }
  4452. }
  4453. }
  4454. });
  4455. var controller_bubble = core_datasetController.extend({
  4456. /**
  4457. * @protected
  4458. */
  4459. dataElementType: elements.Point,
  4460. /**
  4461. * @private
  4462. */
  4463. _dataElementOptions: [
  4464. 'backgroundColor',
  4465. 'borderColor',
  4466. 'borderWidth',
  4467. 'hoverBackgroundColor',
  4468. 'hoverBorderColor',
  4469. 'hoverBorderWidth',
  4470. 'hoverRadius',
  4471. 'hitRadius',
  4472. 'pointStyle',
  4473. 'rotation'
  4474. ],
  4475. /**
  4476. * @protected
  4477. */
  4478. update: function(reset) {
  4479. var me = this;
  4480. var meta = me.getMeta();
  4481. var points = meta.data;
  4482. // Update Points
  4483. helpers$1.each(points, function(point, index) {
  4484. me.updateElement(point, index, reset);
  4485. });
  4486. },
  4487. /**
  4488. * @protected
  4489. */
  4490. updateElement: function(point, index, reset) {
  4491. var me = this;
  4492. var meta = me.getMeta();
  4493. var custom = point.custom || {};
  4494. var xScale = me.getScaleForId(meta.xAxisID);
  4495. var yScale = me.getScaleForId(meta.yAxisID);
  4496. var options = me._resolveDataElementOptions(point, index);
  4497. var data = me.getDataset().data[index];
  4498. var dsIndex = me.index;
  4499. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  4500. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  4501. point._xScale = xScale;
  4502. point._yScale = yScale;
  4503. point._options = options;
  4504. point._datasetIndex = dsIndex;
  4505. point._index = index;
  4506. point._model = {
  4507. backgroundColor: options.backgroundColor,
  4508. borderColor: options.borderColor,
  4509. borderWidth: options.borderWidth,
  4510. hitRadius: options.hitRadius,
  4511. pointStyle: options.pointStyle,
  4512. rotation: options.rotation,
  4513. radius: reset ? 0 : options.radius,
  4514. skip: custom.skip || isNaN(x) || isNaN(y),
  4515. x: x,
  4516. y: y,
  4517. };
  4518. point.pivot();
  4519. },
  4520. /**
  4521. * @protected
  4522. */
  4523. setHoverStyle: function(point) {
  4524. var model = point._model;
  4525. var options = point._options;
  4526. var getHoverColor = helpers$1.getHoverColor;
  4527. point.$previousStyle = {
  4528. backgroundColor: model.backgroundColor,
  4529. borderColor: model.borderColor,
  4530. borderWidth: model.borderWidth,
  4531. radius: model.radius
  4532. };
  4533. model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4534. model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
  4535. model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
  4536. model.radius = options.radius + options.hoverRadius;
  4537. },
  4538. /**
  4539. * @private
  4540. */
  4541. _resolveDataElementOptions: function(point, index) {
  4542. var me = this;
  4543. var chart = me.chart;
  4544. var dataset = me.getDataset();
  4545. var custom = point.custom || {};
  4546. var data = dataset.data[index] || {};
  4547. var values = core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments);
  4548. // Scriptable options
  4549. var context = {
  4550. chart: chart,
  4551. dataIndex: index,
  4552. dataset: dataset,
  4553. datasetIndex: me.index
  4554. };
  4555. // In case values were cached (and thus frozen), we need to clone the values
  4556. if (me._cachedDataOpts === values) {
  4557. values = helpers$1.extend({}, values);
  4558. }
  4559. // Custom radius resolution
  4560. values.radius = resolve$1([
  4561. custom.radius,
  4562. data.r,
  4563. me._config.radius,
  4564. chart.options.elements.point.radius
  4565. ], context, index);
  4566. return values;
  4567. }
  4568. });
  4569. var valueOrDefault$5 = helpers$1.valueOrDefault;
  4570. var PI$1 = Math.PI;
  4571. var DOUBLE_PI$1 = PI$1 * 2;
  4572. var HALF_PI$1 = PI$1 / 2;
  4573. core_defaults._set('doughnut', {
  4574. animation: {
  4575. // Boolean - Whether we animate the rotation of the Doughnut
  4576. animateRotate: true,
  4577. // Boolean - Whether we animate scaling the Doughnut from the centre
  4578. animateScale: false
  4579. },
  4580. hover: {
  4581. mode: 'single'
  4582. },
  4583. legendCallback: function(chart) {
  4584. var list = document.createElement('ul');
  4585. var data = chart.data;
  4586. var datasets = data.datasets;
  4587. var labels = data.labels;
  4588. var i, ilen, listItem, listItemSpan;
  4589. list.setAttribute('class', chart.id + '-legend');
  4590. if (datasets.length) {
  4591. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  4592. listItem = list.appendChild(document.createElement('li'));
  4593. listItemSpan = listItem.appendChild(document.createElement('span'));
  4594. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  4595. if (labels[i]) {
  4596. listItem.appendChild(document.createTextNode(labels[i]));
  4597. }
  4598. }
  4599. }
  4600. return list.outerHTML;
  4601. },
  4602. legend: {
  4603. labels: {
  4604. generateLabels: function(chart) {
  4605. var data = chart.data;
  4606. if (data.labels.length && data.datasets.length) {
  4607. return data.labels.map(function(label, i) {
  4608. var meta = chart.getDatasetMeta(0);
  4609. var style = meta.controller.getStyle(i);
  4610. return {
  4611. text: label,
  4612. fillStyle: style.backgroundColor,
  4613. strokeStyle: style.borderColor,
  4614. lineWidth: style.borderWidth,
  4615. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  4616. // Extra data used for toggling the correct item
  4617. index: i
  4618. };
  4619. });
  4620. }
  4621. return [];
  4622. }
  4623. },
  4624. onClick: function(e, legendItem) {
  4625. var index = legendItem.index;
  4626. var chart = this.chart;
  4627. var i, ilen, meta;
  4628. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  4629. meta = chart.getDatasetMeta(i);
  4630. // toggle visibility of index if exists
  4631. if (meta.data[index]) {
  4632. meta.data[index].hidden = !meta.data[index].hidden;
  4633. }
  4634. }
  4635. chart.update();
  4636. }
  4637. },
  4638. // The percentage of the chart that we cut out of the middle.
  4639. cutoutPercentage: 50,
  4640. // The rotation of the chart, where the first data arc begins.
  4641. rotation: -HALF_PI$1,
  4642. // The total circumference of the chart.
  4643. circumference: DOUBLE_PI$1,
  4644. // Need to override these to give a nice default
  4645. tooltips: {
  4646. callbacks: {
  4647. title: function() {
  4648. return '';
  4649. },
  4650. label: function(tooltipItem, data) {
  4651. var dataLabel = data.labels[tooltipItem.index];
  4652. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  4653. if (helpers$1.isArray(dataLabel)) {
  4654. // show value on first line of multiline label
  4655. // need to clone because we are changing the value
  4656. dataLabel = dataLabel.slice();
  4657. dataLabel[0] += value;
  4658. } else {
  4659. dataLabel += value;
  4660. }
  4661. return dataLabel;
  4662. }
  4663. }
  4664. }
  4665. });
  4666. var controller_doughnut = core_datasetController.extend({
  4667. dataElementType: elements.Arc,
  4668. linkScales: helpers$1.noop,
  4669. /**
  4670. * @private
  4671. */
  4672. _dataElementOptions: [
  4673. 'backgroundColor',
  4674. 'borderColor',
  4675. 'borderWidth',
  4676. 'borderAlign',
  4677. 'hoverBackgroundColor',
  4678. 'hoverBorderColor',
  4679. 'hoverBorderWidth',
  4680. ],
  4681. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  4682. getRingIndex: function(datasetIndex) {
  4683. var ringIndex = 0;
  4684. for (var j = 0; j < datasetIndex; ++j) {
  4685. if (this.chart.isDatasetVisible(j)) {
  4686. ++ringIndex;
  4687. }
  4688. }
  4689. return ringIndex;
  4690. },
  4691. update: function(reset) {
  4692. var me = this;
  4693. var chart = me.chart;
  4694. var chartArea = chart.chartArea;
  4695. var opts = chart.options;
  4696. var ratioX = 1;
  4697. var ratioY = 1;
  4698. var offsetX = 0;
  4699. var offsetY = 0;
  4700. var meta = me.getMeta();
  4701. var arcs = meta.data;
  4702. var cutout = opts.cutoutPercentage / 100 || 0;
  4703. var circumference = opts.circumference;
  4704. var chartWeight = me._getRingWeight(me.index);
  4705. var maxWidth, maxHeight, i, ilen;
  4706. // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc
  4707. if (circumference < DOUBLE_PI$1) {
  4708. var startAngle = opts.rotation % DOUBLE_PI$1;
  4709. startAngle += startAngle >= PI$1 ? -DOUBLE_PI$1 : startAngle < -PI$1 ? DOUBLE_PI$1 : 0;
  4710. var endAngle = startAngle + circumference;
  4711. var startX = Math.cos(startAngle);
  4712. var startY = Math.sin(startAngle);
  4713. var endX = Math.cos(endAngle);
  4714. var endY = Math.sin(endAngle);
  4715. var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI$1;
  4716. var contains90 = (startAngle <= HALF_PI$1 && endAngle >= HALF_PI$1) || endAngle >= DOUBLE_PI$1 + HALF_PI$1;
  4717. var contains180 = startAngle === -PI$1 || endAngle >= PI$1;
  4718. var contains270 = (startAngle <= -HALF_PI$1 && endAngle >= -HALF_PI$1) || endAngle >= PI$1 + HALF_PI$1;
  4719. var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);
  4720. var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);
  4721. var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);
  4722. var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);
  4723. ratioX = (maxX - minX) / 2;
  4724. ratioY = (maxY - minY) / 2;
  4725. offsetX = -(maxX + minX) / 2;
  4726. offsetY = -(maxY + minY) / 2;
  4727. }
  4728. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4729. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  4730. }
  4731. chart.borderWidth = me.getMaxBorderWidth();
  4732. maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;
  4733. maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;
  4734. chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  4735. chart.innerRadius = Math.max(chart.outerRadius * cutout, 0);
  4736. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
  4737. chart.offsetX = offsetX * chart.outerRadius;
  4738. chart.offsetY = offsetY * chart.outerRadius;
  4739. meta.total = me.calculateTotal();
  4740. me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
  4741. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
  4742. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4743. me.updateElement(arcs[i], i, reset);
  4744. }
  4745. },
  4746. updateElement: function(arc, index, reset) {
  4747. var me = this;
  4748. var chart = me.chart;
  4749. var chartArea = chart.chartArea;
  4750. var opts = chart.options;
  4751. var animationOpts = opts.animation;
  4752. var centerX = (chartArea.left + chartArea.right) / 2;
  4753. var centerY = (chartArea.top + chartArea.bottom) / 2;
  4754. var startAngle = opts.rotation; // non reset case handled later
  4755. var endAngle = opts.rotation; // non reset case handled later
  4756. var dataset = me.getDataset();
  4757. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / DOUBLE_PI$1);
  4758. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  4759. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  4760. var options = arc._options || {};
  4761. helpers$1.extend(arc, {
  4762. // Utility
  4763. _datasetIndex: me.index,
  4764. _index: index,
  4765. // Desired view properties
  4766. _model: {
  4767. backgroundColor: options.backgroundColor,
  4768. borderColor: options.borderColor,
  4769. borderWidth: options.borderWidth,
  4770. borderAlign: options.borderAlign,
  4771. x: centerX + chart.offsetX,
  4772. y: centerY + chart.offsetY,
  4773. startAngle: startAngle,
  4774. endAngle: endAngle,
  4775. circumference: circumference,
  4776. outerRadius: outerRadius,
  4777. innerRadius: innerRadius,
  4778. label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  4779. }
  4780. });
  4781. var model = arc._model;
  4782. // Set correct angles if not resetting
  4783. if (!reset || !animationOpts.animateRotate) {
  4784. if (index === 0) {
  4785. model.startAngle = opts.rotation;
  4786. } else {
  4787. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  4788. }
  4789. model.endAngle = model.startAngle + model.circumference;
  4790. }
  4791. arc.pivot();
  4792. },
  4793. calculateTotal: function() {
  4794. var dataset = this.getDataset();
  4795. var meta = this.getMeta();
  4796. var total = 0;
  4797. var value;
  4798. helpers$1.each(meta.data, function(element, index) {
  4799. value = dataset.data[index];
  4800. if (!isNaN(value) && !element.hidden) {
  4801. total += Math.abs(value);
  4802. }
  4803. });
  4804. /* if (total === 0) {
  4805. total = NaN;
  4806. }*/
  4807. return total;
  4808. },
  4809. calculateCircumference: function(value) {
  4810. var total = this.getMeta().total;
  4811. if (total > 0 && !isNaN(value)) {
  4812. return DOUBLE_PI$1 * (Math.abs(value) / total);
  4813. }
  4814. return 0;
  4815. },
  4816. // gets the max border or hover width to properly scale pie charts
  4817. getMaxBorderWidth: function(arcs) {
  4818. var me = this;
  4819. var max = 0;
  4820. var chart = me.chart;
  4821. var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
  4822. if (!arcs) {
  4823. // Find the outmost visible dataset
  4824. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  4825. if (chart.isDatasetVisible(i)) {
  4826. meta = chart.getDatasetMeta(i);
  4827. arcs = meta.data;
  4828. if (i !== me.index) {
  4829. controller = meta.controller;
  4830. }
  4831. break;
  4832. }
  4833. }
  4834. }
  4835. if (!arcs) {
  4836. return 0;
  4837. }
  4838. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4839. arc = arcs[i];
  4840. if (controller) {
  4841. controller._configure();
  4842. options = controller._resolveDataElementOptions(arc, i);
  4843. } else {
  4844. options = arc._options;
  4845. }
  4846. if (options.borderAlign !== 'inner') {
  4847. borderWidth = options.borderWidth;
  4848. hoverWidth = options.hoverBorderWidth;
  4849. max = borderWidth > max ? borderWidth : max;
  4850. max = hoverWidth > max ? hoverWidth : max;
  4851. }
  4852. }
  4853. return max;
  4854. },
  4855. /**
  4856. * @protected
  4857. */
  4858. setHoverStyle: function(arc) {
  4859. var model = arc._model;
  4860. var options = arc._options;
  4861. var getHoverColor = helpers$1.getHoverColor;
  4862. arc.$previousStyle = {
  4863. backgroundColor: model.backgroundColor,
  4864. borderColor: model.borderColor,
  4865. borderWidth: model.borderWidth,
  4866. };
  4867. model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4868. model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
  4869. model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
  4870. },
  4871. /**
  4872. * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
  4873. * @private
  4874. */
  4875. _getRingWeightOffset: function(datasetIndex) {
  4876. var ringWeightOffset = 0;
  4877. for (var i = 0; i < datasetIndex; ++i) {
  4878. if (this.chart.isDatasetVisible(i)) {
  4879. ringWeightOffset += this._getRingWeight(i);
  4880. }
  4881. }
  4882. return ringWeightOffset;
  4883. },
  4884. /**
  4885. * @private
  4886. */
  4887. _getRingWeight: function(dataSetIndex) {
  4888. return Math.max(valueOrDefault$5(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
  4889. },
  4890. /**
  4891. * Returns the sum of all visibile data set weights. This value can be 0.
  4892. * @private
  4893. */
  4894. _getVisibleDatasetWeightTotal: function() {
  4895. return this._getRingWeightOffset(this.chart.data.datasets.length);
  4896. }
  4897. });
  4898. core_defaults._set('horizontalBar', {
  4899. hover: {
  4900. mode: 'index',
  4901. axis: 'y'
  4902. },
  4903. scales: {
  4904. xAxes: [{
  4905. type: 'linear',
  4906. position: 'bottom'
  4907. }],
  4908. yAxes: [{
  4909. type: 'category',
  4910. position: 'left',
  4911. offset: true,
  4912. gridLines: {
  4913. offsetGridLines: true
  4914. }
  4915. }]
  4916. },
  4917. elements: {
  4918. rectangle: {
  4919. borderSkipped: 'left'
  4920. }
  4921. },
  4922. tooltips: {
  4923. mode: 'index',
  4924. axis: 'y'
  4925. }
  4926. });
  4927. core_defaults._set('global', {
  4928. datasets: {
  4929. horizontalBar: {
  4930. categoryPercentage: 0.8,
  4931. barPercentage: 0.9
  4932. }
  4933. }
  4934. });
  4935. var controller_horizontalBar = controller_bar.extend({
  4936. /**
  4937. * @private
  4938. */
  4939. _getValueScaleId: function() {
  4940. return this.getMeta().xAxisID;
  4941. },
  4942. /**
  4943. * @private
  4944. */
  4945. _getIndexScaleId: function() {
  4946. return this.getMeta().yAxisID;
  4947. }
  4948. });
  4949. var valueOrDefault$6 = helpers$1.valueOrDefault;
  4950. var resolve$2 = helpers$1.options.resolve;
  4951. var isPointInArea = helpers$1.canvas._isPointInArea;
  4952. core_defaults._set('line', {
  4953. showLines: true,
  4954. spanGaps: false,
  4955. hover: {
  4956. mode: 'label'
  4957. },
  4958. scales: {
  4959. xAxes: [{
  4960. type: 'category',
  4961. id: 'x-axis-0'
  4962. }],
  4963. yAxes: [{
  4964. type: 'linear',
  4965. id: 'y-axis-0'
  4966. }]
  4967. }
  4968. });
  4969. function scaleClip(scale, halfBorderWidth) {
  4970. var tickOpts = scale && scale.options.ticks || {};
  4971. var reverse = tickOpts.reverse;
  4972. var min = tickOpts.min === undefined ? halfBorderWidth : 0;
  4973. var max = tickOpts.max === undefined ? halfBorderWidth : 0;
  4974. return {
  4975. start: reverse ? max : min,
  4976. end: reverse ? min : max
  4977. };
  4978. }
  4979. function defaultClip(xScale, yScale, borderWidth) {
  4980. var halfBorderWidth = borderWidth / 2;
  4981. var x = scaleClip(xScale, halfBorderWidth);
  4982. var y = scaleClip(yScale, halfBorderWidth);
  4983. return {
  4984. top: y.end,
  4985. right: x.end,
  4986. bottom: y.start,
  4987. left: x.start
  4988. };
  4989. }
  4990. function toClip(value) {
  4991. var t, r, b, l;
  4992. if (helpers$1.isObject(value)) {
  4993. t = value.top;
  4994. r = value.right;
  4995. b = value.bottom;
  4996. l = value.left;
  4997. } else {
  4998. t = r = b = l = value;
  4999. }
  5000. return {
  5001. top: t,
  5002. right: r,
  5003. bottom: b,
  5004. left: l
  5005. };
  5006. }
  5007. var controller_line = core_datasetController.extend({
  5008. datasetElementType: elements.Line,
  5009. dataElementType: elements.Point,
  5010. /**
  5011. * @private
  5012. */
  5013. _datasetElementOptions: [
  5014. 'backgroundColor',
  5015. 'borderCapStyle',
  5016. 'borderColor',
  5017. 'borderDash',
  5018. 'borderDashOffset',
  5019. 'borderJoinStyle',
  5020. 'borderWidth',
  5021. 'cubicInterpolationMode',
  5022. 'fill'
  5023. ],
  5024. /**
  5025. * @private
  5026. */
  5027. _dataElementOptions: {
  5028. backgroundColor: 'pointBackgroundColor',
  5029. borderColor: 'pointBorderColor',
  5030. borderWidth: 'pointBorderWidth',
  5031. hitRadius: 'pointHitRadius',
  5032. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5033. hoverBorderColor: 'pointHoverBorderColor',
  5034. hoverBorderWidth: 'pointHoverBorderWidth',
  5035. hoverRadius: 'pointHoverRadius',
  5036. pointStyle: 'pointStyle',
  5037. radius: 'pointRadius',
  5038. rotation: 'pointRotation'
  5039. },
  5040. update: function(reset) {
  5041. var me = this;
  5042. var meta = me.getMeta();
  5043. var line = meta.dataset;
  5044. var points = meta.data || [];
  5045. var options = me.chart.options;
  5046. var config = me._config;
  5047. var showLine = me._showLine = valueOrDefault$6(config.showLine, options.showLines);
  5048. var i, ilen;
  5049. me._xScale = me.getScaleForId(meta.xAxisID);
  5050. me._yScale = me.getScaleForId(meta.yAxisID);
  5051. // Update Line
  5052. if (showLine) {
  5053. // Compatibility: If the properties are defined with only the old name, use those values
  5054. if (config.tension !== undefined && config.lineTension === undefined) {
  5055. config.lineTension = config.tension;
  5056. }
  5057. // Utility
  5058. line._scale = me._yScale;
  5059. line._datasetIndex = me.index;
  5060. // Data
  5061. line._children = points;
  5062. // Model
  5063. line._model = me._resolveDatasetElementOptions(line);
  5064. line.pivot();
  5065. }
  5066. // Update Points
  5067. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5068. me.updateElement(points[i], i, reset);
  5069. }
  5070. if (showLine && line._model.tension !== 0) {
  5071. me.updateBezierControlPoints();
  5072. }
  5073. // Now pivot the point for animation
  5074. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5075. points[i].pivot();
  5076. }
  5077. },
  5078. updateElement: function(point, index, reset) {
  5079. var me = this;
  5080. var meta = me.getMeta();
  5081. var custom = point.custom || {};
  5082. var dataset = me.getDataset();
  5083. var datasetIndex = me.index;
  5084. var value = dataset.data[index];
  5085. var xScale = me._xScale;
  5086. var yScale = me._yScale;
  5087. var lineModel = meta.dataset._model;
  5088. var x, y;
  5089. var options = me._resolveDataElementOptions(point, index);
  5090. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  5091. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  5092. // Utility
  5093. point._xScale = xScale;
  5094. point._yScale = yScale;
  5095. point._options = options;
  5096. point._datasetIndex = datasetIndex;
  5097. point._index = index;
  5098. // Desired view properties
  5099. point._model = {
  5100. x: x,
  5101. y: y,
  5102. skip: custom.skip || isNaN(x) || isNaN(y),
  5103. // Appearance
  5104. radius: options.radius,
  5105. pointStyle: options.pointStyle,
  5106. rotation: options.rotation,
  5107. backgroundColor: options.backgroundColor,
  5108. borderColor: options.borderColor,
  5109. borderWidth: options.borderWidth,
  5110. tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0),
  5111. steppedLine: lineModel ? lineModel.steppedLine : false,
  5112. // Tooltip
  5113. hitRadius: options.hitRadius
  5114. };
  5115. },
  5116. /**
  5117. * @private
  5118. */
  5119. _resolveDatasetElementOptions: function(element) {
  5120. var me = this;
  5121. var config = me._config;
  5122. var custom = element.custom || {};
  5123. var options = me.chart.options;
  5124. var lineOptions = options.elements.line;
  5125. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5126. // The default behavior of lines is to break at null values, according
  5127. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  5128. // This option gives lines the ability to span gaps
  5129. values.spanGaps = valueOrDefault$6(config.spanGaps, options.spanGaps);
  5130. values.tension = valueOrDefault$6(config.lineTension, lineOptions.tension);
  5131. values.steppedLine = resolve$2([custom.steppedLine, config.steppedLine, lineOptions.stepped]);
  5132. values.clip = toClip(valueOrDefault$6(config.clip, defaultClip(me._xScale, me._yScale, values.borderWidth)));
  5133. return values;
  5134. },
  5135. calculatePointY: function(value, index, datasetIndex) {
  5136. var me = this;
  5137. var chart = me.chart;
  5138. var yScale = me._yScale;
  5139. var sumPos = 0;
  5140. var sumNeg = 0;
  5141. var i, ds, dsMeta, stackedRightValue, rightValue, metasets, ilen;
  5142. if (yScale.options.stacked) {
  5143. rightValue = +yScale.getRightValue(value);
  5144. metasets = chart._getSortedVisibleDatasetMetas();
  5145. ilen = metasets.length;
  5146. for (i = 0; i < ilen; ++i) {
  5147. dsMeta = metasets[i];
  5148. if (dsMeta.index === datasetIndex) {
  5149. break;
  5150. }
  5151. ds = chart.data.datasets[dsMeta.index];
  5152. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id) {
  5153. stackedRightValue = +yScale.getRightValue(ds.data[index]);
  5154. if (stackedRightValue < 0) {
  5155. sumNeg += stackedRightValue || 0;
  5156. } else {
  5157. sumPos += stackedRightValue || 0;
  5158. }
  5159. }
  5160. }
  5161. if (rightValue < 0) {
  5162. return yScale.getPixelForValue(sumNeg + rightValue);
  5163. }
  5164. return yScale.getPixelForValue(sumPos + rightValue);
  5165. }
  5166. return yScale.getPixelForValue(value);
  5167. },
  5168. updateBezierControlPoints: function() {
  5169. var me = this;
  5170. var chart = me.chart;
  5171. var meta = me.getMeta();
  5172. var lineModel = meta.dataset._model;
  5173. var area = chart.chartArea;
  5174. var points = meta.data || [];
  5175. var i, ilen, model, controlPoints;
  5176. // Only consider points that are drawn in case the spanGaps option is used
  5177. if (lineModel.spanGaps) {
  5178. points = points.filter(function(pt) {
  5179. return !pt._model.skip;
  5180. });
  5181. }
  5182. function capControlPoint(pt, min, max) {
  5183. return Math.max(Math.min(pt, max), min);
  5184. }
  5185. if (lineModel.cubicInterpolationMode === 'monotone') {
  5186. helpers$1.splineCurveMonotone(points);
  5187. } else {
  5188. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5189. model = points[i]._model;
  5190. controlPoints = helpers$1.splineCurve(
  5191. helpers$1.previousItem(points, i)._model,
  5192. model,
  5193. helpers$1.nextItem(points, i)._model,
  5194. lineModel.tension
  5195. );
  5196. model.controlPointPreviousX = controlPoints.previous.x;
  5197. model.controlPointPreviousY = controlPoints.previous.y;
  5198. model.controlPointNextX = controlPoints.next.x;
  5199. model.controlPointNextY = controlPoints.next.y;
  5200. }
  5201. }
  5202. if (chart.options.elements.line.capBezierPoints) {
  5203. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5204. model = points[i]._model;
  5205. if (isPointInArea(model, area)) {
  5206. if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
  5207. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  5208. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  5209. }
  5210. if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
  5211. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  5212. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  5213. }
  5214. }
  5215. }
  5216. }
  5217. },
  5218. draw: function() {
  5219. var me = this;
  5220. var chart = me.chart;
  5221. var meta = me.getMeta();
  5222. var points = meta.data || [];
  5223. var area = chart.chartArea;
  5224. var canvas = chart.canvas;
  5225. var i = 0;
  5226. var ilen = points.length;
  5227. var clip;
  5228. if (me._showLine) {
  5229. clip = meta.dataset._model.clip;
  5230. helpers$1.canvas.clipArea(chart.ctx, {
  5231. left: clip.left === false ? 0 : area.left - clip.left,
  5232. right: clip.right === false ? canvas.width : area.right + clip.right,
  5233. top: clip.top === false ? 0 : area.top - clip.top,
  5234. bottom: clip.bottom === false ? canvas.height : area.bottom + clip.bottom
  5235. });
  5236. meta.dataset.draw();
  5237. helpers$1.canvas.unclipArea(chart.ctx);
  5238. }
  5239. // Draw the points
  5240. for (; i < ilen; ++i) {
  5241. points[i].draw(area);
  5242. }
  5243. },
  5244. /**
  5245. * @protected
  5246. */
  5247. setHoverStyle: function(point) {
  5248. var model = point._model;
  5249. var options = point._options;
  5250. var getHoverColor = helpers$1.getHoverColor;
  5251. point.$previousStyle = {
  5252. backgroundColor: model.backgroundColor,
  5253. borderColor: model.borderColor,
  5254. borderWidth: model.borderWidth,
  5255. radius: model.radius
  5256. };
  5257. model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5258. model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));
  5259. model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);
  5260. model.radius = valueOrDefault$6(options.hoverRadius, options.radius);
  5261. },
  5262. });
  5263. var resolve$3 = helpers$1.options.resolve;
  5264. core_defaults._set('polarArea', {
  5265. scale: {
  5266. type: 'radialLinear',
  5267. angleLines: {
  5268. display: false
  5269. },
  5270. gridLines: {
  5271. circular: true
  5272. },
  5273. pointLabels: {
  5274. display: false
  5275. },
  5276. ticks: {
  5277. beginAtZero: true
  5278. }
  5279. },
  5280. // Boolean - Whether to animate the rotation of the chart
  5281. animation: {
  5282. animateRotate: true,
  5283. animateScale: true
  5284. },
  5285. startAngle: -0.5 * Math.PI,
  5286. legendCallback: function(chart) {
  5287. var list = document.createElement('ul');
  5288. var data = chart.data;
  5289. var datasets = data.datasets;
  5290. var labels = data.labels;
  5291. var i, ilen, listItem, listItemSpan;
  5292. list.setAttribute('class', chart.id + '-legend');
  5293. if (datasets.length) {
  5294. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  5295. listItem = list.appendChild(document.createElement('li'));
  5296. listItemSpan = listItem.appendChild(document.createElement('span'));
  5297. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  5298. if (labels[i]) {
  5299. listItem.appendChild(document.createTextNode(labels[i]));
  5300. }
  5301. }
  5302. }
  5303. return list.outerHTML;
  5304. },
  5305. legend: {
  5306. labels: {
  5307. generateLabels: function(chart) {
  5308. var data = chart.data;
  5309. if (data.labels.length && data.datasets.length) {
  5310. return data.labels.map(function(label, i) {
  5311. var meta = chart.getDatasetMeta(0);
  5312. var style = meta.controller.getStyle(i);
  5313. return {
  5314. text: label,
  5315. fillStyle: style.backgroundColor,
  5316. strokeStyle: style.borderColor,
  5317. lineWidth: style.borderWidth,
  5318. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  5319. // Extra data used for toggling the correct item
  5320. index: i
  5321. };
  5322. });
  5323. }
  5324. return [];
  5325. }
  5326. },
  5327. onClick: function(e, legendItem) {
  5328. var index = legendItem.index;
  5329. var chart = this.chart;
  5330. var i, ilen, meta;
  5331. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  5332. meta = chart.getDatasetMeta(i);
  5333. meta.data[index].hidden = !meta.data[index].hidden;
  5334. }
  5335. chart.update();
  5336. }
  5337. },
  5338. // Need to override these to give a nice default
  5339. tooltips: {
  5340. callbacks: {
  5341. title: function() {
  5342. return '';
  5343. },
  5344. label: function(item, data) {
  5345. return data.labels[item.index] + ': ' + item.yLabel;
  5346. }
  5347. }
  5348. }
  5349. });
  5350. var controller_polarArea = core_datasetController.extend({
  5351. dataElementType: elements.Arc,
  5352. linkScales: helpers$1.noop,
  5353. /**
  5354. * @private
  5355. */
  5356. _dataElementOptions: [
  5357. 'backgroundColor',
  5358. 'borderColor',
  5359. 'borderWidth',
  5360. 'borderAlign',
  5361. 'hoverBackgroundColor',
  5362. 'hoverBorderColor',
  5363. 'hoverBorderWidth',
  5364. ],
  5365. /**
  5366. * @private
  5367. */
  5368. _getIndexScaleId: function() {
  5369. return this.chart.scale.id;
  5370. },
  5371. /**
  5372. * @private
  5373. */
  5374. _getValueScaleId: function() {
  5375. return this.chart.scale.id;
  5376. },
  5377. update: function(reset) {
  5378. var me = this;
  5379. var dataset = me.getDataset();
  5380. var meta = me.getMeta();
  5381. var start = me.chart.options.startAngle || 0;
  5382. var starts = me._starts = [];
  5383. var angles = me._angles = [];
  5384. var arcs = meta.data;
  5385. var i, ilen, angle;
  5386. me._updateRadius();
  5387. meta.count = me.countVisibleElements();
  5388. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  5389. starts[i] = start;
  5390. angle = me._computeAngle(i);
  5391. angles[i] = angle;
  5392. start += angle;
  5393. }
  5394. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  5395. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  5396. me.updateElement(arcs[i], i, reset);
  5397. }
  5398. },
  5399. /**
  5400. * @private
  5401. */
  5402. _updateRadius: function() {
  5403. var me = this;
  5404. var chart = me.chart;
  5405. var chartArea = chart.chartArea;
  5406. var opts = chart.options;
  5407. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  5408. chart.outerRadius = Math.max(minSize / 2, 0);
  5409. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  5410. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  5411. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  5412. me.innerRadius = me.outerRadius - chart.radiusLength;
  5413. },
  5414. updateElement: function(arc, index, reset) {
  5415. var me = this;
  5416. var chart = me.chart;
  5417. var dataset = me.getDataset();
  5418. var opts = chart.options;
  5419. var animationOpts = opts.animation;
  5420. var scale = chart.scale;
  5421. var labels = chart.data.labels;
  5422. var centerX = scale.xCenter;
  5423. var centerY = scale.yCenter;
  5424. // var negHalfPI = -0.5 * Math.PI;
  5425. var datasetStartAngle = opts.startAngle;
  5426. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5427. var startAngle = me._starts[index];
  5428. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  5429. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5430. var options = arc._options || {};
  5431. helpers$1.extend(arc, {
  5432. // Utility
  5433. _datasetIndex: me.index,
  5434. _index: index,
  5435. _scale: scale,
  5436. // Desired view properties
  5437. _model: {
  5438. backgroundColor: options.backgroundColor,
  5439. borderColor: options.borderColor,
  5440. borderWidth: options.borderWidth,
  5441. borderAlign: options.borderAlign,
  5442. x: centerX,
  5443. y: centerY,
  5444. innerRadius: 0,
  5445. outerRadius: reset ? resetRadius : distance,
  5446. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  5447. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  5448. label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
  5449. }
  5450. });
  5451. arc.pivot();
  5452. },
  5453. countVisibleElements: function() {
  5454. var dataset = this.getDataset();
  5455. var meta = this.getMeta();
  5456. var count = 0;
  5457. helpers$1.each(meta.data, function(element, index) {
  5458. if (!isNaN(dataset.data[index]) && !element.hidden) {
  5459. count++;
  5460. }
  5461. });
  5462. return count;
  5463. },
  5464. /**
  5465. * @protected
  5466. */
  5467. setHoverStyle: function(arc) {
  5468. var model = arc._model;
  5469. var options = arc._options;
  5470. var getHoverColor = helpers$1.getHoverColor;
  5471. var valueOrDefault = helpers$1.valueOrDefault;
  5472. arc.$previousStyle = {
  5473. backgroundColor: model.backgroundColor,
  5474. borderColor: model.borderColor,
  5475. borderWidth: model.borderWidth,
  5476. };
  5477. model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5478. model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
  5479. model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  5480. },
  5481. /**
  5482. * @private
  5483. */
  5484. _computeAngle: function(index) {
  5485. var me = this;
  5486. var count = this.getMeta().count;
  5487. var dataset = me.getDataset();
  5488. var meta = me.getMeta();
  5489. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  5490. return 0;
  5491. }
  5492. // Scriptable options
  5493. var context = {
  5494. chart: me.chart,
  5495. dataIndex: index,
  5496. dataset: dataset,
  5497. datasetIndex: me.index
  5498. };
  5499. return resolve$3([
  5500. me.chart.options.elements.arc.angle,
  5501. (2 * Math.PI) / count
  5502. ], context, index);
  5503. }
  5504. });
  5505. core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
  5506. core_defaults._set('pie', {
  5507. cutoutPercentage: 0
  5508. });
  5509. // Pie charts are Doughnut chart with different defaults
  5510. var controller_pie = controller_doughnut;
  5511. var valueOrDefault$7 = helpers$1.valueOrDefault;
  5512. core_defaults._set('radar', {
  5513. spanGaps: false,
  5514. scale: {
  5515. type: 'radialLinear'
  5516. },
  5517. elements: {
  5518. line: {
  5519. fill: 'start',
  5520. tension: 0 // no bezier in radar
  5521. }
  5522. }
  5523. });
  5524. var controller_radar = core_datasetController.extend({
  5525. datasetElementType: elements.Line,
  5526. dataElementType: elements.Point,
  5527. linkScales: helpers$1.noop,
  5528. /**
  5529. * @private
  5530. */
  5531. _datasetElementOptions: [
  5532. 'backgroundColor',
  5533. 'borderWidth',
  5534. 'borderColor',
  5535. 'borderCapStyle',
  5536. 'borderDash',
  5537. 'borderDashOffset',
  5538. 'borderJoinStyle',
  5539. 'fill'
  5540. ],
  5541. /**
  5542. * @private
  5543. */
  5544. _dataElementOptions: {
  5545. backgroundColor: 'pointBackgroundColor',
  5546. borderColor: 'pointBorderColor',
  5547. borderWidth: 'pointBorderWidth',
  5548. hitRadius: 'pointHitRadius',
  5549. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5550. hoverBorderColor: 'pointHoverBorderColor',
  5551. hoverBorderWidth: 'pointHoverBorderWidth',
  5552. hoverRadius: 'pointHoverRadius',
  5553. pointStyle: 'pointStyle',
  5554. radius: 'pointRadius',
  5555. rotation: 'pointRotation'
  5556. },
  5557. /**
  5558. * @private
  5559. */
  5560. _getIndexScaleId: function() {
  5561. return this.chart.scale.id;
  5562. },
  5563. /**
  5564. * @private
  5565. */
  5566. _getValueScaleId: function() {
  5567. return this.chart.scale.id;
  5568. },
  5569. update: function(reset) {
  5570. var me = this;
  5571. var meta = me.getMeta();
  5572. var line = meta.dataset;
  5573. var points = meta.data || [];
  5574. var scale = me.chart.scale;
  5575. var config = me._config;
  5576. var i, ilen;
  5577. // Compatibility: If the properties are defined with only the old name, use those values
  5578. if (config.tension !== undefined && config.lineTension === undefined) {
  5579. config.lineTension = config.tension;
  5580. }
  5581. // Utility
  5582. line._scale = scale;
  5583. line._datasetIndex = me.index;
  5584. // Data
  5585. line._children = points;
  5586. line._loop = true;
  5587. // Model
  5588. line._model = me._resolveDatasetElementOptions(line);
  5589. line.pivot();
  5590. // Update Points
  5591. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5592. me.updateElement(points[i], i, reset);
  5593. }
  5594. // Update bezier control points
  5595. me.updateBezierControlPoints();
  5596. // Now pivot the point for animation
  5597. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5598. points[i].pivot();
  5599. }
  5600. },
  5601. updateElement: function(point, index, reset) {
  5602. var me = this;
  5603. var custom = point.custom || {};
  5604. var dataset = me.getDataset();
  5605. var scale = me.chart.scale;
  5606. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  5607. var options = me._resolveDataElementOptions(point, index);
  5608. var lineModel = me.getMeta().dataset._model;
  5609. var x = reset ? scale.xCenter : pointPosition.x;
  5610. var y = reset ? scale.yCenter : pointPosition.y;
  5611. // Utility
  5612. point._scale = scale;
  5613. point._options = options;
  5614. point._datasetIndex = me.index;
  5615. point._index = index;
  5616. // Desired view properties
  5617. point._model = {
  5618. x: x, // value not used in dataset scale, but we want a consistent API between scales
  5619. y: y,
  5620. skip: custom.skip || isNaN(x) || isNaN(y),
  5621. // Appearance
  5622. radius: options.radius,
  5623. pointStyle: options.pointStyle,
  5624. rotation: options.rotation,
  5625. backgroundColor: options.backgroundColor,
  5626. borderColor: options.borderColor,
  5627. borderWidth: options.borderWidth,
  5628. tension: valueOrDefault$7(custom.tension, lineModel ? lineModel.tension : 0),
  5629. // Tooltip
  5630. hitRadius: options.hitRadius
  5631. };
  5632. },
  5633. /**
  5634. * @private
  5635. */
  5636. _resolveDatasetElementOptions: function() {
  5637. var me = this;
  5638. var config = me._config;
  5639. var options = me.chart.options;
  5640. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5641. values.spanGaps = valueOrDefault$7(config.spanGaps, options.spanGaps);
  5642. values.tension = valueOrDefault$7(config.lineTension, options.elements.line.tension);
  5643. return values;
  5644. },
  5645. updateBezierControlPoints: function() {
  5646. var me = this;
  5647. var meta = me.getMeta();
  5648. var area = me.chart.chartArea;
  5649. var points = meta.data || [];
  5650. var i, ilen, model, controlPoints;
  5651. // Only consider points that are drawn in case the spanGaps option is used
  5652. if (meta.dataset._model.spanGaps) {
  5653. points = points.filter(function(pt) {
  5654. return !pt._model.skip;
  5655. });
  5656. }
  5657. function capControlPoint(pt, min, max) {
  5658. return Math.max(Math.min(pt, max), min);
  5659. }
  5660. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5661. model = points[i]._model;
  5662. controlPoints = helpers$1.splineCurve(
  5663. helpers$1.previousItem(points, i, true)._model,
  5664. model,
  5665. helpers$1.nextItem(points, i, true)._model,
  5666. model.tension
  5667. );
  5668. // Prevent the bezier going outside of the bounds of the graph
  5669. model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
  5670. model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
  5671. model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
  5672. model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
  5673. }
  5674. },
  5675. setHoverStyle: function(point) {
  5676. var model = point._model;
  5677. var options = point._options;
  5678. var getHoverColor = helpers$1.getHoverColor;
  5679. point.$previousStyle = {
  5680. backgroundColor: model.backgroundColor,
  5681. borderColor: model.borderColor,
  5682. borderWidth: model.borderWidth,
  5683. radius: model.radius
  5684. };
  5685. model.backgroundColor = valueOrDefault$7(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5686. model.borderColor = valueOrDefault$7(options.hoverBorderColor, getHoverColor(options.borderColor));
  5687. model.borderWidth = valueOrDefault$7(options.hoverBorderWidth, options.borderWidth);
  5688. model.radius = valueOrDefault$7(options.hoverRadius, options.radius);
  5689. }
  5690. });
  5691. core_defaults._set('scatter', {
  5692. hover: {
  5693. mode: 'single'
  5694. },
  5695. scales: {
  5696. xAxes: [{
  5697. id: 'x-axis-1', // need an ID so datasets can reference the scale
  5698. type: 'linear', // scatter should not use a category axis
  5699. position: 'bottom'
  5700. }],
  5701. yAxes: [{
  5702. id: 'y-axis-1',
  5703. type: 'linear',
  5704. position: 'left'
  5705. }]
  5706. },
  5707. tooltips: {
  5708. callbacks: {
  5709. title: function() {
  5710. return ''; // doesn't make sense for scatter since data are formatted as a point
  5711. },
  5712. label: function(item) {
  5713. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  5714. }
  5715. }
  5716. }
  5717. });
  5718. core_defaults._set('global', {
  5719. datasets: {
  5720. scatter: {
  5721. showLine: false
  5722. }
  5723. }
  5724. });
  5725. // Scatter charts use line controllers
  5726. var controller_scatter = controller_line;
  5727. // NOTE export a map in which the key represents the controller type, not
  5728. // the class, and so must be CamelCase in order to be correctly retrieved
  5729. // by the controller in core.controller.js (`controllers[meta.type]`).
  5730. var controllers = {
  5731. bar: controller_bar,
  5732. bubble: controller_bubble,
  5733. doughnut: controller_doughnut,
  5734. horizontalBar: controller_horizontalBar,
  5735. line: controller_line,
  5736. polarArea: controller_polarArea,
  5737. pie: controller_pie,
  5738. radar: controller_radar,
  5739. scatter: controller_scatter
  5740. };
  5741. /**
  5742. * Helper function to get relative position for an event
  5743. * @param {Event|IEvent} event - The event to get the position for
  5744. * @param {Chart} chart - The chart
  5745. * @returns {object} the event position
  5746. */
  5747. function getRelativePosition(e, chart) {
  5748. if (e.native) {
  5749. return {
  5750. x: e.x,
  5751. y: e.y
  5752. };
  5753. }
  5754. return helpers$1.getRelativePosition(e, chart);
  5755. }
  5756. /**
  5757. * Helper function to traverse all of the visible elements in the chart
  5758. * @param {Chart} chart - the chart
  5759. * @param {function} handler - the callback to execute for each visible item
  5760. */
  5761. function parseVisibleItems(chart, handler) {
  5762. var metasets = chart._getSortedVisibleDatasetMetas();
  5763. var metadata, i, j, ilen, jlen, element;
  5764. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  5765. metadata = metasets[i].data;
  5766. for (j = 0, jlen = metadata.length; j < jlen; ++j) {
  5767. element = metadata[j];
  5768. if (!element._view.skip) {
  5769. handler(element);
  5770. }
  5771. }
  5772. }
  5773. }
  5774. /**
  5775. * Helper function to get the items that intersect the event position
  5776. * @param {ChartElement[]} items - elements to filter
  5777. * @param {object} position - the point to be nearest to
  5778. * @return {ChartElement[]} the nearest items
  5779. */
  5780. function getIntersectItems(chart, position) {
  5781. var elements = [];
  5782. parseVisibleItems(chart, function(element) {
  5783. if (element.inRange(position.x, position.y)) {
  5784. elements.push(element);
  5785. }
  5786. });
  5787. return elements;
  5788. }
  5789. /**
  5790. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  5791. * @param {Chart} chart - the chart to look at elements from
  5792. * @param {object} position - the point to be nearest to
  5793. * @param {boolean} intersect - if true, only consider items that intersect the position
  5794. * @param {function} distanceMetric - function to provide the distance between points
  5795. * @return {ChartElement[]} the nearest items
  5796. */
  5797. function getNearestItems(chart, position, intersect, distanceMetric) {
  5798. var minDistance = Number.POSITIVE_INFINITY;
  5799. var nearestItems = [];
  5800. parseVisibleItems(chart, function(element) {
  5801. if (intersect && !element.inRange(position.x, position.y)) {
  5802. return;
  5803. }
  5804. var center = element.getCenterPoint();
  5805. var distance = distanceMetric(position, center);
  5806. if (distance < minDistance) {
  5807. nearestItems = [element];
  5808. minDistance = distance;
  5809. } else if (distance === minDistance) {
  5810. // Can have multiple items at the same distance in which case we sort by size
  5811. nearestItems.push(element);
  5812. }
  5813. });
  5814. return nearestItems;
  5815. }
  5816. /**
  5817. * Get a distance metric function for two points based on the
  5818. * axis mode setting
  5819. * @param {string} axis - the axis mode. x|y|xy
  5820. */
  5821. function getDistanceMetricForAxis(axis) {
  5822. var useX = axis.indexOf('x') !== -1;
  5823. var useY = axis.indexOf('y') !== -1;
  5824. return function(pt1, pt2) {
  5825. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  5826. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  5827. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  5828. };
  5829. }
  5830. function indexMode(chart, e, options) {
  5831. var position = getRelativePosition(e, chart);
  5832. // Default axis for index mode is 'x' to match old behaviour
  5833. options.axis = options.axis || 'x';
  5834. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5835. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5836. var elements = [];
  5837. if (!items.length) {
  5838. return [];
  5839. }
  5840. chart._getSortedVisibleDatasetMetas().forEach(function(meta) {
  5841. var element = meta.data[items[0]._index];
  5842. // don't count items that are skipped (null data)
  5843. if (element && !element._view.skip) {
  5844. elements.push(element);
  5845. }
  5846. });
  5847. return elements;
  5848. }
  5849. /**
  5850. * @interface IInteractionOptions
  5851. */
  5852. /**
  5853. * If true, only consider items that intersect the point
  5854. * @name IInterfaceOptions#boolean
  5855. * @type Boolean
  5856. */
  5857. /**
  5858. * Contains interaction related functions
  5859. * @namespace Chart.Interaction
  5860. */
  5861. var core_interaction = {
  5862. // Helper function for different modes
  5863. modes: {
  5864. single: function(chart, e) {
  5865. var position = getRelativePosition(e, chart);
  5866. var elements = [];
  5867. parseVisibleItems(chart, function(element) {
  5868. if (element.inRange(position.x, position.y)) {
  5869. elements.push(element);
  5870. return elements;
  5871. }
  5872. });
  5873. return elements.slice(0, 1);
  5874. },
  5875. /**
  5876. * @function Chart.Interaction.modes.label
  5877. * @deprecated since version 2.4.0
  5878. * @todo remove at version 3
  5879. * @private
  5880. */
  5881. label: indexMode,
  5882. /**
  5883. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  5884. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  5885. * @function Chart.Interaction.modes.index
  5886. * @since v2.4.0
  5887. * @param {Chart} chart - the chart we are returning items from
  5888. * @param {Event} e - the event we are find things at
  5889. * @param {IInteractionOptions} options - options to use during interaction
  5890. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5891. */
  5892. index: indexMode,
  5893. /**
  5894. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  5895. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  5896. * @function Chart.Interaction.modes.dataset
  5897. * @param {Chart} chart - the chart we are returning items from
  5898. * @param {Event} e - the event we are find things at
  5899. * @param {IInteractionOptions} options - options to use during interaction
  5900. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5901. */
  5902. dataset: function(chart, e, options) {
  5903. var position = getRelativePosition(e, chart);
  5904. options.axis = options.axis || 'xy';
  5905. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5906. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5907. if (items.length > 0) {
  5908. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  5909. }
  5910. return items;
  5911. },
  5912. /**
  5913. * @function Chart.Interaction.modes.x-axis
  5914. * @deprecated since version 2.4.0. Use index mode and intersect == true
  5915. * @todo remove at version 3
  5916. * @private
  5917. */
  5918. 'x-axis': function(chart, e) {
  5919. return indexMode(chart, e, {intersect: false});
  5920. },
  5921. /**
  5922. * Point mode returns all elements that hit test based on the event position
  5923. * of the event
  5924. * @function Chart.Interaction.modes.intersect
  5925. * @param {Chart} chart - the chart we are returning items from
  5926. * @param {Event} e - the event we are find things at
  5927. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5928. */
  5929. point: function(chart, e) {
  5930. var position = getRelativePosition(e, chart);
  5931. return getIntersectItems(chart, position);
  5932. },
  5933. /**
  5934. * nearest mode returns the element closest to the point
  5935. * @function Chart.Interaction.modes.intersect
  5936. * @param {Chart} chart - the chart we are returning items from
  5937. * @param {Event} e - the event we are find things at
  5938. * @param {IInteractionOptions} options - options to use
  5939. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5940. */
  5941. nearest: function(chart, e, options) {
  5942. var position = getRelativePosition(e, chart);
  5943. options.axis = options.axis || 'xy';
  5944. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5945. return getNearestItems(chart, position, options.intersect, distanceMetric);
  5946. },
  5947. /**
  5948. * x mode returns the elements that hit-test at the current x coordinate
  5949. * @function Chart.Interaction.modes.x
  5950. * @param {Chart} chart - the chart we are returning items from
  5951. * @param {Event} e - the event we are find things at
  5952. * @param {IInteractionOptions} options - options to use
  5953. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5954. */
  5955. x: function(chart, e, options) {
  5956. var position = getRelativePosition(e, chart);
  5957. var items = [];
  5958. var intersectsItem = false;
  5959. parseVisibleItems(chart, function(element) {
  5960. if (element.inXRange(position.x)) {
  5961. items.push(element);
  5962. }
  5963. if (element.inRange(position.x, position.y)) {
  5964. intersectsItem = true;
  5965. }
  5966. });
  5967. // If we want to trigger on an intersect and we don't have any items
  5968. // that intersect the position, return nothing
  5969. if (options.intersect && !intersectsItem) {
  5970. items = [];
  5971. }
  5972. return items;
  5973. },
  5974. /**
  5975. * y mode returns the elements that hit-test at the current y coordinate
  5976. * @function Chart.Interaction.modes.y
  5977. * @param {Chart} chart - the chart we are returning items from
  5978. * @param {Event} e - the event we are find things at
  5979. * @param {IInteractionOptions} options - options to use
  5980. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5981. */
  5982. y: function(chart, e, options) {
  5983. var position = getRelativePosition(e, chart);
  5984. var items = [];
  5985. var intersectsItem = false;
  5986. parseVisibleItems(chart, function(element) {
  5987. if (element.inYRange(position.y)) {
  5988. items.push(element);
  5989. }
  5990. if (element.inRange(position.x, position.y)) {
  5991. intersectsItem = true;
  5992. }
  5993. });
  5994. // If we want to trigger on an intersect and we don't have any items
  5995. // that intersect the position, return nothing
  5996. if (options.intersect && !intersectsItem) {
  5997. items = [];
  5998. }
  5999. return items;
  6000. }
  6001. }
  6002. };
  6003. var extend = helpers$1.extend;
  6004. function filterByPosition(array, position) {
  6005. return helpers$1.where(array, function(v) {
  6006. return v.pos === position;
  6007. });
  6008. }
  6009. function sortByWeight(array, reverse) {
  6010. return array.sort(function(a, b) {
  6011. var v0 = reverse ? b : a;
  6012. var v1 = reverse ? a : b;
  6013. return v0.weight === v1.weight ?
  6014. v0.index - v1.index :
  6015. v0.weight - v1.weight;
  6016. });
  6017. }
  6018. function wrapBoxes(boxes) {
  6019. var layoutBoxes = [];
  6020. var i, ilen, box;
  6021. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  6022. box = boxes[i];
  6023. layoutBoxes.push({
  6024. index: i,
  6025. box: box,
  6026. pos: box.position,
  6027. horizontal: box.isHorizontal(),
  6028. weight: box.weight
  6029. });
  6030. }
  6031. return layoutBoxes;
  6032. }
  6033. function setLayoutDims(layouts, params) {
  6034. var i, ilen, layout;
  6035. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  6036. layout = layouts[i];
  6037. // store width used instead of chartArea.w in fitBoxes
  6038. layout.width = layout.horizontal
  6039. ? layout.box.fullWidth && params.availableWidth
  6040. : params.vBoxMaxWidth;
  6041. // store height used instead of chartArea.h in fitBoxes
  6042. layout.height = layout.horizontal && params.hBoxMaxHeight;
  6043. }
  6044. }
  6045. function buildLayoutBoxes(boxes) {
  6046. var layoutBoxes = wrapBoxes(boxes);
  6047. var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  6048. var right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  6049. var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  6050. var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  6051. return {
  6052. leftAndTop: left.concat(top),
  6053. rightAndBottom: right.concat(bottom),
  6054. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  6055. vertical: left.concat(right),
  6056. horizontal: top.concat(bottom)
  6057. };
  6058. }
  6059. function getCombinedMax(maxPadding, chartArea, a, b) {
  6060. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  6061. }
  6062. function updateDims(chartArea, params, layout) {
  6063. var box = layout.box;
  6064. var maxPadding = chartArea.maxPadding;
  6065. var newWidth, newHeight;
  6066. if (layout.size) {
  6067. // this layout was already counted for, lets first reduce old size
  6068. chartArea[layout.pos] -= layout.size;
  6069. }
  6070. layout.size = layout.horizontal ? box.height : box.width;
  6071. chartArea[layout.pos] += layout.size;
  6072. if (box.getPadding) {
  6073. var boxPadding = box.getPadding();
  6074. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  6075. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  6076. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  6077. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  6078. }
  6079. newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right');
  6080. newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom');
  6081. if (newWidth !== chartArea.w || newHeight !== chartArea.h) {
  6082. chartArea.w = newWidth;
  6083. chartArea.h = newHeight;
  6084. // return true if chart area changed in layout's direction
  6085. return layout.horizontal ? newWidth !== chartArea.w : newHeight !== chartArea.h;
  6086. }
  6087. }
  6088. function handleMaxPadding(chartArea) {
  6089. var maxPadding = chartArea.maxPadding;
  6090. function updatePos(pos) {
  6091. var change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  6092. chartArea[pos] += change;
  6093. return change;
  6094. }
  6095. chartArea.y += updatePos('top');
  6096. chartArea.x += updatePos('left');
  6097. updatePos('right');
  6098. updatePos('bottom');
  6099. }
  6100. function getMargins(horizontal, chartArea) {
  6101. var maxPadding = chartArea.maxPadding;
  6102. function marginForPositions(positions) {
  6103. var margin = {left: 0, top: 0, right: 0, bottom: 0};
  6104. positions.forEach(function(pos) {
  6105. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  6106. });
  6107. return margin;
  6108. }
  6109. return horizontal
  6110. ? marginForPositions(['left', 'right'])
  6111. : marginForPositions(['top', 'bottom']);
  6112. }
  6113. function fitBoxes(boxes, chartArea, params) {
  6114. var refitBoxes = [];
  6115. var i, ilen, layout, box, refit, changed;
  6116. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6117. layout = boxes[i];
  6118. box = layout.box;
  6119. box.update(
  6120. layout.width || chartArea.w,
  6121. layout.height || chartArea.h,
  6122. getMargins(layout.horizontal, chartArea)
  6123. );
  6124. if (updateDims(chartArea, params, layout)) {
  6125. changed = true;
  6126. if (refitBoxes.length) {
  6127. // Dimensions changed and there were non full width boxes before this
  6128. // -> we have to refit those
  6129. refit = true;
  6130. }
  6131. }
  6132. if (!box.fullWidth) { // fullWidth boxes don't need to be re-fitted in any case
  6133. refitBoxes.push(layout);
  6134. }
  6135. }
  6136. return refit ? fitBoxes(refitBoxes, chartArea, params) || changed : changed;
  6137. }
  6138. function placeBoxes(boxes, chartArea, params) {
  6139. var userPadding = params.padding;
  6140. var x = chartArea.x;
  6141. var y = chartArea.y;
  6142. var i, ilen, layout, box;
  6143. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6144. layout = boxes[i];
  6145. box = layout.box;
  6146. if (layout.horizontal) {
  6147. box.left = box.fullWidth ? userPadding.left : chartArea.left;
  6148. box.right = box.fullWidth ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;
  6149. box.top = y;
  6150. box.bottom = y + box.height;
  6151. box.width = box.right - box.left;
  6152. y = box.bottom;
  6153. } else {
  6154. box.left = x;
  6155. box.right = x + box.width;
  6156. box.top = chartArea.top;
  6157. box.bottom = chartArea.top + chartArea.h;
  6158. box.height = box.bottom - box.top;
  6159. x = box.right;
  6160. }
  6161. }
  6162. chartArea.x = x;
  6163. chartArea.y = y;
  6164. }
  6165. core_defaults._set('global', {
  6166. layout: {
  6167. padding: {
  6168. top: 0,
  6169. right: 0,
  6170. bottom: 0,
  6171. left: 0
  6172. }
  6173. }
  6174. });
  6175. /**
  6176. * @interface ILayoutItem
  6177. * @prop {string} position - The position of the item in the chart layout. Possible values are
  6178. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  6179. * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  6180. * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  6181. * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  6182. * @prop {function} update - Takes two parameters: width and height. Returns size of item
  6183. * @prop {function} getPadding - Returns an object with padding on the edges
  6184. * @prop {number} width - Width of item. Must be valid after update()
  6185. * @prop {number} height - Height of item. Must be valid after update()
  6186. * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
  6187. * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
  6188. * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
  6189. * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  6190. */
  6191. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  6192. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  6193. // It is this service's responsibility of carrying out that layout.
  6194. var core_layouts = {
  6195. defaults: {},
  6196. /**
  6197. * Register a box to a chart.
  6198. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  6199. * @param {Chart} chart - the chart to use
  6200. * @param {ILayoutItem} item - the item to add to be layed out
  6201. */
  6202. addBox: function(chart, item) {
  6203. if (!chart.boxes) {
  6204. chart.boxes = [];
  6205. }
  6206. // initialize item with default values
  6207. item.fullWidth = item.fullWidth || false;
  6208. item.position = item.position || 'top';
  6209. item.weight = item.weight || 0;
  6210. item._layers = item._layers || function() {
  6211. return [{
  6212. z: 0,
  6213. draw: function() {
  6214. item.draw.apply(item, arguments);
  6215. }
  6216. }];
  6217. };
  6218. chart.boxes.push(item);
  6219. },
  6220. /**
  6221. * Remove a layoutItem from a chart
  6222. * @param {Chart} chart - the chart to remove the box from
  6223. * @param {ILayoutItem} layoutItem - the item to remove from the layout
  6224. */
  6225. removeBox: function(chart, layoutItem) {
  6226. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  6227. if (index !== -1) {
  6228. chart.boxes.splice(index, 1);
  6229. }
  6230. },
  6231. /**
  6232. * Sets (or updates) options on the given `item`.
  6233. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  6234. * @param {ILayoutItem} item - the item to configure with the given options
  6235. * @param {object} options - the new item options.
  6236. */
  6237. configure: function(chart, item, options) {
  6238. var props = ['fullWidth', 'position', 'weight'];
  6239. var ilen = props.length;
  6240. var i = 0;
  6241. var prop;
  6242. for (; i < ilen; ++i) {
  6243. prop = props[i];
  6244. if (options.hasOwnProperty(prop)) {
  6245. item[prop] = options[prop];
  6246. }
  6247. }
  6248. },
  6249. /**
  6250. * Fits boxes of the given chart into the given size by having each box measure itself
  6251. * then running a fitting algorithm
  6252. * @param {Chart} chart - the chart
  6253. * @param {number} width - the width to fit into
  6254. * @param {number} height - the height to fit into
  6255. */
  6256. update: function(chart, width, height) {
  6257. if (!chart) {
  6258. return;
  6259. }
  6260. var layoutOptions = chart.options.layout || {};
  6261. var padding = helpers$1.options.toPadding(layoutOptions.padding);
  6262. var availableWidth = width - padding.width;
  6263. var availableHeight = height - padding.height;
  6264. var boxes = buildLayoutBoxes(chart.boxes);
  6265. var verticalBoxes = boxes.vertical;
  6266. var horizontalBoxes = boxes.horizontal;
  6267. // Essentially we now have any number of boxes on each of the 4 sides.
  6268. // Our canvas looks like the following.
  6269. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  6270. // B1 is the bottom axis
  6271. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  6272. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  6273. // an error will be thrown.
  6274. //
  6275. // |----------------------------------------------------|
  6276. // | T1 (Full Width) |
  6277. // |----------------------------------------------------|
  6278. // | | | T2 | |
  6279. // | |----|-------------------------------------|----|
  6280. // | | | C1 | | C2 | |
  6281. // | | |----| |----| |
  6282. // | | | | |
  6283. // | L1 | L2 | ChartArea (C0) | R1 |
  6284. // | | | | |
  6285. // | | |----| |----| |
  6286. // | | | C3 | | C4 | |
  6287. // | |----|-------------------------------------|----|
  6288. // | | | B1 | |
  6289. // |----------------------------------------------------|
  6290. // | B2 (Full Width) |
  6291. // |----------------------------------------------------|
  6292. //
  6293. var params = Object.freeze({
  6294. outerWidth: width,
  6295. outerHeight: height,
  6296. padding: padding,
  6297. availableWidth: availableWidth,
  6298. vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length,
  6299. hBoxMaxHeight: availableHeight / 2
  6300. });
  6301. var chartArea = extend({
  6302. maxPadding: extend({}, padding),
  6303. w: availableWidth,
  6304. h: availableHeight,
  6305. x: padding.left,
  6306. y: padding.top
  6307. }, padding);
  6308. setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  6309. // First fit vertical boxes
  6310. fitBoxes(verticalBoxes, chartArea, params);
  6311. // Then fit horizontal boxes
  6312. if (fitBoxes(horizontalBoxes, chartArea, params)) {
  6313. // if the area changed, re-fit vertical boxes
  6314. fitBoxes(verticalBoxes, chartArea, params);
  6315. }
  6316. handleMaxPadding(chartArea);
  6317. // Finally place the boxes to correct coordinates
  6318. placeBoxes(boxes.leftAndTop, chartArea, params);
  6319. // Move to opposite side of chart
  6320. chartArea.x += chartArea.w;
  6321. chartArea.y += chartArea.h;
  6322. placeBoxes(boxes.rightAndBottom, chartArea, params);
  6323. chart.chartArea = {
  6324. left: chartArea.left,
  6325. top: chartArea.top,
  6326. right: chartArea.left + chartArea.w,
  6327. bottom: chartArea.top + chartArea.h
  6328. };
  6329. // Finally update boxes in chartArea (radial scale for example)
  6330. helpers$1.each(boxes.chartArea, function(layout) {
  6331. var box = layout.box;
  6332. extend(box, chart.chartArea);
  6333. box.update(chartArea.w, chartArea.h);
  6334. });
  6335. }
  6336. };
  6337. /**
  6338. * Platform fallback implementation (minimal).
  6339. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  6340. */
  6341. var platform_basic = {
  6342. acquireContext: function(item) {
  6343. if (item && item.canvas) {
  6344. // Support for any object associated to a canvas (including a context2d)
  6345. item = item.canvas;
  6346. }
  6347. return item && item.getContext('2d') || null;
  6348. }
  6349. };
  6350. var platform_dom = "/*\n * DOM element rendering detection\n * https://davidwalsh.name/detect-node-insertion\n */\n@keyframes chartjs-render-animation {\n\tfrom { opacity: 0.99; }\n\tto { opacity: 1; }\n}\n\n.chartjs-render-monitor {\n\tanimation: chartjs-render-animation 0.001s;\n}\n\n/*\n * DOM element resizing detection\n * https://github.com/marcj/css-element-queries\n */\n.chartjs-size-monitor,\n.chartjs-size-monitor-expand,\n.chartjs-size-monitor-shrink {\n\tposition: absolute;\n\tdirection: ltr;\n\tleft: 0;\n\ttop: 0;\n\tright: 0;\n\tbottom: 0;\n\toverflow: hidden;\n\tpointer-events: none;\n\tvisibility: hidden;\n\tz-index: -1;\n}\n\n.chartjs-size-monitor-expand > div {\n\tposition: absolute;\n\twidth: 1000000px;\n\theight: 1000000px;\n\tleft: 0;\n\ttop: 0;\n}\n\n.chartjs-size-monitor-shrink > div {\n\tposition: absolute;\n\twidth: 200%;\n\theight: 200%;\n\tleft: 0;\n\ttop: 0;\n}\n";
  6351. var platform_dom$1 = /*#__PURE__*/Object.freeze({
  6352. __proto__: null,
  6353. 'default': platform_dom
  6354. });
  6355. var stylesheet = getCjsExportFromNamespace(platform_dom$1);
  6356. var EXPANDO_KEY = '$chartjs';
  6357. var CSS_PREFIX = 'chartjs-';
  6358. var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';
  6359. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  6360. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  6361. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  6362. /**
  6363. * DOM event types -> Chart.js event types.
  6364. * Note: only events with different types are mapped.
  6365. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  6366. */
  6367. var EVENT_TYPES = {
  6368. touchstart: 'mousedown',
  6369. touchmove: 'mousemove',
  6370. touchend: 'mouseup',
  6371. pointerenter: 'mouseenter',
  6372. pointerdown: 'mousedown',
  6373. pointermove: 'mousemove',
  6374. pointerup: 'mouseup',
  6375. pointerleave: 'mouseout',
  6376. pointerout: 'mouseout'
  6377. };
  6378. /**
  6379. * The "used" size is the final value of a dimension property after all calculations have
  6380. * been performed. This method uses the computed style of `element` but returns undefined
  6381. * if the computed style is not expressed in pixels. That can happen in some cases where
  6382. * `element` has a size relative to its parent and this last one is not yet displayed,
  6383. * for example because of `display: none` on a parent node.
  6384. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  6385. * @returns {number} Size in pixels or undefined if unknown.
  6386. */
  6387. function readUsedSize(element, property) {
  6388. var value = helpers$1.getStyle(element, property);
  6389. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  6390. return matches ? Number(matches[1]) : undefined;
  6391. }
  6392. /**
  6393. * Initializes the canvas style and render size without modifying the canvas display size,
  6394. * since responsiveness is handled by the controller.resize() method. The config is used
  6395. * to determine the aspect ratio to apply in case no explicit height has been specified.
  6396. */
  6397. function initCanvas(canvas, config) {
  6398. var style = canvas.style;
  6399. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  6400. // returns null or '' if no explicit value has been set to the canvas attribute.
  6401. var renderHeight = canvas.getAttribute('height');
  6402. var renderWidth = canvas.getAttribute('width');
  6403. // Chart.js modifies some canvas values that we want to restore on destroy
  6404. canvas[EXPANDO_KEY] = {
  6405. initial: {
  6406. height: renderHeight,
  6407. width: renderWidth,
  6408. style: {
  6409. display: style.display,
  6410. height: style.height,
  6411. width: style.width
  6412. }
  6413. }
  6414. };
  6415. // Force canvas to display as block to avoid extra space caused by inline
  6416. // elements, which would interfere with the responsive resize process.
  6417. // https://github.com/chartjs/Chart.js/issues/2538
  6418. style.display = style.display || 'block';
  6419. if (renderWidth === null || renderWidth === '') {
  6420. var displayWidth = readUsedSize(canvas, 'width');
  6421. if (displayWidth !== undefined) {
  6422. canvas.width = displayWidth;
  6423. }
  6424. }
  6425. if (renderHeight === null || renderHeight === '') {
  6426. if (canvas.style.height === '') {
  6427. // If no explicit render height and style height, let's apply the aspect ratio,
  6428. // which one can be specified by the user but also by charts as default option
  6429. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  6430. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  6431. } else {
  6432. var displayHeight = readUsedSize(canvas, 'height');
  6433. if (displayWidth !== undefined) {
  6434. canvas.height = displayHeight;
  6435. }
  6436. }
  6437. }
  6438. return canvas;
  6439. }
  6440. /**
  6441. * Detects support for options object argument in addEventListener.
  6442. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  6443. * @private
  6444. */
  6445. var supportsEventListenerOptions = (function() {
  6446. var supports = false;
  6447. try {
  6448. var options = Object.defineProperty({}, 'passive', {
  6449. // eslint-disable-next-line getter-return
  6450. get: function() {
  6451. supports = true;
  6452. }
  6453. });
  6454. window.addEventListener('e', null, options);
  6455. } catch (e) {
  6456. // continue regardless of error
  6457. }
  6458. return supports;
  6459. }());
  6460. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  6461. // https://github.com/chartjs/Chart.js/issues/4287
  6462. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  6463. function addListener(node, type, listener) {
  6464. node.addEventListener(type, listener, eventListenerOptions);
  6465. }
  6466. function removeListener(node, type, listener) {
  6467. node.removeEventListener(type, listener, eventListenerOptions);
  6468. }
  6469. function createEvent(type, chart, x, y, nativeEvent) {
  6470. return {
  6471. type: type,
  6472. chart: chart,
  6473. native: nativeEvent || null,
  6474. x: x !== undefined ? x : null,
  6475. y: y !== undefined ? y : null,
  6476. };
  6477. }
  6478. function fromNativeEvent(event, chart) {
  6479. var type = EVENT_TYPES[event.type] || event.type;
  6480. var pos = helpers$1.getRelativePosition(event, chart);
  6481. return createEvent(type, chart, pos.x, pos.y, event);
  6482. }
  6483. function throttled(fn, thisArg) {
  6484. var ticking = false;
  6485. var args = [];
  6486. return function() {
  6487. args = Array.prototype.slice.call(arguments);
  6488. thisArg = thisArg || this;
  6489. if (!ticking) {
  6490. ticking = true;
  6491. helpers$1.requestAnimFrame.call(window, function() {
  6492. ticking = false;
  6493. fn.apply(thisArg, args);
  6494. });
  6495. }
  6496. };
  6497. }
  6498. function createDiv(cls) {
  6499. var el = document.createElement('div');
  6500. el.className = cls || '';
  6501. return el;
  6502. }
  6503. // Implementation based on https://github.com/marcj/css-element-queries
  6504. function createResizer(handler) {
  6505. var maxSize = 1000000;
  6506. // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
  6507. // https://github.com/chartjs/Chart.js/issues/5902
  6508. var resizer = createDiv(CSS_SIZE_MONITOR);
  6509. var expand = createDiv(CSS_SIZE_MONITOR + '-expand');
  6510. var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');
  6511. expand.appendChild(createDiv());
  6512. shrink.appendChild(createDiv());
  6513. resizer.appendChild(expand);
  6514. resizer.appendChild(shrink);
  6515. resizer._reset = function() {
  6516. expand.scrollLeft = maxSize;
  6517. expand.scrollTop = maxSize;
  6518. shrink.scrollLeft = maxSize;
  6519. shrink.scrollTop = maxSize;
  6520. };
  6521. var onScroll = function() {
  6522. resizer._reset();
  6523. handler();
  6524. };
  6525. addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  6526. addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  6527. return resizer;
  6528. }
  6529. // https://davidwalsh.name/detect-node-insertion
  6530. function watchForRender(node, handler) {
  6531. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6532. var proxy = expando.renderProxy = function(e) {
  6533. if (e.animationName === CSS_RENDER_ANIMATION) {
  6534. handler();
  6535. }
  6536. };
  6537. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  6538. addListener(node, type, proxy);
  6539. });
  6540. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  6541. // is removed then added back immediately (same animation frame?). Accessing the
  6542. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  6543. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  6544. // https://github.com/chartjs/Chart.js/issues/4737
  6545. expando.reflow = !!node.offsetParent;
  6546. node.classList.add(CSS_RENDER_MONITOR);
  6547. }
  6548. function unwatchForRender(node) {
  6549. var expando = node[EXPANDO_KEY] || {};
  6550. var proxy = expando.renderProxy;
  6551. if (proxy) {
  6552. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  6553. removeListener(node, type, proxy);
  6554. });
  6555. delete expando.renderProxy;
  6556. }
  6557. node.classList.remove(CSS_RENDER_MONITOR);
  6558. }
  6559. function addResizeListener(node, listener, chart) {
  6560. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6561. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  6562. var resizer = expando.resizer = createResizer(throttled(function() {
  6563. if (expando.resizer) {
  6564. var container = chart.options.maintainAspectRatio && node.parentNode;
  6565. var w = container ? container.clientWidth : 0;
  6566. listener(createEvent('resize', chart));
  6567. if (container && container.clientWidth < w && chart.canvas) {
  6568. // If the container size shrank during chart resize, let's assume
  6569. // scrollbar appeared. So we resize again with the scrollbar visible -
  6570. // effectively making chart smaller and the scrollbar hidden again.
  6571. // Because we are inside `throttled`, and currently `ticking`, scroll
  6572. // events are ignored during this whole 2 resize process.
  6573. // If we assumed wrong and something else happened, we are resizing
  6574. // twice in a frame (potential performance issue)
  6575. listener(createEvent('resize', chart));
  6576. }
  6577. }
  6578. }));
  6579. // The resizer needs to be attached to the node parent, so we first need to be
  6580. // sure that `node` is attached to the DOM before injecting the resizer element.
  6581. watchForRender(node, function() {
  6582. if (expando.resizer) {
  6583. var container = node.parentNode;
  6584. if (container && container !== resizer.parentNode) {
  6585. container.insertBefore(resizer, container.firstChild);
  6586. }
  6587. // The container size might have changed, let's reset the resizer state.
  6588. resizer._reset();
  6589. }
  6590. });
  6591. }
  6592. function removeResizeListener(node) {
  6593. var expando = node[EXPANDO_KEY] || {};
  6594. var resizer = expando.resizer;
  6595. delete expando.resizer;
  6596. unwatchForRender(node);
  6597. if (resizer && resizer.parentNode) {
  6598. resizer.parentNode.removeChild(resizer);
  6599. }
  6600. }
  6601. /**
  6602. * Injects CSS styles inline if the styles are not already present.
  6603. * @param {HTMLDocument|ShadowRoot} rootNode - the node to contain the <style>.
  6604. * @param {string} css - the CSS to be injected.
  6605. */
  6606. function injectCSS(rootNode, css) {
  6607. // https://stackoverflow.com/q/3922139
  6608. var expando = rootNode[EXPANDO_KEY] || (rootNode[EXPANDO_KEY] = {});
  6609. if (!expando.containsStyles) {
  6610. expando.containsStyles = true;
  6611. css = '/* Chart.js */\n' + css;
  6612. var style = document.createElement('style');
  6613. style.setAttribute('type', 'text/css');
  6614. style.appendChild(document.createTextNode(css));
  6615. rootNode.appendChild(style);
  6616. }
  6617. }
  6618. var platform_dom$2 = {
  6619. /**
  6620. * When `true`, prevents the automatic injection of the stylesheet required to
  6621. * correctly detect when the chart is added to the DOM and then resized. This
  6622. * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)
  6623. * to be manually imported to make this library compatible with any CSP.
  6624. * See https://github.com/chartjs/Chart.js/issues/5208
  6625. */
  6626. disableCSSInjection: false,
  6627. /**
  6628. * This property holds whether this platform is enabled for the current environment.
  6629. * Currently used by platform.js to select the proper implementation.
  6630. * @private
  6631. */
  6632. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  6633. /**
  6634. * Initializes resources that depend on platform options.
  6635. * @param {HTMLCanvasElement} canvas - The Canvas element.
  6636. * @private
  6637. */
  6638. _ensureLoaded: function(canvas) {
  6639. if (!this.disableCSSInjection) {
  6640. // If the canvas is in a shadow DOM, then the styles must also be inserted
  6641. // into the same shadow DOM.
  6642. // https://github.com/chartjs/Chart.js/issues/5763
  6643. var root = canvas.getRootNode ? canvas.getRootNode() : document;
  6644. var targetNode = root.host ? root : document.head;
  6645. injectCSS(targetNode, stylesheet);
  6646. }
  6647. },
  6648. acquireContext: function(item, config) {
  6649. if (typeof item === 'string') {
  6650. item = document.getElementById(item);
  6651. } else if (item.length) {
  6652. // Support for array based queries (such as jQuery)
  6653. item = item[0];
  6654. }
  6655. if (item && item.canvas) {
  6656. // Support for any object associated to a canvas (including a context2d)
  6657. item = item.canvas;
  6658. }
  6659. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  6660. // method, for example: https://github.com/kkapsner/CanvasBlocker
  6661. // https://github.com/chartjs/Chart.js/issues/2807
  6662. var context = item && item.getContext && item.getContext('2d');
  6663. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  6664. // inside an iframe or when running in a protected environment. We could guess the
  6665. // types from their toString() value but let's keep things flexible and assume it's
  6666. // a sufficient condition if the item has a context2D which has item as `canvas`.
  6667. // https://github.com/chartjs/Chart.js/issues/3887
  6668. // https://github.com/chartjs/Chart.js/issues/4102
  6669. // https://github.com/chartjs/Chart.js/issues/4152
  6670. if (context && context.canvas === item) {
  6671. // Load platform resources on first chart creation, to make it possible to
  6672. // import the library before setting platform options.
  6673. this._ensureLoaded(item);
  6674. initCanvas(item, config);
  6675. return context;
  6676. }
  6677. return null;
  6678. },
  6679. releaseContext: function(context) {
  6680. var canvas = context.canvas;
  6681. if (!canvas[EXPANDO_KEY]) {
  6682. return;
  6683. }
  6684. var initial = canvas[EXPANDO_KEY].initial;
  6685. ['height', 'width'].forEach(function(prop) {
  6686. var value = initial[prop];
  6687. if (helpers$1.isNullOrUndef(value)) {
  6688. canvas.removeAttribute(prop);
  6689. } else {
  6690. canvas.setAttribute(prop, value);
  6691. }
  6692. });
  6693. helpers$1.each(initial.style || {}, function(value, key) {
  6694. canvas.style[key] = value;
  6695. });
  6696. // The canvas render size might have been changed (and thus the state stack discarded),
  6697. // we can't use save() and restore() to restore the initial state. So make sure that at
  6698. // least the canvas context is reset to the default state by setting the canvas width.
  6699. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  6700. // eslint-disable-next-line no-self-assign
  6701. canvas.width = canvas.width;
  6702. delete canvas[EXPANDO_KEY];
  6703. },
  6704. addEventListener: function(chart, type, listener) {
  6705. var canvas = chart.canvas;
  6706. if (type === 'resize') {
  6707. // Note: the resize event is not supported on all browsers.
  6708. addResizeListener(canvas, listener, chart);
  6709. return;
  6710. }
  6711. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  6712. var proxies = expando.proxies || (expando.proxies = {});
  6713. var proxy = proxies[chart.id + '_' + type] = function(event) {
  6714. listener(fromNativeEvent(event, chart));
  6715. };
  6716. addListener(canvas, type, proxy);
  6717. },
  6718. removeEventListener: function(chart, type, listener) {
  6719. var canvas = chart.canvas;
  6720. if (type === 'resize') {
  6721. // Note: the resize event is not supported on all browsers.
  6722. removeResizeListener(canvas);
  6723. return;
  6724. }
  6725. var expando = listener[EXPANDO_KEY] || {};
  6726. var proxies = expando.proxies || {};
  6727. var proxy = proxies[chart.id + '_' + type];
  6728. if (!proxy) {
  6729. return;
  6730. }
  6731. removeListener(canvas, type, proxy);
  6732. }
  6733. };
  6734. // DEPRECATIONS
  6735. /**
  6736. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  6737. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6738. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  6739. * @function Chart.helpers.addEvent
  6740. * @deprecated since version 2.7.0
  6741. * @todo remove at version 3
  6742. * @private
  6743. */
  6744. helpers$1.addEvent = addListener;
  6745. /**
  6746. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  6747. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6748. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  6749. * @function Chart.helpers.removeEvent
  6750. * @deprecated since version 2.7.0
  6751. * @todo remove at version 3
  6752. * @private
  6753. */
  6754. helpers$1.removeEvent = removeListener;
  6755. // @TODO Make possible to select another platform at build time.
  6756. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;
  6757. /**
  6758. * @namespace Chart.platform
  6759. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  6760. * @since 2.4.0
  6761. */
  6762. var platform = helpers$1.extend({
  6763. /**
  6764. * @since 2.7.0
  6765. */
  6766. initialize: function() {},
  6767. /**
  6768. * Called at chart construction time, returns a context2d instance implementing
  6769. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  6770. * @param {*} item - The native item from which to acquire context (platform specific)
  6771. * @param {object} options - The chart options
  6772. * @returns {CanvasRenderingContext2D} context2d instance
  6773. */
  6774. acquireContext: function() {},
  6775. /**
  6776. * Called at chart destruction time, releases any resources associated to the context
  6777. * previously returned by the acquireContext() method.
  6778. * @param {CanvasRenderingContext2D} context - The context2d instance
  6779. * @returns {boolean} true if the method succeeded, else false
  6780. */
  6781. releaseContext: function() {},
  6782. /**
  6783. * Registers the specified listener on the given chart.
  6784. * @param {Chart} chart - Chart from which to listen for event
  6785. * @param {string} type - The ({@link IEvent}) type to listen for
  6786. * @param {function} listener - Receives a notification (an object that implements
  6787. * the {@link IEvent} interface) when an event of the specified type occurs.
  6788. */
  6789. addEventListener: function() {},
  6790. /**
  6791. * Removes the specified listener previously registered with addEventListener.
  6792. * @param {Chart} chart - Chart from which to remove the listener
  6793. * @param {string} type - The ({@link IEvent}) type to remove
  6794. * @param {function} listener - The listener function to remove from the event target.
  6795. */
  6796. removeEventListener: function() {}
  6797. }, implementation);
  6798. core_defaults._set('global', {
  6799. plugins: {}
  6800. });
  6801. /**
  6802. * The plugin service singleton
  6803. * @namespace Chart.plugins
  6804. * @since 2.1.0
  6805. */
  6806. var core_plugins = {
  6807. /**
  6808. * Globally registered plugins.
  6809. * @private
  6810. */
  6811. _plugins: [],
  6812. /**
  6813. * This identifier is used to invalidate the descriptors cache attached to each chart
  6814. * when a global plugin is registered or unregistered. In this case, the cache ID is
  6815. * incremented and descriptors are regenerated during following API calls.
  6816. * @private
  6817. */
  6818. _cacheId: 0,
  6819. /**
  6820. * Registers the given plugin(s) if not already registered.
  6821. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6822. */
  6823. register: function(plugins) {
  6824. var p = this._plugins;
  6825. ([]).concat(plugins).forEach(function(plugin) {
  6826. if (p.indexOf(plugin) === -1) {
  6827. p.push(plugin);
  6828. }
  6829. });
  6830. this._cacheId++;
  6831. },
  6832. /**
  6833. * Unregisters the given plugin(s) only if registered.
  6834. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6835. */
  6836. unregister: function(plugins) {
  6837. var p = this._plugins;
  6838. ([]).concat(plugins).forEach(function(plugin) {
  6839. var idx = p.indexOf(plugin);
  6840. if (idx !== -1) {
  6841. p.splice(idx, 1);
  6842. }
  6843. });
  6844. this._cacheId++;
  6845. },
  6846. /**
  6847. * Remove all registered plugins.
  6848. * @since 2.1.5
  6849. */
  6850. clear: function() {
  6851. this._plugins = [];
  6852. this._cacheId++;
  6853. },
  6854. /**
  6855. * Returns the number of registered plugins?
  6856. * @returns {number}
  6857. * @since 2.1.5
  6858. */
  6859. count: function() {
  6860. return this._plugins.length;
  6861. },
  6862. /**
  6863. * Returns all registered plugin instances.
  6864. * @returns {IPlugin[]} array of plugin objects.
  6865. * @since 2.1.5
  6866. */
  6867. getAll: function() {
  6868. return this._plugins;
  6869. },
  6870. /**
  6871. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  6872. * This method immediately returns as soon as a plugin explicitly returns false. The
  6873. * returned value can be used, for instance, to interrupt the current action.
  6874. * @param {Chart} chart - The chart instance for which plugins should be called.
  6875. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  6876. * @param {Array} [args] - Extra arguments to apply to the hook call.
  6877. * @returns {boolean} false if any of the plugins return false, else returns true.
  6878. */
  6879. notify: function(chart, hook, args) {
  6880. var descriptors = this.descriptors(chart);
  6881. var ilen = descriptors.length;
  6882. var i, descriptor, plugin, params, method;
  6883. for (i = 0; i < ilen; ++i) {
  6884. descriptor = descriptors[i];
  6885. plugin = descriptor.plugin;
  6886. method = plugin[hook];
  6887. if (typeof method === 'function') {
  6888. params = [chart].concat(args || []);
  6889. params.push(descriptor.options);
  6890. if (method.apply(plugin, params) === false) {
  6891. return false;
  6892. }
  6893. }
  6894. }
  6895. return true;
  6896. },
  6897. /**
  6898. * Returns descriptors of enabled plugins for the given chart.
  6899. * @returns {object[]} [{ plugin, options }]
  6900. * @private
  6901. */
  6902. descriptors: function(chart) {
  6903. var cache = chart.$plugins || (chart.$plugins = {});
  6904. if (cache.id === this._cacheId) {
  6905. return cache.descriptors;
  6906. }
  6907. var plugins = [];
  6908. var descriptors = [];
  6909. var config = (chart && chart.config) || {};
  6910. var options = (config.options && config.options.plugins) || {};
  6911. this._plugins.concat(config.plugins || []).forEach(function(plugin) {
  6912. var idx = plugins.indexOf(plugin);
  6913. if (idx !== -1) {
  6914. return;
  6915. }
  6916. var id = plugin.id;
  6917. var opts = options[id];
  6918. if (opts === false) {
  6919. return;
  6920. }
  6921. if (opts === true) {
  6922. opts = helpers$1.clone(core_defaults.global.plugins[id]);
  6923. }
  6924. plugins.push(plugin);
  6925. descriptors.push({
  6926. plugin: plugin,
  6927. options: opts || {}
  6928. });
  6929. });
  6930. cache.descriptors = descriptors;
  6931. cache.id = this._cacheId;
  6932. return descriptors;
  6933. },
  6934. /**
  6935. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  6936. * but in some cases, this reference can be changed by the user when updating options.
  6937. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  6938. * @private
  6939. */
  6940. _invalidate: function(chart) {
  6941. delete chart.$plugins;
  6942. }
  6943. };
  6944. var core_scaleService = {
  6945. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  6946. // use the new chart options to grab the correct scale
  6947. constructors: {},
  6948. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  6949. // old browsers
  6950. // Scale config defaults
  6951. defaults: {},
  6952. registerScaleType: function(type, scaleConstructor, scaleDefaults) {
  6953. this.constructors[type] = scaleConstructor;
  6954. this.defaults[type] = helpers$1.clone(scaleDefaults);
  6955. },
  6956. getScaleConstructor: function(type) {
  6957. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  6958. },
  6959. getScaleDefaults: function(type) {
  6960. // Return the scale defaults merged with the global settings so that we always use the latest ones
  6961. return this.defaults.hasOwnProperty(type) ? helpers$1.merge({}, [core_defaults.scale, this.defaults[type]]) : {};
  6962. },
  6963. updateScaleDefaults: function(type, additions) {
  6964. var me = this;
  6965. if (me.defaults.hasOwnProperty(type)) {
  6966. me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
  6967. }
  6968. },
  6969. addScalesToLayout: function(chart) {
  6970. // Adds each scale to the chart.boxes array to be sized accordingly
  6971. helpers$1.each(chart.scales, function(scale) {
  6972. // Set ILayoutItem parameters for backwards compatibility
  6973. scale.fullWidth = scale.options.fullWidth;
  6974. scale.position = scale.options.position;
  6975. scale.weight = scale.options.weight;
  6976. core_layouts.addBox(chart, scale);
  6977. });
  6978. }
  6979. };
  6980. var valueOrDefault$8 = helpers$1.valueOrDefault;
  6981. var getRtlHelper = helpers$1.rtl.getRtlAdapter;
  6982. core_defaults._set('global', {
  6983. tooltips: {
  6984. enabled: true,
  6985. custom: null,
  6986. mode: 'nearest',
  6987. position: 'average',
  6988. intersect: true,
  6989. backgroundColor: 'rgba(0,0,0,0.8)',
  6990. titleFontStyle: 'bold',
  6991. titleSpacing: 2,
  6992. titleMarginBottom: 6,
  6993. titleFontColor: '#fff',
  6994. titleAlign: 'left',
  6995. bodySpacing: 2,
  6996. bodyFontColor: '#fff',
  6997. bodyAlign: 'left',
  6998. footerFontStyle: 'bold',
  6999. footerSpacing: 2,
  7000. footerMarginTop: 6,
  7001. footerFontColor: '#fff',
  7002. footerAlign: 'left',
  7003. yPadding: 6,
  7004. xPadding: 6,
  7005. caretPadding: 2,
  7006. caretSize: 5,
  7007. cornerRadius: 6,
  7008. multiKeyBackground: '#fff',
  7009. displayColors: true,
  7010. borderColor: 'rgba(0,0,0,0)',
  7011. borderWidth: 0,
  7012. callbacks: {
  7013. // Args are: (tooltipItems, data)
  7014. beforeTitle: helpers$1.noop,
  7015. title: function(tooltipItems, data) {
  7016. var title = '';
  7017. var labels = data.labels;
  7018. var labelCount = labels ? labels.length : 0;
  7019. if (tooltipItems.length > 0) {
  7020. var item = tooltipItems[0];
  7021. if (item.label) {
  7022. title = item.label;
  7023. } else if (item.xLabel) {
  7024. title = item.xLabel;
  7025. } else if (labelCount > 0 && item.index < labelCount) {
  7026. title = labels[item.index];
  7027. }
  7028. }
  7029. return title;
  7030. },
  7031. afterTitle: helpers$1.noop,
  7032. // Args are: (tooltipItems, data)
  7033. beforeBody: helpers$1.noop,
  7034. // Args are: (tooltipItem, data)
  7035. beforeLabel: helpers$1.noop,
  7036. label: function(tooltipItem, data) {
  7037. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  7038. if (label) {
  7039. label += ': ';
  7040. }
  7041. if (!helpers$1.isNullOrUndef(tooltipItem.value)) {
  7042. label += tooltipItem.value;
  7043. } else {
  7044. label += tooltipItem.yLabel;
  7045. }
  7046. return label;
  7047. },
  7048. labelColor: function(tooltipItem, chart) {
  7049. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  7050. var activeElement = meta.data[tooltipItem.index];
  7051. var view = activeElement._view;
  7052. return {
  7053. borderColor: view.borderColor,
  7054. backgroundColor: view.backgroundColor
  7055. };
  7056. },
  7057. labelTextColor: function() {
  7058. return this._options.bodyFontColor;
  7059. },
  7060. afterLabel: helpers$1.noop,
  7061. // Args are: (tooltipItems, data)
  7062. afterBody: helpers$1.noop,
  7063. // Args are: (tooltipItems, data)
  7064. beforeFooter: helpers$1.noop,
  7065. footer: helpers$1.noop,
  7066. afterFooter: helpers$1.noop
  7067. }
  7068. }
  7069. });
  7070. var positioners = {
  7071. /**
  7072. * Average mode places the tooltip at the average position of the elements shown
  7073. * @function Chart.Tooltip.positioners.average
  7074. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  7075. * @returns {object} tooltip position
  7076. */
  7077. average: function(elements) {
  7078. if (!elements.length) {
  7079. return false;
  7080. }
  7081. var i, len;
  7082. var x = 0;
  7083. var y = 0;
  7084. var count = 0;
  7085. for (i = 0, len = elements.length; i < len; ++i) {
  7086. var el = elements[i];
  7087. if (el && el.hasValue()) {
  7088. var pos = el.tooltipPosition();
  7089. x += pos.x;
  7090. y += pos.y;
  7091. ++count;
  7092. }
  7093. }
  7094. return {
  7095. x: x / count,
  7096. y: y / count
  7097. };
  7098. },
  7099. /**
  7100. * Gets the tooltip position nearest of the item nearest to the event position
  7101. * @function Chart.Tooltip.positioners.nearest
  7102. * @param elements {Chart.Element[]} the tooltip elements
  7103. * @param eventPosition {object} the position of the event in canvas coordinates
  7104. * @returns {object} the tooltip position
  7105. */
  7106. nearest: function(elements, eventPosition) {
  7107. var x = eventPosition.x;
  7108. var y = eventPosition.y;
  7109. var minDistance = Number.POSITIVE_INFINITY;
  7110. var i, len, nearestElement;
  7111. for (i = 0, len = elements.length; i < len; ++i) {
  7112. var el = elements[i];
  7113. if (el && el.hasValue()) {
  7114. var center = el.getCenterPoint();
  7115. var d = helpers$1.distanceBetweenPoints(eventPosition, center);
  7116. if (d < minDistance) {
  7117. minDistance = d;
  7118. nearestElement = el;
  7119. }
  7120. }
  7121. }
  7122. if (nearestElement) {
  7123. var tp = nearestElement.tooltipPosition();
  7124. x = tp.x;
  7125. y = tp.y;
  7126. }
  7127. return {
  7128. x: x,
  7129. y: y
  7130. };
  7131. }
  7132. };
  7133. // Helper to push or concat based on if the 2nd parameter is an array or not
  7134. function pushOrConcat(base, toPush) {
  7135. if (toPush) {
  7136. if (helpers$1.isArray(toPush)) {
  7137. // base = base.concat(toPush);
  7138. Array.prototype.push.apply(base, toPush);
  7139. } else {
  7140. base.push(toPush);
  7141. }
  7142. }
  7143. return base;
  7144. }
  7145. /**
  7146. * Returns array of strings split by newline
  7147. * @param {string} value - The value to split by newline.
  7148. * @returns {string[]} value if newline present - Returned from String split() method
  7149. * @function
  7150. */
  7151. function splitNewlines(str) {
  7152. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  7153. return str.split('\n');
  7154. }
  7155. return str;
  7156. }
  7157. /**
  7158. * Private helper to create a tooltip item model
  7159. * @param element - the chart element (point, arc, bar) to create the tooltip item for
  7160. * @return new tooltip item
  7161. */
  7162. function createTooltipItem(element) {
  7163. var xScale = element._xScale;
  7164. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  7165. var index = element._index;
  7166. var datasetIndex = element._datasetIndex;
  7167. var controller = element._chart.getDatasetMeta(datasetIndex).controller;
  7168. var indexScale = controller._getIndexScale();
  7169. var valueScale = controller._getValueScale();
  7170. return {
  7171. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  7172. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  7173. label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',
  7174. value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',
  7175. index: index,
  7176. datasetIndex: datasetIndex,
  7177. x: element._model.x,
  7178. y: element._model.y
  7179. };
  7180. }
  7181. /**
  7182. * Helper to get the reset model for the tooltip
  7183. * @param tooltipOpts {object} the tooltip options
  7184. */
  7185. function getBaseModel(tooltipOpts) {
  7186. var globalDefaults = core_defaults.global;
  7187. return {
  7188. // Positioning
  7189. xPadding: tooltipOpts.xPadding,
  7190. yPadding: tooltipOpts.yPadding,
  7191. xAlign: tooltipOpts.xAlign,
  7192. yAlign: tooltipOpts.yAlign,
  7193. // Drawing direction and text direction
  7194. rtl: tooltipOpts.rtl,
  7195. textDirection: tooltipOpts.textDirection,
  7196. // Body
  7197. bodyFontColor: tooltipOpts.bodyFontColor,
  7198. _bodyFontFamily: valueOrDefault$8(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  7199. _bodyFontStyle: valueOrDefault$8(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  7200. _bodyAlign: tooltipOpts.bodyAlign,
  7201. bodyFontSize: valueOrDefault$8(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  7202. bodySpacing: tooltipOpts.bodySpacing,
  7203. // Title
  7204. titleFontColor: tooltipOpts.titleFontColor,
  7205. _titleFontFamily: valueOrDefault$8(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  7206. _titleFontStyle: valueOrDefault$8(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  7207. titleFontSize: valueOrDefault$8(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  7208. _titleAlign: tooltipOpts.titleAlign,
  7209. titleSpacing: tooltipOpts.titleSpacing,
  7210. titleMarginBottom: tooltipOpts.titleMarginBottom,
  7211. // Footer
  7212. footerFontColor: tooltipOpts.footerFontColor,
  7213. _footerFontFamily: valueOrDefault$8(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  7214. _footerFontStyle: valueOrDefault$8(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  7215. footerFontSize: valueOrDefault$8(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  7216. _footerAlign: tooltipOpts.footerAlign,
  7217. footerSpacing: tooltipOpts.footerSpacing,
  7218. footerMarginTop: tooltipOpts.footerMarginTop,
  7219. // Appearance
  7220. caretSize: tooltipOpts.caretSize,
  7221. cornerRadius: tooltipOpts.cornerRadius,
  7222. backgroundColor: tooltipOpts.backgroundColor,
  7223. opacity: 0,
  7224. legendColorBackground: tooltipOpts.multiKeyBackground,
  7225. displayColors: tooltipOpts.displayColors,
  7226. borderColor: tooltipOpts.borderColor,
  7227. borderWidth: tooltipOpts.borderWidth
  7228. };
  7229. }
  7230. /**
  7231. * Get the size of the tooltip
  7232. */
  7233. function getTooltipSize(tooltip, model) {
  7234. var ctx = tooltip._chart.ctx;
  7235. var height = model.yPadding * 2; // Tooltip Padding
  7236. var width = 0;
  7237. // Count of all lines in the body
  7238. var body = model.body;
  7239. var combinedBodyLength = body.reduce(function(count, bodyItem) {
  7240. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  7241. }, 0);
  7242. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  7243. var titleLineCount = model.title.length;
  7244. var footerLineCount = model.footer.length;
  7245. var titleFontSize = model.titleFontSize;
  7246. var bodyFontSize = model.bodyFontSize;
  7247. var footerFontSize = model.footerFontSize;
  7248. height += titleLineCount * titleFontSize; // Title Lines
  7249. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  7250. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  7251. height += combinedBodyLength * bodyFontSize; // Body Lines
  7252. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  7253. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  7254. height += footerLineCount * (footerFontSize); // Footer Lines
  7255. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  7256. // Title width
  7257. var widthPadding = 0;
  7258. var maxLineWidth = function(line) {
  7259. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  7260. };
  7261. ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  7262. helpers$1.each(model.title, maxLineWidth);
  7263. // Body width
  7264. ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  7265. helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  7266. // Body lines may include some extra width due to the color box
  7267. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  7268. helpers$1.each(body, function(bodyItem) {
  7269. helpers$1.each(bodyItem.before, maxLineWidth);
  7270. helpers$1.each(bodyItem.lines, maxLineWidth);
  7271. helpers$1.each(bodyItem.after, maxLineWidth);
  7272. });
  7273. // Reset back to 0
  7274. widthPadding = 0;
  7275. // Footer width
  7276. ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  7277. helpers$1.each(model.footer, maxLineWidth);
  7278. // Add padding
  7279. width += 2 * model.xPadding;
  7280. return {
  7281. width: width,
  7282. height: height
  7283. };
  7284. }
  7285. /**
  7286. * Helper to get the alignment of a tooltip given the size
  7287. */
  7288. function determineAlignment(tooltip, size) {
  7289. var model = tooltip._model;
  7290. var chart = tooltip._chart;
  7291. var chartArea = tooltip._chart.chartArea;
  7292. var xAlign = 'center';
  7293. var yAlign = 'center';
  7294. if (model.y < size.height) {
  7295. yAlign = 'top';
  7296. } else if (model.y > (chart.height - size.height)) {
  7297. yAlign = 'bottom';
  7298. }
  7299. var lf, rf; // functions to determine left, right alignment
  7300. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  7301. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  7302. var midX = (chartArea.left + chartArea.right) / 2;
  7303. var midY = (chartArea.top + chartArea.bottom) / 2;
  7304. if (yAlign === 'center') {
  7305. lf = function(x) {
  7306. return x <= midX;
  7307. };
  7308. rf = function(x) {
  7309. return x > midX;
  7310. };
  7311. } else {
  7312. lf = function(x) {
  7313. return x <= (size.width / 2);
  7314. };
  7315. rf = function(x) {
  7316. return x >= (chart.width - (size.width / 2));
  7317. };
  7318. }
  7319. olf = function(x) {
  7320. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  7321. };
  7322. orf = function(x) {
  7323. return x - size.width - model.caretSize - model.caretPadding < 0;
  7324. };
  7325. yf = function(y) {
  7326. return y <= midY ? 'top' : 'bottom';
  7327. };
  7328. if (lf(model.x)) {
  7329. xAlign = 'left';
  7330. // Is tooltip too wide and goes over the right side of the chart.?
  7331. if (olf(model.x)) {
  7332. xAlign = 'center';
  7333. yAlign = yf(model.y);
  7334. }
  7335. } else if (rf(model.x)) {
  7336. xAlign = 'right';
  7337. // Is tooltip too wide and goes outside left edge of canvas?
  7338. if (orf(model.x)) {
  7339. xAlign = 'center';
  7340. yAlign = yf(model.y);
  7341. }
  7342. }
  7343. var opts = tooltip._options;
  7344. return {
  7345. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  7346. yAlign: opts.yAlign ? opts.yAlign : yAlign
  7347. };
  7348. }
  7349. /**
  7350. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  7351. */
  7352. function getBackgroundPoint(vm, size, alignment, chart) {
  7353. // Background Position
  7354. var x = vm.x;
  7355. var y = vm.y;
  7356. var caretSize = vm.caretSize;
  7357. var caretPadding = vm.caretPadding;
  7358. var cornerRadius = vm.cornerRadius;
  7359. var xAlign = alignment.xAlign;
  7360. var yAlign = alignment.yAlign;
  7361. var paddingAndSize = caretSize + caretPadding;
  7362. var radiusAndPadding = cornerRadius + caretPadding;
  7363. if (xAlign === 'right') {
  7364. x -= size.width;
  7365. } else if (xAlign === 'center') {
  7366. x -= (size.width / 2);
  7367. if (x + size.width > chart.width) {
  7368. x = chart.width - size.width;
  7369. }
  7370. if (x < 0) {
  7371. x = 0;
  7372. }
  7373. }
  7374. if (yAlign === 'top') {
  7375. y += paddingAndSize;
  7376. } else if (yAlign === 'bottom') {
  7377. y -= size.height + paddingAndSize;
  7378. } else {
  7379. y -= (size.height / 2);
  7380. }
  7381. if (yAlign === 'center') {
  7382. if (xAlign === 'left') {
  7383. x += paddingAndSize;
  7384. } else if (xAlign === 'right') {
  7385. x -= paddingAndSize;
  7386. }
  7387. } else if (xAlign === 'left') {
  7388. x -= radiusAndPadding;
  7389. } else if (xAlign === 'right') {
  7390. x += radiusAndPadding;
  7391. }
  7392. return {
  7393. x: x,
  7394. y: y
  7395. };
  7396. }
  7397. function getAlignedX(vm, align) {
  7398. return align === 'center'
  7399. ? vm.x + vm.width / 2
  7400. : align === 'right'
  7401. ? vm.x + vm.width - vm.xPadding
  7402. : vm.x + vm.xPadding;
  7403. }
  7404. /**
  7405. * Helper to build before and after body lines
  7406. */
  7407. function getBeforeAfterBodyLines(callback) {
  7408. return pushOrConcat([], splitNewlines(callback));
  7409. }
  7410. var exports$4 = core_element.extend({
  7411. initialize: function() {
  7412. this._model = getBaseModel(this._options);
  7413. this._lastActive = [];
  7414. },
  7415. // Get the title
  7416. // Args are: (tooltipItem, data)
  7417. getTitle: function() {
  7418. var me = this;
  7419. var opts = me._options;
  7420. var callbacks = opts.callbacks;
  7421. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  7422. var title = callbacks.title.apply(me, arguments);
  7423. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  7424. var lines = [];
  7425. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  7426. lines = pushOrConcat(lines, splitNewlines(title));
  7427. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  7428. return lines;
  7429. },
  7430. // Args are: (tooltipItem, data)
  7431. getBeforeBody: function() {
  7432. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  7433. },
  7434. // Args are: (tooltipItem, data)
  7435. getBody: function(tooltipItems, data) {
  7436. var me = this;
  7437. var callbacks = me._options.callbacks;
  7438. var bodyItems = [];
  7439. helpers$1.each(tooltipItems, function(tooltipItem) {
  7440. var bodyItem = {
  7441. before: [],
  7442. lines: [],
  7443. after: []
  7444. };
  7445. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  7446. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  7447. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  7448. bodyItems.push(bodyItem);
  7449. });
  7450. return bodyItems;
  7451. },
  7452. // Args are: (tooltipItem, data)
  7453. getAfterBody: function() {
  7454. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  7455. },
  7456. // Get the footer and beforeFooter and afterFooter lines
  7457. // Args are: (tooltipItem, data)
  7458. getFooter: function() {
  7459. var me = this;
  7460. var callbacks = me._options.callbacks;
  7461. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  7462. var footer = callbacks.footer.apply(me, arguments);
  7463. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  7464. var lines = [];
  7465. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  7466. lines = pushOrConcat(lines, splitNewlines(footer));
  7467. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  7468. return lines;
  7469. },
  7470. update: function(changed) {
  7471. var me = this;
  7472. var opts = me._options;
  7473. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  7474. // that does _view = _model if ease === 1. This causes the 2nd tooltip update to set properties in both the view and model at the same time
  7475. // which breaks any animations.
  7476. var existingModel = me._model;
  7477. var model = me._model = getBaseModel(opts);
  7478. var active = me._active;
  7479. var data = me._data;
  7480. // In the case where active.length === 0 we need to keep these at existing values for good animations
  7481. var alignment = {
  7482. xAlign: existingModel.xAlign,
  7483. yAlign: existingModel.yAlign
  7484. };
  7485. var backgroundPoint = {
  7486. x: existingModel.x,
  7487. y: existingModel.y
  7488. };
  7489. var tooltipSize = {
  7490. width: existingModel.width,
  7491. height: existingModel.height
  7492. };
  7493. var tooltipPosition = {
  7494. x: existingModel.caretX,
  7495. y: existingModel.caretY
  7496. };
  7497. var i, len;
  7498. if (active.length) {
  7499. model.opacity = 1;
  7500. var labelColors = [];
  7501. var labelTextColors = [];
  7502. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  7503. var tooltipItems = [];
  7504. for (i = 0, len = active.length; i < len; ++i) {
  7505. tooltipItems.push(createTooltipItem(active[i]));
  7506. }
  7507. // If the user provided a filter function, use it to modify the tooltip items
  7508. if (opts.filter) {
  7509. tooltipItems = tooltipItems.filter(function(a) {
  7510. return opts.filter(a, data);
  7511. });
  7512. }
  7513. // If the user provided a sorting function, use it to modify the tooltip items
  7514. if (opts.itemSort) {
  7515. tooltipItems = tooltipItems.sort(function(a, b) {
  7516. return opts.itemSort(a, b, data);
  7517. });
  7518. }
  7519. // Determine colors for boxes
  7520. helpers$1.each(tooltipItems, function(tooltipItem) {
  7521. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  7522. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  7523. });
  7524. // Build the Text Lines
  7525. model.title = me.getTitle(tooltipItems, data);
  7526. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  7527. model.body = me.getBody(tooltipItems, data);
  7528. model.afterBody = me.getAfterBody(tooltipItems, data);
  7529. model.footer = me.getFooter(tooltipItems, data);
  7530. // Initial positioning and colors
  7531. model.x = tooltipPosition.x;
  7532. model.y = tooltipPosition.y;
  7533. model.caretPadding = opts.caretPadding;
  7534. model.labelColors = labelColors;
  7535. model.labelTextColors = labelTextColors;
  7536. // data points
  7537. model.dataPoints = tooltipItems;
  7538. // We need to determine alignment of the tooltip
  7539. tooltipSize = getTooltipSize(this, model);
  7540. alignment = determineAlignment(this, tooltipSize);
  7541. // Final Size and Position
  7542. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  7543. } else {
  7544. model.opacity = 0;
  7545. }
  7546. model.xAlign = alignment.xAlign;
  7547. model.yAlign = alignment.yAlign;
  7548. model.x = backgroundPoint.x;
  7549. model.y = backgroundPoint.y;
  7550. model.width = tooltipSize.width;
  7551. model.height = tooltipSize.height;
  7552. // Point where the caret on the tooltip points to
  7553. model.caretX = tooltipPosition.x;
  7554. model.caretY = tooltipPosition.y;
  7555. me._model = model;
  7556. if (changed && opts.custom) {
  7557. opts.custom.call(me, model);
  7558. }
  7559. return me;
  7560. },
  7561. drawCaret: function(tooltipPoint, size) {
  7562. var ctx = this._chart.ctx;
  7563. var vm = this._view;
  7564. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  7565. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  7566. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  7567. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  7568. },
  7569. getCaretPosition: function(tooltipPoint, size, vm) {
  7570. var x1, x2, x3, y1, y2, y3;
  7571. var caretSize = vm.caretSize;
  7572. var cornerRadius = vm.cornerRadius;
  7573. var xAlign = vm.xAlign;
  7574. var yAlign = vm.yAlign;
  7575. var ptX = tooltipPoint.x;
  7576. var ptY = tooltipPoint.y;
  7577. var width = size.width;
  7578. var height = size.height;
  7579. if (yAlign === 'center') {
  7580. y2 = ptY + (height / 2);
  7581. if (xAlign === 'left') {
  7582. x1 = ptX;
  7583. x2 = x1 - caretSize;
  7584. x3 = x1;
  7585. y1 = y2 + caretSize;
  7586. y3 = y2 - caretSize;
  7587. } else {
  7588. x1 = ptX + width;
  7589. x2 = x1 + caretSize;
  7590. x3 = x1;
  7591. y1 = y2 - caretSize;
  7592. y3 = y2 + caretSize;
  7593. }
  7594. } else {
  7595. if (xAlign === 'left') {
  7596. x2 = ptX + cornerRadius + (caretSize);
  7597. x1 = x2 - caretSize;
  7598. x3 = x2 + caretSize;
  7599. } else if (xAlign === 'right') {
  7600. x2 = ptX + width - cornerRadius - caretSize;
  7601. x1 = x2 - caretSize;
  7602. x3 = x2 + caretSize;
  7603. } else {
  7604. x2 = vm.caretX;
  7605. x1 = x2 - caretSize;
  7606. x3 = x2 + caretSize;
  7607. }
  7608. if (yAlign === 'top') {
  7609. y1 = ptY;
  7610. y2 = y1 - caretSize;
  7611. y3 = y1;
  7612. } else {
  7613. y1 = ptY + height;
  7614. y2 = y1 + caretSize;
  7615. y3 = y1;
  7616. // invert drawing order
  7617. var tmp = x3;
  7618. x3 = x1;
  7619. x1 = tmp;
  7620. }
  7621. }
  7622. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  7623. },
  7624. drawTitle: function(pt, vm, ctx) {
  7625. var title = vm.title;
  7626. var length = title.length;
  7627. var titleFontSize, titleSpacing, i;
  7628. if (length) {
  7629. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7630. pt.x = getAlignedX(vm, vm._titleAlign);
  7631. ctx.textAlign = rtlHelper.textAlign(vm._titleAlign);
  7632. ctx.textBaseline = 'middle';
  7633. titleFontSize = vm.titleFontSize;
  7634. titleSpacing = vm.titleSpacing;
  7635. ctx.fillStyle = vm.titleFontColor;
  7636. ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  7637. for (i = 0; i < length; ++i) {
  7638. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFontSize / 2);
  7639. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  7640. if (i + 1 === length) {
  7641. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  7642. }
  7643. }
  7644. }
  7645. },
  7646. drawBody: function(pt, vm, ctx) {
  7647. var bodyFontSize = vm.bodyFontSize;
  7648. var bodySpacing = vm.bodySpacing;
  7649. var bodyAlign = vm._bodyAlign;
  7650. var body = vm.body;
  7651. var drawColorBoxes = vm.displayColors;
  7652. var xLinePadding = 0;
  7653. var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
  7654. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7655. var fillLineOfText = function(line) {
  7656. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyFontSize / 2);
  7657. pt.y += bodyFontSize + bodySpacing;
  7658. };
  7659. var bodyItem, textColor, labelColors, lines, i, j, ilen, jlen;
  7660. var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  7661. ctx.textAlign = bodyAlign;
  7662. ctx.textBaseline = 'middle';
  7663. ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  7664. pt.x = getAlignedX(vm, bodyAlignForCalculation);
  7665. // Before body lines
  7666. ctx.fillStyle = vm.bodyFontColor;
  7667. helpers$1.each(vm.beforeBody, fillLineOfText);
  7668. xLinePadding = drawColorBoxes && bodyAlignForCalculation !== 'right'
  7669. ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
  7670. : 0;
  7671. // Draw body lines now
  7672. for (i = 0, ilen = body.length; i < ilen; ++i) {
  7673. bodyItem = body[i];
  7674. textColor = vm.labelTextColors[i];
  7675. labelColors = vm.labelColors[i];
  7676. ctx.fillStyle = textColor;
  7677. helpers$1.each(bodyItem.before, fillLineOfText);
  7678. lines = bodyItem.lines;
  7679. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  7680. // Draw Legend-like boxes if needed
  7681. if (drawColorBoxes) {
  7682. var rtlColorX = rtlHelper.x(colorX);
  7683. // Fill a white rect so that colours merge nicely if the opacity is < 1
  7684. ctx.fillStyle = vm.legendColorBackground;
  7685. ctx.fillRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7686. // Border
  7687. ctx.lineWidth = 1;
  7688. ctx.strokeStyle = labelColors.borderColor;
  7689. ctx.strokeRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7690. // Inner square
  7691. ctx.fillStyle = labelColors.backgroundColor;
  7692. ctx.fillRect(rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), bodyFontSize - 2), pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  7693. ctx.fillStyle = textColor;
  7694. }
  7695. fillLineOfText(lines[j]);
  7696. }
  7697. helpers$1.each(bodyItem.after, fillLineOfText);
  7698. }
  7699. // Reset back to 0 for after body
  7700. xLinePadding = 0;
  7701. // After body lines
  7702. helpers$1.each(vm.afterBody, fillLineOfText);
  7703. pt.y -= bodySpacing; // Remove last body spacing
  7704. },
  7705. drawFooter: function(pt, vm, ctx) {
  7706. var footer = vm.footer;
  7707. var length = footer.length;
  7708. var footerFontSize, i;
  7709. if (length) {
  7710. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7711. pt.x = getAlignedX(vm, vm._footerAlign);
  7712. pt.y += vm.footerMarginTop;
  7713. ctx.textAlign = rtlHelper.textAlign(vm._footerAlign);
  7714. ctx.textBaseline = 'middle';
  7715. footerFontSize = vm.footerFontSize;
  7716. ctx.fillStyle = vm.footerFontColor;
  7717. ctx.font = helpers$1.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  7718. for (i = 0; i < length; ++i) {
  7719. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFontSize / 2);
  7720. pt.y += footerFontSize + vm.footerSpacing;
  7721. }
  7722. }
  7723. },
  7724. drawBackground: function(pt, vm, ctx, tooltipSize) {
  7725. ctx.fillStyle = vm.backgroundColor;
  7726. ctx.strokeStyle = vm.borderColor;
  7727. ctx.lineWidth = vm.borderWidth;
  7728. var xAlign = vm.xAlign;
  7729. var yAlign = vm.yAlign;
  7730. var x = pt.x;
  7731. var y = pt.y;
  7732. var width = tooltipSize.width;
  7733. var height = tooltipSize.height;
  7734. var radius = vm.cornerRadius;
  7735. ctx.beginPath();
  7736. ctx.moveTo(x + radius, y);
  7737. if (yAlign === 'top') {
  7738. this.drawCaret(pt, tooltipSize);
  7739. }
  7740. ctx.lineTo(x + width - radius, y);
  7741. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  7742. if (yAlign === 'center' && xAlign === 'right') {
  7743. this.drawCaret(pt, tooltipSize);
  7744. }
  7745. ctx.lineTo(x + width, y + height - radius);
  7746. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  7747. if (yAlign === 'bottom') {
  7748. this.drawCaret(pt, tooltipSize);
  7749. }
  7750. ctx.lineTo(x + radius, y + height);
  7751. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  7752. if (yAlign === 'center' && xAlign === 'left') {
  7753. this.drawCaret(pt, tooltipSize);
  7754. }
  7755. ctx.lineTo(x, y + radius);
  7756. ctx.quadraticCurveTo(x, y, x + radius, y);
  7757. ctx.closePath();
  7758. ctx.fill();
  7759. if (vm.borderWidth > 0) {
  7760. ctx.stroke();
  7761. }
  7762. },
  7763. draw: function() {
  7764. var ctx = this._chart.ctx;
  7765. var vm = this._view;
  7766. if (vm.opacity === 0) {
  7767. return;
  7768. }
  7769. var tooltipSize = {
  7770. width: vm.width,
  7771. height: vm.height
  7772. };
  7773. var pt = {
  7774. x: vm.x,
  7775. y: vm.y
  7776. };
  7777. // IE11/Edge does not like very small opacities, so snap to 0
  7778. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  7779. // Truthy/falsey value for empty tooltip
  7780. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  7781. if (this._options.enabled && hasTooltipContent) {
  7782. ctx.save();
  7783. ctx.globalAlpha = opacity;
  7784. // Draw Background
  7785. this.drawBackground(pt, vm, ctx, tooltipSize);
  7786. // Draw Title, Body, and Footer
  7787. pt.y += vm.yPadding;
  7788. helpers$1.rtl.overrideTextDirection(ctx, vm.textDirection);
  7789. // Titles
  7790. this.drawTitle(pt, vm, ctx);
  7791. // Body
  7792. this.drawBody(pt, vm, ctx);
  7793. // Footer
  7794. this.drawFooter(pt, vm, ctx);
  7795. helpers$1.rtl.restoreTextDirection(ctx, vm.textDirection);
  7796. ctx.restore();
  7797. }
  7798. },
  7799. /**
  7800. * Handle an event
  7801. * @private
  7802. * @param {IEvent} event - The event to handle
  7803. * @returns {boolean} true if the tooltip changed
  7804. */
  7805. handleEvent: function(e) {
  7806. var me = this;
  7807. var options = me._options;
  7808. var changed = false;
  7809. me._lastActive = me._lastActive || [];
  7810. // Find Active Elements for tooltips
  7811. if (e.type === 'mouseout') {
  7812. me._active = [];
  7813. } else {
  7814. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  7815. if (options.reverse) {
  7816. me._active.reverse();
  7817. }
  7818. }
  7819. // Remember Last Actives
  7820. changed = !helpers$1.arrayEquals(me._active, me._lastActive);
  7821. // Only handle target event on tooltip change
  7822. if (changed) {
  7823. me._lastActive = me._active;
  7824. if (options.enabled || options.custom) {
  7825. me._eventPosition = {
  7826. x: e.x,
  7827. y: e.y
  7828. };
  7829. me.update(true);
  7830. me.pivot();
  7831. }
  7832. }
  7833. return changed;
  7834. }
  7835. });
  7836. /**
  7837. * @namespace Chart.Tooltip.positioners
  7838. */
  7839. var positioners_1 = positioners;
  7840. var core_tooltip = exports$4;
  7841. core_tooltip.positioners = positioners_1;
  7842. var valueOrDefault$9 = helpers$1.valueOrDefault;
  7843. core_defaults._set('global', {
  7844. elements: {},
  7845. events: [
  7846. 'mousemove',
  7847. 'mouseout',
  7848. 'click',
  7849. 'touchstart',
  7850. 'touchmove'
  7851. ],
  7852. hover: {
  7853. onHover: null,
  7854. mode: 'nearest',
  7855. intersect: true,
  7856. animationDuration: 400
  7857. },
  7858. onClick: null,
  7859. maintainAspectRatio: true,
  7860. responsive: true,
  7861. responsiveAnimationDuration: 0
  7862. });
  7863. /**
  7864. * Recursively merge the given config objects representing the `scales` option
  7865. * by incorporating scale defaults in `xAxes` and `yAxes` array items, then
  7866. * returns a deep copy of the result, thus doesn't alter inputs.
  7867. */
  7868. function mergeScaleConfig(/* config objects ... */) {
  7869. return helpers$1.merge({}, [].slice.call(arguments), {
  7870. merger: function(key, target, source, options) {
  7871. if (key === 'xAxes' || key === 'yAxes') {
  7872. var slen = source[key].length;
  7873. var i, type, scale;
  7874. if (!target[key]) {
  7875. target[key] = [];
  7876. }
  7877. for (i = 0; i < slen; ++i) {
  7878. scale = source[key][i];
  7879. type = valueOrDefault$9(scale.type, key === 'xAxes' ? 'category' : 'linear');
  7880. if (i >= target[key].length) {
  7881. target[key].push({});
  7882. }
  7883. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  7884. // new/untyped scale or type changed: let's apply the new defaults
  7885. // then merge source scale to correctly overwrite the defaults.
  7886. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
  7887. } else {
  7888. // scales type are the same
  7889. helpers$1.merge(target[key][i], scale);
  7890. }
  7891. }
  7892. } else {
  7893. helpers$1._merger(key, target, source, options);
  7894. }
  7895. }
  7896. });
  7897. }
  7898. /**
  7899. * Recursively merge the given config objects as the root options by handling
  7900. * default scale options for the `scales` and `scale` properties, then returns
  7901. * a deep copy of the result, thus doesn't alter inputs.
  7902. */
  7903. function mergeConfig(/* config objects ... */) {
  7904. return helpers$1.merge({}, [].slice.call(arguments), {
  7905. merger: function(key, target, source, options) {
  7906. var tval = target[key] || {};
  7907. var sval = source[key];
  7908. if (key === 'scales') {
  7909. // scale config merging is complex. Add our own function here for that
  7910. target[key] = mergeScaleConfig(tval, sval);
  7911. } else if (key === 'scale') {
  7912. // used in polar area & radar charts since there is only one scale
  7913. target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
  7914. } else {
  7915. helpers$1._merger(key, target, source, options);
  7916. }
  7917. }
  7918. });
  7919. }
  7920. function initConfig(config) {
  7921. config = config || {};
  7922. // Do NOT use mergeConfig for the data object because this method merges arrays
  7923. // and so would change references to labels and datasets, preventing data updates.
  7924. var data = config.data = config.data || {};
  7925. data.datasets = data.datasets || [];
  7926. data.labels = data.labels || [];
  7927. config.options = mergeConfig(
  7928. core_defaults.global,
  7929. core_defaults[config.type],
  7930. config.options || {});
  7931. return config;
  7932. }
  7933. function updateConfig(chart) {
  7934. var newOptions = chart.options;
  7935. helpers$1.each(chart.scales, function(scale) {
  7936. core_layouts.removeBox(chart, scale);
  7937. });
  7938. newOptions = mergeConfig(
  7939. core_defaults.global,
  7940. core_defaults[chart.config.type],
  7941. newOptions);
  7942. chart.options = chart.config.options = newOptions;
  7943. chart.ensureScalesHaveIDs();
  7944. chart.buildOrUpdateScales();
  7945. // Tooltip
  7946. chart.tooltip._options = newOptions.tooltips;
  7947. chart.tooltip.initialize();
  7948. }
  7949. function nextAvailableScaleId(axesOpts, prefix, index) {
  7950. var id;
  7951. var hasId = function(obj) {
  7952. return obj.id === id;
  7953. };
  7954. do {
  7955. id = prefix + index++;
  7956. } while (helpers$1.findIndex(axesOpts, hasId) >= 0);
  7957. return id;
  7958. }
  7959. function positionIsHorizontal(position) {
  7960. return position === 'top' || position === 'bottom';
  7961. }
  7962. function compare2Level(l1, l2) {
  7963. return function(a, b) {
  7964. return a[l1] === b[l1]
  7965. ? a[l2] - b[l2]
  7966. : a[l1] - b[l1];
  7967. };
  7968. }
  7969. var Chart = function(item, config) {
  7970. this.construct(item, config);
  7971. return this;
  7972. };
  7973. helpers$1.extend(Chart.prototype, /** @lends Chart */ {
  7974. /**
  7975. * @private
  7976. */
  7977. construct: function(item, config) {
  7978. var me = this;
  7979. config = initConfig(config);
  7980. var context = platform.acquireContext(item, config);
  7981. var canvas = context && context.canvas;
  7982. var height = canvas && canvas.height;
  7983. var width = canvas && canvas.width;
  7984. me.id = helpers$1.uid();
  7985. me.ctx = context;
  7986. me.canvas = canvas;
  7987. me.config = config;
  7988. me.width = width;
  7989. me.height = height;
  7990. me.aspectRatio = height ? width / height : null;
  7991. me.options = config.options;
  7992. me._bufferedRender = false;
  7993. me._layers = [];
  7994. /**
  7995. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  7996. * the "instance" still need to be defined since it might be called from plugins.
  7997. * @prop Chart#chart
  7998. * @deprecated since version 2.6.0
  7999. * @todo remove at version 3
  8000. * @private
  8001. */
  8002. me.chart = me;
  8003. me.controller = me; // chart.chart.controller #inception
  8004. // Add the chart instance to the global namespace
  8005. Chart.instances[me.id] = me;
  8006. // Define alias to the config data: `chart.data === chart.config.data`
  8007. Object.defineProperty(me, 'data', {
  8008. get: function() {
  8009. return me.config.data;
  8010. },
  8011. set: function(value) {
  8012. me.config.data = value;
  8013. }
  8014. });
  8015. if (!context || !canvas) {
  8016. // The given item is not a compatible context2d element, let's return before finalizing
  8017. // the chart initialization but after setting basic chart / controller properties that
  8018. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  8019. // https://github.com/chartjs/Chart.js/issues/2807
  8020. console.error("Failed to create chart: can't acquire context from the given item");
  8021. return;
  8022. }
  8023. me.initialize();
  8024. me.update();
  8025. },
  8026. /**
  8027. * @private
  8028. */
  8029. initialize: function() {
  8030. var me = this;
  8031. // Before init plugin notification
  8032. core_plugins.notify(me, 'beforeInit');
  8033. helpers$1.retinaScale(me, me.options.devicePixelRatio);
  8034. me.bindEvents();
  8035. if (me.options.responsive) {
  8036. // Initial resize before chart draws (must be silent to preserve initial animations).
  8037. me.resize(true);
  8038. }
  8039. me.initToolTip();
  8040. // After init plugin notification
  8041. core_plugins.notify(me, 'afterInit');
  8042. return me;
  8043. },
  8044. clear: function() {
  8045. helpers$1.canvas.clear(this);
  8046. return this;
  8047. },
  8048. stop: function() {
  8049. // Stops any current animation loop occurring
  8050. core_animations.cancelAnimation(this);
  8051. return this;
  8052. },
  8053. resize: function(silent) {
  8054. var me = this;
  8055. var options = me.options;
  8056. var canvas = me.canvas;
  8057. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  8058. // the canvas render width and height will be casted to integers so make sure that
  8059. // the canvas display style uses the same integer values to avoid blurring effect.
  8060. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  8061. var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
  8062. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
  8063. if (me.width === newWidth && me.height === newHeight) {
  8064. return;
  8065. }
  8066. canvas.width = me.width = newWidth;
  8067. canvas.height = me.height = newHeight;
  8068. canvas.style.width = newWidth + 'px';
  8069. canvas.style.height = newHeight + 'px';
  8070. helpers$1.retinaScale(me, options.devicePixelRatio);
  8071. if (!silent) {
  8072. // Notify any plugins about the resize
  8073. var newSize = {width: newWidth, height: newHeight};
  8074. core_plugins.notify(me, 'resize', [newSize]);
  8075. // Notify of resize
  8076. if (options.onResize) {
  8077. options.onResize(me, newSize);
  8078. }
  8079. me.stop();
  8080. me.update({
  8081. duration: options.responsiveAnimationDuration
  8082. });
  8083. }
  8084. },
  8085. ensureScalesHaveIDs: function() {
  8086. var options = this.options;
  8087. var scalesOptions = options.scales || {};
  8088. var scaleOptions = options.scale;
  8089. helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {
  8090. if (!xAxisOptions.id) {
  8091. xAxisOptions.id = nextAvailableScaleId(scalesOptions.xAxes, 'x-axis-', index);
  8092. }
  8093. });
  8094. helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {
  8095. if (!yAxisOptions.id) {
  8096. yAxisOptions.id = nextAvailableScaleId(scalesOptions.yAxes, 'y-axis-', index);
  8097. }
  8098. });
  8099. if (scaleOptions) {
  8100. scaleOptions.id = scaleOptions.id || 'scale';
  8101. }
  8102. },
  8103. /**
  8104. * Builds a map of scale ID to scale object for future lookup.
  8105. */
  8106. buildOrUpdateScales: function() {
  8107. var me = this;
  8108. var options = me.options;
  8109. var scales = me.scales || {};
  8110. var items = [];
  8111. var updated = Object.keys(scales).reduce(function(obj, id) {
  8112. obj[id] = false;
  8113. return obj;
  8114. }, {});
  8115. if (options.scales) {
  8116. items = items.concat(
  8117. (options.scales.xAxes || []).map(function(xAxisOptions) {
  8118. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  8119. }),
  8120. (options.scales.yAxes || []).map(function(yAxisOptions) {
  8121. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  8122. })
  8123. );
  8124. }
  8125. if (options.scale) {
  8126. items.push({
  8127. options: options.scale,
  8128. dtype: 'radialLinear',
  8129. isDefault: true,
  8130. dposition: 'chartArea'
  8131. });
  8132. }
  8133. helpers$1.each(items, function(item) {
  8134. var scaleOptions = item.options;
  8135. var id = scaleOptions.id;
  8136. var scaleType = valueOrDefault$9(scaleOptions.type, item.dtype);
  8137. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  8138. scaleOptions.position = item.dposition;
  8139. }
  8140. updated[id] = true;
  8141. var scale = null;
  8142. if (id in scales && scales[id].type === scaleType) {
  8143. scale = scales[id];
  8144. scale.options = scaleOptions;
  8145. scale.ctx = me.ctx;
  8146. scale.chart = me;
  8147. } else {
  8148. var scaleClass = core_scaleService.getScaleConstructor(scaleType);
  8149. if (!scaleClass) {
  8150. return;
  8151. }
  8152. scale = new scaleClass({
  8153. id: id,
  8154. type: scaleType,
  8155. options: scaleOptions,
  8156. ctx: me.ctx,
  8157. chart: me
  8158. });
  8159. scales[scale.id] = scale;
  8160. }
  8161. scale.mergeTicksOptions();
  8162. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  8163. // and consider it as a regular scale part of the "scales"" map only! This would
  8164. // make the logic easier and remove some useless? custom code.
  8165. if (item.isDefault) {
  8166. me.scale = scale;
  8167. }
  8168. });
  8169. // clear up discarded scales
  8170. helpers$1.each(updated, function(hasUpdated, id) {
  8171. if (!hasUpdated) {
  8172. delete scales[id];
  8173. }
  8174. });
  8175. me.scales = scales;
  8176. core_scaleService.addScalesToLayout(this);
  8177. },
  8178. buildOrUpdateControllers: function() {
  8179. var me = this;
  8180. var newControllers = [];
  8181. var datasets = me.data.datasets;
  8182. var i, ilen;
  8183. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  8184. var dataset = datasets[i];
  8185. var meta = me.getDatasetMeta(i);
  8186. var type = dataset.type || me.config.type;
  8187. if (meta.type && meta.type !== type) {
  8188. me.destroyDatasetMeta(i);
  8189. meta = me.getDatasetMeta(i);
  8190. }
  8191. meta.type = type;
  8192. meta.order = dataset.order || 0;
  8193. meta.index = i;
  8194. if (meta.controller) {
  8195. meta.controller.updateIndex(i);
  8196. meta.controller.linkScales();
  8197. } else {
  8198. var ControllerClass = controllers[meta.type];
  8199. if (ControllerClass === undefined) {
  8200. throw new Error('"' + meta.type + '" is not a chart type.');
  8201. }
  8202. meta.controller = new ControllerClass(me, i);
  8203. newControllers.push(meta.controller);
  8204. }
  8205. }
  8206. return newControllers;
  8207. },
  8208. /**
  8209. * Reset the elements of all datasets
  8210. * @private
  8211. */
  8212. resetElements: function() {
  8213. var me = this;
  8214. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  8215. me.getDatasetMeta(datasetIndex).controller.reset();
  8216. }, me);
  8217. },
  8218. /**
  8219. * Resets the chart back to it's state before the initial animation
  8220. */
  8221. reset: function() {
  8222. this.resetElements();
  8223. this.tooltip.initialize();
  8224. },
  8225. update: function(config) {
  8226. var me = this;
  8227. var i, ilen;
  8228. if (!config || typeof config !== 'object') {
  8229. // backwards compatibility
  8230. config = {
  8231. duration: config,
  8232. lazy: arguments[1]
  8233. };
  8234. }
  8235. updateConfig(me);
  8236. // plugins options references might have change, let's invalidate the cache
  8237. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  8238. core_plugins._invalidate(me);
  8239. if (core_plugins.notify(me, 'beforeUpdate') === false) {
  8240. return;
  8241. }
  8242. // In case the entire data object changed
  8243. me.tooltip._data = me.data;
  8244. // Make sure dataset controllers are updated and new controllers are reset
  8245. var newControllers = me.buildOrUpdateControllers();
  8246. // Make sure all dataset controllers have correct meta data counts
  8247. for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
  8248. me.getDatasetMeta(i).controller.buildOrUpdateElements();
  8249. }
  8250. me.updateLayout();
  8251. // Can only reset the new controllers after the scales have been updated
  8252. if (me.options.animation && me.options.animation.duration) {
  8253. helpers$1.each(newControllers, function(controller) {
  8254. controller.reset();
  8255. });
  8256. }
  8257. me.updateDatasets();
  8258. // Need to reset tooltip in case it is displayed with elements that are removed
  8259. // after update.
  8260. me.tooltip.initialize();
  8261. // Last active contains items that were previously in the tooltip.
  8262. // When we reset the tooltip, we need to clear it
  8263. me.lastActive = [];
  8264. // Do this before render so that any plugins that need final scale updates can use it
  8265. core_plugins.notify(me, 'afterUpdate');
  8266. me._layers.sort(compare2Level('z', '_idx'));
  8267. if (me._bufferedRender) {
  8268. me._bufferedRequest = {
  8269. duration: config.duration,
  8270. easing: config.easing,
  8271. lazy: config.lazy
  8272. };
  8273. } else {
  8274. me.render(config);
  8275. }
  8276. },
  8277. /**
  8278. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  8279. * hook, in which case, plugins will not be called on `afterLayout`.
  8280. * @private
  8281. */
  8282. updateLayout: function() {
  8283. var me = this;
  8284. if (core_plugins.notify(me, 'beforeLayout') === false) {
  8285. return;
  8286. }
  8287. core_layouts.update(this, this.width, this.height);
  8288. me._layers = [];
  8289. helpers$1.each(me.boxes, function(box) {
  8290. // _configure is called twice, once in core.scale.update and once here.
  8291. // Here the boxes are fully updated and at their final positions.
  8292. if (box._configure) {
  8293. box._configure();
  8294. }
  8295. me._layers.push.apply(me._layers, box._layers());
  8296. }, me);
  8297. me._layers.forEach(function(item, index) {
  8298. item._idx = index;
  8299. });
  8300. /**
  8301. * Provided for backward compatibility, use `afterLayout` instead.
  8302. * @method IPlugin#afterScaleUpdate
  8303. * @deprecated since version 2.5.0
  8304. * @todo remove at version 3
  8305. * @private
  8306. */
  8307. core_plugins.notify(me, 'afterScaleUpdate');
  8308. core_plugins.notify(me, 'afterLayout');
  8309. },
  8310. /**
  8311. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  8312. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  8313. * @private
  8314. */
  8315. updateDatasets: function() {
  8316. var me = this;
  8317. if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  8318. return;
  8319. }
  8320. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8321. me.updateDataset(i);
  8322. }
  8323. core_plugins.notify(me, 'afterDatasetsUpdate');
  8324. },
  8325. /**
  8326. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  8327. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  8328. * @private
  8329. */
  8330. updateDataset: function(index) {
  8331. var me = this;
  8332. var meta = me.getDatasetMeta(index);
  8333. var args = {
  8334. meta: meta,
  8335. index: index
  8336. };
  8337. if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  8338. return;
  8339. }
  8340. meta.controller._update();
  8341. core_plugins.notify(me, 'afterDatasetUpdate', [args]);
  8342. },
  8343. render: function(config) {
  8344. var me = this;
  8345. if (!config || typeof config !== 'object') {
  8346. // backwards compatibility
  8347. config = {
  8348. duration: config,
  8349. lazy: arguments[1]
  8350. };
  8351. }
  8352. var animationOptions = me.options.animation;
  8353. var duration = valueOrDefault$9(config.duration, animationOptions && animationOptions.duration);
  8354. var lazy = config.lazy;
  8355. if (core_plugins.notify(me, 'beforeRender') === false) {
  8356. return;
  8357. }
  8358. var onComplete = function(animation) {
  8359. core_plugins.notify(me, 'afterRender');
  8360. helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
  8361. };
  8362. if (animationOptions && duration) {
  8363. var animation = new core_animation({
  8364. numSteps: duration / 16.66, // 60 fps
  8365. easing: config.easing || animationOptions.easing,
  8366. render: function(chart, animationObject) {
  8367. var easingFunction = helpers$1.easing.effects[animationObject.easing];
  8368. var currentStep = animationObject.currentStep;
  8369. var stepDecimal = currentStep / animationObject.numSteps;
  8370. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  8371. },
  8372. onAnimationProgress: animationOptions.onProgress,
  8373. onAnimationComplete: onComplete
  8374. });
  8375. core_animations.addAnimation(me, animation, duration, lazy);
  8376. } else {
  8377. me.draw();
  8378. // See https://github.com/chartjs/Chart.js/issues/3781
  8379. onComplete(new core_animation({numSteps: 0, chart: me}));
  8380. }
  8381. return me;
  8382. },
  8383. draw: function(easingValue) {
  8384. var me = this;
  8385. var i, layers;
  8386. me.clear();
  8387. if (helpers$1.isNullOrUndef(easingValue)) {
  8388. easingValue = 1;
  8389. }
  8390. me.transition(easingValue);
  8391. if (me.width <= 0 || me.height <= 0) {
  8392. return;
  8393. }
  8394. if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  8395. return;
  8396. }
  8397. // Because of plugin hooks (before/afterDatasetsDraw), datasets can't
  8398. // currently be part of layers. Instead, we draw
  8399. // layers <= 0 before(default, backward compat), and the rest after
  8400. layers = me._layers;
  8401. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  8402. layers[i].draw(me.chartArea);
  8403. }
  8404. me.drawDatasets(easingValue);
  8405. // Rest of layers
  8406. for (; i < layers.length; ++i) {
  8407. layers[i].draw(me.chartArea);
  8408. }
  8409. me._drawTooltip(easingValue);
  8410. core_plugins.notify(me, 'afterDraw', [easingValue]);
  8411. },
  8412. /**
  8413. * @private
  8414. */
  8415. transition: function(easingValue) {
  8416. var me = this;
  8417. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  8418. if (me.isDatasetVisible(i)) {
  8419. me.getDatasetMeta(i).controller.transition(easingValue);
  8420. }
  8421. }
  8422. me.tooltip.transition(easingValue);
  8423. },
  8424. /**
  8425. * @private
  8426. */
  8427. _getSortedDatasetMetas: function(filterVisible) {
  8428. var me = this;
  8429. var datasets = me.data.datasets || [];
  8430. var result = [];
  8431. var i, ilen;
  8432. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  8433. if (!filterVisible || me.isDatasetVisible(i)) {
  8434. result.push(me.getDatasetMeta(i));
  8435. }
  8436. }
  8437. result.sort(compare2Level('order', 'index'));
  8438. return result;
  8439. },
  8440. /**
  8441. * @private
  8442. */
  8443. _getSortedVisibleDatasetMetas: function() {
  8444. return this._getSortedDatasetMetas(true);
  8445. },
  8446. /**
  8447. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  8448. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  8449. * @private
  8450. */
  8451. drawDatasets: function(easingValue) {
  8452. var me = this;
  8453. var metasets, i;
  8454. if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  8455. return;
  8456. }
  8457. metasets = me._getSortedVisibleDatasetMetas();
  8458. for (i = metasets.length - 1; i >= 0; --i) {
  8459. me.drawDataset(metasets[i], easingValue);
  8460. }
  8461. core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  8462. },
  8463. /**
  8464. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  8465. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  8466. * @private
  8467. */
  8468. drawDataset: function(meta, easingValue) {
  8469. var me = this;
  8470. var args = {
  8471. meta: meta,
  8472. index: meta.index,
  8473. easingValue: easingValue
  8474. };
  8475. if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  8476. return;
  8477. }
  8478. meta.controller.draw(easingValue);
  8479. core_plugins.notify(me, 'afterDatasetDraw', [args]);
  8480. },
  8481. /**
  8482. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  8483. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  8484. * @private
  8485. */
  8486. _drawTooltip: function(easingValue) {
  8487. var me = this;
  8488. var tooltip = me.tooltip;
  8489. var args = {
  8490. tooltip: tooltip,
  8491. easingValue: easingValue
  8492. };
  8493. if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  8494. return;
  8495. }
  8496. tooltip.draw();
  8497. core_plugins.notify(me, 'afterTooltipDraw', [args]);
  8498. },
  8499. /**
  8500. * Get the single element that was clicked on
  8501. * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  8502. */
  8503. getElementAtEvent: function(e) {
  8504. return core_interaction.modes.single(this, e);
  8505. },
  8506. getElementsAtEvent: function(e) {
  8507. return core_interaction.modes.label(this, e, {intersect: true});
  8508. },
  8509. getElementsAtXAxis: function(e) {
  8510. return core_interaction.modes['x-axis'](this, e, {intersect: true});
  8511. },
  8512. getElementsAtEventForMode: function(e, mode, options) {
  8513. var method = core_interaction.modes[mode];
  8514. if (typeof method === 'function') {
  8515. return method(this, e, options);
  8516. }
  8517. return [];
  8518. },
  8519. getDatasetAtEvent: function(e) {
  8520. return core_interaction.modes.dataset(this, e, {intersect: true});
  8521. },
  8522. getDatasetMeta: function(datasetIndex) {
  8523. var me = this;
  8524. var dataset = me.data.datasets[datasetIndex];
  8525. if (!dataset._meta) {
  8526. dataset._meta = {};
  8527. }
  8528. var meta = dataset._meta[me.id];
  8529. if (!meta) {
  8530. meta = dataset._meta[me.id] = {
  8531. type: null,
  8532. data: [],
  8533. dataset: null,
  8534. controller: null,
  8535. hidden: null, // See isDatasetVisible() comment
  8536. xAxisID: null,
  8537. yAxisID: null,
  8538. order: dataset.order || 0,
  8539. index: datasetIndex
  8540. };
  8541. }
  8542. return meta;
  8543. },
  8544. getVisibleDatasetCount: function() {
  8545. var count = 0;
  8546. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  8547. if (this.isDatasetVisible(i)) {
  8548. count++;
  8549. }
  8550. }
  8551. return count;
  8552. },
  8553. isDatasetVisible: function(datasetIndex) {
  8554. var meta = this.getDatasetMeta(datasetIndex);
  8555. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  8556. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  8557. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  8558. },
  8559. generateLegend: function() {
  8560. return this.options.legendCallback(this);
  8561. },
  8562. /**
  8563. * @private
  8564. */
  8565. destroyDatasetMeta: function(datasetIndex) {
  8566. var id = this.id;
  8567. var dataset = this.data.datasets[datasetIndex];
  8568. var meta = dataset._meta && dataset._meta[id];
  8569. if (meta) {
  8570. meta.controller.destroy();
  8571. delete dataset._meta[id];
  8572. }
  8573. },
  8574. destroy: function() {
  8575. var me = this;
  8576. var canvas = me.canvas;
  8577. var i, ilen;
  8578. me.stop();
  8579. // dataset controllers need to cleanup associated data
  8580. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8581. me.destroyDatasetMeta(i);
  8582. }
  8583. if (canvas) {
  8584. me.unbindEvents();
  8585. helpers$1.canvas.clear(me);
  8586. platform.releaseContext(me.ctx);
  8587. me.canvas = null;
  8588. me.ctx = null;
  8589. }
  8590. core_plugins.notify(me, 'destroy');
  8591. delete Chart.instances[me.id];
  8592. },
  8593. toBase64Image: function() {
  8594. return this.canvas.toDataURL.apply(this.canvas, arguments);
  8595. },
  8596. initToolTip: function() {
  8597. var me = this;
  8598. me.tooltip = new core_tooltip({
  8599. _chart: me,
  8600. _chartInstance: me, // deprecated, backward compatibility
  8601. _data: me.data,
  8602. _options: me.options.tooltips
  8603. }, me);
  8604. },
  8605. /**
  8606. * @private
  8607. */
  8608. bindEvents: function() {
  8609. var me = this;
  8610. var listeners = me._listeners = {};
  8611. var listener = function() {
  8612. me.eventHandler.apply(me, arguments);
  8613. };
  8614. helpers$1.each(me.options.events, function(type) {
  8615. platform.addEventListener(me, type, listener);
  8616. listeners[type] = listener;
  8617. });
  8618. // Elements used to detect size change should not be injected for non responsive charts.
  8619. // See https://github.com/chartjs/Chart.js/issues/2210
  8620. if (me.options.responsive) {
  8621. listener = function() {
  8622. me.resize();
  8623. };
  8624. platform.addEventListener(me, 'resize', listener);
  8625. listeners.resize = listener;
  8626. }
  8627. },
  8628. /**
  8629. * @private
  8630. */
  8631. unbindEvents: function() {
  8632. var me = this;
  8633. var listeners = me._listeners;
  8634. if (!listeners) {
  8635. return;
  8636. }
  8637. delete me._listeners;
  8638. helpers$1.each(listeners, function(listener, type) {
  8639. platform.removeEventListener(me, type, listener);
  8640. });
  8641. },
  8642. updateHoverStyle: function(elements, mode, enabled) {
  8643. var prefix = enabled ? 'set' : 'remove';
  8644. var element, i, ilen;
  8645. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  8646. element = elements[i];
  8647. if (element) {
  8648. this.getDatasetMeta(element._datasetIndex).controller[prefix + 'HoverStyle'](element);
  8649. }
  8650. }
  8651. if (mode === 'dataset') {
  8652. this.getDatasetMeta(elements[0]._datasetIndex).controller['_' + prefix + 'DatasetHoverStyle']();
  8653. }
  8654. },
  8655. /**
  8656. * @private
  8657. */
  8658. eventHandler: function(e) {
  8659. var me = this;
  8660. var tooltip = me.tooltip;
  8661. if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
  8662. return;
  8663. }
  8664. // Buffer any update calls so that renders do not occur
  8665. me._bufferedRender = true;
  8666. me._bufferedRequest = null;
  8667. var changed = me.handleEvent(e);
  8668. // for smooth tooltip animations issue #4989
  8669. // the tooltip should be the source of change
  8670. // Animation check workaround:
  8671. // tooltip._start will be null when tooltip isn't animating
  8672. if (tooltip) {
  8673. changed = tooltip._start
  8674. ? tooltip.handleEvent(e)
  8675. : changed | tooltip.handleEvent(e);
  8676. }
  8677. core_plugins.notify(me, 'afterEvent', [e]);
  8678. var bufferedRequest = me._bufferedRequest;
  8679. if (bufferedRequest) {
  8680. // If we have an update that was triggered, we need to do a normal render
  8681. me.render(bufferedRequest);
  8682. } else if (changed && !me.animating) {
  8683. // If entering, leaving, or changing elements, animate the change via pivot
  8684. me.stop();
  8685. // We only need to render at this point. Updating will cause scales to be
  8686. // recomputed generating flicker & using more memory than necessary.
  8687. me.render({
  8688. duration: me.options.hover.animationDuration,
  8689. lazy: true
  8690. });
  8691. }
  8692. me._bufferedRender = false;
  8693. me._bufferedRequest = null;
  8694. return me;
  8695. },
  8696. /**
  8697. * Handle an event
  8698. * @private
  8699. * @param {IEvent} event the event to handle
  8700. * @return {boolean} true if the chart needs to re-render
  8701. */
  8702. handleEvent: function(e) {
  8703. var me = this;
  8704. var options = me.options || {};
  8705. var hoverOptions = options.hover;
  8706. var changed = false;
  8707. me.lastActive = me.lastActive || [];
  8708. // Find Active Elements for hover and tooltips
  8709. if (e.type === 'mouseout') {
  8710. me.active = [];
  8711. } else {
  8712. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  8713. }
  8714. // Invoke onHover hook
  8715. // Need to call with native event here to not break backwards compatibility
  8716. helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  8717. if (e.type === 'mouseup' || e.type === 'click') {
  8718. if (options.onClick) {
  8719. // Use e.native here for backwards compatibility
  8720. options.onClick.call(me, e.native, me.active);
  8721. }
  8722. }
  8723. // Remove styling for last active (even if it may still be active)
  8724. if (me.lastActive.length) {
  8725. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  8726. }
  8727. // Built in hover styling
  8728. if (me.active.length && hoverOptions.mode) {
  8729. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  8730. }
  8731. changed = !helpers$1.arrayEquals(me.active, me.lastActive);
  8732. // Remember Last Actives
  8733. me.lastActive = me.active;
  8734. return changed;
  8735. }
  8736. });
  8737. /**
  8738. * NOTE(SB) We actually don't use this container anymore but we need to keep it
  8739. * for backward compatibility. Though, it can still be useful for plugins that
  8740. * would need to work on multiple charts?!
  8741. */
  8742. Chart.instances = {};
  8743. var core_controller = Chart;
  8744. // DEPRECATIONS
  8745. /**
  8746. * Provided for backward compatibility, use Chart instead.
  8747. * @class Chart.Controller
  8748. * @deprecated since version 2.6
  8749. * @todo remove at version 3
  8750. * @private
  8751. */
  8752. Chart.Controller = Chart;
  8753. /**
  8754. * Provided for backward compatibility, not available anymore.
  8755. * @namespace Chart
  8756. * @deprecated since version 2.8
  8757. * @todo remove at version 3
  8758. * @private
  8759. */
  8760. Chart.types = {};
  8761. /**
  8762. * Provided for backward compatibility, not available anymore.
  8763. * @namespace Chart.helpers.configMerge
  8764. * @deprecated since version 2.8.0
  8765. * @todo remove at version 3
  8766. * @private
  8767. */
  8768. helpers$1.configMerge = mergeConfig;
  8769. /**
  8770. * Provided for backward compatibility, not available anymore.
  8771. * @namespace Chart.helpers.scaleMerge
  8772. * @deprecated since version 2.8.0
  8773. * @todo remove at version 3
  8774. * @private
  8775. */
  8776. helpers$1.scaleMerge = mergeScaleConfig;
  8777. var core_helpers = function() {
  8778. // -- Basic js utility methods
  8779. helpers$1.where = function(collection, filterCallback) {
  8780. if (helpers$1.isArray(collection) && Array.prototype.filter) {
  8781. return collection.filter(filterCallback);
  8782. }
  8783. var filtered = [];
  8784. helpers$1.each(collection, function(item) {
  8785. if (filterCallback(item)) {
  8786. filtered.push(item);
  8787. }
  8788. });
  8789. return filtered;
  8790. };
  8791. helpers$1.findIndex = Array.prototype.findIndex ?
  8792. function(array, callback, scope) {
  8793. return array.findIndex(callback, scope);
  8794. } :
  8795. function(array, callback, scope) {
  8796. scope = scope === undefined ? array : scope;
  8797. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  8798. if (callback.call(scope, array[i], i, array)) {
  8799. return i;
  8800. }
  8801. }
  8802. return -1;
  8803. };
  8804. helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
  8805. // Default to start of the array
  8806. if (helpers$1.isNullOrUndef(startIndex)) {
  8807. startIndex = -1;
  8808. }
  8809. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  8810. var currentItem = arrayToSearch[i];
  8811. if (filterCallback(currentItem)) {
  8812. return currentItem;
  8813. }
  8814. }
  8815. };
  8816. helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
  8817. // Default to end of the array
  8818. if (helpers$1.isNullOrUndef(startIndex)) {
  8819. startIndex = arrayToSearch.length;
  8820. }
  8821. for (var i = startIndex - 1; i >= 0; i--) {
  8822. var currentItem = arrayToSearch[i];
  8823. if (filterCallback(currentItem)) {
  8824. return currentItem;
  8825. }
  8826. }
  8827. };
  8828. // -- Math methods
  8829. helpers$1.isNumber = function(n) {
  8830. return !isNaN(parseFloat(n)) && isFinite(n);
  8831. };
  8832. helpers$1.almostEquals = function(x, y, epsilon) {
  8833. return Math.abs(x - y) < epsilon;
  8834. };
  8835. helpers$1.almostWhole = function(x, epsilon) {
  8836. var rounded = Math.round(x);
  8837. return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
  8838. };
  8839. helpers$1.max = function(array) {
  8840. return array.reduce(function(max, value) {
  8841. if (!isNaN(value)) {
  8842. return Math.max(max, value);
  8843. }
  8844. return max;
  8845. }, Number.NEGATIVE_INFINITY);
  8846. };
  8847. helpers$1.min = function(array) {
  8848. return array.reduce(function(min, value) {
  8849. if (!isNaN(value)) {
  8850. return Math.min(min, value);
  8851. }
  8852. return min;
  8853. }, Number.POSITIVE_INFINITY);
  8854. };
  8855. helpers$1.sign = Math.sign ?
  8856. function(x) {
  8857. return Math.sign(x);
  8858. } :
  8859. function(x) {
  8860. x = +x; // convert to a number
  8861. if (x === 0 || isNaN(x)) {
  8862. return x;
  8863. }
  8864. return x > 0 ? 1 : -1;
  8865. };
  8866. helpers$1.toRadians = function(degrees) {
  8867. return degrees * (Math.PI / 180);
  8868. };
  8869. helpers$1.toDegrees = function(radians) {
  8870. return radians * (180 / Math.PI);
  8871. };
  8872. /**
  8873. * Returns the number of decimal places
  8874. * i.e. the number of digits after the decimal point, of the value of this Number.
  8875. * @param {number} x - A number.
  8876. * @returns {number} The number of decimal places.
  8877. * @private
  8878. */
  8879. helpers$1._decimalPlaces = function(x) {
  8880. if (!helpers$1.isFinite(x)) {
  8881. return;
  8882. }
  8883. var e = 1;
  8884. var p = 0;
  8885. while (Math.round(x * e) / e !== x) {
  8886. e *= 10;
  8887. p++;
  8888. }
  8889. return p;
  8890. };
  8891. // Gets the angle from vertical upright to the point about a centre.
  8892. helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {
  8893. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  8894. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  8895. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  8896. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  8897. if (angle < (-0.5 * Math.PI)) {
  8898. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  8899. }
  8900. return {
  8901. angle: angle,
  8902. distance: radialDistanceFromCenter
  8903. };
  8904. };
  8905. helpers$1.distanceBetweenPoints = function(pt1, pt2) {
  8906. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  8907. };
  8908. /**
  8909. * Provided for backward compatibility, not available anymore
  8910. * @function Chart.helpers.aliasPixel
  8911. * @deprecated since version 2.8.0
  8912. * @todo remove at version 3
  8913. */
  8914. helpers$1.aliasPixel = function(pixelWidth) {
  8915. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  8916. };
  8917. /**
  8918. * Returns the aligned pixel value to avoid anti-aliasing blur
  8919. * @param {Chart} chart - The chart instance.
  8920. * @param {number} pixel - A pixel value.
  8921. * @param {number} width - The width of the element.
  8922. * @returns {number} The aligned pixel value.
  8923. * @private
  8924. */
  8925. helpers$1._alignPixel = function(chart, pixel, width) {
  8926. var devicePixelRatio = chart.currentDevicePixelRatio;
  8927. var halfWidth = width / 2;
  8928. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  8929. };
  8930. helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
  8931. // Props to Rob Spencer at scaled innovation for his post on splining between points
  8932. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  8933. // This function must also respect "skipped" points
  8934. var previous = firstPoint.skip ? middlePoint : firstPoint;
  8935. var current = middlePoint;
  8936. var next = afterPoint.skip ? middlePoint : afterPoint;
  8937. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  8938. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  8939. var s01 = d01 / (d01 + d12);
  8940. var s12 = d12 / (d01 + d12);
  8941. // If all points are the same, s01 & s02 will be inf
  8942. s01 = isNaN(s01) ? 0 : s01;
  8943. s12 = isNaN(s12) ? 0 : s12;
  8944. var fa = t * s01; // scaling factor for triangle Ta
  8945. var fb = t * s12;
  8946. return {
  8947. previous: {
  8948. x: current.x - fa * (next.x - previous.x),
  8949. y: current.y - fa * (next.y - previous.y)
  8950. },
  8951. next: {
  8952. x: current.x + fb * (next.x - previous.x),
  8953. y: current.y + fb * (next.y - previous.y)
  8954. }
  8955. };
  8956. };
  8957. helpers$1.EPSILON = Number.EPSILON || 1e-14;
  8958. helpers$1.splineCurveMonotone = function(points) {
  8959. // This function calculates Bézier control points in a similar way than |splineCurve|,
  8960. // but preserves monotonicity of the provided data and ensures no local extremums are added
  8961. // between the dataset discrete points due to the interpolation.
  8962. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  8963. var pointsWithTangents = (points || []).map(function(point) {
  8964. return {
  8965. model: point._model,
  8966. deltaK: 0,
  8967. mK: 0
  8968. };
  8969. });
  8970. // Calculate slopes (deltaK) and initialize tangents (mK)
  8971. var pointsLen = pointsWithTangents.length;
  8972. var i, pointBefore, pointCurrent, pointAfter;
  8973. for (i = 0; i < pointsLen; ++i) {
  8974. pointCurrent = pointsWithTangents[i];
  8975. if (pointCurrent.model.skip) {
  8976. continue;
  8977. }
  8978. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8979. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8980. if (pointAfter && !pointAfter.model.skip) {
  8981. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  8982. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  8983. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  8984. }
  8985. if (!pointBefore || pointBefore.model.skip) {
  8986. pointCurrent.mK = pointCurrent.deltaK;
  8987. } else if (!pointAfter || pointAfter.model.skip) {
  8988. pointCurrent.mK = pointBefore.deltaK;
  8989. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  8990. pointCurrent.mK = 0;
  8991. } else {
  8992. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  8993. }
  8994. }
  8995. // Adjust tangents to ensure monotonic properties
  8996. var alphaK, betaK, tauK, squaredMagnitude;
  8997. for (i = 0; i < pointsLen - 1; ++i) {
  8998. pointCurrent = pointsWithTangents[i];
  8999. pointAfter = pointsWithTangents[i + 1];
  9000. if (pointCurrent.model.skip || pointAfter.model.skip) {
  9001. continue;
  9002. }
  9003. if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  9004. pointCurrent.mK = pointAfter.mK = 0;
  9005. continue;
  9006. }
  9007. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  9008. betaK = pointAfter.mK / pointCurrent.deltaK;
  9009. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  9010. if (squaredMagnitude <= 9) {
  9011. continue;
  9012. }
  9013. tauK = 3 / Math.sqrt(squaredMagnitude);
  9014. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  9015. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  9016. }
  9017. // Compute control points
  9018. var deltaX;
  9019. for (i = 0; i < pointsLen; ++i) {
  9020. pointCurrent = pointsWithTangents[i];
  9021. if (pointCurrent.model.skip) {
  9022. continue;
  9023. }
  9024. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  9025. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  9026. if (pointBefore && !pointBefore.model.skip) {
  9027. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  9028. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  9029. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  9030. }
  9031. if (pointAfter && !pointAfter.model.skip) {
  9032. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  9033. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  9034. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  9035. }
  9036. }
  9037. };
  9038. helpers$1.nextItem = function(collection, index, loop) {
  9039. if (loop) {
  9040. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  9041. }
  9042. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  9043. };
  9044. helpers$1.previousItem = function(collection, index, loop) {
  9045. if (loop) {
  9046. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  9047. }
  9048. return index <= 0 ? collection[0] : collection[index - 1];
  9049. };
  9050. // Implementation of the nice number algorithm used in determining where axis labels will go
  9051. helpers$1.niceNum = function(range, round) {
  9052. var exponent = Math.floor(helpers$1.log10(range));
  9053. var fraction = range / Math.pow(10, exponent);
  9054. var niceFraction;
  9055. if (round) {
  9056. if (fraction < 1.5) {
  9057. niceFraction = 1;
  9058. } else if (fraction < 3) {
  9059. niceFraction = 2;
  9060. } else if (fraction < 7) {
  9061. niceFraction = 5;
  9062. } else {
  9063. niceFraction = 10;
  9064. }
  9065. } else if (fraction <= 1.0) {
  9066. niceFraction = 1;
  9067. } else if (fraction <= 2) {
  9068. niceFraction = 2;
  9069. } else if (fraction <= 5) {
  9070. niceFraction = 5;
  9071. } else {
  9072. niceFraction = 10;
  9073. }
  9074. return niceFraction * Math.pow(10, exponent);
  9075. };
  9076. // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  9077. helpers$1.requestAnimFrame = (function() {
  9078. if (typeof window === 'undefined') {
  9079. return function(callback) {
  9080. callback();
  9081. };
  9082. }
  9083. return window.requestAnimationFrame ||
  9084. window.webkitRequestAnimationFrame ||
  9085. window.mozRequestAnimationFrame ||
  9086. window.oRequestAnimationFrame ||
  9087. window.msRequestAnimationFrame ||
  9088. function(callback) {
  9089. return window.setTimeout(callback, 1000 / 60);
  9090. };
  9091. }());
  9092. // -- DOM methods
  9093. helpers$1.getRelativePosition = function(evt, chart) {
  9094. var mouseX, mouseY;
  9095. var e = evt.originalEvent || evt;
  9096. var canvas = evt.target || evt.srcElement;
  9097. var boundingRect = canvas.getBoundingClientRect();
  9098. var touches = e.touches;
  9099. if (touches && touches.length > 0) {
  9100. mouseX = touches[0].clientX;
  9101. mouseY = touches[0].clientY;
  9102. } else {
  9103. mouseX = e.clientX;
  9104. mouseY = e.clientY;
  9105. }
  9106. // Scale mouse coordinates into canvas coordinates
  9107. // by following the pattern laid out by 'jerryj' in the comments of
  9108. // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  9109. var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
  9110. var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
  9111. var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
  9112. var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
  9113. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  9114. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  9115. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  9116. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  9117. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  9118. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  9119. return {
  9120. x: mouseX,
  9121. y: mouseY
  9122. };
  9123. };
  9124. // Private helper function to convert max-width/max-height values that may be percentages into a number
  9125. function parseMaxStyle(styleValue, node, parentProperty) {
  9126. var valueInPixels;
  9127. if (typeof styleValue === 'string') {
  9128. valueInPixels = parseInt(styleValue, 10);
  9129. if (styleValue.indexOf('%') !== -1) {
  9130. // percentage * size in dimension
  9131. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  9132. }
  9133. } else {
  9134. valueInPixels = styleValue;
  9135. }
  9136. return valueInPixels;
  9137. }
  9138. /**
  9139. * Returns if the given value contains an effective constraint.
  9140. * @private
  9141. */
  9142. function isConstrainedValue(value) {
  9143. return value !== undefined && value !== null && value !== 'none';
  9144. }
  9145. /**
  9146. * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
  9147. * @param {HTMLElement} domNode - the node to check the constraint on
  9148. * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
  9149. * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
  9150. * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
  9151. */
  9152. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  9153. var view = document.defaultView;
  9154. var parentNode = helpers$1._getParentNode(domNode);
  9155. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  9156. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  9157. var hasCNode = isConstrainedValue(constrainedNode);
  9158. var hasCContainer = isConstrainedValue(constrainedContainer);
  9159. var infinity = Number.POSITIVE_INFINITY;
  9160. if (hasCNode || hasCContainer) {
  9161. return Math.min(
  9162. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  9163. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  9164. }
  9165. return 'none';
  9166. }
  9167. // returns Number or undefined if no constraint
  9168. helpers$1.getConstraintWidth = function(domNode) {
  9169. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  9170. };
  9171. // returns Number or undefined if no constraint
  9172. helpers$1.getConstraintHeight = function(domNode) {
  9173. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  9174. };
  9175. /**
  9176. * @private
  9177. */
  9178. helpers$1._calculatePadding = function(container, padding, parentDimension) {
  9179. padding = helpers$1.getStyle(container, padding);
  9180. return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
  9181. };
  9182. /**
  9183. * @private
  9184. */
  9185. helpers$1._getParentNode = function(domNode) {
  9186. var parent = domNode.parentNode;
  9187. if (parent && parent.toString() === '[object ShadowRoot]') {
  9188. parent = parent.host;
  9189. }
  9190. return parent;
  9191. };
  9192. helpers$1.getMaximumWidth = function(domNode) {
  9193. var container = helpers$1._getParentNode(domNode);
  9194. if (!container) {
  9195. return domNode.clientWidth;
  9196. }
  9197. var clientWidth = container.clientWidth;
  9198. var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
  9199. var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
  9200. var w = clientWidth - paddingLeft - paddingRight;
  9201. var cw = helpers$1.getConstraintWidth(domNode);
  9202. return isNaN(cw) ? w : Math.min(w, cw);
  9203. };
  9204. helpers$1.getMaximumHeight = function(domNode) {
  9205. var container = helpers$1._getParentNode(domNode);
  9206. if (!container) {
  9207. return domNode.clientHeight;
  9208. }
  9209. var clientHeight = container.clientHeight;
  9210. var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
  9211. var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
  9212. var h = clientHeight - paddingTop - paddingBottom;
  9213. var ch = helpers$1.getConstraintHeight(domNode);
  9214. return isNaN(ch) ? h : Math.min(h, ch);
  9215. };
  9216. helpers$1.getStyle = function(el, property) {
  9217. return el.currentStyle ?
  9218. el.currentStyle[property] :
  9219. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  9220. };
  9221. helpers$1.retinaScale = function(chart, forceRatio) {
  9222. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  9223. if (pixelRatio === 1) {
  9224. return;
  9225. }
  9226. var canvas = chart.canvas;
  9227. var height = chart.height;
  9228. var width = chart.width;
  9229. canvas.height = height * pixelRatio;
  9230. canvas.width = width * pixelRatio;
  9231. chart.ctx.scale(pixelRatio, pixelRatio);
  9232. // If no style has been set on the canvas, the render size is used as display size,
  9233. // making the chart visually bigger, so let's enforce it to the "correct" values.
  9234. // See https://github.com/chartjs/Chart.js/issues/3575
  9235. if (!canvas.style.height && !canvas.style.width) {
  9236. canvas.style.height = height + 'px';
  9237. canvas.style.width = width + 'px';
  9238. }
  9239. };
  9240. // -- Canvas methods
  9241. helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {
  9242. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  9243. };
  9244. helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {
  9245. cache = cache || {};
  9246. var data = cache.data = cache.data || {};
  9247. var gc = cache.garbageCollect = cache.garbageCollect || [];
  9248. if (cache.font !== font) {
  9249. data = cache.data = {};
  9250. gc = cache.garbageCollect = [];
  9251. cache.font = font;
  9252. }
  9253. ctx.font = font;
  9254. var longest = 0;
  9255. var ilen = arrayOfThings.length;
  9256. var i, j, jlen, thing, nestedThing;
  9257. for (i = 0; i < ilen; i++) {
  9258. thing = arrayOfThings[i];
  9259. // Undefined strings and arrays should not be measured
  9260. if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
  9261. longest = helpers$1.measureText(ctx, data, gc, longest, thing);
  9262. } else if (helpers$1.isArray(thing)) {
  9263. // if it is an array lets measure each element
  9264. // to do maybe simplify this function a bit so we can do this more recursively?
  9265. for (j = 0, jlen = thing.length; j < jlen; j++) {
  9266. nestedThing = thing[j];
  9267. // Undefined strings and arrays should not be measured
  9268. if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
  9269. longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
  9270. }
  9271. }
  9272. }
  9273. }
  9274. var gcLen = gc.length / 2;
  9275. if (gcLen > arrayOfThings.length) {
  9276. for (i = 0; i < gcLen; i++) {
  9277. delete data[gc[i]];
  9278. }
  9279. gc.splice(0, gcLen);
  9280. }
  9281. return longest;
  9282. };
  9283. helpers$1.measureText = function(ctx, data, gc, longest, string) {
  9284. var textWidth = data[string];
  9285. if (!textWidth) {
  9286. textWidth = data[string] = ctx.measureText(string).width;
  9287. gc.push(string);
  9288. }
  9289. if (textWidth > longest) {
  9290. longest = textWidth;
  9291. }
  9292. return longest;
  9293. };
  9294. /**
  9295. * @deprecated
  9296. */
  9297. helpers$1.numberOfLabelLines = function(arrayOfThings) {
  9298. var numberOfLines = 1;
  9299. helpers$1.each(arrayOfThings, function(thing) {
  9300. if (helpers$1.isArray(thing)) {
  9301. if (thing.length > numberOfLines) {
  9302. numberOfLines = thing.length;
  9303. }
  9304. }
  9305. });
  9306. return numberOfLines;
  9307. };
  9308. helpers$1.color = !chartjsColor ?
  9309. function(value) {
  9310. console.error('Color.js not found!');
  9311. return value;
  9312. } :
  9313. function(value) {
  9314. /* global CanvasGradient */
  9315. if (value instanceof CanvasGradient) {
  9316. value = core_defaults.global.defaultColor;
  9317. }
  9318. return chartjsColor(value);
  9319. };
  9320. helpers$1.getHoverColor = function(colorValue) {
  9321. /* global CanvasPattern */
  9322. return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
  9323. colorValue :
  9324. helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  9325. };
  9326. };
  9327. function abstract() {
  9328. throw new Error(
  9329. 'This method is not implemented: either no adapter can ' +
  9330. 'be found or an incomplete integration was provided.'
  9331. );
  9332. }
  9333. /**
  9334. * Date adapter (current used by the time scale)
  9335. * @namespace Chart._adapters._date
  9336. * @memberof Chart._adapters
  9337. * @private
  9338. */
  9339. /**
  9340. * Currently supported unit string values.
  9341. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
  9342. * @memberof Chart._adapters._date
  9343. * @name Unit
  9344. */
  9345. /**
  9346. * @class
  9347. */
  9348. function DateAdapter(options) {
  9349. this.options = options || {};
  9350. }
  9351. helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
  9352. /**
  9353. * Returns a map of time formats for the supported formatting units defined
  9354. * in Unit as well as 'datetime' representing a detailed date/time string.
  9355. * @returns {{string: string}}
  9356. */
  9357. formats: abstract,
  9358. /**
  9359. * Parses the given `value` and return the associated timestamp.
  9360. * @param {any} value - the value to parse (usually comes from the data)
  9361. * @param {string} [format] - the expected data format
  9362. * @returns {(number|null)}
  9363. * @function
  9364. */
  9365. parse: abstract,
  9366. /**
  9367. * Returns the formatted date in the specified `format` for a given `timestamp`.
  9368. * @param {number} timestamp - the timestamp to format
  9369. * @param {string} format - the date/time token
  9370. * @return {string}
  9371. * @function
  9372. */
  9373. format: abstract,
  9374. /**
  9375. * Adds the specified `amount` of `unit` to the given `timestamp`.
  9376. * @param {number} timestamp - the input timestamp
  9377. * @param {number} amount - the amount to add
  9378. * @param {Unit} unit - the unit as string
  9379. * @return {number}
  9380. * @function
  9381. */
  9382. add: abstract,
  9383. /**
  9384. * Returns the number of `unit` between the given timestamps.
  9385. * @param {number} max - the input timestamp (reference)
  9386. * @param {number} min - the timestamp to substract
  9387. * @param {Unit} unit - the unit as string
  9388. * @return {number}
  9389. * @function
  9390. */
  9391. diff: abstract,
  9392. /**
  9393. * Returns start of `unit` for the given `timestamp`.
  9394. * @param {number} timestamp - the input timestamp
  9395. * @param {Unit} unit - the unit as string
  9396. * @param {number} [weekday] - the ISO day of the week with 1 being Monday
  9397. * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
  9398. * @function
  9399. */
  9400. startOf: abstract,
  9401. /**
  9402. * Returns end of `unit` for the given `timestamp`.
  9403. * @param {number} timestamp - the input timestamp
  9404. * @param {Unit} unit - the unit as string
  9405. * @function
  9406. */
  9407. endOf: abstract,
  9408. // DEPRECATIONS
  9409. /**
  9410. * Provided for backward compatibility for scale.getValueForPixel(),
  9411. * this method should be overridden only by the moment adapter.
  9412. * @deprecated since version 2.8.0
  9413. * @todo remove at version 3
  9414. * @private
  9415. */
  9416. _create: function(value) {
  9417. return value;
  9418. }
  9419. });
  9420. DateAdapter.override = function(members) {
  9421. helpers$1.extend(DateAdapter.prototype, members);
  9422. };
  9423. var _date = DateAdapter;
  9424. var core_adapters = {
  9425. _date: _date
  9426. };
  9427. /**
  9428. * Namespace to hold static tick generation functions
  9429. * @namespace Chart.Ticks
  9430. */
  9431. var core_ticks = {
  9432. /**
  9433. * Namespace to hold formatters for different types of ticks
  9434. * @namespace Chart.Ticks.formatters
  9435. */
  9436. formatters: {
  9437. /**
  9438. * Formatter for value labels
  9439. * @method Chart.Ticks.formatters.values
  9440. * @param value the value to display
  9441. * @return {string|string[]} the label to display
  9442. */
  9443. values: function(value) {
  9444. return helpers$1.isArray(value) ? value : '' + value;
  9445. },
  9446. /**
  9447. * Formatter for linear numeric ticks
  9448. * @method Chart.Ticks.formatters.linear
  9449. * @param tickValue {number} the value to be formatted
  9450. * @param index {number} the position of the tickValue parameter in the ticks array
  9451. * @param ticks {number[]} the list of ticks being converted
  9452. * @return {string} string representation of the tickValue parameter
  9453. */
  9454. linear: function(tickValue, index, ticks) {
  9455. // If we have lots of ticks, don't use the ones
  9456. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  9457. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  9458. if (Math.abs(delta) > 1) {
  9459. if (tickValue !== Math.floor(tickValue)) {
  9460. // not an integer
  9461. delta = tickValue - Math.floor(tickValue);
  9462. }
  9463. }
  9464. var logDelta = helpers$1.log10(Math.abs(delta));
  9465. var tickString = '';
  9466. if (tickValue !== 0) {
  9467. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  9468. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  9469. var logTick = helpers$1.log10(Math.abs(tickValue));
  9470. var numExponential = Math.floor(logTick) - Math.floor(logDelta);
  9471. numExponential = Math.max(Math.min(numExponential, 20), 0);
  9472. tickString = tickValue.toExponential(numExponential);
  9473. } else {
  9474. var numDecimal = -1 * Math.floor(logDelta);
  9475. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  9476. tickString = tickValue.toFixed(numDecimal);
  9477. }
  9478. } else {
  9479. tickString = '0'; // never show decimal places for 0
  9480. }
  9481. return tickString;
  9482. },
  9483. logarithmic: function(tickValue, index, ticks) {
  9484. var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
  9485. if (tickValue === 0) {
  9486. return '0';
  9487. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  9488. return tickValue.toExponential();
  9489. }
  9490. return '';
  9491. }
  9492. }
  9493. };
  9494. var isArray = helpers$1.isArray;
  9495. var isNullOrUndef = helpers$1.isNullOrUndef;
  9496. var valueOrDefault$a = helpers$1.valueOrDefault;
  9497. var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
  9498. core_defaults._set('scale', {
  9499. display: true,
  9500. position: 'left',
  9501. offset: false,
  9502. // grid line settings
  9503. gridLines: {
  9504. display: true,
  9505. color: 'rgba(0,0,0,0.1)',
  9506. lineWidth: 1,
  9507. drawBorder: true,
  9508. drawOnChartArea: true,
  9509. drawTicks: true,
  9510. tickMarkLength: 10,
  9511. zeroLineWidth: 1,
  9512. zeroLineColor: 'rgba(0,0,0,0.25)',
  9513. zeroLineBorderDash: [],
  9514. zeroLineBorderDashOffset: 0.0,
  9515. offsetGridLines: false,
  9516. borderDash: [],
  9517. borderDashOffset: 0.0
  9518. },
  9519. // scale label
  9520. scaleLabel: {
  9521. // display property
  9522. display: false,
  9523. // actual label
  9524. labelString: '',
  9525. // top/bottom padding
  9526. padding: {
  9527. top: 4,
  9528. bottom: 4
  9529. }
  9530. },
  9531. // label settings
  9532. ticks: {
  9533. beginAtZero: false,
  9534. minRotation: 0,
  9535. maxRotation: 50,
  9536. mirror: false,
  9537. padding: 0,
  9538. reverse: false,
  9539. display: true,
  9540. autoSkip: true,
  9541. autoSkipPadding: 0,
  9542. labelOffset: 0,
  9543. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  9544. callback: core_ticks.formatters.values,
  9545. minor: {},
  9546. major: {}
  9547. }
  9548. });
  9549. /** Returns a new array containing numItems from arr */
  9550. function sample(arr, numItems) {
  9551. var result = [];
  9552. var increment = arr.length / numItems;
  9553. var i = 0;
  9554. var len = arr.length;
  9555. for (; i < len; i += increment) {
  9556. result.push(arr[Math.floor(i)]);
  9557. }
  9558. return result;
  9559. }
  9560. function getPixelForGridLine(scale, index, offsetGridLines) {
  9561. var length = scale.getTicks().length;
  9562. var validIndex = Math.min(index, length - 1);
  9563. var lineValue = scale.getPixelForTick(validIndex);
  9564. var start = scale._startPixel;
  9565. var end = scale._endPixel;
  9566. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  9567. var offset;
  9568. if (offsetGridLines) {
  9569. if (length === 1) {
  9570. offset = Math.max(lineValue - start, end - lineValue);
  9571. } else if (index === 0) {
  9572. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  9573. } else {
  9574. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  9575. }
  9576. lineValue += validIndex < index ? offset : -offset;
  9577. // Return undefined if the pixel is out of the range
  9578. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  9579. return;
  9580. }
  9581. }
  9582. return lineValue;
  9583. }
  9584. function garbageCollect(caches, length) {
  9585. helpers$1.each(caches, function(cache) {
  9586. var gc = cache.gc;
  9587. var gcLen = gc.length / 2;
  9588. var i;
  9589. if (gcLen > length) {
  9590. for (i = 0; i < gcLen; ++i) {
  9591. delete cache.data[gc[i]];
  9592. }
  9593. gc.splice(0, gcLen);
  9594. }
  9595. });
  9596. }
  9597. /**
  9598. * Returns {width, height, offset} objects for the first, last, widest, highest tick
  9599. * labels where offset indicates the anchor point offset from the top in pixels.
  9600. */
  9601. function computeLabelSizes(ctx, tickFonts, ticks, caches) {
  9602. var length = ticks.length;
  9603. var widths = [];
  9604. var heights = [];
  9605. var offsets = [];
  9606. var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest;
  9607. for (i = 0; i < length; ++i) {
  9608. label = ticks[i].label;
  9609. tickFont = ticks[i].major ? tickFonts.major : tickFonts.minor;
  9610. ctx.font = fontString = tickFont.string;
  9611. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  9612. lineHeight = tickFont.lineHeight;
  9613. width = height = 0;
  9614. // Undefined labels and arrays should not be measured
  9615. if (!isNullOrUndef(label) && !isArray(label)) {
  9616. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, label);
  9617. height = lineHeight;
  9618. } else if (isArray(label)) {
  9619. // if it is an array let's measure each element
  9620. for (j = 0, jlen = label.length; j < jlen; ++j) {
  9621. nestedLabel = label[j];
  9622. // Undefined labels and arrays should not be measured
  9623. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  9624. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  9625. height += lineHeight;
  9626. }
  9627. }
  9628. }
  9629. widths.push(width);
  9630. heights.push(height);
  9631. offsets.push(lineHeight / 2);
  9632. }
  9633. garbageCollect(caches, length);
  9634. widest = widths.indexOf(Math.max.apply(null, widths));
  9635. highest = heights.indexOf(Math.max.apply(null, heights));
  9636. function valueAt(idx) {
  9637. return {
  9638. width: widths[idx] || 0,
  9639. height: heights[idx] || 0,
  9640. offset: offsets[idx] || 0
  9641. };
  9642. }
  9643. return {
  9644. first: valueAt(0),
  9645. last: valueAt(length - 1),
  9646. widest: valueAt(widest),
  9647. highest: valueAt(highest)
  9648. };
  9649. }
  9650. function getTickMarkLength(options) {
  9651. return options.drawTicks ? options.tickMarkLength : 0;
  9652. }
  9653. function getScaleLabelHeight(options) {
  9654. var font, padding;
  9655. if (!options.display) {
  9656. return 0;
  9657. }
  9658. font = helpers$1.options._parseFont(options);
  9659. padding = helpers$1.options.toPadding(options.padding);
  9660. return font.lineHeight + padding.height;
  9661. }
  9662. function parseFontOptions(options, nestedOpts) {
  9663. return helpers$1.extend(helpers$1.options._parseFont({
  9664. fontFamily: valueOrDefault$a(nestedOpts.fontFamily, options.fontFamily),
  9665. fontSize: valueOrDefault$a(nestedOpts.fontSize, options.fontSize),
  9666. fontStyle: valueOrDefault$a(nestedOpts.fontStyle, options.fontStyle),
  9667. lineHeight: valueOrDefault$a(nestedOpts.lineHeight, options.lineHeight)
  9668. }), {
  9669. color: helpers$1.options.resolve([nestedOpts.fontColor, options.fontColor, core_defaults.global.defaultFontColor])
  9670. });
  9671. }
  9672. function parseTickFontOptions(options) {
  9673. var minor = parseFontOptions(options, options.minor);
  9674. var major = options.major.enabled ? parseFontOptions(options, options.major) : minor;
  9675. return {minor: minor, major: major};
  9676. }
  9677. function nonSkipped(ticksToFilter) {
  9678. var filtered = [];
  9679. var item, index, len;
  9680. for (index = 0, len = ticksToFilter.length; index < len; ++index) {
  9681. item = ticksToFilter[index];
  9682. if (typeof item._index !== 'undefined') {
  9683. filtered.push(item);
  9684. }
  9685. }
  9686. return filtered;
  9687. }
  9688. function getEvenSpacing(arr) {
  9689. var len = arr.length;
  9690. var i, diff;
  9691. if (len < 2) {
  9692. return false;
  9693. }
  9694. for (diff = arr[0], i = 1; i < len; ++i) {
  9695. if (arr[i] - arr[i - 1] !== diff) {
  9696. return false;
  9697. }
  9698. }
  9699. return diff;
  9700. }
  9701. function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
  9702. var evenMajorSpacing = getEvenSpacing(majorIndices);
  9703. var spacing = (ticks.length - 1) / ticksLimit;
  9704. var factors, factor, i, ilen;
  9705. // If the major ticks are evenly spaced apart, place the minor ticks
  9706. // so that they divide the major ticks into even chunks
  9707. if (!evenMajorSpacing) {
  9708. return Math.max(spacing, 1);
  9709. }
  9710. factors = helpers$1.math._factorize(evenMajorSpacing);
  9711. for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
  9712. factor = factors[i];
  9713. if (factor > spacing) {
  9714. return factor;
  9715. }
  9716. }
  9717. return Math.max(spacing, 1);
  9718. }
  9719. function getMajorIndices(ticks) {
  9720. var result = [];
  9721. var i, ilen;
  9722. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  9723. if (ticks[i].major) {
  9724. result.push(i);
  9725. }
  9726. }
  9727. return result;
  9728. }
  9729. function skipMajors(ticks, majorIndices, spacing) {
  9730. var count = 0;
  9731. var next = majorIndices[0];
  9732. var i, tick;
  9733. spacing = Math.ceil(spacing);
  9734. for (i = 0; i < ticks.length; i++) {
  9735. tick = ticks[i];
  9736. if (i === next) {
  9737. tick._index = i;
  9738. count++;
  9739. next = majorIndices[count * spacing];
  9740. } else {
  9741. delete tick.label;
  9742. }
  9743. }
  9744. }
  9745. function skip(ticks, spacing, majorStart, majorEnd) {
  9746. var start = valueOrDefault$a(majorStart, 0);
  9747. var end = Math.min(valueOrDefault$a(majorEnd, ticks.length), ticks.length);
  9748. var count = 0;
  9749. var length, i, tick, next;
  9750. spacing = Math.ceil(spacing);
  9751. if (majorEnd) {
  9752. length = majorEnd - majorStart;
  9753. spacing = length / Math.floor(length / spacing);
  9754. }
  9755. next = start;
  9756. while (next < 0) {
  9757. count++;
  9758. next = Math.round(start + count * spacing);
  9759. }
  9760. for (i = Math.max(start, 0); i < end; i++) {
  9761. tick = ticks[i];
  9762. if (i === next) {
  9763. tick._index = i;
  9764. count++;
  9765. next = Math.round(start + count * spacing);
  9766. } else {
  9767. delete tick.label;
  9768. }
  9769. }
  9770. }
  9771. var Scale = core_element.extend({
  9772. zeroLineIndex: 0,
  9773. /**
  9774. * Get the padding needed for the scale
  9775. * @method getPadding
  9776. * @private
  9777. * @returns {Padding} the necessary padding
  9778. */
  9779. getPadding: function() {
  9780. var me = this;
  9781. return {
  9782. left: me.paddingLeft || 0,
  9783. top: me.paddingTop || 0,
  9784. right: me.paddingRight || 0,
  9785. bottom: me.paddingBottom || 0
  9786. };
  9787. },
  9788. /**
  9789. * Returns the scale tick objects ({label, major})
  9790. * @since 2.7
  9791. */
  9792. getTicks: function() {
  9793. return this._ticks;
  9794. },
  9795. /**
  9796. * @private
  9797. */
  9798. _getLabels: function() {
  9799. var data = this.chart.data;
  9800. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  9801. },
  9802. // These methods are ordered by lifecyle. Utilities then follow.
  9803. // Any function defined here is inherited by all scale types.
  9804. // Any function can be extended by the scale type
  9805. /**
  9806. * Provided for backward compatibility, not available anymore
  9807. * @function Chart.Scale.mergeTicksOptions
  9808. * @deprecated since version 2.8.0
  9809. * @todo remove at version 3
  9810. */
  9811. mergeTicksOptions: function() {
  9812. // noop
  9813. },
  9814. beforeUpdate: function() {
  9815. helpers$1.callback(this.options.beforeUpdate, [this]);
  9816. },
  9817. /**
  9818. * @param {number} maxWidth - the max width in pixels
  9819. * @param {number} maxHeight - the max height in pixels
  9820. * @param {object} margins - the space between the edge of the other scales and edge of the chart
  9821. * This space comes from two sources:
  9822. * - padding - space that's required to show the labels at the edges of the scale
  9823. * - thickness of scales or legends in another orientation
  9824. */
  9825. update: function(maxWidth, maxHeight, margins) {
  9826. var me = this;
  9827. var tickOpts = me.options.ticks;
  9828. var sampleSize = tickOpts.sampleSize;
  9829. var i, ilen, labels, ticks, samplingEnabled;
  9830. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  9831. me.beforeUpdate();
  9832. // Absorb the master measurements
  9833. me.maxWidth = maxWidth;
  9834. me.maxHeight = maxHeight;
  9835. me.margins = helpers$1.extend({
  9836. left: 0,
  9837. right: 0,
  9838. top: 0,
  9839. bottom: 0
  9840. }, margins);
  9841. me._ticks = null;
  9842. me.ticks = null;
  9843. me._labelSizes = null;
  9844. me._maxLabelLines = 0;
  9845. me.longestLabelWidth = 0;
  9846. me.longestTextCache = me.longestTextCache || {};
  9847. me._gridLineItems = null;
  9848. me._labelItems = null;
  9849. // Dimensions
  9850. me.beforeSetDimensions();
  9851. me.setDimensions();
  9852. me.afterSetDimensions();
  9853. // Data min/max
  9854. me.beforeDataLimits();
  9855. me.determineDataLimits();
  9856. me.afterDataLimits();
  9857. // Ticks - `this.ticks` is now DEPRECATED!
  9858. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  9859. // and must not be accessed directly from outside this class. `this.ticks` being
  9860. // around for long time and not marked as private, we can't change its structure
  9861. // without unexpected breaking changes. If you need to access the scale ticks,
  9862. // use scale.getTicks() instead.
  9863. me.beforeBuildTicks();
  9864. // New implementations should return an array of objects but for BACKWARD COMPAT,
  9865. // we still support no return (`this.ticks` internally set by calling this method).
  9866. ticks = me.buildTicks() || [];
  9867. // Allow modification of ticks in callback.
  9868. ticks = me.afterBuildTicks(ticks) || ticks;
  9869. // Ensure ticks contains ticks in new tick format
  9870. if ((!ticks || !ticks.length) && me.ticks) {
  9871. ticks = [];
  9872. for (i = 0, ilen = me.ticks.length; i < ilen; ++i) {
  9873. ticks.push({
  9874. value: me.ticks[i],
  9875. major: false
  9876. });
  9877. }
  9878. }
  9879. me._ticks = ticks;
  9880. // Compute tick rotation and fit using a sampled subset of labels
  9881. // We generally don't need to compute the size of every single label for determining scale size
  9882. samplingEnabled = sampleSize < ticks.length;
  9883. labels = me._convertTicksToLabels(samplingEnabled ? sample(ticks, sampleSize) : ticks);
  9884. // _configure is called twice, once here, once from core.controller.updateLayout.
  9885. // Here we haven't been positioned yet, but dimensions are correct.
  9886. // Variables set in _configure are needed for calculateTickRotation, and
  9887. // it's ok that coordinates are not correct there, only dimensions matter.
  9888. me._configure();
  9889. // Tick Rotation
  9890. me.beforeCalculateTickRotation();
  9891. me.calculateTickRotation();
  9892. me.afterCalculateTickRotation();
  9893. me.beforeFit();
  9894. me.fit();
  9895. me.afterFit();
  9896. // Auto-skip
  9897. me._ticksToDraw = tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto') ? me._autoSkip(ticks) : ticks;
  9898. if (samplingEnabled) {
  9899. // Generate labels using all non-skipped ticks
  9900. labels = me._convertTicksToLabels(me._ticksToDraw);
  9901. }
  9902. me.ticks = labels; // BACKWARD COMPATIBILITY
  9903. // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
  9904. me.afterUpdate();
  9905. // TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused
  9906. // make maxWidth and maxHeight private
  9907. return me.minSize;
  9908. },
  9909. /**
  9910. * @private
  9911. */
  9912. _configure: function() {
  9913. var me = this;
  9914. var reversePixels = me.options.ticks.reverse;
  9915. var startPixel, endPixel;
  9916. if (me.isHorizontal()) {
  9917. startPixel = me.left;
  9918. endPixel = me.right;
  9919. } else {
  9920. startPixel = me.top;
  9921. endPixel = me.bottom;
  9922. // by default vertical scales are from bottom to top, so pixels are reversed
  9923. reversePixels = !reversePixels;
  9924. }
  9925. me._startPixel = startPixel;
  9926. me._endPixel = endPixel;
  9927. me._reversePixels = reversePixels;
  9928. me._length = endPixel - startPixel;
  9929. },
  9930. afterUpdate: function() {
  9931. helpers$1.callback(this.options.afterUpdate, [this]);
  9932. },
  9933. //
  9934. beforeSetDimensions: function() {
  9935. helpers$1.callback(this.options.beforeSetDimensions, [this]);
  9936. },
  9937. setDimensions: function() {
  9938. var me = this;
  9939. // Set the unconstrained dimension before label rotation
  9940. if (me.isHorizontal()) {
  9941. // Reset position before calculating rotation
  9942. me.width = me.maxWidth;
  9943. me.left = 0;
  9944. me.right = me.width;
  9945. } else {
  9946. me.height = me.maxHeight;
  9947. // Reset position before calculating rotation
  9948. me.top = 0;
  9949. me.bottom = me.height;
  9950. }
  9951. // Reset padding
  9952. me.paddingLeft = 0;
  9953. me.paddingTop = 0;
  9954. me.paddingRight = 0;
  9955. me.paddingBottom = 0;
  9956. },
  9957. afterSetDimensions: function() {
  9958. helpers$1.callback(this.options.afterSetDimensions, [this]);
  9959. },
  9960. // Data limits
  9961. beforeDataLimits: function() {
  9962. helpers$1.callback(this.options.beforeDataLimits, [this]);
  9963. },
  9964. determineDataLimits: helpers$1.noop,
  9965. afterDataLimits: function() {
  9966. helpers$1.callback(this.options.afterDataLimits, [this]);
  9967. },
  9968. //
  9969. beforeBuildTicks: function() {
  9970. helpers$1.callback(this.options.beforeBuildTicks, [this]);
  9971. },
  9972. buildTicks: helpers$1.noop,
  9973. afterBuildTicks: function(ticks) {
  9974. var me = this;
  9975. // ticks is empty for old axis implementations here
  9976. if (isArray(ticks) && ticks.length) {
  9977. return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
  9978. }
  9979. // Support old implementations (that modified `this.ticks` directly in buildTicks)
  9980. me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
  9981. return ticks;
  9982. },
  9983. beforeTickToLabelConversion: function() {
  9984. helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
  9985. },
  9986. convertTicksToLabels: function() {
  9987. var me = this;
  9988. // Convert ticks to strings
  9989. var tickOpts = me.options.ticks;
  9990. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  9991. },
  9992. afterTickToLabelConversion: function() {
  9993. helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
  9994. },
  9995. //
  9996. beforeCalculateTickRotation: function() {
  9997. helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
  9998. },
  9999. calculateTickRotation: function() {
  10000. var me = this;
  10001. var options = me.options;
  10002. var tickOpts = options.ticks;
  10003. var numTicks = me.getTicks().length;
  10004. var minRotation = tickOpts.minRotation || 0;
  10005. var maxRotation = tickOpts.maxRotation;
  10006. var labelRotation = minRotation;
  10007. var labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal;
  10008. if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
  10009. me.labelRotation = minRotation;
  10010. return;
  10011. }
  10012. labelSizes = me._getLabelSizes();
  10013. maxLabelWidth = labelSizes.widest.width;
  10014. maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;
  10015. // Estimate the width of each grid based on the canvas width, the maximum
  10016. // label width and the number of tick intervals
  10017. maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);
  10018. tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
  10019. // Allow 3 pixels x2 padding either side for label readability
  10020. if (maxLabelWidth + 6 > tickWidth) {
  10021. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  10022. maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)
  10023. - tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
  10024. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  10025. labelRotation = helpers$1.toDegrees(Math.min(
  10026. Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
  10027. Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
  10028. ));
  10029. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  10030. }
  10031. me.labelRotation = labelRotation;
  10032. },
  10033. afterCalculateTickRotation: function() {
  10034. helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
  10035. },
  10036. //
  10037. beforeFit: function() {
  10038. helpers$1.callback(this.options.beforeFit, [this]);
  10039. },
  10040. fit: function() {
  10041. var me = this;
  10042. // Reset
  10043. var minSize = me.minSize = {
  10044. width: 0,
  10045. height: 0
  10046. };
  10047. var chart = me.chart;
  10048. var opts = me.options;
  10049. var tickOpts = opts.ticks;
  10050. var scaleLabelOpts = opts.scaleLabel;
  10051. var gridLineOpts = opts.gridLines;
  10052. var display = me._isVisible();
  10053. var isBottom = opts.position === 'bottom';
  10054. var isHorizontal = me.isHorizontal();
  10055. // Width
  10056. if (isHorizontal) {
  10057. minSize.width = me.maxWidth;
  10058. } else if (display) {
  10059. minSize.width = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10060. }
  10061. // height
  10062. if (!isHorizontal) {
  10063. minSize.height = me.maxHeight; // fill all the height
  10064. } else if (display) {
  10065. minSize.height = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10066. }
  10067. // Don't bother fitting the ticks if we are not showing the labels
  10068. if (tickOpts.display && display) {
  10069. var tickFonts = parseTickFontOptions(tickOpts);
  10070. var labelSizes = me._getLabelSizes();
  10071. var firstLabelSize = labelSizes.first;
  10072. var lastLabelSize = labelSizes.last;
  10073. var widestLabelSize = labelSizes.widest;
  10074. var highestLabelSize = labelSizes.highest;
  10075. var lineSpace = tickFonts.minor.lineHeight * 0.4;
  10076. var tickPadding = tickOpts.padding;
  10077. if (isHorizontal) {
  10078. // A horizontal axis is more constrained by the height.
  10079. var isRotated = me.labelRotation !== 0;
  10080. var angleRadians = helpers$1.toRadians(me.labelRotation);
  10081. var cosRotation = Math.cos(angleRadians);
  10082. var sinRotation = Math.sin(angleRadians);
  10083. var labelHeight = sinRotation * widestLabelSize.width
  10084. + cosRotation * (highestLabelSize.height - (isRotated ? highestLabelSize.offset : 0))
  10085. + (isRotated ? 0 : lineSpace); // padding
  10086. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  10087. var offsetLeft = me.getPixelForTick(0) - me.left;
  10088. var offsetRight = me.right - me.getPixelForTick(me.getTicks().length - 1);
  10089. var paddingLeft, paddingRight;
  10090. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  10091. // which means that the right padding is dominated by the font height
  10092. if (isRotated) {
  10093. paddingLeft = isBottom ?
  10094. cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset :
  10095. sinRotation * (firstLabelSize.height - firstLabelSize.offset);
  10096. paddingRight = isBottom ?
  10097. sinRotation * (lastLabelSize.height - lastLabelSize.offset) :
  10098. cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset;
  10099. } else {
  10100. paddingLeft = firstLabelSize.width / 2;
  10101. paddingRight = lastLabelSize.width / 2;
  10102. }
  10103. // Adjust padding taking into account changes in offsets
  10104. // and add 3 px to move away from canvas edges
  10105. me.paddingLeft = Math.max((paddingLeft - offsetLeft) * me.width / (me.width - offsetLeft), 0) + 3;
  10106. me.paddingRight = Math.max((paddingRight - offsetRight) * me.width / (me.width - offsetRight), 0) + 3;
  10107. } else {
  10108. // A vertical axis is more constrained by the width. Labels are the
  10109. // dominant factor here, so get that length first and account for padding
  10110. var labelWidth = tickOpts.mirror ? 0 :
  10111. // use lineSpace for consistency with horizontal axis
  10112. // tickPadding is not implemented for horizontal
  10113. widestLabelSize.width + tickPadding + lineSpace;
  10114. minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth);
  10115. me.paddingTop = firstLabelSize.height / 2;
  10116. me.paddingBottom = lastLabelSize.height / 2;
  10117. }
  10118. }
  10119. me.handleMargins();
  10120. if (isHorizontal) {
  10121. me.width = me._length = chart.width - me.margins.left - me.margins.right;
  10122. me.height = minSize.height;
  10123. } else {
  10124. me.width = minSize.width;
  10125. me.height = me._length = chart.height - me.margins.top - me.margins.bottom;
  10126. }
  10127. },
  10128. /**
  10129. * Handle margins and padding interactions
  10130. * @private
  10131. */
  10132. handleMargins: function() {
  10133. var me = this;
  10134. if (me.margins) {
  10135. me.margins.left = Math.max(me.paddingLeft, me.margins.left);
  10136. me.margins.top = Math.max(me.paddingTop, me.margins.top);
  10137. me.margins.right = Math.max(me.paddingRight, me.margins.right);
  10138. me.margins.bottom = Math.max(me.paddingBottom, me.margins.bottom);
  10139. }
  10140. },
  10141. afterFit: function() {
  10142. helpers$1.callback(this.options.afterFit, [this]);
  10143. },
  10144. // Shared Methods
  10145. isHorizontal: function() {
  10146. var pos = this.options.position;
  10147. return pos === 'top' || pos === 'bottom';
  10148. },
  10149. isFullWidth: function() {
  10150. return this.options.fullWidth;
  10151. },
  10152. // Get the correct value. NaN bad inputs, If the value type is object get the x or y based on whether we are horizontal or not
  10153. getRightValue: function(rawValue) {
  10154. // Null and undefined values first
  10155. if (isNullOrUndef(rawValue)) {
  10156. return NaN;
  10157. }
  10158. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  10159. if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
  10160. return NaN;
  10161. }
  10162. // If it is in fact an object, dive in one more level
  10163. if (rawValue) {
  10164. if (this.isHorizontal()) {
  10165. if (rawValue.x !== undefined) {
  10166. return this.getRightValue(rawValue.x);
  10167. }
  10168. } else if (rawValue.y !== undefined) {
  10169. return this.getRightValue(rawValue.y);
  10170. }
  10171. }
  10172. // Value is good, return it
  10173. return rawValue;
  10174. },
  10175. _convertTicksToLabels: function(ticks) {
  10176. var me = this;
  10177. var labels, i, ilen;
  10178. me.ticks = ticks.map(function(tick) {
  10179. return tick.value;
  10180. });
  10181. me.beforeTickToLabelConversion();
  10182. // New implementations should return the formatted tick labels but for BACKWARD
  10183. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  10184. // this method and supposed to contain only string values).
  10185. labels = me.convertTicksToLabels(ticks) || me.ticks;
  10186. me.afterTickToLabelConversion();
  10187. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  10188. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10189. ticks[i].label = labels[i];
  10190. }
  10191. return labels;
  10192. },
  10193. /**
  10194. * @private
  10195. */
  10196. _getLabelSizes: function() {
  10197. var me = this;
  10198. var labelSizes = me._labelSizes;
  10199. if (!labelSizes) {
  10200. me._labelSizes = labelSizes = computeLabelSizes(me.ctx, parseTickFontOptions(me.options.ticks), me.getTicks(), me.longestTextCache);
  10201. me.longestLabelWidth = labelSizes.widest.width;
  10202. }
  10203. return labelSizes;
  10204. },
  10205. /**
  10206. * @private
  10207. */
  10208. _parseValue: function(value) {
  10209. var start, end, min, max;
  10210. if (isArray(value)) {
  10211. start = +this.getRightValue(value[0]);
  10212. end = +this.getRightValue(value[1]);
  10213. min = Math.min(start, end);
  10214. max = Math.max(start, end);
  10215. } else {
  10216. value = +this.getRightValue(value);
  10217. start = undefined;
  10218. end = value;
  10219. min = value;
  10220. max = value;
  10221. }
  10222. return {
  10223. min: min,
  10224. max: max,
  10225. start: start,
  10226. end: end
  10227. };
  10228. },
  10229. /**
  10230. * @private
  10231. */
  10232. _getScaleLabel: function(rawValue) {
  10233. var v = this._parseValue(rawValue);
  10234. if (v.start !== undefined) {
  10235. return '[' + v.start + ', ' + v.end + ']';
  10236. }
  10237. return +this.getRightValue(rawValue);
  10238. },
  10239. /**
  10240. * Used to get the value to display in the tooltip for the data at the given index
  10241. * @param index
  10242. * @param datasetIndex
  10243. */
  10244. getLabelForIndex: helpers$1.noop,
  10245. /**
  10246. * Returns the location of the given data point. Value can either be an index or a numerical value
  10247. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10248. * @param value
  10249. * @param index
  10250. * @param datasetIndex
  10251. */
  10252. getPixelForValue: helpers$1.noop,
  10253. /**
  10254. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  10255. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10256. * @param pixel
  10257. */
  10258. getValueForPixel: helpers$1.noop,
  10259. /**
  10260. * Returns the location of the tick at the given index
  10261. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10262. */
  10263. getPixelForTick: function(index) {
  10264. var me = this;
  10265. var offset = me.options.offset;
  10266. var numTicks = me._ticks.length;
  10267. var tickWidth = 1 / Math.max(numTicks - (offset ? 0 : 1), 1);
  10268. return index < 0 || index > numTicks - 1
  10269. ? null
  10270. : me.getPixelForDecimal(index * tickWidth + (offset ? tickWidth / 2 : 0));
  10271. },
  10272. /**
  10273. * Utility for getting the pixel location of a percentage of scale
  10274. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10275. */
  10276. getPixelForDecimal: function(decimal) {
  10277. var me = this;
  10278. if (me._reversePixels) {
  10279. decimal = 1 - decimal;
  10280. }
  10281. return me._startPixel + decimal * me._length;
  10282. },
  10283. getDecimalForPixel: function(pixel) {
  10284. var decimal = (pixel - this._startPixel) / this._length;
  10285. return this._reversePixels ? 1 - decimal : decimal;
  10286. },
  10287. /**
  10288. * Returns the pixel for the minimum chart value
  10289. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10290. */
  10291. getBasePixel: function() {
  10292. return this.getPixelForValue(this.getBaseValue());
  10293. },
  10294. getBaseValue: function() {
  10295. var me = this;
  10296. var min = me.min;
  10297. var max = me.max;
  10298. return me.beginAtZero ? 0 :
  10299. min < 0 && max < 0 ? max :
  10300. min > 0 && max > 0 ? min :
  10301. 0;
  10302. },
  10303. /**
  10304. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  10305. * @private
  10306. */
  10307. _autoSkip: function(ticks) {
  10308. var me = this;
  10309. var tickOpts = me.options.ticks;
  10310. var axisLength = me._length;
  10311. var ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1;
  10312. var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  10313. var numMajorIndices = majorIndices.length;
  10314. var first = majorIndices[0];
  10315. var last = majorIndices[numMajorIndices - 1];
  10316. var i, ilen, spacing, avgMajorSpacing;
  10317. // If there are too many major ticks to display them all
  10318. if (numMajorIndices > ticksLimit) {
  10319. skipMajors(ticks, majorIndices, numMajorIndices / ticksLimit);
  10320. return nonSkipped(ticks);
  10321. }
  10322. spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit);
  10323. if (numMajorIndices > 0) {
  10324. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  10325. skip(ticks, spacing, majorIndices[i], majorIndices[i + 1]);
  10326. }
  10327. avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null;
  10328. skip(ticks, spacing, helpers$1.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  10329. skip(ticks, spacing, last, helpers$1.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  10330. return nonSkipped(ticks);
  10331. }
  10332. skip(ticks, spacing);
  10333. return nonSkipped(ticks);
  10334. },
  10335. /**
  10336. * @private
  10337. */
  10338. _tickSize: function() {
  10339. var me = this;
  10340. var optionTicks = me.options.ticks;
  10341. // Calculate space needed by label in axis direction.
  10342. var rot = helpers$1.toRadians(me.labelRotation);
  10343. var cos = Math.abs(Math.cos(rot));
  10344. var sin = Math.abs(Math.sin(rot));
  10345. var labelSizes = me._getLabelSizes();
  10346. var padding = optionTicks.autoSkipPadding || 0;
  10347. var w = labelSizes ? labelSizes.widest.width + padding : 0;
  10348. var h = labelSizes ? labelSizes.highest.height + padding : 0;
  10349. // Calculate space needed for 1 tick in axis direction.
  10350. return me.isHorizontal()
  10351. ? h * cos > w * sin ? w / cos : h / sin
  10352. : h * sin < w * cos ? h / cos : w / sin;
  10353. },
  10354. /**
  10355. * @private
  10356. */
  10357. _isVisible: function() {
  10358. var me = this;
  10359. var chart = me.chart;
  10360. var display = me.options.display;
  10361. var i, ilen, meta;
  10362. if (display !== 'auto') {
  10363. return !!display;
  10364. }
  10365. // When 'auto', the scale is visible if at least one associated dataset is visible.
  10366. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  10367. if (chart.isDatasetVisible(i)) {
  10368. meta = chart.getDatasetMeta(i);
  10369. if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
  10370. return true;
  10371. }
  10372. }
  10373. }
  10374. return false;
  10375. },
  10376. /**
  10377. * @private
  10378. */
  10379. _computeGridLineItems: function(chartArea) {
  10380. var me = this;
  10381. var chart = me.chart;
  10382. var options = me.options;
  10383. var gridLines = options.gridLines;
  10384. var position = options.position;
  10385. var offsetGridLines = gridLines.offsetGridLines;
  10386. var isHorizontal = me.isHorizontal();
  10387. var ticks = me._ticksToDraw;
  10388. var ticksLength = ticks.length + (offsetGridLines ? 1 : 0);
  10389. var tl = getTickMarkLength(gridLines);
  10390. var items = [];
  10391. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10392. var axisHalfWidth = axisWidth / 2;
  10393. var alignPixel = helpers$1._alignPixel;
  10394. var alignBorderValue = function(pixel) {
  10395. return alignPixel(chart, pixel, axisWidth);
  10396. };
  10397. var borderValue, i, tick, lineValue, alignedLineValue;
  10398. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, lineWidth, lineColor, borderDash, borderDashOffset;
  10399. if (position === 'top') {
  10400. borderValue = alignBorderValue(me.bottom);
  10401. ty1 = me.bottom - tl;
  10402. ty2 = borderValue - axisHalfWidth;
  10403. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  10404. y2 = chartArea.bottom;
  10405. } else if (position === 'bottom') {
  10406. borderValue = alignBorderValue(me.top);
  10407. y1 = chartArea.top;
  10408. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  10409. ty1 = borderValue + axisHalfWidth;
  10410. ty2 = me.top + tl;
  10411. } else if (position === 'left') {
  10412. borderValue = alignBorderValue(me.right);
  10413. tx1 = me.right - tl;
  10414. tx2 = borderValue - axisHalfWidth;
  10415. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  10416. x2 = chartArea.right;
  10417. } else {
  10418. borderValue = alignBorderValue(me.left);
  10419. x1 = chartArea.left;
  10420. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  10421. tx1 = borderValue + axisHalfWidth;
  10422. tx2 = me.left + tl;
  10423. }
  10424. for (i = 0; i < ticksLength; ++i) {
  10425. tick = ticks[i] || {};
  10426. // autoskipper skipped this tick (#4635)
  10427. if (isNullOrUndef(tick.label) && i < ticks.length) {
  10428. continue;
  10429. }
  10430. if (i === me.zeroLineIndex && options.offset === offsetGridLines) {
  10431. // Draw the first index specially
  10432. lineWidth = gridLines.zeroLineWidth;
  10433. lineColor = gridLines.zeroLineColor;
  10434. borderDash = gridLines.zeroLineBorderDash || [];
  10435. borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
  10436. } else {
  10437. lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, i, 1);
  10438. lineColor = valueAtIndexOrDefault(gridLines.color, i, 'rgba(0,0,0,0.1)');
  10439. borderDash = gridLines.borderDash || [];
  10440. borderDashOffset = gridLines.borderDashOffset || 0.0;
  10441. }
  10442. lineValue = getPixelForGridLine(me, tick._index || i, offsetGridLines);
  10443. // Skip if the pixel is out of the range
  10444. if (lineValue === undefined) {
  10445. continue;
  10446. }
  10447. alignedLineValue = alignPixel(chart, lineValue, lineWidth);
  10448. if (isHorizontal) {
  10449. tx1 = tx2 = x1 = x2 = alignedLineValue;
  10450. } else {
  10451. ty1 = ty2 = y1 = y2 = alignedLineValue;
  10452. }
  10453. items.push({
  10454. tx1: tx1,
  10455. ty1: ty1,
  10456. tx2: tx2,
  10457. ty2: ty2,
  10458. x1: x1,
  10459. y1: y1,
  10460. x2: x2,
  10461. y2: y2,
  10462. width: lineWidth,
  10463. color: lineColor,
  10464. borderDash: borderDash,
  10465. borderDashOffset: borderDashOffset,
  10466. });
  10467. }
  10468. items.ticksLength = ticksLength;
  10469. items.borderValue = borderValue;
  10470. return items;
  10471. },
  10472. /**
  10473. * @private
  10474. */
  10475. _computeLabelItems: function() {
  10476. var me = this;
  10477. var options = me.options;
  10478. var optionTicks = options.ticks;
  10479. var position = options.position;
  10480. var isMirrored = optionTicks.mirror;
  10481. var isHorizontal = me.isHorizontal();
  10482. var ticks = me._ticksToDraw;
  10483. var fonts = parseTickFontOptions(optionTicks);
  10484. var tickPadding = optionTicks.padding;
  10485. var tl = getTickMarkLength(options.gridLines);
  10486. var rotation = -helpers$1.toRadians(me.labelRotation);
  10487. var items = [];
  10488. var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  10489. if (position === 'top') {
  10490. y = me.bottom - tl - tickPadding;
  10491. textAlign = !rotation ? 'center' : 'left';
  10492. } else if (position === 'bottom') {
  10493. y = me.top + tl + tickPadding;
  10494. textAlign = !rotation ? 'center' : 'right';
  10495. } else if (position === 'left') {
  10496. x = me.right - (isMirrored ? 0 : tl) - tickPadding;
  10497. textAlign = isMirrored ? 'left' : 'right';
  10498. } else {
  10499. x = me.left + (isMirrored ? 0 : tl) + tickPadding;
  10500. textAlign = isMirrored ? 'right' : 'left';
  10501. }
  10502. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10503. tick = ticks[i];
  10504. label = tick.label;
  10505. // autoskipper skipped this tick (#4635)
  10506. if (isNullOrUndef(label)) {
  10507. continue;
  10508. }
  10509. pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset;
  10510. font = tick.major ? fonts.major : fonts.minor;
  10511. lineHeight = font.lineHeight;
  10512. lineCount = isArray(label) ? label.length : 1;
  10513. if (isHorizontal) {
  10514. x = pixel;
  10515. textOffset = position === 'top'
  10516. ? ((!rotation ? 0.5 : 1) - lineCount) * lineHeight
  10517. : (!rotation ? 0.5 : 0) * lineHeight;
  10518. } else {
  10519. y = pixel;
  10520. textOffset = (1 - lineCount) * lineHeight / 2;
  10521. }
  10522. items.push({
  10523. x: x,
  10524. y: y,
  10525. rotation: rotation,
  10526. label: label,
  10527. font: font,
  10528. textOffset: textOffset,
  10529. textAlign: textAlign
  10530. });
  10531. }
  10532. return items;
  10533. },
  10534. /**
  10535. * @private
  10536. */
  10537. _drawGrid: function(chartArea) {
  10538. var me = this;
  10539. var gridLines = me.options.gridLines;
  10540. if (!gridLines.display) {
  10541. return;
  10542. }
  10543. var ctx = me.ctx;
  10544. var chart = me.chart;
  10545. var alignPixel = helpers$1._alignPixel;
  10546. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10547. var items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
  10548. var width, color, i, ilen, item;
  10549. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10550. item = items[i];
  10551. width = item.width;
  10552. color = item.color;
  10553. if (width && color) {
  10554. ctx.save();
  10555. ctx.lineWidth = width;
  10556. ctx.strokeStyle = color;
  10557. if (ctx.setLineDash) {
  10558. ctx.setLineDash(item.borderDash);
  10559. ctx.lineDashOffset = item.borderDashOffset;
  10560. }
  10561. ctx.beginPath();
  10562. if (gridLines.drawTicks) {
  10563. ctx.moveTo(item.tx1, item.ty1);
  10564. ctx.lineTo(item.tx2, item.ty2);
  10565. }
  10566. if (gridLines.drawOnChartArea) {
  10567. ctx.moveTo(item.x1, item.y1);
  10568. ctx.lineTo(item.x2, item.y2);
  10569. }
  10570. ctx.stroke();
  10571. ctx.restore();
  10572. }
  10573. }
  10574. if (axisWidth) {
  10575. // Draw the line at the edge of the axis
  10576. var firstLineWidth = axisWidth;
  10577. var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, items.ticksLength - 1, 1);
  10578. var borderValue = items.borderValue;
  10579. var x1, x2, y1, y2;
  10580. if (me.isHorizontal()) {
  10581. x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
  10582. x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  10583. y1 = y2 = borderValue;
  10584. } else {
  10585. y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
  10586. y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  10587. x1 = x2 = borderValue;
  10588. }
  10589. ctx.lineWidth = axisWidth;
  10590. ctx.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
  10591. ctx.beginPath();
  10592. ctx.moveTo(x1, y1);
  10593. ctx.lineTo(x2, y2);
  10594. ctx.stroke();
  10595. }
  10596. },
  10597. /**
  10598. * @private
  10599. */
  10600. _drawLabels: function() {
  10601. var me = this;
  10602. var optionTicks = me.options.ticks;
  10603. if (!optionTicks.display) {
  10604. return;
  10605. }
  10606. var ctx = me.ctx;
  10607. var items = me._labelItems || (me._labelItems = me._computeLabelItems());
  10608. var i, j, ilen, jlen, item, tickFont, label, y;
  10609. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10610. item = items[i];
  10611. tickFont = item.font;
  10612. // Make sure we draw text in the correct color and font
  10613. ctx.save();
  10614. ctx.translate(item.x, item.y);
  10615. ctx.rotate(item.rotation);
  10616. ctx.font = tickFont.string;
  10617. ctx.fillStyle = tickFont.color;
  10618. ctx.textBaseline = 'middle';
  10619. ctx.textAlign = item.textAlign;
  10620. label = item.label;
  10621. y = item.textOffset;
  10622. if (isArray(label)) {
  10623. for (j = 0, jlen = label.length; j < jlen; ++j) {
  10624. // We just make sure the multiline element is a string here..
  10625. ctx.fillText('' + label[j], 0, y);
  10626. y += tickFont.lineHeight;
  10627. }
  10628. } else {
  10629. ctx.fillText(label, 0, y);
  10630. }
  10631. ctx.restore();
  10632. }
  10633. },
  10634. /**
  10635. * @private
  10636. */
  10637. _drawTitle: function() {
  10638. var me = this;
  10639. var ctx = me.ctx;
  10640. var options = me.options;
  10641. var scaleLabel = options.scaleLabel;
  10642. if (!scaleLabel.display) {
  10643. return;
  10644. }
  10645. var scaleLabelFontColor = valueOrDefault$a(scaleLabel.fontColor, core_defaults.global.defaultFontColor);
  10646. var scaleLabelFont = helpers$1.options._parseFont(scaleLabel);
  10647. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
  10648. var halfLineHeight = scaleLabelFont.lineHeight / 2;
  10649. var position = options.position;
  10650. var rotation = 0;
  10651. var scaleLabelX, scaleLabelY;
  10652. if (me.isHorizontal()) {
  10653. scaleLabelX = me.left + me.width / 2; // midpoint of the width
  10654. scaleLabelY = position === 'bottom'
  10655. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  10656. : me.top + halfLineHeight + scaleLabelPadding.top;
  10657. } else {
  10658. var isLeft = position === 'left';
  10659. scaleLabelX = isLeft
  10660. ? me.left + halfLineHeight + scaleLabelPadding.top
  10661. : me.right - halfLineHeight - scaleLabelPadding.top;
  10662. scaleLabelY = me.top + me.height / 2;
  10663. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  10664. }
  10665. ctx.save();
  10666. ctx.translate(scaleLabelX, scaleLabelY);
  10667. ctx.rotate(rotation);
  10668. ctx.textAlign = 'center';
  10669. ctx.textBaseline = 'middle';
  10670. ctx.fillStyle = scaleLabelFontColor; // render in correct colour
  10671. ctx.font = scaleLabelFont.string;
  10672. ctx.fillText(scaleLabel.labelString, 0, 0);
  10673. ctx.restore();
  10674. },
  10675. draw: function(chartArea) {
  10676. var me = this;
  10677. if (!me._isVisible()) {
  10678. return;
  10679. }
  10680. me._drawGrid(chartArea);
  10681. me._drawTitle();
  10682. me._drawLabels();
  10683. },
  10684. /**
  10685. * @private
  10686. */
  10687. _layers: function() {
  10688. var me = this;
  10689. var opts = me.options;
  10690. var tz = opts.ticks && opts.ticks.z || 0;
  10691. var gz = opts.gridLines && opts.gridLines.z || 0;
  10692. if (!me._isVisible() || tz === gz || me.draw !== me._draw) {
  10693. // backward compatibility: draw has been overridden by custom scale
  10694. return [{
  10695. z: tz,
  10696. draw: function() {
  10697. me.draw.apply(me, arguments);
  10698. }
  10699. }];
  10700. }
  10701. return [{
  10702. z: gz,
  10703. draw: function() {
  10704. me._drawGrid.apply(me, arguments);
  10705. me._drawTitle.apply(me, arguments);
  10706. }
  10707. }, {
  10708. z: tz,
  10709. draw: function() {
  10710. me._drawLabels.apply(me, arguments);
  10711. }
  10712. }];
  10713. },
  10714. /**
  10715. * @private
  10716. */
  10717. _getMatchingVisibleMetas: function(type) {
  10718. var me = this;
  10719. var isHorizontal = me.isHorizontal();
  10720. return me.chart._getSortedVisibleDatasetMetas()
  10721. .filter(function(meta) {
  10722. return (!type || meta.type === type)
  10723. && (isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id);
  10724. });
  10725. }
  10726. });
  10727. Scale.prototype._draw = Scale.prototype.draw;
  10728. var core_scale = Scale;
  10729. var isNullOrUndef$1 = helpers$1.isNullOrUndef;
  10730. var defaultConfig = {
  10731. position: 'bottom'
  10732. };
  10733. var scale_category = core_scale.extend({
  10734. determineDataLimits: function() {
  10735. var me = this;
  10736. var labels = me._getLabels();
  10737. var ticksOpts = me.options.ticks;
  10738. var min = ticksOpts.min;
  10739. var max = ticksOpts.max;
  10740. var minIndex = 0;
  10741. var maxIndex = labels.length - 1;
  10742. var findIndex;
  10743. if (min !== undefined) {
  10744. // user specified min value
  10745. findIndex = labels.indexOf(min);
  10746. if (findIndex >= 0) {
  10747. minIndex = findIndex;
  10748. }
  10749. }
  10750. if (max !== undefined) {
  10751. // user specified max value
  10752. findIndex = labels.indexOf(max);
  10753. if (findIndex >= 0) {
  10754. maxIndex = findIndex;
  10755. }
  10756. }
  10757. me.minIndex = minIndex;
  10758. me.maxIndex = maxIndex;
  10759. me.min = labels[minIndex];
  10760. me.max = labels[maxIndex];
  10761. },
  10762. buildTicks: function() {
  10763. var me = this;
  10764. var labels = me._getLabels();
  10765. var minIndex = me.minIndex;
  10766. var maxIndex = me.maxIndex;
  10767. // If we are viewing some subset of labels, slice the original array
  10768. me.ticks = (minIndex === 0 && maxIndex === labels.length - 1) ? labels : labels.slice(minIndex, maxIndex + 1);
  10769. },
  10770. getLabelForIndex: function(index, datasetIndex) {
  10771. var me = this;
  10772. var chart = me.chart;
  10773. if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {
  10774. return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);
  10775. }
  10776. return me._getLabels()[index];
  10777. },
  10778. _configure: function() {
  10779. var me = this;
  10780. var offset = me.options.offset;
  10781. var ticks = me.ticks;
  10782. core_scale.prototype._configure.call(me);
  10783. if (!me.isHorizontal()) {
  10784. // For backward compatibility, vertical category scale reverse is inverted.
  10785. me._reversePixels = !me._reversePixels;
  10786. }
  10787. if (!ticks) {
  10788. return;
  10789. }
  10790. me._startValue = me.minIndex - (offset ? 0.5 : 0);
  10791. me._valueRange = Math.max(ticks.length - (offset ? 0 : 1), 1);
  10792. },
  10793. // Used to get data value locations. Value can either be an index or a numerical value
  10794. getPixelForValue: function(value, index, datasetIndex) {
  10795. var me = this;
  10796. var valueCategory, labels, idx;
  10797. if (!isNullOrUndef$1(index) && !isNullOrUndef$1(datasetIndex)) {
  10798. value = me.chart.data.datasets[datasetIndex].data[index];
  10799. }
  10800. // If value is a data object, then index is the index in the data array,
  10801. // not the index of the scale. We need to change that.
  10802. if (!isNullOrUndef$1(value)) {
  10803. valueCategory = me.isHorizontal() ? value.x : value.y;
  10804. }
  10805. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  10806. labels = me._getLabels();
  10807. value = helpers$1.valueOrDefault(valueCategory, value);
  10808. idx = labels.indexOf(value);
  10809. index = idx !== -1 ? idx : index;
  10810. if (isNaN(index)) {
  10811. index = value;
  10812. }
  10813. }
  10814. return me.getPixelForDecimal((index - me._startValue) / me._valueRange);
  10815. },
  10816. getPixelForTick: function(index) {
  10817. var ticks = this.ticks;
  10818. return index < 0 || index > ticks.length - 1
  10819. ? null
  10820. : this.getPixelForValue(ticks[index], index + this.minIndex);
  10821. },
  10822. getValueForPixel: function(pixel) {
  10823. var me = this;
  10824. var value = Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
  10825. return Math.min(Math.max(value, 0), me.ticks.length - 1);
  10826. },
  10827. getBasePixel: function() {
  10828. return this.bottom;
  10829. }
  10830. });
  10831. // INTERNAL: static default options, registered in src/index.js
  10832. var _defaults = defaultConfig;
  10833. scale_category._defaults = _defaults;
  10834. var noop = helpers$1.noop;
  10835. var isNullOrUndef$2 = helpers$1.isNullOrUndef;
  10836. /**
  10837. * Generate a set of linear ticks
  10838. * @param generationOptions the options used to generate the ticks
  10839. * @param dataRange the range of the data
  10840. * @returns {number[]} array of tick values
  10841. */
  10842. function generateTicks(generationOptions, dataRange) {
  10843. var ticks = [];
  10844. // To get a "nice" value for the tick spacing, we will use the appropriately named
  10845. // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  10846. // for details.
  10847. var MIN_SPACING = 1e-14;
  10848. var stepSize = generationOptions.stepSize;
  10849. var unit = stepSize || 1;
  10850. var maxNumSpaces = generationOptions.maxTicks - 1;
  10851. var min = generationOptions.min;
  10852. var max = generationOptions.max;
  10853. var precision = generationOptions.precision;
  10854. var rmin = dataRange.min;
  10855. var rmax = dataRange.max;
  10856. var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
  10857. var factor, niceMin, niceMax, numSpaces;
  10858. // Beyond MIN_SPACING floating point numbers being to lose precision
  10859. // such that we can't do the math necessary to generate ticks
  10860. if (spacing < MIN_SPACING && isNullOrUndef$2(min) && isNullOrUndef$2(max)) {
  10861. return [rmin, rmax];
  10862. }
  10863. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  10864. if (numSpaces > maxNumSpaces) {
  10865. // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
  10866. spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
  10867. }
  10868. if (stepSize || isNullOrUndef$2(precision)) {
  10869. // If a precision is not specified, calculate factor based on spacing
  10870. factor = Math.pow(10, helpers$1._decimalPlaces(spacing));
  10871. } else {
  10872. // If the user specified a precision, round to that number of decimal places
  10873. factor = Math.pow(10, precision);
  10874. spacing = Math.ceil(spacing * factor) / factor;
  10875. }
  10876. niceMin = Math.floor(rmin / spacing) * spacing;
  10877. niceMax = Math.ceil(rmax / spacing) * spacing;
  10878. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  10879. if (stepSize) {
  10880. // If very close to our whole number, use it.
  10881. if (!isNullOrUndef$2(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
  10882. niceMin = min;
  10883. }
  10884. if (!isNullOrUndef$2(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
  10885. niceMax = max;
  10886. }
  10887. }
  10888. numSpaces = (niceMax - niceMin) / spacing;
  10889. // If very close to our rounded value, use it.
  10890. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  10891. numSpaces = Math.round(numSpaces);
  10892. } else {
  10893. numSpaces = Math.ceil(numSpaces);
  10894. }
  10895. niceMin = Math.round(niceMin * factor) / factor;
  10896. niceMax = Math.round(niceMax * factor) / factor;
  10897. ticks.push(isNullOrUndef$2(min) ? niceMin : min);
  10898. for (var j = 1; j < numSpaces; ++j) {
  10899. ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
  10900. }
  10901. ticks.push(isNullOrUndef$2(max) ? niceMax : max);
  10902. return ticks;
  10903. }
  10904. var scale_linearbase = core_scale.extend({
  10905. getRightValue: function(value) {
  10906. if (typeof value === 'string') {
  10907. return +value;
  10908. }
  10909. return core_scale.prototype.getRightValue.call(this, value);
  10910. },
  10911. handleTickRangeOptions: function() {
  10912. var me = this;
  10913. var opts = me.options;
  10914. var tickOpts = opts.ticks;
  10915. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  10916. // do nothing since that would make the chart weird. If the user really wants a weird chart
  10917. // axis, they can manually override it
  10918. if (tickOpts.beginAtZero) {
  10919. var minSign = helpers$1.sign(me.min);
  10920. var maxSign = helpers$1.sign(me.max);
  10921. if (minSign < 0 && maxSign < 0) {
  10922. // move the top up to 0
  10923. me.max = 0;
  10924. } else if (minSign > 0 && maxSign > 0) {
  10925. // move the bottom down to 0
  10926. me.min = 0;
  10927. }
  10928. }
  10929. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  10930. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  10931. if (tickOpts.min !== undefined) {
  10932. me.min = tickOpts.min;
  10933. } else if (tickOpts.suggestedMin !== undefined) {
  10934. if (me.min === null) {
  10935. me.min = tickOpts.suggestedMin;
  10936. } else {
  10937. me.min = Math.min(me.min, tickOpts.suggestedMin);
  10938. }
  10939. }
  10940. if (tickOpts.max !== undefined) {
  10941. me.max = tickOpts.max;
  10942. } else if (tickOpts.suggestedMax !== undefined) {
  10943. if (me.max === null) {
  10944. me.max = tickOpts.suggestedMax;
  10945. } else {
  10946. me.max = Math.max(me.max, tickOpts.suggestedMax);
  10947. }
  10948. }
  10949. if (setMin !== setMax) {
  10950. // We set the min or the max but not both.
  10951. // So ensure that our range is good
  10952. // Inverted or 0 length range can happen when
  10953. // ticks.min is set, and no datasets are visible
  10954. if (me.min >= me.max) {
  10955. if (setMin) {
  10956. me.max = me.min + 1;
  10957. } else {
  10958. me.min = me.max - 1;
  10959. }
  10960. }
  10961. }
  10962. if (me.min === me.max) {
  10963. me.max++;
  10964. if (!tickOpts.beginAtZero) {
  10965. me.min--;
  10966. }
  10967. }
  10968. },
  10969. getTickLimit: function() {
  10970. var me = this;
  10971. var tickOpts = me.options.ticks;
  10972. var stepSize = tickOpts.stepSize;
  10973. var maxTicksLimit = tickOpts.maxTicksLimit;
  10974. var maxTicks;
  10975. if (stepSize) {
  10976. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  10977. } else {
  10978. maxTicks = me._computeTickLimit();
  10979. maxTicksLimit = maxTicksLimit || 11;
  10980. }
  10981. if (maxTicksLimit) {
  10982. maxTicks = Math.min(maxTicksLimit, maxTicks);
  10983. }
  10984. return maxTicks;
  10985. },
  10986. _computeTickLimit: function() {
  10987. return Number.POSITIVE_INFINITY;
  10988. },
  10989. handleDirectionalChanges: noop,
  10990. buildTicks: function() {
  10991. var me = this;
  10992. var opts = me.options;
  10993. var tickOpts = opts.ticks;
  10994. // Figure out what the max number of ticks we can support it is based on the size of
  10995. // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
  10996. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  10997. // the graph. Make sure we always have at least 2 ticks
  10998. var maxTicks = me.getTickLimit();
  10999. maxTicks = Math.max(2, maxTicks);
  11000. var numericGeneratorOptions = {
  11001. maxTicks: maxTicks,
  11002. min: tickOpts.min,
  11003. max: tickOpts.max,
  11004. precision: tickOpts.precision,
  11005. stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  11006. };
  11007. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  11008. me.handleDirectionalChanges();
  11009. // At this point, we need to update our max and min given the tick values since we have expanded the
  11010. // range of the scale
  11011. me.max = helpers$1.max(ticks);
  11012. me.min = helpers$1.min(ticks);
  11013. if (tickOpts.reverse) {
  11014. ticks.reverse();
  11015. me.start = me.max;
  11016. me.end = me.min;
  11017. } else {
  11018. me.start = me.min;
  11019. me.end = me.max;
  11020. }
  11021. },
  11022. convertTicksToLabels: function() {
  11023. var me = this;
  11024. me.ticksAsNumbers = me.ticks.slice();
  11025. me.zeroLineIndex = me.ticks.indexOf(0);
  11026. core_scale.prototype.convertTicksToLabels.call(me);
  11027. },
  11028. _configure: function() {
  11029. var me = this;
  11030. var ticks = me.getTicks();
  11031. var start = me.min;
  11032. var end = me.max;
  11033. var offset;
  11034. core_scale.prototype._configure.call(me);
  11035. if (me.options.offset && ticks.length) {
  11036. offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  11037. start -= offset;
  11038. end += offset;
  11039. }
  11040. me._startValue = start;
  11041. me._endValue = end;
  11042. me._valueRange = end - start;
  11043. }
  11044. });
  11045. var defaultConfig$1 = {
  11046. position: 'left',
  11047. ticks: {
  11048. callback: core_ticks.formatters.linear
  11049. }
  11050. };
  11051. var DEFAULT_MIN = 0;
  11052. var DEFAULT_MAX = 1;
  11053. function getOrCreateStack(stacks, stacked, meta) {
  11054. var key = [
  11055. meta.type,
  11056. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11057. stacked === undefined && meta.stack === undefined ? meta.index : '',
  11058. meta.stack
  11059. ].join('.');
  11060. if (stacks[key] === undefined) {
  11061. stacks[key] = {
  11062. pos: [],
  11063. neg: []
  11064. };
  11065. }
  11066. return stacks[key];
  11067. }
  11068. function stackData(scale, stacks, meta, data) {
  11069. var opts = scale.options;
  11070. var stacked = opts.stacked;
  11071. var stack = getOrCreateStack(stacks, stacked, meta);
  11072. var pos = stack.pos;
  11073. var neg = stack.neg;
  11074. var ilen = data.length;
  11075. var i, value;
  11076. for (i = 0; i < ilen; ++i) {
  11077. value = scale._parseValue(data[i]);
  11078. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11079. continue;
  11080. }
  11081. pos[i] = pos[i] || 0;
  11082. neg[i] = neg[i] || 0;
  11083. if (opts.relativePoints) {
  11084. pos[i] = 100;
  11085. } else if (value.min < 0 || value.max < 0) {
  11086. neg[i] += value.min;
  11087. } else {
  11088. pos[i] += value.max;
  11089. }
  11090. }
  11091. }
  11092. function updateMinMax(scale, meta, data) {
  11093. var ilen = data.length;
  11094. var i, value;
  11095. for (i = 0; i < ilen; ++i) {
  11096. value = scale._parseValue(data[i]);
  11097. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11098. continue;
  11099. }
  11100. scale.min = Math.min(scale.min, value.min);
  11101. scale.max = Math.max(scale.max, value.max);
  11102. }
  11103. }
  11104. var scale_linear = scale_linearbase.extend({
  11105. determineDataLimits: function() {
  11106. var me = this;
  11107. var opts = me.options;
  11108. var chart = me.chart;
  11109. var datasets = chart.data.datasets;
  11110. var metasets = me._getMatchingVisibleMetas();
  11111. var hasStacks = opts.stacked;
  11112. var stacks = {};
  11113. var ilen = metasets.length;
  11114. var i, meta, data, values;
  11115. me.min = Number.POSITIVE_INFINITY;
  11116. me.max = Number.NEGATIVE_INFINITY;
  11117. if (hasStacks === undefined) {
  11118. for (i = 0; !hasStacks && i < ilen; ++i) {
  11119. meta = metasets[i];
  11120. hasStacks = meta.stack !== undefined;
  11121. }
  11122. }
  11123. for (i = 0; i < ilen; ++i) {
  11124. meta = metasets[i];
  11125. data = datasets[meta.index].data;
  11126. if (hasStacks) {
  11127. stackData(me, stacks, meta, data);
  11128. } else {
  11129. updateMinMax(me, meta, data);
  11130. }
  11131. }
  11132. helpers$1.each(stacks, function(stackValues) {
  11133. values = stackValues.pos.concat(stackValues.neg);
  11134. me.min = Math.min(me.min, helpers$1.min(values));
  11135. me.max = Math.max(me.max, helpers$1.max(values));
  11136. });
  11137. me.min = helpers$1.isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  11138. me.max = helpers$1.isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  11139. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11140. me.handleTickRangeOptions();
  11141. },
  11142. // Returns the maximum number of ticks based on the scale dimension
  11143. _computeTickLimit: function() {
  11144. var me = this;
  11145. var tickFont;
  11146. if (me.isHorizontal()) {
  11147. return Math.ceil(me.width / 40);
  11148. }
  11149. tickFont = helpers$1.options._parseFont(me.options.ticks);
  11150. return Math.ceil(me.height / tickFont.lineHeight);
  11151. },
  11152. // Called after the ticks are built. We need
  11153. handleDirectionalChanges: function() {
  11154. if (!this.isHorizontal()) {
  11155. // We are in a vertical orientation. The top value is the highest. So reverse the array
  11156. this.ticks.reverse();
  11157. }
  11158. },
  11159. getLabelForIndex: function(index, datasetIndex) {
  11160. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11161. },
  11162. // Utils
  11163. getPixelForValue: function(value) {
  11164. var me = this;
  11165. return me.getPixelForDecimal((+me.getRightValue(value) - me._startValue) / me._valueRange);
  11166. },
  11167. getValueForPixel: function(pixel) {
  11168. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  11169. },
  11170. getPixelForTick: function(index) {
  11171. var ticks = this.ticksAsNumbers;
  11172. if (index < 0 || index > ticks.length - 1) {
  11173. return null;
  11174. }
  11175. return this.getPixelForValue(ticks[index]);
  11176. }
  11177. });
  11178. // INTERNAL: static default options, registered in src/index.js
  11179. var _defaults$1 = defaultConfig$1;
  11180. scale_linear._defaults = _defaults$1;
  11181. var valueOrDefault$b = helpers$1.valueOrDefault;
  11182. var log10 = helpers$1.math.log10;
  11183. /**
  11184. * Generate a set of logarithmic ticks
  11185. * @param generationOptions the options used to generate the ticks
  11186. * @param dataRange the range of the data
  11187. * @returns {number[]} array of tick values
  11188. */
  11189. function generateTicks$1(generationOptions, dataRange) {
  11190. var ticks = [];
  11191. var tickVal = valueOrDefault$b(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  11192. var endExp = Math.floor(log10(dataRange.max));
  11193. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  11194. var exp, significand;
  11195. if (tickVal === 0) {
  11196. exp = Math.floor(log10(dataRange.minNotZero));
  11197. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  11198. ticks.push(tickVal);
  11199. tickVal = significand * Math.pow(10, exp);
  11200. } else {
  11201. exp = Math.floor(log10(tickVal));
  11202. significand = Math.floor(tickVal / Math.pow(10, exp));
  11203. }
  11204. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  11205. do {
  11206. ticks.push(tickVal);
  11207. ++significand;
  11208. if (significand === 10) {
  11209. significand = 1;
  11210. ++exp;
  11211. precision = exp >= 0 ? 1 : precision;
  11212. }
  11213. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  11214. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  11215. var lastTick = valueOrDefault$b(generationOptions.max, tickVal);
  11216. ticks.push(lastTick);
  11217. return ticks;
  11218. }
  11219. var defaultConfig$2 = {
  11220. position: 'left',
  11221. // label settings
  11222. ticks: {
  11223. callback: core_ticks.formatters.logarithmic
  11224. }
  11225. };
  11226. // TODO(v3): change this to positiveOrDefault
  11227. function nonNegativeOrDefault(value, defaultValue) {
  11228. return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;
  11229. }
  11230. var scale_logarithmic = core_scale.extend({
  11231. determineDataLimits: function() {
  11232. var me = this;
  11233. var opts = me.options;
  11234. var chart = me.chart;
  11235. var datasets = chart.data.datasets;
  11236. var isHorizontal = me.isHorizontal();
  11237. function IDMatches(meta) {
  11238. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  11239. }
  11240. var datasetIndex, meta, value, data, i, ilen;
  11241. // Calculate Range
  11242. me.min = Number.POSITIVE_INFINITY;
  11243. me.max = Number.NEGATIVE_INFINITY;
  11244. me.minNotZero = Number.POSITIVE_INFINITY;
  11245. var hasStacks = opts.stacked;
  11246. if (hasStacks === undefined) {
  11247. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11248. meta = chart.getDatasetMeta(datasetIndex);
  11249. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  11250. meta.stack !== undefined) {
  11251. hasStacks = true;
  11252. break;
  11253. }
  11254. }
  11255. }
  11256. if (opts.stacked || hasStacks) {
  11257. var valuesPerStack = {};
  11258. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11259. meta = chart.getDatasetMeta(datasetIndex);
  11260. var key = [
  11261. meta.type,
  11262. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11263. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  11264. meta.stack
  11265. ].join('.');
  11266. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11267. if (valuesPerStack[key] === undefined) {
  11268. valuesPerStack[key] = [];
  11269. }
  11270. data = datasets[datasetIndex].data;
  11271. for (i = 0, ilen = data.length; i < ilen; i++) {
  11272. var values = valuesPerStack[key];
  11273. value = me._parseValue(data[i]);
  11274. // invalid, hidden and negative values are ignored
  11275. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11276. continue;
  11277. }
  11278. values[i] = values[i] || 0;
  11279. values[i] += value.max;
  11280. }
  11281. }
  11282. }
  11283. helpers$1.each(valuesPerStack, function(valuesForType) {
  11284. if (valuesForType.length > 0) {
  11285. var minVal = helpers$1.min(valuesForType);
  11286. var maxVal = helpers$1.max(valuesForType);
  11287. me.min = Math.min(me.min, minVal);
  11288. me.max = Math.max(me.max, maxVal);
  11289. }
  11290. });
  11291. } else {
  11292. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11293. meta = chart.getDatasetMeta(datasetIndex);
  11294. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11295. data = datasets[datasetIndex].data;
  11296. for (i = 0, ilen = data.length; i < ilen; i++) {
  11297. value = me._parseValue(data[i]);
  11298. // invalid, hidden and negative values are ignored
  11299. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11300. continue;
  11301. }
  11302. me.min = Math.min(value.min, me.min);
  11303. me.max = Math.max(value.max, me.max);
  11304. if (value.min !== 0) {
  11305. me.minNotZero = Math.min(value.min, me.minNotZero);
  11306. }
  11307. }
  11308. }
  11309. }
  11310. }
  11311. me.min = helpers$1.isFinite(me.min) ? me.min : null;
  11312. me.max = helpers$1.isFinite(me.max) ? me.max : null;
  11313. me.minNotZero = helpers$1.isFinite(me.minNotZero) ? me.minNotZero : null;
  11314. // Common base implementation to handle ticks.min, ticks.max
  11315. this.handleTickRangeOptions();
  11316. },
  11317. handleTickRangeOptions: function() {
  11318. var me = this;
  11319. var tickOpts = me.options.ticks;
  11320. var DEFAULT_MIN = 1;
  11321. var DEFAULT_MAX = 10;
  11322. me.min = nonNegativeOrDefault(tickOpts.min, me.min);
  11323. me.max = nonNegativeOrDefault(tickOpts.max, me.max);
  11324. if (me.min === me.max) {
  11325. if (me.min !== 0 && me.min !== null) {
  11326. me.min = Math.pow(10, Math.floor(log10(me.min)) - 1);
  11327. me.max = Math.pow(10, Math.floor(log10(me.max)) + 1);
  11328. } else {
  11329. me.min = DEFAULT_MIN;
  11330. me.max = DEFAULT_MAX;
  11331. }
  11332. }
  11333. if (me.min === null) {
  11334. me.min = Math.pow(10, Math.floor(log10(me.max)) - 1);
  11335. }
  11336. if (me.max === null) {
  11337. me.max = me.min !== 0
  11338. ? Math.pow(10, Math.floor(log10(me.min)) + 1)
  11339. : DEFAULT_MAX;
  11340. }
  11341. if (me.minNotZero === null) {
  11342. if (me.min > 0) {
  11343. me.minNotZero = me.min;
  11344. } else if (me.max < 1) {
  11345. me.minNotZero = Math.pow(10, Math.floor(log10(me.max)));
  11346. } else {
  11347. me.minNotZero = DEFAULT_MIN;
  11348. }
  11349. }
  11350. },
  11351. buildTicks: function() {
  11352. var me = this;
  11353. var tickOpts = me.options.ticks;
  11354. var reverse = !me.isHorizontal();
  11355. var generationOptions = {
  11356. min: nonNegativeOrDefault(tickOpts.min),
  11357. max: nonNegativeOrDefault(tickOpts.max)
  11358. };
  11359. var ticks = me.ticks = generateTicks$1(generationOptions, me);
  11360. // At this point, we need to update our max and min given the tick values since we have expanded the
  11361. // range of the scale
  11362. me.max = helpers$1.max(ticks);
  11363. me.min = helpers$1.min(ticks);
  11364. if (tickOpts.reverse) {
  11365. reverse = !reverse;
  11366. me.start = me.max;
  11367. me.end = me.min;
  11368. } else {
  11369. me.start = me.min;
  11370. me.end = me.max;
  11371. }
  11372. if (reverse) {
  11373. ticks.reverse();
  11374. }
  11375. },
  11376. convertTicksToLabels: function() {
  11377. this.tickValues = this.ticks.slice();
  11378. core_scale.prototype.convertTicksToLabels.call(this);
  11379. },
  11380. // Get the correct tooltip label
  11381. getLabelForIndex: function(index, datasetIndex) {
  11382. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11383. },
  11384. getPixelForTick: function(index) {
  11385. var ticks = this.tickValues;
  11386. if (index < 0 || index > ticks.length - 1) {
  11387. return null;
  11388. }
  11389. return this.getPixelForValue(ticks[index]);
  11390. },
  11391. /**
  11392. * Returns the value of the first tick.
  11393. * @param {number} value - The minimum not zero value.
  11394. * @return {number} The first tick value.
  11395. * @private
  11396. */
  11397. _getFirstTickValue: function(value) {
  11398. var exp = Math.floor(log10(value));
  11399. var significand = Math.floor(value / Math.pow(10, exp));
  11400. return significand * Math.pow(10, exp);
  11401. },
  11402. _configure: function() {
  11403. var me = this;
  11404. var start = me.min;
  11405. var offset = 0;
  11406. core_scale.prototype._configure.call(me);
  11407. if (start === 0) {
  11408. start = me._getFirstTickValue(me.minNotZero);
  11409. offset = valueOrDefault$b(me.options.ticks.fontSize, core_defaults.global.defaultFontSize) / me._length;
  11410. }
  11411. me._startValue = log10(start);
  11412. me._valueOffset = offset;
  11413. me._valueRange = (log10(me.max) - log10(start)) / (1 - offset);
  11414. },
  11415. getPixelForValue: function(value) {
  11416. var me = this;
  11417. var decimal = 0;
  11418. value = +me.getRightValue(value);
  11419. if (value > me.min && value > 0) {
  11420. decimal = (log10(value) - me._startValue) / me._valueRange + me._valueOffset;
  11421. }
  11422. return me.getPixelForDecimal(decimal);
  11423. },
  11424. getValueForPixel: function(pixel) {
  11425. var me = this;
  11426. var decimal = me.getDecimalForPixel(pixel);
  11427. return decimal === 0 && me.min === 0
  11428. ? 0
  11429. : Math.pow(10, me._startValue + (decimal - me._valueOffset) * me._valueRange);
  11430. }
  11431. });
  11432. // INTERNAL: static default options, registered in src/index.js
  11433. var _defaults$2 = defaultConfig$2;
  11434. scale_logarithmic._defaults = _defaults$2;
  11435. var valueOrDefault$c = helpers$1.valueOrDefault;
  11436. var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
  11437. var resolve$4 = helpers$1.options.resolve;
  11438. var defaultConfig$3 = {
  11439. display: true,
  11440. // Boolean - Whether to animate scaling the chart from the centre
  11441. animate: true,
  11442. position: 'chartArea',
  11443. angleLines: {
  11444. display: true,
  11445. color: 'rgba(0,0,0,0.1)',
  11446. lineWidth: 1,
  11447. borderDash: [],
  11448. borderDashOffset: 0.0
  11449. },
  11450. gridLines: {
  11451. circular: false
  11452. },
  11453. // label settings
  11454. ticks: {
  11455. // Boolean - Show a backdrop to the scale label
  11456. showLabelBackdrop: true,
  11457. // String - The colour of the label backdrop
  11458. backdropColor: 'rgba(255,255,255,0.75)',
  11459. // Number - The backdrop padding above & below the label in pixels
  11460. backdropPaddingY: 2,
  11461. // Number - The backdrop padding to the side of the label in pixels
  11462. backdropPaddingX: 2,
  11463. callback: core_ticks.formatters.linear
  11464. },
  11465. pointLabels: {
  11466. // Boolean - if true, show point labels
  11467. display: true,
  11468. // Number - Point label font size in pixels
  11469. fontSize: 10,
  11470. // Function - Used to convert point labels
  11471. callback: function(label) {
  11472. return label;
  11473. }
  11474. }
  11475. };
  11476. function getTickBackdropHeight(opts) {
  11477. var tickOpts = opts.ticks;
  11478. if (tickOpts.display && opts.display) {
  11479. return valueOrDefault$c(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
  11480. }
  11481. return 0;
  11482. }
  11483. function measureLabelSize(ctx, lineHeight, label) {
  11484. if (helpers$1.isArray(label)) {
  11485. return {
  11486. w: helpers$1.longestText(ctx, ctx.font, label),
  11487. h: label.length * lineHeight
  11488. };
  11489. }
  11490. return {
  11491. w: ctx.measureText(label).width,
  11492. h: lineHeight
  11493. };
  11494. }
  11495. function determineLimits(angle, pos, size, min, max) {
  11496. if (angle === min || angle === max) {
  11497. return {
  11498. start: pos - (size / 2),
  11499. end: pos + (size / 2)
  11500. };
  11501. } else if (angle < min || angle > max) {
  11502. return {
  11503. start: pos - size,
  11504. end: pos
  11505. };
  11506. }
  11507. return {
  11508. start: pos,
  11509. end: pos + size
  11510. };
  11511. }
  11512. /**
  11513. * Helper function to fit a radial linear scale with point labels
  11514. */
  11515. function fitWithPointLabels(scale) {
  11516. // Right, this is really confusing and there is a lot of maths going on here
  11517. // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  11518. //
  11519. // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  11520. //
  11521. // Solution:
  11522. //
  11523. // We assume the radius of the polygon is half the size of the canvas at first
  11524. // at each index we check if the text overlaps.
  11525. //
  11526. // Where it does, we store that angle and that index.
  11527. //
  11528. // After finding the largest index and angle we calculate how much we need to remove
  11529. // from the shape radius to move the point inwards by that x.
  11530. //
  11531. // We average the left and right distances to get the maximum shape radius that can fit in the box
  11532. // along with labels.
  11533. //
  11534. // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  11535. // on each side, removing that from the size, halving it and adding the left x protrusion width.
  11536. //
  11537. // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  11538. // and position it in the most space efficient manner
  11539. //
  11540. // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  11541. var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
  11542. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  11543. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  11544. var furthestLimits = {
  11545. l: 0,
  11546. r: scale.width,
  11547. t: 0,
  11548. b: scale.height - scale.paddingTop
  11549. };
  11550. var furthestAngles = {};
  11551. var i, textSize, pointPosition;
  11552. scale.ctx.font = plFont.string;
  11553. scale._pointLabelSizes = [];
  11554. var valueCount = scale.chart.data.labels.length;
  11555. for (i = 0; i < valueCount; i++) {
  11556. pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
  11557. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);
  11558. scale._pointLabelSizes[i] = textSize;
  11559. // Add quarter circle to make degree 0 mean top of circle
  11560. var angleRadians = scale.getIndexAngle(i);
  11561. var angle = helpers$1.toDegrees(angleRadians) % 360;
  11562. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  11563. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  11564. if (hLimits.start < furthestLimits.l) {
  11565. furthestLimits.l = hLimits.start;
  11566. furthestAngles.l = angleRadians;
  11567. }
  11568. if (hLimits.end > furthestLimits.r) {
  11569. furthestLimits.r = hLimits.end;
  11570. furthestAngles.r = angleRadians;
  11571. }
  11572. if (vLimits.start < furthestLimits.t) {
  11573. furthestLimits.t = vLimits.start;
  11574. furthestAngles.t = angleRadians;
  11575. }
  11576. if (vLimits.end > furthestLimits.b) {
  11577. furthestLimits.b = vLimits.end;
  11578. furthestAngles.b = angleRadians;
  11579. }
  11580. }
  11581. scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  11582. }
  11583. function getTextAlignForAngle(angle) {
  11584. if (angle === 0 || angle === 180) {
  11585. return 'center';
  11586. } else if (angle < 180) {
  11587. return 'left';
  11588. }
  11589. return 'right';
  11590. }
  11591. function fillText(ctx, text, position, lineHeight) {
  11592. var y = position.y + lineHeight / 2;
  11593. var i, ilen;
  11594. if (helpers$1.isArray(text)) {
  11595. for (i = 0, ilen = text.length; i < ilen; ++i) {
  11596. ctx.fillText(text[i], position.x, y);
  11597. y += lineHeight;
  11598. }
  11599. } else {
  11600. ctx.fillText(text, position.x, y);
  11601. }
  11602. }
  11603. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  11604. if (angle === 90 || angle === 270) {
  11605. position.y -= (textSize.h / 2);
  11606. } else if (angle > 270 || angle < 90) {
  11607. position.y -= textSize.h;
  11608. }
  11609. }
  11610. function drawPointLabels(scale) {
  11611. var ctx = scale.ctx;
  11612. var opts = scale.options;
  11613. var pointLabelOpts = opts.pointLabels;
  11614. var tickBackdropHeight = getTickBackdropHeight(opts);
  11615. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  11616. var plFont = helpers$1.options._parseFont(pointLabelOpts);
  11617. ctx.save();
  11618. ctx.font = plFont.string;
  11619. ctx.textBaseline = 'middle';
  11620. for (var i = scale.chart.data.labels.length - 1; i >= 0; i--) {
  11621. // Extra pixels out for some label spacing
  11622. var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  11623. var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
  11624. // Keep this in loop since we may support array properties here
  11625. var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
  11626. ctx.fillStyle = pointLabelFontColor;
  11627. var angleRadians = scale.getIndexAngle(i);
  11628. var angle = helpers$1.toDegrees(angleRadians);
  11629. ctx.textAlign = getTextAlignForAngle(angle);
  11630. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  11631. fillText(ctx, scale.pointLabels[i], pointLabelPosition, plFont.lineHeight);
  11632. }
  11633. ctx.restore();
  11634. }
  11635. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  11636. var ctx = scale.ctx;
  11637. var circular = gridLineOpts.circular;
  11638. var valueCount = scale.chart.data.labels.length;
  11639. var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
  11640. var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
  11641. var pointPosition;
  11642. if ((!circular && !valueCount) || !lineColor || !lineWidth) {
  11643. return;
  11644. }
  11645. ctx.save();
  11646. ctx.strokeStyle = lineColor;
  11647. ctx.lineWidth = lineWidth;
  11648. if (ctx.setLineDash) {
  11649. ctx.setLineDash(gridLineOpts.borderDash || []);
  11650. ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
  11651. }
  11652. ctx.beginPath();
  11653. if (circular) {
  11654. // Draw circular arcs between the points
  11655. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  11656. } else {
  11657. // Draw straight lines connecting each index
  11658. pointPosition = scale.getPointPosition(0, radius);
  11659. ctx.moveTo(pointPosition.x, pointPosition.y);
  11660. for (var i = 1; i < valueCount; i++) {
  11661. pointPosition = scale.getPointPosition(i, radius);
  11662. ctx.lineTo(pointPosition.x, pointPosition.y);
  11663. }
  11664. }
  11665. ctx.closePath();
  11666. ctx.stroke();
  11667. ctx.restore();
  11668. }
  11669. function numberOrZero(param) {
  11670. return helpers$1.isNumber(param) ? param : 0;
  11671. }
  11672. var scale_radialLinear = scale_linearbase.extend({
  11673. setDimensions: function() {
  11674. var me = this;
  11675. // Set the unconstrained dimension before label rotation
  11676. me.width = me.maxWidth;
  11677. me.height = me.maxHeight;
  11678. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  11679. me.xCenter = Math.floor(me.width / 2);
  11680. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  11681. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  11682. },
  11683. determineDataLimits: function() {
  11684. var me = this;
  11685. var chart = me.chart;
  11686. var min = Number.POSITIVE_INFINITY;
  11687. var max = Number.NEGATIVE_INFINITY;
  11688. helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {
  11689. if (chart.isDatasetVisible(datasetIndex)) {
  11690. var meta = chart.getDatasetMeta(datasetIndex);
  11691. helpers$1.each(dataset.data, function(rawValue, index) {
  11692. var value = +me.getRightValue(rawValue);
  11693. if (isNaN(value) || meta.data[index].hidden) {
  11694. return;
  11695. }
  11696. min = Math.min(value, min);
  11697. max = Math.max(value, max);
  11698. });
  11699. }
  11700. });
  11701. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  11702. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  11703. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11704. me.handleTickRangeOptions();
  11705. },
  11706. // Returns the maximum number of ticks based on the scale dimension
  11707. _computeTickLimit: function() {
  11708. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  11709. },
  11710. convertTicksToLabels: function() {
  11711. var me = this;
  11712. scale_linearbase.prototype.convertTicksToLabels.call(me);
  11713. // Point labels
  11714. me.pointLabels = me.chart.data.labels.map(function() {
  11715. var label = helpers$1.callback(me.options.pointLabels.callback, arguments, me);
  11716. return label || label === 0 ? label : '';
  11717. });
  11718. },
  11719. getLabelForIndex: function(index, datasetIndex) {
  11720. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  11721. },
  11722. fit: function() {
  11723. var me = this;
  11724. var opts = me.options;
  11725. if (opts.display && opts.pointLabels.display) {
  11726. fitWithPointLabels(me);
  11727. } else {
  11728. me.setCenterPoint(0, 0, 0, 0);
  11729. }
  11730. },
  11731. /**
  11732. * Set radius reductions and determine new radius and center point
  11733. * @private
  11734. */
  11735. setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
  11736. var me = this;
  11737. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  11738. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  11739. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  11740. var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  11741. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  11742. radiusReductionRight = numberOrZero(radiusReductionRight);
  11743. radiusReductionTop = numberOrZero(radiusReductionTop);
  11744. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  11745. me.drawingArea = Math.min(
  11746. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  11747. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  11748. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  11749. },
  11750. setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
  11751. var me = this;
  11752. var maxRight = me.width - rightMovement - me.drawingArea;
  11753. var maxLeft = leftMovement + me.drawingArea;
  11754. var maxTop = topMovement + me.drawingArea;
  11755. var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  11756. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  11757. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  11758. },
  11759. getIndexAngle: function(index) {
  11760. var chart = this.chart;
  11761. var angleMultiplier = 360 / chart.data.labels.length;
  11762. var options = chart.options || {};
  11763. var startAngle = options.startAngle || 0;
  11764. // Start from the top instead of right, so remove a quarter of the circle
  11765. var angle = (index * angleMultiplier + startAngle) % 360;
  11766. return (angle < 0 ? angle + 360 : angle) * Math.PI * 2 / 360;
  11767. },
  11768. getDistanceFromCenterForValue: function(value) {
  11769. var me = this;
  11770. if (helpers$1.isNullOrUndef(value)) {
  11771. return NaN;
  11772. }
  11773. // Take into account half font size + the yPadding of the top value
  11774. var scalingFactor = me.drawingArea / (me.max - me.min);
  11775. if (me.options.ticks.reverse) {
  11776. return (me.max - value) * scalingFactor;
  11777. }
  11778. return (value - me.min) * scalingFactor;
  11779. },
  11780. getPointPosition: function(index, distanceFromCenter) {
  11781. var me = this;
  11782. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  11783. return {
  11784. x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
  11785. y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
  11786. };
  11787. },
  11788. getPointPositionForValue: function(index, value) {
  11789. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  11790. },
  11791. getBasePosition: function(index) {
  11792. var me = this;
  11793. var min = me.min;
  11794. var max = me.max;
  11795. return me.getPointPositionForValue(index || 0,
  11796. me.beginAtZero ? 0 :
  11797. min < 0 && max < 0 ? max :
  11798. min > 0 && max > 0 ? min :
  11799. 0);
  11800. },
  11801. /**
  11802. * @private
  11803. */
  11804. _drawGrid: function() {
  11805. var me = this;
  11806. var ctx = me.ctx;
  11807. var opts = me.options;
  11808. var gridLineOpts = opts.gridLines;
  11809. var angleLineOpts = opts.angleLines;
  11810. var lineWidth = valueOrDefault$c(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
  11811. var lineColor = valueOrDefault$c(angleLineOpts.color, gridLineOpts.color);
  11812. var i, offset, position;
  11813. if (opts.pointLabels.display) {
  11814. drawPointLabels(me);
  11815. }
  11816. if (gridLineOpts.display) {
  11817. helpers$1.each(me.ticks, function(label, index) {
  11818. if (index !== 0) {
  11819. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11820. drawRadiusLine(me, gridLineOpts, offset, index);
  11821. }
  11822. });
  11823. }
  11824. if (angleLineOpts.display && lineWidth && lineColor) {
  11825. ctx.save();
  11826. ctx.lineWidth = lineWidth;
  11827. ctx.strokeStyle = lineColor;
  11828. if (ctx.setLineDash) {
  11829. ctx.setLineDash(resolve$4([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
  11830. ctx.lineDashOffset = resolve$4([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
  11831. }
  11832. for (i = me.chart.data.labels.length - 1; i >= 0; i--) {
  11833. offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
  11834. position = me.getPointPosition(i, offset);
  11835. ctx.beginPath();
  11836. ctx.moveTo(me.xCenter, me.yCenter);
  11837. ctx.lineTo(position.x, position.y);
  11838. ctx.stroke();
  11839. }
  11840. ctx.restore();
  11841. }
  11842. },
  11843. /**
  11844. * @private
  11845. */
  11846. _drawLabels: function() {
  11847. var me = this;
  11848. var ctx = me.ctx;
  11849. var opts = me.options;
  11850. var tickOpts = opts.ticks;
  11851. if (!tickOpts.display) {
  11852. return;
  11853. }
  11854. var startAngle = me.getIndexAngle(0);
  11855. var tickFont = helpers$1.options._parseFont(tickOpts);
  11856. var tickFontColor = valueOrDefault$c(tickOpts.fontColor, core_defaults.global.defaultFontColor);
  11857. var offset, width;
  11858. ctx.save();
  11859. ctx.font = tickFont.string;
  11860. ctx.translate(me.xCenter, me.yCenter);
  11861. ctx.rotate(startAngle);
  11862. ctx.textAlign = 'center';
  11863. ctx.textBaseline = 'middle';
  11864. helpers$1.each(me.ticks, function(label, index) {
  11865. if (index === 0 && !tickOpts.reverse) {
  11866. return;
  11867. }
  11868. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11869. if (tickOpts.showLabelBackdrop) {
  11870. width = ctx.measureText(label).width;
  11871. ctx.fillStyle = tickOpts.backdropColor;
  11872. ctx.fillRect(
  11873. -width / 2 - tickOpts.backdropPaddingX,
  11874. -offset - tickFont.size / 2 - tickOpts.backdropPaddingY,
  11875. width + tickOpts.backdropPaddingX * 2,
  11876. tickFont.size + tickOpts.backdropPaddingY * 2
  11877. );
  11878. }
  11879. ctx.fillStyle = tickFontColor;
  11880. ctx.fillText(label, 0, -offset);
  11881. });
  11882. ctx.restore();
  11883. },
  11884. /**
  11885. * @private
  11886. */
  11887. _drawTitle: helpers$1.noop
  11888. });
  11889. // INTERNAL: static default options, registered in src/index.js
  11890. var _defaults$3 = defaultConfig$3;
  11891. scale_radialLinear._defaults = _defaults$3;
  11892. var deprecated$1 = helpers$1._deprecated;
  11893. var resolve$5 = helpers$1.options.resolve;
  11894. var valueOrDefault$d = helpers$1.valueOrDefault;
  11895. // Integer constants are from the ES6 spec.
  11896. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  11897. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  11898. var INTERVALS = {
  11899. millisecond: {
  11900. common: true,
  11901. size: 1,
  11902. steps: 1000
  11903. },
  11904. second: {
  11905. common: true,
  11906. size: 1000,
  11907. steps: 60
  11908. },
  11909. minute: {
  11910. common: true,
  11911. size: 60000,
  11912. steps: 60
  11913. },
  11914. hour: {
  11915. common: true,
  11916. size: 3600000,
  11917. steps: 24
  11918. },
  11919. day: {
  11920. common: true,
  11921. size: 86400000,
  11922. steps: 30
  11923. },
  11924. week: {
  11925. common: false,
  11926. size: 604800000,
  11927. steps: 4
  11928. },
  11929. month: {
  11930. common: true,
  11931. size: 2.628e9,
  11932. steps: 12
  11933. },
  11934. quarter: {
  11935. common: false,
  11936. size: 7.884e9,
  11937. steps: 4
  11938. },
  11939. year: {
  11940. common: true,
  11941. size: 3.154e10
  11942. }
  11943. };
  11944. var UNITS = Object.keys(INTERVALS);
  11945. function sorter(a, b) {
  11946. return a - b;
  11947. }
  11948. function arrayUnique(items) {
  11949. var hash = {};
  11950. var out = [];
  11951. var i, ilen, item;
  11952. for (i = 0, ilen = items.length; i < ilen; ++i) {
  11953. item = items[i];
  11954. if (!hash[item]) {
  11955. hash[item] = true;
  11956. out.push(item);
  11957. }
  11958. }
  11959. return out;
  11960. }
  11961. function getMin(options) {
  11962. return helpers$1.valueOrDefault(options.time.min, options.ticks.min);
  11963. }
  11964. function getMax(options) {
  11965. return helpers$1.valueOrDefault(options.time.max, options.ticks.max);
  11966. }
  11967. /**
  11968. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  11969. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  11970. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  11971. * extremity (left + width or top + height). Note that it would be more optimized to directly
  11972. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  11973. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  11974. *
  11975. * @param {number[]} timestamps - timestamps sorted from lowest to highest.
  11976. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
  11977. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  11978. * If 'series', timestamps will be positioned at the same distance from each other. In this
  11979. * case, only timestamps that break the time linearity are registered, meaning that in the
  11980. * best case, all timestamps are linear, the table contains only min and max.
  11981. */
  11982. function buildLookupTable(timestamps, min, max, distribution) {
  11983. if (distribution === 'linear' || !timestamps.length) {
  11984. return [
  11985. {time: min, pos: 0},
  11986. {time: max, pos: 1}
  11987. ];
  11988. }
  11989. var table = [];
  11990. var items = [min];
  11991. var i, ilen, prev, curr, next;
  11992. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  11993. curr = timestamps[i];
  11994. if (curr > min && curr < max) {
  11995. items.push(curr);
  11996. }
  11997. }
  11998. items.push(max);
  11999. for (i = 0, ilen = items.length; i < ilen; ++i) {
  12000. next = items[i + 1];
  12001. prev = items[i - 1];
  12002. curr = items[i];
  12003. // only add points that breaks the scale linearity
  12004. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  12005. table.push({time: curr, pos: i / (ilen - 1)});
  12006. }
  12007. }
  12008. return table;
  12009. }
  12010. // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  12011. function lookup(table, key, value) {
  12012. var lo = 0;
  12013. var hi = table.length - 1;
  12014. var mid, i0, i1;
  12015. while (lo >= 0 && lo <= hi) {
  12016. mid = (lo + hi) >> 1;
  12017. i0 = table[mid - 1] || null;
  12018. i1 = table[mid];
  12019. if (!i0) {
  12020. // given value is outside table (before first item)
  12021. return {lo: null, hi: i1};
  12022. } else if (i1[key] < value) {
  12023. lo = mid + 1;
  12024. } else if (i0[key] > value) {
  12025. hi = mid - 1;
  12026. } else {
  12027. return {lo: i0, hi: i1};
  12028. }
  12029. }
  12030. // given value is outside table (after last item)
  12031. return {lo: i1, hi: null};
  12032. }
  12033. /**
  12034. * Linearly interpolates the given source `value` using the table items `skey` values and
  12035. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  12036. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  12037. * index [0, 1] or [n - 1, n] are used for the interpolation.
  12038. */
  12039. function interpolate$1(table, skey, sval, tkey) {
  12040. var range = lookup(table, skey, sval);
  12041. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  12042. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  12043. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  12044. var span = next[skey] - prev[skey];
  12045. var ratio = span ? (sval - prev[skey]) / span : 0;
  12046. var offset = (next[tkey] - prev[tkey]) * ratio;
  12047. return prev[tkey] + offset;
  12048. }
  12049. function toTimestamp(scale, input) {
  12050. var adapter = scale._adapter;
  12051. var options = scale.options.time;
  12052. var parser = options.parser;
  12053. var format = parser || options.format;
  12054. var value = input;
  12055. if (typeof parser === 'function') {
  12056. value = parser(value);
  12057. }
  12058. // Only parse if its not a timestamp already
  12059. if (!helpers$1.isFinite(value)) {
  12060. value = typeof format === 'string'
  12061. ? adapter.parse(value, format)
  12062. : adapter.parse(value);
  12063. }
  12064. if (value !== null) {
  12065. return +value;
  12066. }
  12067. // Labels are in an incompatible format and no `parser` has been provided.
  12068. // The user might still use the deprecated `format` option for parsing.
  12069. if (!parser && typeof format === 'function') {
  12070. value = format(input);
  12071. // `format` could return something else than a timestamp, if so, parse it
  12072. if (!helpers$1.isFinite(value)) {
  12073. value = adapter.parse(value);
  12074. }
  12075. }
  12076. return value;
  12077. }
  12078. function parse(scale, input) {
  12079. if (helpers$1.isNullOrUndef(input)) {
  12080. return null;
  12081. }
  12082. var options = scale.options.time;
  12083. var value = toTimestamp(scale, scale.getRightValue(input));
  12084. if (value === null) {
  12085. return value;
  12086. }
  12087. if (options.round) {
  12088. value = +scale._adapter.startOf(value, options.round);
  12089. }
  12090. return value;
  12091. }
  12092. /**
  12093. * Figures out what unit results in an appropriate number of auto-generated ticks
  12094. */
  12095. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  12096. var ilen = UNITS.length;
  12097. var i, interval, factor;
  12098. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  12099. interval = INTERVALS[UNITS[i]];
  12100. factor = interval.steps ? interval.steps : MAX_INTEGER;
  12101. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  12102. return UNITS[i];
  12103. }
  12104. }
  12105. return UNITS[ilen - 1];
  12106. }
  12107. /**
  12108. * Figures out what unit to format a set of ticks with
  12109. */
  12110. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  12111. var i, unit;
  12112. for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  12113. unit = UNITS[i];
  12114. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  12115. return unit;
  12116. }
  12117. }
  12118. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  12119. }
  12120. function determineMajorUnit(unit) {
  12121. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  12122. if (INTERVALS[UNITS[i]].common) {
  12123. return UNITS[i];
  12124. }
  12125. }
  12126. }
  12127. /**
  12128. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  12129. * `minor` unit using the given scale time `options`.
  12130. * Important: this method can return ticks outside the min and max range, it's the
  12131. * responsibility of the calling code to clamp values if needed.
  12132. */
  12133. function generate(scale, min, max, capacity) {
  12134. var adapter = scale._adapter;
  12135. var options = scale.options;
  12136. var timeOpts = options.time;
  12137. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  12138. var stepSize = resolve$5([timeOpts.stepSize, timeOpts.unitStepSize, 1]);
  12139. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  12140. var first = min;
  12141. var ticks = [];
  12142. var time;
  12143. // For 'week' unit, handle the first day of week option
  12144. if (weekday) {
  12145. first = +adapter.startOf(first, 'isoWeek', weekday);
  12146. }
  12147. // Align first ticks on unit
  12148. first = +adapter.startOf(first, weekday ? 'day' : minor);
  12149. // Prevent browser from freezing in case user options request millions of milliseconds
  12150. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  12151. throw min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor;
  12152. }
  12153. for (time = first; time < max; time = +adapter.add(time, stepSize, minor)) {
  12154. ticks.push(time);
  12155. }
  12156. if (time === max || options.bounds === 'ticks') {
  12157. ticks.push(time);
  12158. }
  12159. return ticks;
  12160. }
  12161. /**
  12162. * Returns the start and end offsets from edges in the form of {start, end}
  12163. * where each value is a relative width to the scale and ranges between 0 and 1.
  12164. * They add extra margins on the both sides by scaling down the original scale.
  12165. * Offsets are added when the `offset` option is true.
  12166. */
  12167. function computeOffsets(table, ticks, min, max, options) {
  12168. var start = 0;
  12169. var end = 0;
  12170. var first, last;
  12171. if (options.offset && ticks.length) {
  12172. first = interpolate$1(table, 'time', ticks[0], 'pos');
  12173. if (ticks.length === 1) {
  12174. start = 1 - first;
  12175. } else {
  12176. start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
  12177. }
  12178. last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
  12179. if (ticks.length === 1) {
  12180. end = last;
  12181. } else {
  12182. end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
  12183. }
  12184. }
  12185. return {start: start, end: end, factor: 1 / (start + 1 + end)};
  12186. }
  12187. function setMajorTicks(scale, ticks, map, majorUnit) {
  12188. var adapter = scale._adapter;
  12189. var first = +adapter.startOf(ticks[0].value, majorUnit);
  12190. var last = ticks[ticks.length - 1].value;
  12191. var major, index;
  12192. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  12193. index = map[major];
  12194. if (index >= 0) {
  12195. ticks[index].major = true;
  12196. }
  12197. }
  12198. return ticks;
  12199. }
  12200. function ticksFromTimestamps(scale, values, majorUnit) {
  12201. var ticks = [];
  12202. var map = {};
  12203. var ilen = values.length;
  12204. var i, value;
  12205. for (i = 0; i < ilen; ++i) {
  12206. value = values[i];
  12207. map[value] = i;
  12208. ticks.push({
  12209. value: value,
  12210. major: false
  12211. });
  12212. }
  12213. // We set the major ticks separately from the above loop because calling startOf for every tick
  12214. // is expensive when there is a large number of ticks
  12215. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  12216. }
  12217. var defaultConfig$4 = {
  12218. position: 'bottom',
  12219. /**
  12220. * Data distribution along the scale:
  12221. * - 'linear': data are spread according to their time (distances can vary),
  12222. * - 'series': data are spread at the same distance from each other.
  12223. * @see https://github.com/chartjs/Chart.js/pull/4507
  12224. * @since 2.7.0
  12225. */
  12226. distribution: 'linear',
  12227. /**
  12228. * Scale boundary strategy (bypassed by min/max time options)
  12229. * - `data`: make sure data are fully visible, ticks outside are removed
  12230. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  12231. * @see https://github.com/chartjs/Chart.js/pull/4556
  12232. * @since 2.7.0
  12233. */
  12234. bounds: 'data',
  12235. adapters: {},
  12236. time: {
  12237. parser: false, // false == a pattern string from https://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment
  12238. unit: false, // false == automatic or override with week, month, year, etc.
  12239. round: false, // none, or override with week, month, year, etc.
  12240. displayFormat: false, // DEPRECATED
  12241. isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
  12242. minUnit: 'millisecond',
  12243. displayFormats: {}
  12244. },
  12245. ticks: {
  12246. autoSkip: false,
  12247. /**
  12248. * Ticks generation input values:
  12249. * - 'auto': generates "optimal" ticks based on scale size and time options.
  12250. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  12251. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  12252. * @see https://github.com/chartjs/Chart.js/pull/4507
  12253. * @since 2.7.0
  12254. */
  12255. source: 'auto',
  12256. major: {
  12257. enabled: false
  12258. }
  12259. }
  12260. };
  12261. var scale_time = core_scale.extend({
  12262. initialize: function() {
  12263. this.mergeTicksOptions();
  12264. core_scale.prototype.initialize.call(this);
  12265. },
  12266. update: function() {
  12267. var me = this;
  12268. var options = me.options;
  12269. var time = options.time || (options.time = {});
  12270. var adapter = me._adapter = new core_adapters._date(options.adapters.date);
  12271. // DEPRECATIONS: output a message only one time per update
  12272. deprecated$1('time scale', time.format, 'time.format', 'time.parser');
  12273. deprecated$1('time scale', time.min, 'time.min', 'ticks.min');
  12274. deprecated$1('time scale', time.max, 'time.max', 'ticks.max');
  12275. // Backward compatibility: before introducing adapter, `displayFormats` was
  12276. // supposed to contain *all* unit/string pairs but this can't be resolved
  12277. // when loading the scale (adapters are loaded afterward), so let's populate
  12278. // missing formats on update
  12279. helpers$1.mergeIf(time.displayFormats, adapter.formats());
  12280. return core_scale.prototype.update.apply(me, arguments);
  12281. },
  12282. /**
  12283. * Allows data to be referenced via 't' attribute
  12284. */
  12285. getRightValue: function(rawValue) {
  12286. if (rawValue && rawValue.t !== undefined) {
  12287. rawValue = rawValue.t;
  12288. }
  12289. return core_scale.prototype.getRightValue.call(this, rawValue);
  12290. },
  12291. determineDataLimits: function() {
  12292. var me = this;
  12293. var chart = me.chart;
  12294. var adapter = me._adapter;
  12295. var options = me.options;
  12296. var unit = options.time.unit || 'day';
  12297. var min = MAX_INTEGER;
  12298. var max = MIN_INTEGER;
  12299. var timestamps = [];
  12300. var datasets = [];
  12301. var labels = [];
  12302. var i, j, ilen, jlen, data, timestamp, labelsAdded;
  12303. var dataLabels = me._getLabels();
  12304. for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
  12305. labels.push(parse(me, dataLabels[i]));
  12306. }
  12307. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  12308. if (chart.isDatasetVisible(i)) {
  12309. data = chart.data.datasets[i].data;
  12310. // Let's consider that all data have the same format.
  12311. if (helpers$1.isObject(data[0])) {
  12312. datasets[i] = [];
  12313. for (j = 0, jlen = data.length; j < jlen; ++j) {
  12314. timestamp = parse(me, data[j]);
  12315. timestamps.push(timestamp);
  12316. datasets[i][j] = timestamp;
  12317. }
  12318. } else {
  12319. datasets[i] = labels.slice(0);
  12320. if (!labelsAdded) {
  12321. timestamps = timestamps.concat(labels);
  12322. labelsAdded = true;
  12323. }
  12324. }
  12325. } else {
  12326. datasets[i] = [];
  12327. }
  12328. }
  12329. if (labels.length) {
  12330. min = Math.min(min, labels[0]);
  12331. max = Math.max(max, labels[labels.length - 1]);
  12332. }
  12333. if (timestamps.length) {
  12334. timestamps = ilen > 1 ? arrayUnique(timestamps).sort(sorter) : timestamps.sort(sorter);
  12335. min = Math.min(min, timestamps[0]);
  12336. max = Math.max(max, timestamps[timestamps.length - 1]);
  12337. }
  12338. min = parse(me, getMin(options)) || min;
  12339. max = parse(me, getMax(options)) || max;
  12340. // In case there is no valid min/max, set limits based on unit time option
  12341. min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
  12342. max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;
  12343. // Make sure that max is strictly higher than min (required by the lookup table)
  12344. me.min = Math.min(min, max);
  12345. me.max = Math.max(min + 1, max);
  12346. // PRIVATE
  12347. me._table = [];
  12348. me._timestamps = {
  12349. data: timestamps,
  12350. datasets: datasets,
  12351. labels: labels
  12352. };
  12353. },
  12354. buildTicks: function() {
  12355. var me = this;
  12356. var min = me.min;
  12357. var max = me.max;
  12358. var options = me.options;
  12359. var tickOpts = options.ticks;
  12360. var timeOpts = options.time;
  12361. var timestamps = me._timestamps;
  12362. var ticks = [];
  12363. var capacity = me.getLabelCapacity(min);
  12364. var source = tickOpts.source;
  12365. var distribution = options.distribution;
  12366. var i, ilen, timestamp;
  12367. if (source === 'data' || (source === 'auto' && distribution === 'series')) {
  12368. timestamps = timestamps.data;
  12369. } else if (source === 'labels') {
  12370. timestamps = timestamps.labels;
  12371. } else {
  12372. timestamps = generate(me, min, max, capacity);
  12373. }
  12374. if (options.bounds === 'ticks' && timestamps.length) {
  12375. min = timestamps[0];
  12376. max = timestamps[timestamps.length - 1];
  12377. }
  12378. // Enforce limits with user min/max options
  12379. min = parse(me, getMin(options)) || min;
  12380. max = parse(me, getMax(options)) || max;
  12381. // Remove ticks outside the min/max range
  12382. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12383. timestamp = timestamps[i];
  12384. if (timestamp >= min && timestamp <= max) {
  12385. ticks.push(timestamp);
  12386. }
  12387. }
  12388. me.min = min;
  12389. me.max = max;
  12390. // PRIVATE
  12391. // determineUnitForFormatting relies on the number of ticks so we don't use it when
  12392. // autoSkip is enabled because we don't yet know what the final number of ticks will be
  12393. me._unit = timeOpts.unit || (tickOpts.autoSkip
  12394. ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, capacity)
  12395. : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
  12396. me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
  12397. : determineMajorUnit(me._unit);
  12398. me._table = buildLookupTable(me._timestamps.data, min, max, distribution);
  12399. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  12400. if (tickOpts.reverse) {
  12401. ticks.reverse();
  12402. }
  12403. return ticksFromTimestamps(me, ticks, me._majorUnit);
  12404. },
  12405. getLabelForIndex: function(index, datasetIndex) {
  12406. var me = this;
  12407. var adapter = me._adapter;
  12408. var data = me.chart.data;
  12409. var timeOpts = me.options.time;
  12410. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  12411. var value = data.datasets[datasetIndex].data[index];
  12412. if (helpers$1.isObject(value)) {
  12413. label = me.getRightValue(value);
  12414. }
  12415. if (timeOpts.tooltipFormat) {
  12416. return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
  12417. }
  12418. if (typeof label === 'string') {
  12419. return label;
  12420. }
  12421. return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
  12422. },
  12423. /**
  12424. * Function to format an individual tick mark
  12425. * @private
  12426. */
  12427. tickFormatFunction: function(time, index, ticks, format) {
  12428. var me = this;
  12429. var adapter = me._adapter;
  12430. var options = me.options;
  12431. var formats = options.time.displayFormats;
  12432. var minorFormat = formats[me._unit];
  12433. var majorUnit = me._majorUnit;
  12434. var majorFormat = formats[majorUnit];
  12435. var tick = ticks[index];
  12436. var tickOpts = options.ticks;
  12437. var major = majorUnit && majorFormat && tick && tick.major;
  12438. var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
  12439. var nestedTickOpts = major ? tickOpts.major : tickOpts.minor;
  12440. var formatter = resolve$5([
  12441. nestedTickOpts.callback,
  12442. nestedTickOpts.userCallback,
  12443. tickOpts.callback,
  12444. tickOpts.userCallback
  12445. ]);
  12446. return formatter ? formatter(label, index, ticks) : label;
  12447. },
  12448. convertTicksToLabels: function(ticks) {
  12449. var labels = [];
  12450. var i, ilen;
  12451. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  12452. labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
  12453. }
  12454. return labels;
  12455. },
  12456. /**
  12457. * @private
  12458. */
  12459. getPixelForOffset: function(time) {
  12460. var me = this;
  12461. var offsets = me._offsets;
  12462. var pos = interpolate$1(me._table, 'time', time, 'pos');
  12463. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  12464. },
  12465. getPixelForValue: function(value, index, datasetIndex) {
  12466. var me = this;
  12467. var time = null;
  12468. if (index !== undefined && datasetIndex !== undefined) {
  12469. time = me._timestamps.datasets[datasetIndex][index];
  12470. }
  12471. if (time === null) {
  12472. time = parse(me, value);
  12473. }
  12474. if (time !== null) {
  12475. return me.getPixelForOffset(time);
  12476. }
  12477. },
  12478. getPixelForTick: function(index) {
  12479. var ticks = this.getTicks();
  12480. return index >= 0 && index < ticks.length ?
  12481. this.getPixelForOffset(ticks[index].value) :
  12482. null;
  12483. },
  12484. getValueForPixel: function(pixel) {
  12485. var me = this;
  12486. var offsets = me._offsets;
  12487. var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  12488. var time = interpolate$1(me._table, 'pos', pos, 'time');
  12489. // DEPRECATION, we should return time directly
  12490. return me._adapter._create(time);
  12491. },
  12492. /**
  12493. * @private
  12494. */
  12495. _getLabelSize: function(label) {
  12496. var me = this;
  12497. var ticksOpts = me.options.ticks;
  12498. var tickLabelWidth = me.ctx.measureText(label).width;
  12499. var angle = helpers$1.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  12500. var cosRotation = Math.cos(angle);
  12501. var sinRotation = Math.sin(angle);
  12502. var tickFontSize = valueOrDefault$d(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
  12503. return {
  12504. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  12505. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  12506. };
  12507. },
  12508. /**
  12509. * Crude approximation of what the label width might be
  12510. * @private
  12511. */
  12512. getLabelWidth: function(label) {
  12513. return this._getLabelSize(label).w;
  12514. },
  12515. /**
  12516. * @private
  12517. */
  12518. getLabelCapacity: function(exampleTime) {
  12519. var me = this;
  12520. var timeOpts = me.options.time;
  12521. var displayFormats = timeOpts.displayFormats;
  12522. // pick the longest format (milliseconds) for guestimation
  12523. var format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  12524. var exampleLabel = me.tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
  12525. var size = me._getLabelSize(exampleLabel);
  12526. var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h);
  12527. if (me.options.offset) {
  12528. capacity--;
  12529. }
  12530. return capacity > 0 ? capacity : 1;
  12531. }
  12532. });
  12533. // INTERNAL: static default options, registered in src/index.js
  12534. var _defaults$4 = defaultConfig$4;
  12535. scale_time._defaults = _defaults$4;
  12536. var scales = {
  12537. category: scale_category,
  12538. linear: scale_linear,
  12539. logarithmic: scale_logarithmic,
  12540. radialLinear: scale_radialLinear,
  12541. time: scale_time
  12542. };
  12543. var FORMATS = {
  12544. datetime: 'MMM D, YYYY, h:mm:ss a',
  12545. millisecond: 'h:mm:ss.SSS a',
  12546. second: 'h:mm:ss a',
  12547. minute: 'h:mm a',
  12548. hour: 'hA',
  12549. day: 'MMM D',
  12550. week: 'll',
  12551. month: 'MMM YYYY',
  12552. quarter: '[Q]Q - YYYY',
  12553. year: 'YYYY'
  12554. };
  12555. core_adapters._date.override(typeof moment === 'function' ? {
  12556. _id: 'moment', // DEBUG ONLY
  12557. formats: function() {
  12558. return FORMATS;
  12559. },
  12560. parse: function(value, format) {
  12561. if (typeof value === 'string' && typeof format === 'string') {
  12562. value = moment(value, format);
  12563. } else if (!(value instanceof moment)) {
  12564. value = moment(value);
  12565. }
  12566. return value.isValid() ? value.valueOf() : null;
  12567. },
  12568. format: function(time, format) {
  12569. return moment(time).format(format);
  12570. },
  12571. add: function(time, amount, unit) {
  12572. return moment(time).add(amount, unit).valueOf();
  12573. },
  12574. diff: function(max, min, unit) {
  12575. return moment(max).diff(moment(min), unit);
  12576. },
  12577. startOf: function(time, unit, weekday) {
  12578. time = moment(time);
  12579. if (unit === 'isoWeek') {
  12580. return time.isoWeekday(weekday).valueOf();
  12581. }
  12582. return time.startOf(unit).valueOf();
  12583. },
  12584. endOf: function(time, unit) {
  12585. return moment(time).endOf(unit).valueOf();
  12586. },
  12587. // DEPRECATIONS
  12588. /**
  12589. * Provided for backward compatibility with scale.getValueForPixel().
  12590. * @deprecated since version 2.8.0
  12591. * @todo remove at version 3
  12592. * @private
  12593. */
  12594. _create: function(time) {
  12595. return moment(time);
  12596. },
  12597. } : {});
  12598. core_defaults._set('global', {
  12599. plugins: {
  12600. filler: {
  12601. propagate: true
  12602. }
  12603. }
  12604. });
  12605. var mappers = {
  12606. dataset: function(source) {
  12607. var index = source.fill;
  12608. var chart = source.chart;
  12609. var meta = chart.getDatasetMeta(index);
  12610. var visible = meta && chart.isDatasetVisible(index);
  12611. var points = (visible && meta.dataset._children) || [];
  12612. var length = points.length || 0;
  12613. return !length ? null : function(point, i) {
  12614. return (i < length && points[i]._view) || null;
  12615. };
  12616. },
  12617. boundary: function(source) {
  12618. var boundary = source.boundary;
  12619. var x = boundary ? boundary.x : null;
  12620. var y = boundary ? boundary.y : null;
  12621. if (helpers$1.isArray(boundary)) {
  12622. return function(point, i) {
  12623. return boundary[i];
  12624. };
  12625. }
  12626. return function(point) {
  12627. return {
  12628. x: x === null ? point.x : x,
  12629. y: y === null ? point.y : y,
  12630. };
  12631. };
  12632. }
  12633. };
  12634. // @todo if (fill[0] === '#')
  12635. function decodeFill(el, index, count) {
  12636. var model = el._model || {};
  12637. var fill = model.fill;
  12638. var target;
  12639. if (fill === undefined) {
  12640. fill = !!model.backgroundColor;
  12641. }
  12642. if (fill === false || fill === null) {
  12643. return false;
  12644. }
  12645. if (fill === true) {
  12646. return 'origin';
  12647. }
  12648. target = parseFloat(fill, 10);
  12649. if (isFinite(target) && Math.floor(target) === target) {
  12650. if (fill[0] === '-' || fill[0] === '+') {
  12651. target = index + target;
  12652. }
  12653. if (target === index || target < 0 || target >= count) {
  12654. return false;
  12655. }
  12656. return target;
  12657. }
  12658. switch (fill) {
  12659. // compatibility
  12660. case 'bottom':
  12661. return 'start';
  12662. case 'top':
  12663. return 'end';
  12664. case 'zero':
  12665. return 'origin';
  12666. // supported boundaries
  12667. case 'origin':
  12668. case 'start':
  12669. case 'end':
  12670. return fill;
  12671. // invalid fill values
  12672. default:
  12673. return false;
  12674. }
  12675. }
  12676. function computeLinearBoundary(source) {
  12677. var model = source.el._model || {};
  12678. var scale = source.el._scale || {};
  12679. var fill = source.fill;
  12680. var target = null;
  12681. var horizontal;
  12682. if (isFinite(fill)) {
  12683. return null;
  12684. }
  12685. // Backward compatibility: until v3, we still need to support boundary values set on
  12686. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  12687. // controllers might still use it (e.g. the Smith chart).
  12688. if (fill === 'start') {
  12689. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  12690. } else if (fill === 'end') {
  12691. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  12692. } else if (model.scaleZero !== undefined) {
  12693. target = model.scaleZero;
  12694. } else if (scale.getBasePixel) {
  12695. target = scale.getBasePixel();
  12696. }
  12697. if (target !== undefined && target !== null) {
  12698. if (target.x !== undefined && target.y !== undefined) {
  12699. return target;
  12700. }
  12701. if (helpers$1.isFinite(target)) {
  12702. horizontal = scale.isHorizontal();
  12703. return {
  12704. x: horizontal ? target : null,
  12705. y: horizontal ? null : target
  12706. };
  12707. }
  12708. }
  12709. return null;
  12710. }
  12711. function computeCircularBoundary(source) {
  12712. var scale = source.el._scale;
  12713. var options = scale.options;
  12714. var length = scale.chart.data.labels.length;
  12715. var fill = source.fill;
  12716. var target = [];
  12717. var start, end, center, i, point;
  12718. if (!length) {
  12719. return null;
  12720. }
  12721. start = options.ticks.reverse ? scale.max : scale.min;
  12722. end = options.ticks.reverse ? scale.min : scale.max;
  12723. center = scale.getPointPositionForValue(0, start);
  12724. for (i = 0; i < length; ++i) {
  12725. point = fill === 'start' || fill === 'end'
  12726. ? scale.getPointPositionForValue(i, fill === 'start' ? start : end)
  12727. : scale.getBasePosition(i);
  12728. if (options.gridLines.circular) {
  12729. point.cx = center.x;
  12730. point.cy = center.y;
  12731. point.angle = scale.getIndexAngle(i) - Math.PI / 2;
  12732. }
  12733. target.push(point);
  12734. }
  12735. return target;
  12736. }
  12737. function computeBoundary(source) {
  12738. var scale = source.el._scale || {};
  12739. if (scale.getPointPositionForValue) {
  12740. return computeCircularBoundary(source);
  12741. }
  12742. return computeLinearBoundary(source);
  12743. }
  12744. function resolveTarget(sources, index, propagate) {
  12745. var source = sources[index];
  12746. var fill = source.fill;
  12747. var visited = [index];
  12748. var target;
  12749. if (!propagate) {
  12750. return fill;
  12751. }
  12752. while (fill !== false && visited.indexOf(fill) === -1) {
  12753. if (!isFinite(fill)) {
  12754. return fill;
  12755. }
  12756. target = sources[fill];
  12757. if (!target) {
  12758. return false;
  12759. }
  12760. if (target.visible) {
  12761. return fill;
  12762. }
  12763. visited.push(fill);
  12764. fill = target.fill;
  12765. }
  12766. return false;
  12767. }
  12768. function createMapper(source) {
  12769. var fill = source.fill;
  12770. var type = 'dataset';
  12771. if (fill === false) {
  12772. return null;
  12773. }
  12774. if (!isFinite(fill)) {
  12775. type = 'boundary';
  12776. }
  12777. return mappers[type](source);
  12778. }
  12779. function isDrawable(point) {
  12780. return point && !point.skip;
  12781. }
  12782. function drawArea(ctx, curve0, curve1, len0, len1) {
  12783. var i, cx, cy, r;
  12784. if (!len0 || !len1) {
  12785. return;
  12786. }
  12787. // building first area curve (normal)
  12788. ctx.moveTo(curve0[0].x, curve0[0].y);
  12789. for (i = 1; i < len0; ++i) {
  12790. helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  12791. }
  12792. if (curve1[0].angle !== undefined) {
  12793. cx = curve1[0].cx;
  12794. cy = curve1[0].cy;
  12795. r = Math.sqrt(Math.pow(curve1[0].x - cx, 2) + Math.pow(curve1[0].y - cy, 2));
  12796. for (i = len1 - 1; i > 0; --i) {
  12797. ctx.arc(cx, cy, r, curve1[i].angle, curve1[i - 1].angle, true);
  12798. }
  12799. return;
  12800. }
  12801. // joining the two area curves
  12802. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  12803. // building opposite area curve (reverse)
  12804. for (i = len1 - 1; i > 0; --i) {
  12805. helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  12806. }
  12807. }
  12808. function doFill(ctx, points, mapper, view, color, loop) {
  12809. var count = points.length;
  12810. var span = view.spanGaps;
  12811. var curve0 = [];
  12812. var curve1 = [];
  12813. var len0 = 0;
  12814. var len1 = 0;
  12815. var i, ilen, index, p0, p1, d0, d1, loopOffset;
  12816. ctx.beginPath();
  12817. for (i = 0, ilen = count; i < ilen; ++i) {
  12818. index = i % count;
  12819. p0 = points[index]._view;
  12820. p1 = mapper(p0, index, view);
  12821. d0 = isDrawable(p0);
  12822. d1 = isDrawable(p1);
  12823. if (loop && loopOffset === undefined && d0) {
  12824. loopOffset = i + 1;
  12825. ilen = count + loopOffset;
  12826. }
  12827. if (d0 && d1) {
  12828. len0 = curve0.push(p0);
  12829. len1 = curve1.push(p1);
  12830. } else if (len0 && len1) {
  12831. if (!span) {
  12832. drawArea(ctx, curve0, curve1, len0, len1);
  12833. len0 = len1 = 0;
  12834. curve0 = [];
  12835. curve1 = [];
  12836. } else {
  12837. if (d0) {
  12838. curve0.push(p0);
  12839. }
  12840. if (d1) {
  12841. curve1.push(p1);
  12842. }
  12843. }
  12844. }
  12845. }
  12846. drawArea(ctx, curve0, curve1, len0, len1);
  12847. ctx.closePath();
  12848. ctx.fillStyle = color;
  12849. ctx.fill();
  12850. }
  12851. var plugin_filler = {
  12852. id: 'filler',
  12853. afterDatasetsUpdate: function(chart, options) {
  12854. var count = (chart.data.datasets || []).length;
  12855. var propagate = options.propagate;
  12856. var sources = [];
  12857. var meta, i, el, source;
  12858. for (i = 0; i < count; ++i) {
  12859. meta = chart.getDatasetMeta(i);
  12860. el = meta.dataset;
  12861. source = null;
  12862. if (el && el._model && el instanceof elements.Line) {
  12863. source = {
  12864. visible: chart.isDatasetVisible(i),
  12865. fill: decodeFill(el, i, count),
  12866. chart: chart,
  12867. el: el
  12868. };
  12869. }
  12870. meta.$filler = source;
  12871. sources.push(source);
  12872. }
  12873. for (i = 0; i < count; ++i) {
  12874. source = sources[i];
  12875. if (!source) {
  12876. continue;
  12877. }
  12878. source.fill = resolveTarget(sources, i, propagate);
  12879. source.boundary = computeBoundary(source);
  12880. source.mapper = createMapper(source);
  12881. }
  12882. },
  12883. beforeDatasetsDraw: function(chart) {
  12884. var metasets = chart._getSortedVisibleDatasetMetas();
  12885. var ctx = chart.ctx;
  12886. var meta, i, el, view, points, mapper, color;
  12887. for (i = metasets.length - 1; i >= 0; --i) {
  12888. meta = metasets[i].$filler;
  12889. if (!meta || !meta.visible) {
  12890. continue;
  12891. }
  12892. el = meta.el;
  12893. view = el._view;
  12894. points = el._children || [];
  12895. mapper = meta.mapper;
  12896. color = view.backgroundColor || core_defaults.global.defaultColor;
  12897. if (mapper && color && points.length) {
  12898. helpers$1.canvas.clipArea(ctx, chart.chartArea);
  12899. doFill(ctx, points, mapper, view, color, el._loop);
  12900. helpers$1.canvas.unclipArea(ctx);
  12901. }
  12902. }
  12903. }
  12904. };
  12905. var getRtlHelper$1 = helpers$1.rtl.getRtlAdapter;
  12906. var noop$1 = helpers$1.noop;
  12907. var valueOrDefault$e = helpers$1.valueOrDefault;
  12908. core_defaults._set('global', {
  12909. legend: {
  12910. display: true,
  12911. position: 'top',
  12912. align: 'center',
  12913. fullWidth: true,
  12914. reverse: false,
  12915. weight: 1000,
  12916. // a callback that will handle
  12917. onClick: function(e, legendItem) {
  12918. var index = legendItem.datasetIndex;
  12919. var ci = this.chart;
  12920. var meta = ci.getDatasetMeta(index);
  12921. // See controller.isDatasetVisible comment
  12922. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  12923. // We hid a dataset ... rerender the chart
  12924. ci.update();
  12925. },
  12926. onHover: null,
  12927. onLeave: null,
  12928. labels: {
  12929. boxWidth: 40,
  12930. padding: 10,
  12931. // Generates labels shown in the legend
  12932. // Valid properties to return:
  12933. // text : text to display
  12934. // fillStyle : fill of coloured box
  12935. // strokeStyle: stroke of coloured box
  12936. // hidden : if this legend item refers to a hidden item
  12937. // lineCap : cap style for line
  12938. // lineDash
  12939. // lineDashOffset :
  12940. // lineJoin :
  12941. // lineWidth :
  12942. generateLabels: function(chart) {
  12943. var datasets = chart.data.datasets;
  12944. var options = chart.options.legend || {};
  12945. var usePointStyle = options.labels && options.labels.usePointStyle;
  12946. return chart._getSortedDatasetMetas().map(function(meta) {
  12947. var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  12948. return {
  12949. text: datasets[meta.index].label,
  12950. fillStyle: style.backgroundColor,
  12951. hidden: !chart.isDatasetVisible(meta.index),
  12952. lineCap: style.borderCapStyle,
  12953. lineDash: style.borderDash,
  12954. lineDashOffset: style.borderDashOffset,
  12955. lineJoin: style.borderJoinStyle,
  12956. lineWidth: style.borderWidth,
  12957. strokeStyle: style.borderColor,
  12958. pointStyle: style.pointStyle,
  12959. rotation: style.rotation,
  12960. // Below is extra data used for toggling the datasets
  12961. datasetIndex: meta.index
  12962. };
  12963. }, this);
  12964. }
  12965. }
  12966. },
  12967. legendCallback: function(chart) {
  12968. var list = document.createElement('ul');
  12969. var datasets = chart.data.datasets;
  12970. var i, ilen, listItem, listItemSpan;
  12971. list.setAttribute('class', chart.id + '-legend');
  12972. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  12973. listItem = list.appendChild(document.createElement('li'));
  12974. listItemSpan = listItem.appendChild(document.createElement('span'));
  12975. listItemSpan.style.backgroundColor = datasets[i].backgroundColor;
  12976. if (datasets[i].label) {
  12977. listItem.appendChild(document.createTextNode(datasets[i].label));
  12978. }
  12979. }
  12980. return list.outerHTML;
  12981. }
  12982. });
  12983. /**
  12984. * Helper function to get the box width based on the usePointStyle option
  12985. * @param {object} labelopts - the label options on the legend
  12986. * @param {number} fontSize - the label font size
  12987. * @return {number} width of the color box area
  12988. */
  12989. function getBoxWidth(labelOpts, fontSize) {
  12990. return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
  12991. fontSize :
  12992. labelOpts.boxWidth;
  12993. }
  12994. /**
  12995. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  12996. */
  12997. var Legend = core_element.extend({
  12998. initialize: function(config) {
  12999. var me = this;
  13000. helpers$1.extend(me, config);
  13001. // Contains hit boxes for each dataset (in dataset order)
  13002. me.legendHitBoxes = [];
  13003. /**
  13004. * @private
  13005. */
  13006. me._hoveredItem = null;
  13007. // Are we in doughnut mode which has a different data type
  13008. me.doughnutMode = false;
  13009. },
  13010. // These methods are ordered by lifecycle. Utilities then follow.
  13011. // Any function defined here is inherited by all legend types.
  13012. // Any function can be extended by the legend type
  13013. beforeUpdate: noop$1,
  13014. update: function(maxWidth, maxHeight, margins) {
  13015. var me = this;
  13016. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  13017. me.beforeUpdate();
  13018. // Absorb the master measurements
  13019. me.maxWidth = maxWidth;
  13020. me.maxHeight = maxHeight;
  13021. me.margins = margins;
  13022. // Dimensions
  13023. me.beforeSetDimensions();
  13024. me.setDimensions();
  13025. me.afterSetDimensions();
  13026. // Labels
  13027. me.beforeBuildLabels();
  13028. me.buildLabels();
  13029. me.afterBuildLabels();
  13030. // Fit
  13031. me.beforeFit();
  13032. me.fit();
  13033. me.afterFit();
  13034. //
  13035. me.afterUpdate();
  13036. return me.minSize;
  13037. },
  13038. afterUpdate: noop$1,
  13039. //
  13040. beforeSetDimensions: noop$1,
  13041. setDimensions: function() {
  13042. var me = this;
  13043. // Set the unconstrained dimension before label rotation
  13044. if (me.isHorizontal()) {
  13045. // Reset position before calculating rotation
  13046. me.width = me.maxWidth;
  13047. me.left = 0;
  13048. me.right = me.width;
  13049. } else {
  13050. me.height = me.maxHeight;
  13051. // Reset position before calculating rotation
  13052. me.top = 0;
  13053. me.bottom = me.height;
  13054. }
  13055. // Reset padding
  13056. me.paddingLeft = 0;
  13057. me.paddingTop = 0;
  13058. me.paddingRight = 0;
  13059. me.paddingBottom = 0;
  13060. // Reset minSize
  13061. me.minSize = {
  13062. width: 0,
  13063. height: 0
  13064. };
  13065. },
  13066. afterSetDimensions: noop$1,
  13067. //
  13068. beforeBuildLabels: noop$1,
  13069. buildLabels: function() {
  13070. var me = this;
  13071. var labelOpts = me.options.labels || {};
  13072. var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
  13073. if (labelOpts.filter) {
  13074. legendItems = legendItems.filter(function(item) {
  13075. return labelOpts.filter(item, me.chart.data);
  13076. });
  13077. }
  13078. if (me.options.reverse) {
  13079. legendItems.reverse();
  13080. }
  13081. me.legendItems = legendItems;
  13082. },
  13083. afterBuildLabels: noop$1,
  13084. //
  13085. beforeFit: noop$1,
  13086. fit: function() {
  13087. var me = this;
  13088. var opts = me.options;
  13089. var labelOpts = opts.labels;
  13090. var display = opts.display;
  13091. var ctx = me.ctx;
  13092. var labelFont = helpers$1.options._parseFont(labelOpts);
  13093. var fontSize = labelFont.size;
  13094. // Reset hit boxes
  13095. var hitboxes = me.legendHitBoxes = [];
  13096. var minSize = me.minSize;
  13097. var isHorizontal = me.isHorizontal();
  13098. if (isHorizontal) {
  13099. minSize.width = me.maxWidth; // fill all the width
  13100. minSize.height = display ? 10 : 0;
  13101. } else {
  13102. minSize.width = display ? 10 : 0;
  13103. minSize.height = me.maxHeight; // fill all the height
  13104. }
  13105. // Increase sizes here
  13106. if (!display) {
  13107. me.width = minSize.width = me.height = minSize.height = 0;
  13108. return;
  13109. }
  13110. ctx.font = labelFont.string;
  13111. if (isHorizontal) {
  13112. // Labels
  13113. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  13114. var lineWidths = me.lineWidths = [0];
  13115. var totalHeight = 0;
  13116. ctx.textAlign = 'left';
  13117. ctx.textBaseline = 'middle';
  13118. helpers$1.each(me.legendItems, function(legendItem, i) {
  13119. var boxWidth = getBoxWidth(labelOpts, fontSize);
  13120. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  13121. if (i === 0 || lineWidths[lineWidths.length - 1] + width + 2 * labelOpts.padding > minSize.width) {
  13122. totalHeight += fontSize + labelOpts.padding;
  13123. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  13124. }
  13125. // Store the hitbox width and height here. Final position will be updated in `draw`
  13126. hitboxes[i] = {
  13127. left: 0,
  13128. top: 0,
  13129. width: width,
  13130. height: fontSize
  13131. };
  13132. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  13133. });
  13134. minSize.height += totalHeight;
  13135. } else {
  13136. var vPadding = labelOpts.padding;
  13137. var columnWidths = me.columnWidths = [];
  13138. var columnHeights = me.columnHeights = [];
  13139. var totalWidth = labelOpts.padding;
  13140. var currentColWidth = 0;
  13141. var currentColHeight = 0;
  13142. helpers$1.each(me.legendItems, function(legendItem, i) {
  13143. var boxWidth = getBoxWidth(labelOpts, fontSize);
  13144. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  13145. // If too tall, go to new column
  13146. if (i > 0 && currentColHeight + fontSize + 2 * vPadding > minSize.height) {
  13147. totalWidth += currentColWidth + labelOpts.padding;
  13148. columnWidths.push(currentColWidth); // previous column width
  13149. columnHeights.push(currentColHeight);
  13150. currentColWidth = 0;
  13151. currentColHeight = 0;
  13152. }
  13153. // Get max width
  13154. currentColWidth = Math.max(currentColWidth, itemWidth);
  13155. currentColHeight += fontSize + vPadding;
  13156. // Store the hitbox width and height here. Final position will be updated in `draw`
  13157. hitboxes[i] = {
  13158. left: 0,
  13159. top: 0,
  13160. width: itemWidth,
  13161. height: fontSize
  13162. };
  13163. });
  13164. totalWidth += currentColWidth;
  13165. columnWidths.push(currentColWidth);
  13166. columnHeights.push(currentColHeight);
  13167. minSize.width += totalWidth;
  13168. }
  13169. me.width = minSize.width;
  13170. me.height = minSize.height;
  13171. },
  13172. afterFit: noop$1,
  13173. // Shared Methods
  13174. isHorizontal: function() {
  13175. return this.options.position === 'top' || this.options.position === 'bottom';
  13176. },
  13177. // Actually draw the legend on the canvas
  13178. draw: function() {
  13179. var me = this;
  13180. var opts = me.options;
  13181. var labelOpts = opts.labels;
  13182. var globalDefaults = core_defaults.global;
  13183. var defaultColor = globalDefaults.defaultColor;
  13184. var lineDefault = globalDefaults.elements.line;
  13185. var legendHeight = me.height;
  13186. var columnHeights = me.columnHeights;
  13187. var legendWidth = me.width;
  13188. var lineWidths = me.lineWidths;
  13189. if (!opts.display) {
  13190. return;
  13191. }
  13192. var rtlHelper = getRtlHelper$1(opts.rtl, me.left, me.minSize.width);
  13193. var ctx = me.ctx;
  13194. var fontColor = valueOrDefault$e(labelOpts.fontColor, globalDefaults.defaultFontColor);
  13195. var labelFont = helpers$1.options._parseFont(labelOpts);
  13196. var fontSize = labelFont.size;
  13197. var cursor;
  13198. // Canvas setup
  13199. ctx.textAlign = rtlHelper.textAlign('left');
  13200. ctx.textBaseline = 'middle';
  13201. ctx.lineWidth = 0.5;
  13202. ctx.strokeStyle = fontColor; // for strikethrough effect
  13203. ctx.fillStyle = fontColor; // render in correct colour
  13204. ctx.font = labelFont.string;
  13205. var boxWidth = getBoxWidth(labelOpts, fontSize);
  13206. var hitboxes = me.legendHitBoxes;
  13207. // current position
  13208. var drawLegendBox = function(x, y, legendItem) {
  13209. if (isNaN(boxWidth) || boxWidth <= 0) {
  13210. return;
  13211. }
  13212. // Set the ctx for the box
  13213. ctx.save();
  13214. var lineWidth = valueOrDefault$e(legendItem.lineWidth, lineDefault.borderWidth);
  13215. ctx.fillStyle = valueOrDefault$e(legendItem.fillStyle, defaultColor);
  13216. ctx.lineCap = valueOrDefault$e(legendItem.lineCap, lineDefault.borderCapStyle);
  13217. ctx.lineDashOffset = valueOrDefault$e(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  13218. ctx.lineJoin = valueOrDefault$e(legendItem.lineJoin, lineDefault.borderJoinStyle);
  13219. ctx.lineWidth = lineWidth;
  13220. ctx.strokeStyle = valueOrDefault$e(legendItem.strokeStyle, defaultColor);
  13221. if (ctx.setLineDash) {
  13222. // IE 9 and 10 do not support line dash
  13223. ctx.setLineDash(valueOrDefault$e(legendItem.lineDash, lineDefault.borderDash));
  13224. }
  13225. if (labelOpts && labelOpts.usePointStyle) {
  13226. // Recalculate x and y for drawPoint() because its expecting
  13227. // x and y to be center of figure (instead of top left)
  13228. var radius = boxWidth * Math.SQRT2 / 2;
  13229. var centerX = rtlHelper.xPlus(x, boxWidth / 2);
  13230. var centerY = y + fontSize / 2;
  13231. // Draw pointStyle as legend symbol
  13232. helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY, legendItem.rotation);
  13233. } else {
  13234. // Draw box as legend symbol
  13235. ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  13236. if (lineWidth !== 0) {
  13237. ctx.strokeRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  13238. }
  13239. }
  13240. ctx.restore();
  13241. };
  13242. var fillText = function(x, y, legendItem, textWidth) {
  13243. var halfFontSize = fontSize / 2;
  13244. var xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize);
  13245. var yMiddle = y + halfFontSize;
  13246. ctx.fillText(legendItem.text, xLeft, yMiddle);
  13247. if (legendItem.hidden) {
  13248. // Strikethrough the text if hidden
  13249. ctx.beginPath();
  13250. ctx.lineWidth = 2;
  13251. ctx.moveTo(xLeft, yMiddle);
  13252. ctx.lineTo(rtlHelper.xPlus(xLeft, textWidth), yMiddle);
  13253. ctx.stroke();
  13254. }
  13255. };
  13256. var alignmentOffset = function(dimension, blockSize) {
  13257. switch (opts.align) {
  13258. case 'start':
  13259. return labelOpts.padding;
  13260. case 'end':
  13261. return dimension - blockSize;
  13262. default: // center
  13263. return (dimension - blockSize + labelOpts.padding) / 2;
  13264. }
  13265. };
  13266. // Horizontal
  13267. var isHorizontal = me.isHorizontal();
  13268. if (isHorizontal) {
  13269. cursor = {
  13270. x: me.left + alignmentOffset(legendWidth, lineWidths[0]),
  13271. y: me.top + labelOpts.padding,
  13272. line: 0
  13273. };
  13274. } else {
  13275. cursor = {
  13276. x: me.left + labelOpts.padding,
  13277. y: me.top + alignmentOffset(legendHeight, columnHeights[0]),
  13278. line: 0
  13279. };
  13280. }
  13281. helpers$1.rtl.overrideTextDirection(me.ctx, opts.textDirection);
  13282. var itemHeight = fontSize + labelOpts.padding;
  13283. helpers$1.each(me.legendItems, function(legendItem, i) {
  13284. var textWidth = ctx.measureText(legendItem.text).width;
  13285. var width = boxWidth + (fontSize / 2) + textWidth;
  13286. var x = cursor.x;
  13287. var y = cursor.y;
  13288. rtlHelper.setWidth(me.minSize.width);
  13289. // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
  13290. // instead of me.right and me.bottom because me.width and me.height
  13291. // may have been changed since me.minSize was calculated
  13292. if (isHorizontal) {
  13293. if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
  13294. y = cursor.y += itemHeight;
  13295. cursor.line++;
  13296. x = cursor.x = me.left + alignmentOffset(legendWidth, lineWidths[cursor.line]);
  13297. }
  13298. } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
  13299. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  13300. cursor.line++;
  13301. y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]);
  13302. }
  13303. var realX = rtlHelper.x(x);
  13304. drawLegendBox(realX, y, legendItem);
  13305. hitboxes[i].left = rtlHelper.leftForLtr(realX, hitboxes[i].width);
  13306. hitboxes[i].top = y;
  13307. // Fill the actual label
  13308. fillText(realX, y, legendItem, textWidth);
  13309. if (isHorizontal) {
  13310. cursor.x += width + labelOpts.padding;
  13311. } else {
  13312. cursor.y += itemHeight;
  13313. }
  13314. });
  13315. helpers$1.rtl.restoreTextDirection(me.ctx, opts.textDirection);
  13316. },
  13317. /**
  13318. * @private
  13319. */
  13320. _getLegendItemAt: function(x, y) {
  13321. var me = this;
  13322. var i, hitBox, lh;
  13323. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  13324. // See if we are touching one of the dataset boxes
  13325. lh = me.legendHitBoxes;
  13326. for (i = 0; i < lh.length; ++i) {
  13327. hitBox = lh[i];
  13328. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  13329. // Touching an element
  13330. return me.legendItems[i];
  13331. }
  13332. }
  13333. }
  13334. return null;
  13335. },
  13336. /**
  13337. * Handle an event
  13338. * @private
  13339. * @param {IEvent} event - The event to handle
  13340. */
  13341. handleEvent: function(e) {
  13342. var me = this;
  13343. var opts = me.options;
  13344. var type = e.type === 'mouseup' ? 'click' : e.type;
  13345. var hoveredItem;
  13346. if (type === 'mousemove') {
  13347. if (!opts.onHover && !opts.onLeave) {
  13348. return;
  13349. }
  13350. } else if (type === 'click') {
  13351. if (!opts.onClick) {
  13352. return;
  13353. }
  13354. } else {
  13355. return;
  13356. }
  13357. // Chart event already has relative position in it
  13358. hoveredItem = me._getLegendItemAt(e.x, e.y);
  13359. if (type === 'click') {
  13360. if (hoveredItem && opts.onClick) {
  13361. // use e.native for backwards compatibility
  13362. opts.onClick.call(me, e.native, hoveredItem);
  13363. }
  13364. } else {
  13365. if (opts.onLeave && hoveredItem !== me._hoveredItem) {
  13366. if (me._hoveredItem) {
  13367. opts.onLeave.call(me, e.native, me._hoveredItem);
  13368. }
  13369. me._hoveredItem = hoveredItem;
  13370. }
  13371. if (opts.onHover && hoveredItem) {
  13372. // use e.native for backwards compatibility
  13373. opts.onHover.call(me, e.native, hoveredItem);
  13374. }
  13375. }
  13376. }
  13377. });
  13378. function createNewLegendAndAttach(chart, legendOpts) {
  13379. var legend = new Legend({
  13380. ctx: chart.ctx,
  13381. options: legendOpts,
  13382. chart: chart
  13383. });
  13384. core_layouts.configure(chart, legend, legendOpts);
  13385. core_layouts.addBox(chart, legend);
  13386. chart.legend = legend;
  13387. }
  13388. var plugin_legend = {
  13389. id: 'legend',
  13390. /**
  13391. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  13392. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  13393. * the plugin, which one will be re-exposed in the chart.js file.
  13394. * https://github.com/chartjs/Chart.js/pull/2640
  13395. * @private
  13396. */
  13397. _element: Legend,
  13398. beforeInit: function(chart) {
  13399. var legendOpts = chart.options.legend;
  13400. if (legendOpts) {
  13401. createNewLegendAndAttach(chart, legendOpts);
  13402. }
  13403. },
  13404. beforeUpdate: function(chart) {
  13405. var legendOpts = chart.options.legend;
  13406. var legend = chart.legend;
  13407. if (legendOpts) {
  13408. helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
  13409. if (legend) {
  13410. core_layouts.configure(chart, legend, legendOpts);
  13411. legend.options = legendOpts;
  13412. } else {
  13413. createNewLegendAndAttach(chart, legendOpts);
  13414. }
  13415. } else if (legend) {
  13416. core_layouts.removeBox(chart, legend);
  13417. delete chart.legend;
  13418. }
  13419. },
  13420. afterEvent: function(chart, e) {
  13421. var legend = chart.legend;
  13422. if (legend) {
  13423. legend.handleEvent(e);
  13424. }
  13425. }
  13426. };
  13427. var noop$2 = helpers$1.noop;
  13428. core_defaults._set('global', {
  13429. title: {
  13430. display: false,
  13431. fontStyle: 'bold',
  13432. fullWidth: true,
  13433. padding: 10,
  13434. position: 'top',
  13435. text: '',
  13436. weight: 2000 // by default greater than legend (1000) to be above
  13437. }
  13438. });
  13439. /**
  13440. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  13441. */
  13442. var Title = core_element.extend({
  13443. initialize: function(config) {
  13444. var me = this;
  13445. helpers$1.extend(me, config);
  13446. // Contains hit boxes for each dataset (in dataset order)
  13447. me.legendHitBoxes = [];
  13448. },
  13449. // These methods are ordered by lifecycle. Utilities then follow.
  13450. beforeUpdate: noop$2,
  13451. update: function(maxWidth, maxHeight, margins) {
  13452. var me = this;
  13453. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  13454. me.beforeUpdate();
  13455. // Absorb the master measurements
  13456. me.maxWidth = maxWidth;
  13457. me.maxHeight = maxHeight;
  13458. me.margins = margins;
  13459. // Dimensions
  13460. me.beforeSetDimensions();
  13461. me.setDimensions();
  13462. me.afterSetDimensions();
  13463. // Labels
  13464. me.beforeBuildLabels();
  13465. me.buildLabels();
  13466. me.afterBuildLabels();
  13467. // Fit
  13468. me.beforeFit();
  13469. me.fit();
  13470. me.afterFit();
  13471. //
  13472. me.afterUpdate();
  13473. return me.minSize;
  13474. },
  13475. afterUpdate: noop$2,
  13476. //
  13477. beforeSetDimensions: noop$2,
  13478. setDimensions: function() {
  13479. var me = this;
  13480. // Set the unconstrained dimension before label rotation
  13481. if (me.isHorizontal()) {
  13482. // Reset position before calculating rotation
  13483. me.width = me.maxWidth;
  13484. me.left = 0;
  13485. me.right = me.width;
  13486. } else {
  13487. me.height = me.maxHeight;
  13488. // Reset position before calculating rotation
  13489. me.top = 0;
  13490. me.bottom = me.height;
  13491. }
  13492. // Reset padding
  13493. me.paddingLeft = 0;
  13494. me.paddingTop = 0;
  13495. me.paddingRight = 0;
  13496. me.paddingBottom = 0;
  13497. // Reset minSize
  13498. me.minSize = {
  13499. width: 0,
  13500. height: 0
  13501. };
  13502. },
  13503. afterSetDimensions: noop$2,
  13504. //
  13505. beforeBuildLabels: noop$2,
  13506. buildLabels: noop$2,
  13507. afterBuildLabels: noop$2,
  13508. //
  13509. beforeFit: noop$2,
  13510. fit: function() {
  13511. var me = this;
  13512. var opts = me.options;
  13513. var minSize = me.minSize = {};
  13514. var isHorizontal = me.isHorizontal();
  13515. var lineCount, textSize;
  13516. if (!opts.display) {
  13517. me.width = minSize.width = me.height = minSize.height = 0;
  13518. return;
  13519. }
  13520. lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
  13521. textSize = lineCount * helpers$1.options._parseFont(opts).lineHeight + opts.padding * 2;
  13522. me.width = minSize.width = isHorizontal ? me.maxWidth : textSize;
  13523. me.height = minSize.height = isHorizontal ? textSize : me.maxHeight;
  13524. },
  13525. afterFit: noop$2,
  13526. // Shared Methods
  13527. isHorizontal: function() {
  13528. var pos = this.options.position;
  13529. return pos === 'top' || pos === 'bottom';
  13530. },
  13531. // Actually draw the title block on the canvas
  13532. draw: function() {
  13533. var me = this;
  13534. var ctx = me.ctx;
  13535. var opts = me.options;
  13536. if (!opts.display) {
  13537. return;
  13538. }
  13539. var fontOpts = helpers$1.options._parseFont(opts);
  13540. var lineHeight = fontOpts.lineHeight;
  13541. var offset = lineHeight / 2 + opts.padding;
  13542. var rotation = 0;
  13543. var top = me.top;
  13544. var left = me.left;
  13545. var bottom = me.bottom;
  13546. var right = me.right;
  13547. var maxWidth, titleX, titleY;
  13548. ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
  13549. ctx.font = fontOpts.string;
  13550. // Horizontal
  13551. if (me.isHorizontal()) {
  13552. titleX = left + ((right - left) / 2); // midpoint of the width
  13553. titleY = top + offset;
  13554. maxWidth = right - left;
  13555. } else {
  13556. titleX = opts.position === 'left' ? left + offset : right - offset;
  13557. titleY = top + ((bottom - top) / 2);
  13558. maxWidth = bottom - top;
  13559. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  13560. }
  13561. ctx.save();
  13562. ctx.translate(titleX, titleY);
  13563. ctx.rotate(rotation);
  13564. ctx.textAlign = 'center';
  13565. ctx.textBaseline = 'middle';
  13566. var text = opts.text;
  13567. if (helpers$1.isArray(text)) {
  13568. var y = 0;
  13569. for (var i = 0; i < text.length; ++i) {
  13570. ctx.fillText(text[i], 0, y, maxWidth);
  13571. y += lineHeight;
  13572. }
  13573. } else {
  13574. ctx.fillText(text, 0, 0, maxWidth);
  13575. }
  13576. ctx.restore();
  13577. }
  13578. });
  13579. function createNewTitleBlockAndAttach(chart, titleOpts) {
  13580. var title = new Title({
  13581. ctx: chart.ctx,
  13582. options: titleOpts,
  13583. chart: chart
  13584. });
  13585. core_layouts.configure(chart, title, titleOpts);
  13586. core_layouts.addBox(chart, title);
  13587. chart.titleBlock = title;
  13588. }
  13589. var plugin_title = {
  13590. id: 'title',
  13591. /**
  13592. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  13593. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  13594. * the plugin, which one will be re-exposed in the chart.js file.
  13595. * https://github.com/chartjs/Chart.js/pull/2640
  13596. * @private
  13597. */
  13598. _element: Title,
  13599. beforeInit: function(chart) {
  13600. var titleOpts = chart.options.title;
  13601. if (titleOpts) {
  13602. createNewTitleBlockAndAttach(chart, titleOpts);
  13603. }
  13604. },
  13605. beforeUpdate: function(chart) {
  13606. var titleOpts = chart.options.title;
  13607. var titleBlock = chart.titleBlock;
  13608. if (titleOpts) {
  13609. helpers$1.mergeIf(titleOpts, core_defaults.global.title);
  13610. if (titleBlock) {
  13611. core_layouts.configure(chart, titleBlock, titleOpts);
  13612. titleBlock.options = titleOpts;
  13613. } else {
  13614. createNewTitleBlockAndAttach(chart, titleOpts);
  13615. }
  13616. } else if (titleBlock) {
  13617. core_layouts.removeBox(chart, titleBlock);
  13618. delete chart.titleBlock;
  13619. }
  13620. }
  13621. };
  13622. var plugins = {};
  13623. var filler = plugin_filler;
  13624. var legend = plugin_legend;
  13625. var title = plugin_title;
  13626. plugins.filler = filler;
  13627. plugins.legend = legend;
  13628. plugins.title = title;
  13629. /**
  13630. * @namespace Chart
  13631. */
  13632. core_controller.helpers = helpers$1;
  13633. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  13634. core_helpers();
  13635. core_controller._adapters = core_adapters;
  13636. core_controller.Animation = core_animation;
  13637. core_controller.animationService = core_animations;
  13638. core_controller.controllers = controllers;
  13639. core_controller.DatasetController = core_datasetController;
  13640. core_controller.defaults = core_defaults;
  13641. core_controller.Element = core_element;
  13642. core_controller.elements = elements;
  13643. core_controller.Interaction = core_interaction;
  13644. core_controller.layouts = core_layouts;
  13645. core_controller.platform = platform;
  13646. core_controller.plugins = core_plugins;
  13647. core_controller.Scale = core_scale;
  13648. core_controller.scaleService = core_scaleService;
  13649. core_controller.Ticks = core_ticks;
  13650. core_controller.Tooltip = core_tooltip;
  13651. // Register built-in scales
  13652. core_controller.helpers.each(scales, function(scale, type) {
  13653. core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
  13654. });
  13655. // Load to register built-in adapters (as side effects)
  13656. // Loading built-in plugins
  13657. for (var k in plugins) {
  13658. if (plugins.hasOwnProperty(k)) {
  13659. core_controller.plugins.register(plugins[k]);
  13660. }
  13661. }
  13662. core_controller.platform.initialize();
  13663. var src = core_controller;
  13664. if (typeof window !== 'undefined') {
  13665. window.Chart = core_controller;
  13666. }
  13667. // DEPRECATIONS
  13668. /**
  13669. * Provided for backward compatibility, not available anymore
  13670. * @namespace Chart.Chart
  13671. * @deprecated since version 2.8.0
  13672. * @todo remove at version 3
  13673. * @private
  13674. */
  13675. core_controller.Chart = core_controller;
  13676. /**
  13677. * Provided for backward compatibility, not available anymore
  13678. * @namespace Chart.Legend
  13679. * @deprecated since version 2.1.5
  13680. * @todo remove at version 3
  13681. * @private
  13682. */
  13683. core_controller.Legend = plugins.legend._element;
  13684. /**
  13685. * Provided for backward compatibility, not available anymore
  13686. * @namespace Chart.Title
  13687. * @deprecated since version 2.1.5
  13688. * @todo remove at version 3
  13689. * @private
  13690. */
  13691. core_controller.Title = plugins.title._element;
  13692. /**
  13693. * Provided for backward compatibility, use Chart.plugins instead
  13694. * @namespace Chart.pluginService
  13695. * @deprecated since version 2.1.5
  13696. * @todo remove at version 3
  13697. * @private
  13698. */
  13699. core_controller.pluginService = core_controller.plugins;
  13700. /**
  13701. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  13702. * effect, instead simply create/register plugins via plain JavaScript objects.
  13703. * @interface Chart.PluginBase
  13704. * @deprecated since version 2.5.0
  13705. * @todo remove at version 3
  13706. * @private
  13707. */
  13708. core_controller.PluginBase = core_controller.Element.extend({});
  13709. /**
  13710. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  13711. * @namespace Chart.canvasHelpers
  13712. * @deprecated since version 2.6.0
  13713. * @todo remove at version 3
  13714. * @private
  13715. */
  13716. core_controller.canvasHelpers = core_controller.helpers.canvas;
  13717. /**
  13718. * Provided for backward compatibility, use Chart.layouts instead.
  13719. * @namespace Chart.layoutService
  13720. * @deprecated since version 2.7.3
  13721. * @todo remove at version 3
  13722. * @private
  13723. */
  13724. core_controller.layoutService = core_controller.layouts;
  13725. /**
  13726. * Provided for backward compatibility, not available anymore.
  13727. * @namespace Chart.LinearScaleBase
  13728. * @deprecated since version 2.8
  13729. * @todo remove at version 3
  13730. * @private
  13731. */
  13732. core_controller.LinearScaleBase = scale_linearbase;
  13733. /**
  13734. * Provided for backward compatibility, instead we should create a new Chart
  13735. * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
  13736. * @deprecated since version 2.8.0
  13737. * @todo remove at version 3
  13738. */
  13739. core_controller.helpers.each(
  13740. [
  13741. 'Bar',
  13742. 'Bubble',
  13743. 'Doughnut',
  13744. 'Line',
  13745. 'PolarArea',
  13746. 'Radar',
  13747. 'Scatter'
  13748. ],
  13749. function(klass) {
  13750. core_controller[klass] = function(ctx, cfg) {
  13751. return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
  13752. type: klass.charAt(0).toLowerCase() + klass.slice(1)
  13753. }));
  13754. };
  13755. }
  13756. );
  13757. return src;
  13758. })));