Chart.js 387 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680
  1. /*!
  2. * Chart.js v2.8.0
  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.Chart = factory(global.moment));
  11. }(this, (function (moment) { 'use strict';
  12. moment = moment && moment.hasOwnProperty('default') ? moment['default'] : moment;
  13. /* MIT license */
  14. var conversions = {
  15. rgb2hsl: rgb2hsl,
  16. rgb2hsv: rgb2hsv,
  17. rgb2hwb: rgb2hwb,
  18. rgb2cmyk: rgb2cmyk,
  19. rgb2keyword: rgb2keyword,
  20. rgb2xyz: rgb2xyz,
  21. rgb2lab: rgb2lab,
  22. rgb2lch: rgb2lch,
  23. hsl2rgb: hsl2rgb,
  24. hsl2hsv: hsl2hsv,
  25. hsl2hwb: hsl2hwb,
  26. hsl2cmyk: hsl2cmyk,
  27. hsl2keyword: hsl2keyword,
  28. hsv2rgb: hsv2rgb,
  29. hsv2hsl: hsv2hsl,
  30. hsv2hwb: hsv2hwb,
  31. hsv2cmyk: hsv2cmyk,
  32. hsv2keyword: hsv2keyword,
  33. hwb2rgb: hwb2rgb,
  34. hwb2hsl: hwb2hsl,
  35. hwb2hsv: hwb2hsv,
  36. hwb2cmyk: hwb2cmyk,
  37. hwb2keyword: hwb2keyword,
  38. cmyk2rgb: cmyk2rgb,
  39. cmyk2hsl: cmyk2hsl,
  40. cmyk2hsv: cmyk2hsv,
  41. cmyk2hwb: cmyk2hwb,
  42. cmyk2keyword: cmyk2keyword,
  43. keyword2rgb: keyword2rgb,
  44. keyword2hsl: keyword2hsl,
  45. keyword2hsv: keyword2hsv,
  46. keyword2hwb: keyword2hwb,
  47. keyword2cmyk: keyword2cmyk,
  48. keyword2lab: keyword2lab,
  49. keyword2xyz: keyword2xyz,
  50. xyz2rgb: xyz2rgb,
  51. xyz2lab: xyz2lab,
  52. xyz2lch: xyz2lch,
  53. lab2xyz: lab2xyz,
  54. lab2rgb: lab2rgb,
  55. lab2lch: lab2lch,
  56. lch2lab: lch2lab,
  57. lch2xyz: lch2xyz,
  58. lch2rgb: lch2rgb
  59. };
  60. function rgb2hsl(rgb) {
  61. var r = rgb[0]/255,
  62. g = rgb[1]/255,
  63. b = rgb[2]/255,
  64. min = Math.min(r, g, b),
  65. max = Math.max(r, g, b),
  66. delta = max - min,
  67. h, s, l;
  68. if (max == min)
  69. h = 0;
  70. else if (r == max)
  71. h = (g - b) / delta;
  72. else if (g == max)
  73. h = 2 + (b - r) / delta;
  74. else if (b == max)
  75. h = 4 + (r - g)/ delta;
  76. h = Math.min(h * 60, 360);
  77. if (h < 0)
  78. h += 360;
  79. l = (min + max) / 2;
  80. if (max == min)
  81. s = 0;
  82. else if (l <= 0.5)
  83. s = delta / (max + min);
  84. else
  85. s = delta / (2 - max - min);
  86. return [h, s * 100, l * 100];
  87. }
  88. function rgb2hsv(rgb) {
  89. var r = rgb[0],
  90. g = rgb[1],
  91. b = rgb[2],
  92. min = Math.min(r, g, b),
  93. max = Math.max(r, g, b),
  94. delta = max - min,
  95. h, s, v;
  96. if (max == 0)
  97. s = 0;
  98. else
  99. s = (delta/max * 1000)/10;
  100. if (max == min)
  101. h = 0;
  102. else if (r == max)
  103. h = (g - b) / delta;
  104. else if (g == max)
  105. h = 2 + (b - r) / delta;
  106. else if (b == max)
  107. h = 4 + (r - g) / delta;
  108. h = Math.min(h * 60, 360);
  109. if (h < 0)
  110. h += 360;
  111. v = ((max / 255) * 1000) / 10;
  112. return [h, s, v];
  113. }
  114. function rgb2hwb(rgb) {
  115. var r = rgb[0],
  116. g = rgb[1],
  117. b = rgb[2],
  118. h = rgb2hsl(rgb)[0],
  119. w = 1/255 * Math.min(r, Math.min(g, b)),
  120. b = 1 - 1/255 * Math.max(r, Math.max(g, b));
  121. return [h, w * 100, b * 100];
  122. }
  123. function rgb2cmyk(rgb) {
  124. var r = rgb[0] / 255,
  125. g = rgb[1] / 255,
  126. b = rgb[2] / 255,
  127. c, m, y, k;
  128. k = Math.min(1 - r, 1 - g, 1 - b);
  129. c = (1 - r - k) / (1 - k) || 0;
  130. m = (1 - g - k) / (1 - k) || 0;
  131. y = (1 - b - k) / (1 - k) || 0;
  132. return [c * 100, m * 100, y * 100, k * 100];
  133. }
  134. function rgb2keyword(rgb) {
  135. return reverseKeywords[JSON.stringify(rgb)];
  136. }
  137. function rgb2xyz(rgb) {
  138. var r = rgb[0] / 255,
  139. g = rgb[1] / 255,
  140. b = rgb[2] / 255;
  141. // assume sRGB
  142. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  143. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  144. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  145. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  146. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  147. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  148. return [x * 100, y *100, z * 100];
  149. }
  150. function rgb2lab(rgb) {
  151. var xyz = rgb2xyz(rgb),
  152. x = xyz[0],
  153. y = xyz[1],
  154. z = xyz[2],
  155. l, a, b;
  156. x /= 95.047;
  157. y /= 100;
  158. z /= 108.883;
  159. x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
  160. y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
  161. z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
  162. l = (116 * y) - 16;
  163. a = 500 * (x - y);
  164. b = 200 * (y - z);
  165. return [l, a, b];
  166. }
  167. function rgb2lch(args) {
  168. return lab2lch(rgb2lab(args));
  169. }
  170. function hsl2rgb(hsl) {
  171. var h = hsl[0] / 360,
  172. s = hsl[1] / 100,
  173. l = hsl[2] / 100,
  174. t1, t2, t3, rgb, val;
  175. if (s == 0) {
  176. val = l * 255;
  177. return [val, val, val];
  178. }
  179. if (l < 0.5)
  180. t2 = l * (1 + s);
  181. else
  182. t2 = l + s - l * s;
  183. t1 = 2 * l - t2;
  184. rgb = [0, 0, 0];
  185. for (var i = 0; i < 3; i++) {
  186. t3 = h + 1 / 3 * - (i - 1);
  187. t3 < 0 && t3++;
  188. t3 > 1 && t3--;
  189. if (6 * t3 < 1)
  190. val = t1 + (t2 - t1) * 6 * t3;
  191. else if (2 * t3 < 1)
  192. val = t2;
  193. else if (3 * t3 < 2)
  194. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  195. else
  196. val = t1;
  197. rgb[i] = val * 255;
  198. }
  199. return rgb;
  200. }
  201. function hsl2hsv(hsl) {
  202. var h = hsl[0],
  203. s = hsl[1] / 100,
  204. l = hsl[2] / 100,
  205. sv, v;
  206. if(l === 0) {
  207. // no need to do calc on black
  208. // also avoids divide by 0 error
  209. return [0, 0, 0];
  210. }
  211. l *= 2;
  212. s *= (l <= 1) ? l : 2 - l;
  213. v = (l + s) / 2;
  214. sv = (2 * s) / (l + s);
  215. return [h, sv * 100, v * 100];
  216. }
  217. function hsl2hwb(args) {
  218. return rgb2hwb(hsl2rgb(args));
  219. }
  220. function hsl2cmyk(args) {
  221. return rgb2cmyk(hsl2rgb(args));
  222. }
  223. function hsl2keyword(args) {
  224. return rgb2keyword(hsl2rgb(args));
  225. }
  226. function hsv2rgb(hsv) {
  227. var h = hsv[0] / 60,
  228. s = hsv[1] / 100,
  229. v = hsv[2] / 100,
  230. hi = Math.floor(h) % 6;
  231. var f = h - Math.floor(h),
  232. p = 255 * v * (1 - s),
  233. q = 255 * v * (1 - (s * f)),
  234. t = 255 * v * (1 - (s * (1 - f))),
  235. v = 255 * v;
  236. switch(hi) {
  237. case 0:
  238. return [v, t, p];
  239. case 1:
  240. return [q, v, p];
  241. case 2:
  242. return [p, v, t];
  243. case 3:
  244. return [p, q, v];
  245. case 4:
  246. return [t, p, v];
  247. case 5:
  248. return [v, p, q];
  249. }
  250. }
  251. function hsv2hsl(hsv) {
  252. var h = hsv[0],
  253. s = hsv[1] / 100,
  254. v = hsv[2] / 100,
  255. sl, l;
  256. l = (2 - s) * v;
  257. sl = s * v;
  258. sl /= (l <= 1) ? l : 2 - l;
  259. sl = sl || 0;
  260. l /= 2;
  261. return [h, sl * 100, l * 100];
  262. }
  263. function hsv2hwb(args) {
  264. return rgb2hwb(hsv2rgb(args))
  265. }
  266. function hsv2cmyk(args) {
  267. return rgb2cmyk(hsv2rgb(args));
  268. }
  269. function hsv2keyword(args) {
  270. return rgb2keyword(hsv2rgb(args));
  271. }
  272. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  273. function hwb2rgb(hwb) {
  274. var h = hwb[0] / 360,
  275. wh = hwb[1] / 100,
  276. bl = hwb[2] / 100,
  277. ratio = wh + bl,
  278. i, v, f, n;
  279. // wh + bl cant be > 1
  280. if (ratio > 1) {
  281. wh /= ratio;
  282. bl /= ratio;
  283. }
  284. i = Math.floor(6 * h);
  285. v = 1 - bl;
  286. f = 6 * h - i;
  287. if ((i & 0x01) != 0) {
  288. f = 1 - f;
  289. }
  290. n = wh + f * (v - wh); // linear interpolation
  291. switch (i) {
  292. default:
  293. case 6:
  294. case 0: r = v; g = n; b = wh; break;
  295. case 1: r = n; g = v; b = wh; break;
  296. case 2: r = wh; g = v; b = n; break;
  297. case 3: r = wh; g = n; b = v; break;
  298. case 4: r = n; g = wh; b = v; break;
  299. case 5: r = v; g = wh; b = n; break;
  300. }
  301. return [r * 255, g * 255, b * 255];
  302. }
  303. function hwb2hsl(args) {
  304. return rgb2hsl(hwb2rgb(args));
  305. }
  306. function hwb2hsv(args) {
  307. return rgb2hsv(hwb2rgb(args));
  308. }
  309. function hwb2cmyk(args) {
  310. return rgb2cmyk(hwb2rgb(args));
  311. }
  312. function hwb2keyword(args) {
  313. return rgb2keyword(hwb2rgb(args));
  314. }
  315. function cmyk2rgb(cmyk) {
  316. var c = cmyk[0] / 100,
  317. m = cmyk[1] / 100,
  318. y = cmyk[2] / 100,
  319. k = cmyk[3] / 100,
  320. r, g, b;
  321. r = 1 - Math.min(1, c * (1 - k) + k);
  322. g = 1 - Math.min(1, m * (1 - k) + k);
  323. b = 1 - Math.min(1, y * (1 - k) + k);
  324. return [r * 255, g * 255, b * 255];
  325. }
  326. function cmyk2hsl(args) {
  327. return rgb2hsl(cmyk2rgb(args));
  328. }
  329. function cmyk2hsv(args) {
  330. return rgb2hsv(cmyk2rgb(args));
  331. }
  332. function cmyk2hwb(args) {
  333. return rgb2hwb(cmyk2rgb(args));
  334. }
  335. function cmyk2keyword(args) {
  336. return rgb2keyword(cmyk2rgb(args));
  337. }
  338. function xyz2rgb(xyz) {
  339. var x = xyz[0] / 100,
  340. y = xyz[1] / 100,
  341. z = xyz[2] / 100,
  342. r, g, b;
  343. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  344. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  345. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  346. // assume sRGB
  347. r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  348. : r = (r * 12.92);
  349. g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  350. : g = (g * 12.92);
  351. b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  352. : b = (b * 12.92);
  353. r = Math.min(Math.max(0, r), 1);
  354. g = Math.min(Math.max(0, g), 1);
  355. b = Math.min(Math.max(0, b), 1);
  356. return [r * 255, g * 255, b * 255];
  357. }
  358. function xyz2lab(xyz) {
  359. var x = xyz[0],
  360. y = xyz[1],
  361. z = xyz[2],
  362. l, a, b;
  363. x /= 95.047;
  364. y /= 100;
  365. z /= 108.883;
  366. x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
  367. y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
  368. z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
  369. l = (116 * y) - 16;
  370. a = 500 * (x - y);
  371. b = 200 * (y - z);
  372. return [l, a, b];
  373. }
  374. function xyz2lch(args) {
  375. return lab2lch(xyz2lab(args));
  376. }
  377. function lab2xyz(lab) {
  378. var l = lab[0],
  379. a = lab[1],
  380. b = lab[2],
  381. x, y, z, y2;
  382. if (l <= 8) {
  383. y = (l * 100) / 903.3;
  384. y2 = (7.787 * (y / 100)) + (16 / 116);
  385. } else {
  386. y = 100 * Math.pow((l + 16) / 116, 3);
  387. y2 = Math.pow(y / 100, 1/3);
  388. }
  389. x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3);
  390. z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3);
  391. return [x, y, z];
  392. }
  393. function lab2lch(lab) {
  394. var l = lab[0],
  395. a = lab[1],
  396. b = lab[2],
  397. hr, h, c;
  398. hr = Math.atan2(b, a);
  399. h = hr * 360 / 2 / Math.PI;
  400. if (h < 0) {
  401. h += 360;
  402. }
  403. c = Math.sqrt(a * a + b * b);
  404. return [l, c, h];
  405. }
  406. function lab2rgb(args) {
  407. return xyz2rgb(lab2xyz(args));
  408. }
  409. function lch2lab(lch) {
  410. var l = lch[0],
  411. c = lch[1],
  412. h = lch[2],
  413. a, b, hr;
  414. hr = h / 360 * 2 * Math.PI;
  415. a = c * Math.cos(hr);
  416. b = c * Math.sin(hr);
  417. return [l, a, b];
  418. }
  419. function lch2xyz(args) {
  420. return lab2xyz(lch2lab(args));
  421. }
  422. function lch2rgb(args) {
  423. return lab2rgb(lch2lab(args));
  424. }
  425. function keyword2rgb(keyword) {
  426. return cssKeywords[keyword];
  427. }
  428. function keyword2hsl(args) {
  429. return rgb2hsl(keyword2rgb(args));
  430. }
  431. function keyword2hsv(args) {
  432. return rgb2hsv(keyword2rgb(args));
  433. }
  434. function keyword2hwb(args) {
  435. return rgb2hwb(keyword2rgb(args));
  436. }
  437. function keyword2cmyk(args) {
  438. return rgb2cmyk(keyword2rgb(args));
  439. }
  440. function keyword2lab(args) {
  441. return rgb2lab(keyword2rgb(args));
  442. }
  443. function keyword2xyz(args) {
  444. return rgb2xyz(keyword2rgb(args));
  445. }
  446. var cssKeywords = {
  447. aliceblue: [240,248,255],
  448. antiquewhite: [250,235,215],
  449. aqua: [0,255,255],
  450. aquamarine: [127,255,212],
  451. azure: [240,255,255],
  452. beige: [245,245,220],
  453. bisque: [255,228,196],
  454. black: [0,0,0],
  455. blanchedalmond: [255,235,205],
  456. blue: [0,0,255],
  457. blueviolet: [138,43,226],
  458. brown: [165,42,42],
  459. burlywood: [222,184,135],
  460. cadetblue: [95,158,160],
  461. chartreuse: [127,255,0],
  462. chocolate: [210,105,30],
  463. coral: [255,127,80],
  464. cornflowerblue: [100,149,237],
  465. cornsilk: [255,248,220],
  466. crimson: [220,20,60],
  467. cyan: [0,255,255],
  468. darkblue: [0,0,139],
  469. darkcyan: [0,139,139],
  470. darkgoldenrod: [184,134,11],
  471. darkgray: [169,169,169],
  472. darkgreen: [0,100,0],
  473. darkgrey: [169,169,169],
  474. darkkhaki: [189,183,107],
  475. darkmagenta: [139,0,139],
  476. darkolivegreen: [85,107,47],
  477. darkorange: [255,140,0],
  478. darkorchid: [153,50,204],
  479. darkred: [139,0,0],
  480. darksalmon: [233,150,122],
  481. darkseagreen: [143,188,143],
  482. darkslateblue: [72,61,139],
  483. darkslategray: [47,79,79],
  484. darkslategrey: [47,79,79],
  485. darkturquoise: [0,206,209],
  486. darkviolet: [148,0,211],
  487. deeppink: [255,20,147],
  488. deepskyblue: [0,191,255],
  489. dimgray: [105,105,105],
  490. dimgrey: [105,105,105],
  491. dodgerblue: [30,144,255],
  492. firebrick: [178,34,34],
  493. floralwhite: [255,250,240],
  494. forestgreen: [34,139,34],
  495. fuchsia: [255,0,255],
  496. gainsboro: [220,220,220],
  497. ghostwhite: [248,248,255],
  498. gold: [255,215,0],
  499. goldenrod: [218,165,32],
  500. gray: [128,128,128],
  501. green: [0,128,0],
  502. greenyellow: [173,255,47],
  503. grey: [128,128,128],
  504. honeydew: [240,255,240],
  505. hotpink: [255,105,180],
  506. indianred: [205,92,92],
  507. indigo: [75,0,130],
  508. ivory: [255,255,240],
  509. khaki: [240,230,140],
  510. lavender: [230,230,250],
  511. lavenderblush: [255,240,245],
  512. lawngreen: [124,252,0],
  513. lemonchiffon: [255,250,205],
  514. lightblue: [173,216,230],
  515. lightcoral: [240,128,128],
  516. lightcyan: [224,255,255],
  517. lightgoldenrodyellow: [250,250,210],
  518. lightgray: [211,211,211],
  519. lightgreen: [144,238,144],
  520. lightgrey: [211,211,211],
  521. lightpink: [255,182,193],
  522. lightsalmon: [255,160,122],
  523. lightseagreen: [32,178,170],
  524. lightskyblue: [135,206,250],
  525. lightslategray: [119,136,153],
  526. lightslategrey: [119,136,153],
  527. lightsteelblue: [176,196,222],
  528. lightyellow: [255,255,224],
  529. lime: [0,255,0],
  530. limegreen: [50,205,50],
  531. linen: [250,240,230],
  532. magenta: [255,0,255],
  533. maroon: [128,0,0],
  534. mediumaquamarine: [102,205,170],
  535. mediumblue: [0,0,205],
  536. mediumorchid: [186,85,211],
  537. mediumpurple: [147,112,219],
  538. mediumseagreen: [60,179,113],
  539. mediumslateblue: [123,104,238],
  540. mediumspringgreen: [0,250,154],
  541. mediumturquoise: [72,209,204],
  542. mediumvioletred: [199,21,133],
  543. midnightblue: [25,25,112],
  544. mintcream: [245,255,250],
  545. mistyrose: [255,228,225],
  546. moccasin: [255,228,181],
  547. navajowhite: [255,222,173],
  548. navy: [0,0,128],
  549. oldlace: [253,245,230],
  550. olive: [128,128,0],
  551. olivedrab: [107,142,35],
  552. orange: [255,165,0],
  553. orangered: [255,69,0],
  554. orchid: [218,112,214],
  555. palegoldenrod: [238,232,170],
  556. palegreen: [152,251,152],
  557. paleturquoise: [175,238,238],
  558. palevioletred: [219,112,147],
  559. papayawhip: [255,239,213],
  560. peachpuff: [255,218,185],
  561. peru: [205,133,63],
  562. pink: [255,192,203],
  563. plum: [221,160,221],
  564. powderblue: [176,224,230],
  565. purple: [128,0,128],
  566. rebeccapurple: [102, 51, 153],
  567. red: [255,0,0],
  568. rosybrown: [188,143,143],
  569. royalblue: [65,105,225],
  570. saddlebrown: [139,69,19],
  571. salmon: [250,128,114],
  572. sandybrown: [244,164,96],
  573. seagreen: [46,139,87],
  574. seashell: [255,245,238],
  575. sienna: [160,82,45],
  576. silver: [192,192,192],
  577. skyblue: [135,206,235],
  578. slateblue: [106,90,205],
  579. slategray: [112,128,144],
  580. slategrey: [112,128,144],
  581. snow: [255,250,250],
  582. springgreen: [0,255,127],
  583. steelblue: [70,130,180],
  584. tan: [210,180,140],
  585. teal: [0,128,128],
  586. thistle: [216,191,216],
  587. tomato: [255,99,71],
  588. turquoise: [64,224,208],
  589. violet: [238,130,238],
  590. wheat: [245,222,179],
  591. white: [255,255,255],
  592. whitesmoke: [245,245,245],
  593. yellow: [255,255,0],
  594. yellowgreen: [154,205,50]
  595. };
  596. var reverseKeywords = {};
  597. for (var key in cssKeywords) {
  598. reverseKeywords[JSON.stringify(cssKeywords[key])] = key;
  599. }
  600. var convert = function() {
  601. return new Converter();
  602. };
  603. for (var func in conversions) {
  604. // export Raw versions
  605. convert[func + "Raw"] = (function(func) {
  606. // accept array or plain args
  607. return function(arg) {
  608. if (typeof arg == "number")
  609. arg = Array.prototype.slice.call(arguments);
  610. return conversions[func](arg);
  611. }
  612. })(func);
  613. var pair = /(\w+)2(\w+)/.exec(func),
  614. from = pair[1],
  615. to = pair[2];
  616. // export rgb2hsl and ["rgb"]["hsl"]
  617. convert[from] = convert[from] || {};
  618. convert[from][to] = convert[func] = (function(func) {
  619. return function(arg) {
  620. if (typeof arg == "number")
  621. arg = Array.prototype.slice.call(arguments);
  622. var val = conversions[func](arg);
  623. if (typeof val == "string" || val === undefined)
  624. return val; // keyword
  625. for (var i = 0; i < val.length; i++)
  626. val[i] = Math.round(val[i]);
  627. return val;
  628. }
  629. })(func);
  630. }
  631. /* Converter does lazy conversion and caching */
  632. var Converter = function() {
  633. this.convs = {};
  634. };
  635. /* Either get the values for a space or
  636. set the values for a space, depending on args */
  637. Converter.prototype.routeSpace = function(space, args) {
  638. var values = args[0];
  639. if (values === undefined) {
  640. // color.rgb()
  641. return this.getValues(space);
  642. }
  643. // color.rgb(10, 10, 10)
  644. if (typeof values == "number") {
  645. values = Array.prototype.slice.call(args);
  646. }
  647. return this.setValues(space, values);
  648. };
  649. /* Set the values for a space, invalidating cache */
  650. Converter.prototype.setValues = function(space, values) {
  651. this.space = space;
  652. this.convs = {};
  653. this.convs[space] = values;
  654. return this;
  655. };
  656. /* Get the values for a space. If there's already
  657. a conversion for the space, fetch it, otherwise
  658. compute it */
  659. Converter.prototype.getValues = function(space) {
  660. var vals = this.convs[space];
  661. if (!vals) {
  662. var fspace = this.space,
  663. from = this.convs[fspace];
  664. vals = convert[fspace][space](from);
  665. this.convs[space] = vals;
  666. }
  667. return vals;
  668. };
  669. ["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) {
  670. Converter.prototype[space] = function(vals) {
  671. return this.routeSpace(space, arguments);
  672. };
  673. });
  674. var colorConvert = convert;
  675. var colorName = {
  676. "aliceblue": [240, 248, 255],
  677. "antiquewhite": [250, 235, 215],
  678. "aqua": [0, 255, 255],
  679. "aquamarine": [127, 255, 212],
  680. "azure": [240, 255, 255],
  681. "beige": [245, 245, 220],
  682. "bisque": [255, 228, 196],
  683. "black": [0, 0, 0],
  684. "blanchedalmond": [255, 235, 205],
  685. "blue": [0, 0, 255],
  686. "blueviolet": [138, 43, 226],
  687. "brown": [165, 42, 42],
  688. "burlywood": [222, 184, 135],
  689. "cadetblue": [95, 158, 160],
  690. "chartreuse": [127, 255, 0],
  691. "chocolate": [210, 105, 30],
  692. "coral": [255, 127, 80],
  693. "cornflowerblue": [100, 149, 237],
  694. "cornsilk": [255, 248, 220],
  695. "crimson": [220, 20, 60],
  696. "cyan": [0, 255, 255],
  697. "darkblue": [0, 0, 139],
  698. "darkcyan": [0, 139, 139],
  699. "darkgoldenrod": [184, 134, 11],
  700. "darkgray": [169, 169, 169],
  701. "darkgreen": [0, 100, 0],
  702. "darkgrey": [169, 169, 169],
  703. "darkkhaki": [189, 183, 107],
  704. "darkmagenta": [139, 0, 139],
  705. "darkolivegreen": [85, 107, 47],
  706. "darkorange": [255, 140, 0],
  707. "darkorchid": [153, 50, 204],
  708. "darkred": [139, 0, 0],
  709. "darksalmon": [233, 150, 122],
  710. "darkseagreen": [143, 188, 143],
  711. "darkslateblue": [72, 61, 139],
  712. "darkslategray": [47, 79, 79],
  713. "darkslategrey": [47, 79, 79],
  714. "darkturquoise": [0, 206, 209],
  715. "darkviolet": [148, 0, 211],
  716. "deeppink": [255, 20, 147],
  717. "deepskyblue": [0, 191, 255],
  718. "dimgray": [105, 105, 105],
  719. "dimgrey": [105, 105, 105],
  720. "dodgerblue": [30, 144, 255],
  721. "firebrick": [178, 34, 34],
  722. "floralwhite": [255, 250, 240],
  723. "forestgreen": [34, 139, 34],
  724. "fuchsia": [255, 0, 255],
  725. "gainsboro": [220, 220, 220],
  726. "ghostwhite": [248, 248, 255],
  727. "gold": [255, 215, 0],
  728. "goldenrod": [218, 165, 32],
  729. "gray": [128, 128, 128],
  730. "green": [0, 128, 0],
  731. "greenyellow": [173, 255, 47],
  732. "grey": [128, 128, 128],
  733. "honeydew": [240, 255, 240],
  734. "hotpink": [255, 105, 180],
  735. "indianred": [205, 92, 92],
  736. "indigo": [75, 0, 130],
  737. "ivory": [255, 255, 240],
  738. "khaki": [240, 230, 140],
  739. "lavender": [230, 230, 250],
  740. "lavenderblush": [255, 240, 245],
  741. "lawngreen": [124, 252, 0],
  742. "lemonchiffon": [255, 250, 205],
  743. "lightblue": [173, 216, 230],
  744. "lightcoral": [240, 128, 128],
  745. "lightcyan": [224, 255, 255],
  746. "lightgoldenrodyellow": [250, 250, 210],
  747. "lightgray": [211, 211, 211],
  748. "lightgreen": [144, 238, 144],
  749. "lightgrey": [211, 211, 211],
  750. "lightpink": [255, 182, 193],
  751. "lightsalmon": [255, 160, 122],
  752. "lightseagreen": [32, 178, 170],
  753. "lightskyblue": [135, 206, 250],
  754. "lightslategray": [119, 136, 153],
  755. "lightslategrey": [119, 136, 153],
  756. "lightsteelblue": [176, 196, 222],
  757. "lightyellow": [255, 255, 224],
  758. "lime": [0, 255, 0],
  759. "limegreen": [50, 205, 50],
  760. "linen": [250, 240, 230],
  761. "magenta": [255, 0, 255],
  762. "maroon": [128, 0, 0],
  763. "mediumaquamarine": [102, 205, 170],
  764. "mediumblue": [0, 0, 205],
  765. "mediumorchid": [186, 85, 211],
  766. "mediumpurple": [147, 112, 219],
  767. "mediumseagreen": [60, 179, 113],
  768. "mediumslateblue": [123, 104, 238],
  769. "mediumspringgreen": [0, 250, 154],
  770. "mediumturquoise": [72, 209, 204],
  771. "mediumvioletred": [199, 21, 133],
  772. "midnightblue": [25, 25, 112],
  773. "mintcream": [245, 255, 250],
  774. "mistyrose": [255, 228, 225],
  775. "moccasin": [255, 228, 181],
  776. "navajowhite": [255, 222, 173],
  777. "navy": [0, 0, 128],
  778. "oldlace": [253, 245, 230],
  779. "olive": [128, 128, 0],
  780. "olivedrab": [107, 142, 35],
  781. "orange": [255, 165, 0],
  782. "orangered": [255, 69, 0],
  783. "orchid": [218, 112, 214],
  784. "palegoldenrod": [238, 232, 170],
  785. "palegreen": [152, 251, 152],
  786. "paleturquoise": [175, 238, 238],
  787. "palevioletred": [219, 112, 147],
  788. "papayawhip": [255, 239, 213],
  789. "peachpuff": [255, 218, 185],
  790. "peru": [205, 133, 63],
  791. "pink": [255, 192, 203],
  792. "plum": [221, 160, 221],
  793. "powderblue": [176, 224, 230],
  794. "purple": [128, 0, 128],
  795. "rebeccapurple": [102, 51, 153],
  796. "red": [255, 0, 0],
  797. "rosybrown": [188, 143, 143],
  798. "royalblue": [65, 105, 225],
  799. "saddlebrown": [139, 69, 19],
  800. "salmon": [250, 128, 114],
  801. "sandybrown": [244, 164, 96],
  802. "seagreen": [46, 139, 87],
  803. "seashell": [255, 245, 238],
  804. "sienna": [160, 82, 45],
  805. "silver": [192, 192, 192],
  806. "skyblue": [135, 206, 235],
  807. "slateblue": [106, 90, 205],
  808. "slategray": [112, 128, 144],
  809. "slategrey": [112, 128, 144],
  810. "snow": [255, 250, 250],
  811. "springgreen": [0, 255, 127],
  812. "steelblue": [70, 130, 180],
  813. "tan": [210, 180, 140],
  814. "teal": [0, 128, 128],
  815. "thistle": [216, 191, 216],
  816. "tomato": [255, 99, 71],
  817. "turquoise": [64, 224, 208],
  818. "violet": [238, 130, 238],
  819. "wheat": [245, 222, 179],
  820. "white": [255, 255, 255],
  821. "whitesmoke": [245, 245, 245],
  822. "yellow": [255, 255, 0],
  823. "yellowgreen": [154, 205, 50]
  824. };
  825. /* MIT license */
  826. var colorString = {
  827. getRgba: getRgba,
  828. getHsla: getHsla,
  829. getRgb: getRgb,
  830. getHsl: getHsl,
  831. getHwb: getHwb,
  832. getAlpha: getAlpha,
  833. hexString: hexString,
  834. rgbString: rgbString,
  835. rgbaString: rgbaString,
  836. percentString: percentString,
  837. percentaString: percentaString,
  838. hslString: hslString,
  839. hslaString: hslaString,
  840. hwbString: hwbString,
  841. keyword: keyword
  842. };
  843. function getRgba(string) {
  844. if (!string) {
  845. return;
  846. }
  847. var abbr = /^#([a-fA-F0-9]{3,4})$/i,
  848. hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
  849. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  850. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  851. keyword = /(\w+)/;
  852. var rgb = [0, 0, 0],
  853. a = 1,
  854. match = string.match(abbr),
  855. hexAlpha = "";
  856. if (match) {
  857. match = match[1];
  858. hexAlpha = match[3];
  859. for (var i = 0; i < rgb.length; i++) {
  860. rgb[i] = parseInt(match[i] + match[i], 16);
  861. }
  862. if (hexAlpha) {
  863. a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
  864. }
  865. }
  866. else if (match = string.match(hex)) {
  867. hexAlpha = match[2];
  868. match = match[1];
  869. for (var i = 0; i < rgb.length; i++) {
  870. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  871. }
  872. if (hexAlpha) {
  873. a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
  874. }
  875. }
  876. else if (match = string.match(rgba)) {
  877. for (var i = 0; i < rgb.length; i++) {
  878. rgb[i] = parseInt(match[i + 1]);
  879. }
  880. a = parseFloat(match[4]);
  881. }
  882. else if (match = string.match(per)) {
  883. for (var i = 0; i < rgb.length; i++) {
  884. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  885. }
  886. a = parseFloat(match[4]);
  887. }
  888. else if (match = string.match(keyword)) {
  889. if (match[1] == "transparent") {
  890. return [0, 0, 0, 0];
  891. }
  892. rgb = colorName[match[1]];
  893. if (!rgb) {
  894. return;
  895. }
  896. }
  897. for (var i = 0; i < rgb.length; i++) {
  898. rgb[i] = scale(rgb[i], 0, 255);
  899. }
  900. if (!a && a != 0) {
  901. a = 1;
  902. }
  903. else {
  904. a = scale(a, 0, 1);
  905. }
  906. rgb[3] = a;
  907. return rgb;
  908. }
  909. function getHsla(string) {
  910. if (!string) {
  911. return;
  912. }
  913. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  914. var match = string.match(hsl);
  915. if (match) {
  916. var alpha = parseFloat(match[4]);
  917. var h = scale(parseInt(match[1]), 0, 360),
  918. s = scale(parseFloat(match[2]), 0, 100),
  919. l = scale(parseFloat(match[3]), 0, 100),
  920. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  921. return [h, s, l, a];
  922. }
  923. }
  924. function getHwb(string) {
  925. if (!string) {
  926. return;
  927. }
  928. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  929. var match = string.match(hwb);
  930. if (match) {
  931. var alpha = parseFloat(match[4]);
  932. var h = scale(parseInt(match[1]), 0, 360),
  933. w = scale(parseFloat(match[2]), 0, 100),
  934. b = scale(parseFloat(match[3]), 0, 100),
  935. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  936. return [h, w, b, a];
  937. }
  938. }
  939. function getRgb(string) {
  940. var rgba = getRgba(string);
  941. return rgba && rgba.slice(0, 3);
  942. }
  943. function getHsl(string) {
  944. var hsla = getHsla(string);
  945. return hsla && hsla.slice(0, 3);
  946. }
  947. function getAlpha(string) {
  948. var vals = getRgba(string);
  949. if (vals) {
  950. return vals[3];
  951. }
  952. else if (vals = getHsla(string)) {
  953. return vals[3];
  954. }
  955. else if (vals = getHwb(string)) {
  956. return vals[3];
  957. }
  958. }
  959. // generators
  960. function hexString(rgba, a) {
  961. var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
  962. return "#" + hexDouble(rgba[0])
  963. + hexDouble(rgba[1])
  964. + hexDouble(rgba[2])
  965. + (
  966. (a >= 0 && a < 1)
  967. ? hexDouble(Math.round(a * 255))
  968. : ""
  969. );
  970. }
  971. function rgbString(rgba, alpha) {
  972. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  973. return rgbaString(rgba, alpha);
  974. }
  975. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  976. }
  977. function rgbaString(rgba, alpha) {
  978. if (alpha === undefined) {
  979. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  980. }
  981. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  982. + ", " + alpha + ")";
  983. }
  984. function percentString(rgba, alpha) {
  985. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  986. return percentaString(rgba, alpha);
  987. }
  988. var r = Math.round(rgba[0]/255 * 100),
  989. g = Math.round(rgba[1]/255 * 100),
  990. b = Math.round(rgba[2]/255 * 100);
  991. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  992. }
  993. function percentaString(rgba, alpha) {
  994. var r = Math.round(rgba[0]/255 * 100),
  995. g = Math.round(rgba[1]/255 * 100),
  996. b = Math.round(rgba[2]/255 * 100);
  997. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  998. }
  999. function hslString(hsla, alpha) {
  1000. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  1001. return hslaString(hsla, alpha);
  1002. }
  1003. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  1004. }
  1005. function hslaString(hsla, alpha) {
  1006. if (alpha === undefined) {
  1007. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  1008. }
  1009. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  1010. + alpha + ")";
  1011. }
  1012. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  1013. // (hwb have alpha optional & 1 is default value)
  1014. function hwbString(hwb, alpha) {
  1015. if (alpha === undefined) {
  1016. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  1017. }
  1018. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  1019. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  1020. }
  1021. function keyword(rgb) {
  1022. return reverseNames[rgb.slice(0, 3)];
  1023. }
  1024. // helpers
  1025. function scale(num, min, max) {
  1026. return Math.min(Math.max(min, num), max);
  1027. }
  1028. function hexDouble(num) {
  1029. var str = num.toString(16).toUpperCase();
  1030. return (str.length < 2) ? "0" + str : str;
  1031. }
  1032. //create a list of reverse color names
  1033. var reverseNames = {};
  1034. for (var name in colorName) {
  1035. reverseNames[colorName[name]] = name;
  1036. }
  1037. /* MIT license */
  1038. var Color = function (obj) {
  1039. if (obj instanceof Color) {
  1040. return obj;
  1041. }
  1042. if (!(this instanceof Color)) {
  1043. return new Color(obj);
  1044. }
  1045. this.valid = false;
  1046. this.values = {
  1047. rgb: [0, 0, 0],
  1048. hsl: [0, 0, 0],
  1049. hsv: [0, 0, 0],
  1050. hwb: [0, 0, 0],
  1051. cmyk: [0, 0, 0, 0],
  1052. alpha: 1
  1053. };
  1054. // parse Color() argument
  1055. var vals;
  1056. if (typeof obj === 'string') {
  1057. vals = colorString.getRgba(obj);
  1058. if (vals) {
  1059. this.setValues('rgb', vals);
  1060. } else if (vals = colorString.getHsla(obj)) {
  1061. this.setValues('hsl', vals);
  1062. } else if (vals = colorString.getHwb(obj)) {
  1063. this.setValues('hwb', vals);
  1064. }
  1065. } else if (typeof obj === 'object') {
  1066. vals = obj;
  1067. if (vals.r !== undefined || vals.red !== undefined) {
  1068. this.setValues('rgb', vals);
  1069. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  1070. this.setValues('hsl', vals);
  1071. } else if (vals.v !== undefined || vals.value !== undefined) {
  1072. this.setValues('hsv', vals);
  1073. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  1074. this.setValues('hwb', vals);
  1075. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  1076. this.setValues('cmyk', vals);
  1077. }
  1078. }
  1079. };
  1080. Color.prototype = {
  1081. isValid: function () {
  1082. return this.valid;
  1083. },
  1084. rgb: function () {
  1085. return this.setSpace('rgb', arguments);
  1086. },
  1087. hsl: function () {
  1088. return this.setSpace('hsl', arguments);
  1089. },
  1090. hsv: function () {
  1091. return this.setSpace('hsv', arguments);
  1092. },
  1093. hwb: function () {
  1094. return this.setSpace('hwb', arguments);
  1095. },
  1096. cmyk: function () {
  1097. return this.setSpace('cmyk', arguments);
  1098. },
  1099. rgbArray: function () {
  1100. return this.values.rgb;
  1101. },
  1102. hslArray: function () {
  1103. return this.values.hsl;
  1104. },
  1105. hsvArray: function () {
  1106. return this.values.hsv;
  1107. },
  1108. hwbArray: function () {
  1109. var values = this.values;
  1110. if (values.alpha !== 1) {
  1111. return values.hwb.concat([values.alpha]);
  1112. }
  1113. return values.hwb;
  1114. },
  1115. cmykArray: function () {
  1116. return this.values.cmyk;
  1117. },
  1118. rgbaArray: function () {
  1119. var values = this.values;
  1120. return values.rgb.concat([values.alpha]);
  1121. },
  1122. hslaArray: function () {
  1123. var values = this.values;
  1124. return values.hsl.concat([values.alpha]);
  1125. },
  1126. alpha: function (val) {
  1127. if (val === undefined) {
  1128. return this.values.alpha;
  1129. }
  1130. this.setValues('alpha', val);
  1131. return this;
  1132. },
  1133. red: function (val) {
  1134. return this.setChannel('rgb', 0, val);
  1135. },
  1136. green: function (val) {
  1137. return this.setChannel('rgb', 1, val);
  1138. },
  1139. blue: function (val) {
  1140. return this.setChannel('rgb', 2, val);
  1141. },
  1142. hue: function (val) {
  1143. if (val) {
  1144. val %= 360;
  1145. val = val < 0 ? 360 + val : val;
  1146. }
  1147. return this.setChannel('hsl', 0, val);
  1148. },
  1149. saturation: function (val) {
  1150. return this.setChannel('hsl', 1, val);
  1151. },
  1152. lightness: function (val) {
  1153. return this.setChannel('hsl', 2, val);
  1154. },
  1155. saturationv: function (val) {
  1156. return this.setChannel('hsv', 1, val);
  1157. },
  1158. whiteness: function (val) {
  1159. return this.setChannel('hwb', 1, val);
  1160. },
  1161. blackness: function (val) {
  1162. return this.setChannel('hwb', 2, val);
  1163. },
  1164. value: function (val) {
  1165. return this.setChannel('hsv', 2, val);
  1166. },
  1167. cyan: function (val) {
  1168. return this.setChannel('cmyk', 0, val);
  1169. },
  1170. magenta: function (val) {
  1171. return this.setChannel('cmyk', 1, val);
  1172. },
  1173. yellow: function (val) {
  1174. return this.setChannel('cmyk', 2, val);
  1175. },
  1176. black: function (val) {
  1177. return this.setChannel('cmyk', 3, val);
  1178. },
  1179. hexString: function () {
  1180. return colorString.hexString(this.values.rgb);
  1181. },
  1182. rgbString: function () {
  1183. return colorString.rgbString(this.values.rgb, this.values.alpha);
  1184. },
  1185. rgbaString: function () {
  1186. return colorString.rgbaString(this.values.rgb, this.values.alpha);
  1187. },
  1188. percentString: function () {
  1189. return colorString.percentString(this.values.rgb, this.values.alpha);
  1190. },
  1191. hslString: function () {
  1192. return colorString.hslString(this.values.hsl, this.values.alpha);
  1193. },
  1194. hslaString: function () {
  1195. return colorString.hslaString(this.values.hsl, this.values.alpha);
  1196. },
  1197. hwbString: function () {
  1198. return colorString.hwbString(this.values.hwb, this.values.alpha);
  1199. },
  1200. keyword: function () {
  1201. return colorString.keyword(this.values.rgb, this.values.alpha);
  1202. },
  1203. rgbNumber: function () {
  1204. var rgb = this.values.rgb;
  1205. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  1206. },
  1207. luminosity: function () {
  1208. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  1209. var rgb = this.values.rgb;
  1210. var lum = [];
  1211. for (var i = 0; i < rgb.length; i++) {
  1212. var chan = rgb[i] / 255;
  1213. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  1214. }
  1215. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  1216. },
  1217. contrast: function (color2) {
  1218. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  1219. var lum1 = this.luminosity();
  1220. var lum2 = color2.luminosity();
  1221. if (lum1 > lum2) {
  1222. return (lum1 + 0.05) / (lum2 + 0.05);
  1223. }
  1224. return (lum2 + 0.05) / (lum1 + 0.05);
  1225. },
  1226. level: function (color2) {
  1227. var contrastRatio = this.contrast(color2);
  1228. if (contrastRatio >= 7.1) {
  1229. return 'AAA';
  1230. }
  1231. return (contrastRatio >= 4.5) ? 'AA' : '';
  1232. },
  1233. dark: function () {
  1234. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  1235. var rgb = this.values.rgb;
  1236. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  1237. return yiq < 128;
  1238. },
  1239. light: function () {
  1240. return !this.dark();
  1241. },
  1242. negate: function () {
  1243. var rgb = [];
  1244. for (var i = 0; i < 3; i++) {
  1245. rgb[i] = 255 - this.values.rgb[i];
  1246. }
  1247. this.setValues('rgb', rgb);
  1248. return this;
  1249. },
  1250. lighten: function (ratio) {
  1251. var hsl = this.values.hsl;
  1252. hsl[2] += hsl[2] * ratio;
  1253. this.setValues('hsl', hsl);
  1254. return this;
  1255. },
  1256. darken: function (ratio) {
  1257. var hsl = this.values.hsl;
  1258. hsl[2] -= hsl[2] * ratio;
  1259. this.setValues('hsl', hsl);
  1260. return this;
  1261. },
  1262. saturate: function (ratio) {
  1263. var hsl = this.values.hsl;
  1264. hsl[1] += hsl[1] * ratio;
  1265. this.setValues('hsl', hsl);
  1266. return this;
  1267. },
  1268. desaturate: function (ratio) {
  1269. var hsl = this.values.hsl;
  1270. hsl[1] -= hsl[1] * ratio;
  1271. this.setValues('hsl', hsl);
  1272. return this;
  1273. },
  1274. whiten: function (ratio) {
  1275. var hwb = this.values.hwb;
  1276. hwb[1] += hwb[1] * ratio;
  1277. this.setValues('hwb', hwb);
  1278. return this;
  1279. },
  1280. blacken: function (ratio) {
  1281. var hwb = this.values.hwb;
  1282. hwb[2] += hwb[2] * ratio;
  1283. this.setValues('hwb', hwb);
  1284. return this;
  1285. },
  1286. greyscale: function () {
  1287. var rgb = this.values.rgb;
  1288. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  1289. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  1290. this.setValues('rgb', [val, val, val]);
  1291. return this;
  1292. },
  1293. clearer: function (ratio) {
  1294. var alpha = this.values.alpha;
  1295. this.setValues('alpha', alpha - (alpha * ratio));
  1296. return this;
  1297. },
  1298. opaquer: function (ratio) {
  1299. var alpha = this.values.alpha;
  1300. this.setValues('alpha', alpha + (alpha * ratio));
  1301. return this;
  1302. },
  1303. rotate: function (degrees) {
  1304. var hsl = this.values.hsl;
  1305. var hue = (hsl[0] + degrees) % 360;
  1306. hsl[0] = hue < 0 ? 360 + hue : hue;
  1307. this.setValues('hsl', hsl);
  1308. return this;
  1309. },
  1310. /**
  1311. * Ported from sass implementation in C
  1312. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  1313. */
  1314. mix: function (mixinColor, weight) {
  1315. var color1 = this;
  1316. var color2 = mixinColor;
  1317. var p = weight === undefined ? 0.5 : weight;
  1318. var w = 2 * p - 1;
  1319. var a = color1.alpha() - color2.alpha();
  1320. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  1321. var w2 = 1 - w1;
  1322. return this
  1323. .rgb(
  1324. w1 * color1.red() + w2 * color2.red(),
  1325. w1 * color1.green() + w2 * color2.green(),
  1326. w1 * color1.blue() + w2 * color2.blue()
  1327. )
  1328. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  1329. },
  1330. toJSON: function () {
  1331. return this.rgb();
  1332. },
  1333. clone: function () {
  1334. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  1335. // making the final build way to big to embed in Chart.js. So let's do it manually,
  1336. // assuming that values to clone are 1 dimension arrays containing only numbers,
  1337. // except 'alpha' which is a number.
  1338. var result = new Color();
  1339. var source = this.values;
  1340. var target = result.values;
  1341. var value, type;
  1342. for (var prop in source) {
  1343. if (source.hasOwnProperty(prop)) {
  1344. value = source[prop];
  1345. type = ({}).toString.call(value);
  1346. if (type === '[object Array]') {
  1347. target[prop] = value.slice(0);
  1348. } else if (type === '[object Number]') {
  1349. target[prop] = value;
  1350. } else {
  1351. console.error('unexpected color value:', value);
  1352. }
  1353. }
  1354. }
  1355. return result;
  1356. }
  1357. };
  1358. Color.prototype.spaces = {
  1359. rgb: ['red', 'green', 'blue'],
  1360. hsl: ['hue', 'saturation', 'lightness'],
  1361. hsv: ['hue', 'saturation', 'value'],
  1362. hwb: ['hue', 'whiteness', 'blackness'],
  1363. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  1364. };
  1365. Color.prototype.maxes = {
  1366. rgb: [255, 255, 255],
  1367. hsl: [360, 100, 100],
  1368. hsv: [360, 100, 100],
  1369. hwb: [360, 100, 100],
  1370. cmyk: [100, 100, 100, 100]
  1371. };
  1372. Color.prototype.getValues = function (space) {
  1373. var values = this.values;
  1374. var vals = {};
  1375. for (var i = 0; i < space.length; i++) {
  1376. vals[space.charAt(i)] = values[space][i];
  1377. }
  1378. if (values.alpha !== 1) {
  1379. vals.a = values.alpha;
  1380. }
  1381. // {r: 255, g: 255, b: 255, a: 0.4}
  1382. return vals;
  1383. };
  1384. Color.prototype.setValues = function (space, vals) {
  1385. var values = this.values;
  1386. var spaces = this.spaces;
  1387. var maxes = this.maxes;
  1388. var alpha = 1;
  1389. var i;
  1390. this.valid = true;
  1391. if (space === 'alpha') {
  1392. alpha = vals;
  1393. } else if (vals.length) {
  1394. // [10, 10, 10]
  1395. values[space] = vals.slice(0, space.length);
  1396. alpha = vals[space.length];
  1397. } else if (vals[space.charAt(0)] !== undefined) {
  1398. // {r: 10, g: 10, b: 10}
  1399. for (i = 0; i < space.length; i++) {
  1400. values[space][i] = vals[space.charAt(i)];
  1401. }
  1402. alpha = vals.a;
  1403. } else if (vals[spaces[space][0]] !== undefined) {
  1404. // {red: 10, green: 10, blue: 10}
  1405. var chans = spaces[space];
  1406. for (i = 0; i < space.length; i++) {
  1407. values[space][i] = vals[chans[i]];
  1408. }
  1409. alpha = vals.alpha;
  1410. }
  1411. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  1412. if (space === 'alpha') {
  1413. return false;
  1414. }
  1415. var capped;
  1416. // cap values of the space prior converting all values
  1417. for (i = 0; i < space.length; i++) {
  1418. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  1419. values[space][i] = Math.round(capped);
  1420. }
  1421. // convert to all the other color spaces
  1422. for (var sname in spaces) {
  1423. if (sname !== space) {
  1424. values[sname] = colorConvert[space][sname](values[space]);
  1425. }
  1426. }
  1427. return true;
  1428. };
  1429. Color.prototype.setSpace = function (space, args) {
  1430. var vals = args[0];
  1431. if (vals === undefined) {
  1432. // color.rgb()
  1433. return this.getValues(space);
  1434. }
  1435. // color.rgb(10, 10, 10)
  1436. if (typeof vals === 'number') {
  1437. vals = Array.prototype.slice.call(args);
  1438. }
  1439. this.setValues(space, vals);
  1440. return this;
  1441. };
  1442. Color.prototype.setChannel = function (space, index, val) {
  1443. var svalues = this.values[space];
  1444. if (val === undefined) {
  1445. // color.red()
  1446. return svalues[index];
  1447. } else if (val === svalues[index]) {
  1448. // color.red(color.red())
  1449. return this;
  1450. }
  1451. // color.red(100)
  1452. svalues[index] = val;
  1453. this.setValues(space, svalues);
  1454. return this;
  1455. };
  1456. if (typeof window !== 'undefined') {
  1457. window.Color = Color;
  1458. }
  1459. var chartjsColor = Color;
  1460. /**
  1461. * @namespace Chart.helpers
  1462. */
  1463. var helpers = {
  1464. /**
  1465. * An empty function that can be used, for example, for optional callback.
  1466. */
  1467. noop: function() {},
  1468. /**
  1469. * Returns a unique id, sequentially generated from a global variable.
  1470. * @returns {number}
  1471. * @function
  1472. */
  1473. uid: (function() {
  1474. var id = 0;
  1475. return function() {
  1476. return id++;
  1477. };
  1478. }()),
  1479. /**
  1480. * Returns true if `value` is neither null nor undefined, else returns false.
  1481. * @param {*} value - The value to test.
  1482. * @returns {boolean}
  1483. * @since 2.7.0
  1484. */
  1485. isNullOrUndef: function(value) {
  1486. return value === null || typeof value === 'undefined';
  1487. },
  1488. /**
  1489. * Returns true if `value` is an array (including typed arrays), else returns false.
  1490. * @param {*} value - The value to test.
  1491. * @returns {boolean}
  1492. * @function
  1493. */
  1494. isArray: function(value) {
  1495. if (Array.isArray && Array.isArray(value)) {
  1496. return true;
  1497. }
  1498. var type = Object.prototype.toString.call(value);
  1499. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  1500. return true;
  1501. }
  1502. return false;
  1503. },
  1504. /**
  1505. * Returns true if `value` is an object (excluding null), else returns false.
  1506. * @param {*} value - The value to test.
  1507. * @returns {boolean}
  1508. * @since 2.7.0
  1509. */
  1510. isObject: function(value) {
  1511. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  1512. },
  1513. /**
  1514. * Returns true if `value` is a finite number, else returns false
  1515. * @param {*} value - The value to test.
  1516. * @returns {boolean}
  1517. */
  1518. isFinite: function(value) {
  1519. return (typeof value === 'number' || value instanceof Number) && isFinite(value);
  1520. },
  1521. /**
  1522. * Returns `value` if defined, else returns `defaultValue`.
  1523. * @param {*} value - The value to return if defined.
  1524. * @param {*} defaultValue - The value to return if `value` is undefined.
  1525. * @returns {*}
  1526. */
  1527. valueOrDefault: function(value, defaultValue) {
  1528. return typeof value === 'undefined' ? defaultValue : value;
  1529. },
  1530. /**
  1531. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  1532. * @param {Array} value - The array to lookup for value at `index`.
  1533. * @param {number} index - The index in `value` to lookup for value.
  1534. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  1535. * @returns {*}
  1536. */
  1537. valueAtIndexOrDefault: function(value, index, defaultValue) {
  1538. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  1539. },
  1540. /**
  1541. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  1542. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  1543. * @param {function} fn - The function to call.
  1544. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  1545. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1546. * @returns {*}
  1547. */
  1548. callback: function(fn, args, thisArg) {
  1549. if (fn && typeof fn.call === 'function') {
  1550. return fn.apply(thisArg, args);
  1551. }
  1552. },
  1553. /**
  1554. * Note(SB) for performance sake, this method should only be used when loopable type
  1555. * is unknown or in none intensive code (not called often and small loopable). Else
  1556. * it's preferable to use a regular for() loop and save extra function calls.
  1557. * @param {object|Array} loopable - The object or array to be iterated.
  1558. * @param {function} fn - The function to call for each item.
  1559. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1560. * @param {boolean} [reverse] - If true, iterates backward on the loopable.
  1561. */
  1562. each: function(loopable, fn, thisArg, reverse) {
  1563. var i, len, keys;
  1564. if (helpers.isArray(loopable)) {
  1565. len = loopable.length;
  1566. if (reverse) {
  1567. for (i = len - 1; i >= 0; i--) {
  1568. fn.call(thisArg, loopable[i], i);
  1569. }
  1570. } else {
  1571. for (i = 0; i < len; i++) {
  1572. fn.call(thisArg, loopable[i], i);
  1573. }
  1574. }
  1575. } else if (helpers.isObject(loopable)) {
  1576. keys = Object.keys(loopable);
  1577. len = keys.length;
  1578. for (i = 0; i < len; i++) {
  1579. fn.call(thisArg, loopable[keys[i]], keys[i]);
  1580. }
  1581. }
  1582. },
  1583. /**
  1584. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  1585. * @see https://stackoverflow.com/a/14853974
  1586. * @param {Array} a0 - The array to compare
  1587. * @param {Array} a1 - The array to compare
  1588. * @returns {boolean}
  1589. */
  1590. arrayEquals: function(a0, a1) {
  1591. var i, ilen, v0, v1;
  1592. if (!a0 || !a1 || a0.length !== a1.length) {
  1593. return false;
  1594. }
  1595. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  1596. v0 = a0[i];
  1597. v1 = a1[i];
  1598. if (v0 instanceof Array && v1 instanceof Array) {
  1599. if (!helpers.arrayEquals(v0, v1)) {
  1600. return false;
  1601. }
  1602. } else if (v0 !== v1) {
  1603. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  1604. return false;
  1605. }
  1606. }
  1607. return true;
  1608. },
  1609. /**
  1610. * Returns a deep copy of `source` without keeping references on objects and arrays.
  1611. * @param {*} source - The value to clone.
  1612. * @returns {*}
  1613. */
  1614. clone: function(source) {
  1615. if (helpers.isArray(source)) {
  1616. return source.map(helpers.clone);
  1617. }
  1618. if (helpers.isObject(source)) {
  1619. var target = {};
  1620. var keys = Object.keys(source);
  1621. var klen = keys.length;
  1622. var k = 0;
  1623. for (; k < klen; ++k) {
  1624. target[keys[k]] = helpers.clone(source[keys[k]]);
  1625. }
  1626. return target;
  1627. }
  1628. return source;
  1629. },
  1630. /**
  1631. * The default merger when Chart.helpers.merge is called without merger option.
  1632. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
  1633. * @private
  1634. */
  1635. _merger: function(key, target, source, options) {
  1636. var tval = target[key];
  1637. var sval = source[key];
  1638. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1639. helpers.merge(tval, sval, options);
  1640. } else {
  1641. target[key] = helpers.clone(sval);
  1642. }
  1643. },
  1644. /**
  1645. * Merges source[key] in target[key] only if target[key] is undefined.
  1646. * @private
  1647. */
  1648. _mergerIf: function(key, target, source) {
  1649. var tval = target[key];
  1650. var sval = source[key];
  1651. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1652. helpers.mergeIf(tval, sval);
  1653. } else if (!target.hasOwnProperty(key)) {
  1654. target[key] = helpers.clone(sval);
  1655. }
  1656. },
  1657. /**
  1658. * Recursively deep copies `source` properties into `target` with the given `options`.
  1659. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  1660. * @param {object} target - The target object in which all sources are merged into.
  1661. * @param {object|object[]} source - Object(s) to merge into `target`.
  1662. * @param {object} [options] - Merging options:
  1663. * @param {function} [options.merger] - The merge method (key, target, source, options)
  1664. * @returns {object} The `target` object.
  1665. */
  1666. merge: function(target, source, options) {
  1667. var sources = helpers.isArray(source) ? source : [source];
  1668. var ilen = sources.length;
  1669. var merge, i, keys, klen, k;
  1670. if (!helpers.isObject(target)) {
  1671. return target;
  1672. }
  1673. options = options || {};
  1674. merge = options.merger || helpers._merger;
  1675. for (i = 0; i < ilen; ++i) {
  1676. source = sources[i];
  1677. if (!helpers.isObject(source)) {
  1678. continue;
  1679. }
  1680. keys = Object.keys(source);
  1681. for (k = 0, klen = keys.length; k < klen; ++k) {
  1682. merge(keys[k], target, source, options);
  1683. }
  1684. }
  1685. return target;
  1686. },
  1687. /**
  1688. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  1689. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  1690. * @param {object} target - The target object in which all sources are merged into.
  1691. * @param {object|object[]} source - Object(s) to merge into `target`.
  1692. * @returns {object} The `target` object.
  1693. */
  1694. mergeIf: function(target, source) {
  1695. return helpers.merge(target, source, {merger: helpers._mergerIf});
  1696. },
  1697. /**
  1698. * Applies the contents of two or more objects together into the first object.
  1699. * @param {object} target - The target object in which all objects are merged into.
  1700. * @param {object} arg1 - Object containing additional properties to merge in target.
  1701. * @param {object} argN - Additional objects containing properties to merge in target.
  1702. * @returns {object} The `target` object.
  1703. */
  1704. extend: function(target) {
  1705. var setFn = function(value, key) {
  1706. target[key] = value;
  1707. };
  1708. for (var i = 1, ilen = arguments.length; i < ilen; ++i) {
  1709. helpers.each(arguments[i], setFn);
  1710. }
  1711. return target;
  1712. },
  1713. /**
  1714. * Basic javascript inheritance based on the model created in Backbone.js
  1715. */
  1716. inherits: function(extensions) {
  1717. var me = this;
  1718. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
  1719. return me.apply(this, arguments);
  1720. };
  1721. var Surrogate = function() {
  1722. this.constructor = ChartElement;
  1723. };
  1724. Surrogate.prototype = me.prototype;
  1725. ChartElement.prototype = new Surrogate();
  1726. ChartElement.extend = helpers.inherits;
  1727. if (extensions) {
  1728. helpers.extend(ChartElement.prototype, extensions);
  1729. }
  1730. ChartElement.__super__ = me.prototype;
  1731. return ChartElement;
  1732. }
  1733. };
  1734. var helpers_core = helpers;
  1735. // DEPRECATIONS
  1736. /**
  1737. * Provided for backward compatibility, use Chart.helpers.callback instead.
  1738. * @function Chart.helpers.callCallback
  1739. * @deprecated since version 2.6.0
  1740. * @todo remove at version 3
  1741. * @private
  1742. */
  1743. helpers.callCallback = helpers.callback;
  1744. /**
  1745. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  1746. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  1747. * @function Chart.helpers.indexOf
  1748. * @deprecated since version 2.7.0
  1749. * @todo remove at version 3
  1750. * @private
  1751. */
  1752. helpers.indexOf = function(array, item, fromIndex) {
  1753. return Array.prototype.indexOf.call(array, item, fromIndex);
  1754. };
  1755. /**
  1756. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  1757. * @function Chart.helpers.getValueOrDefault
  1758. * @deprecated since version 2.7.0
  1759. * @todo remove at version 3
  1760. * @private
  1761. */
  1762. helpers.getValueOrDefault = helpers.valueOrDefault;
  1763. /**
  1764. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  1765. * @function Chart.helpers.getValueAtIndexOrDefault
  1766. * @deprecated since version 2.7.0
  1767. * @todo remove at version 3
  1768. * @private
  1769. */
  1770. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  1771. /**
  1772. * Easing functions adapted from Robert Penner's easing equations.
  1773. * @namespace Chart.helpers.easingEffects
  1774. * @see http://www.robertpenner.com/easing/
  1775. */
  1776. var effects = {
  1777. linear: function(t) {
  1778. return t;
  1779. },
  1780. easeInQuad: function(t) {
  1781. return t * t;
  1782. },
  1783. easeOutQuad: function(t) {
  1784. return -t * (t - 2);
  1785. },
  1786. easeInOutQuad: function(t) {
  1787. if ((t /= 0.5) < 1) {
  1788. return 0.5 * t * t;
  1789. }
  1790. return -0.5 * ((--t) * (t - 2) - 1);
  1791. },
  1792. easeInCubic: function(t) {
  1793. return t * t * t;
  1794. },
  1795. easeOutCubic: function(t) {
  1796. return (t = t - 1) * t * t + 1;
  1797. },
  1798. easeInOutCubic: function(t) {
  1799. if ((t /= 0.5) < 1) {
  1800. return 0.5 * t * t * t;
  1801. }
  1802. return 0.5 * ((t -= 2) * t * t + 2);
  1803. },
  1804. easeInQuart: function(t) {
  1805. return t * t * t * t;
  1806. },
  1807. easeOutQuart: function(t) {
  1808. return -((t = t - 1) * t * t * t - 1);
  1809. },
  1810. easeInOutQuart: function(t) {
  1811. if ((t /= 0.5) < 1) {
  1812. return 0.5 * t * t * t * t;
  1813. }
  1814. return -0.5 * ((t -= 2) * t * t * t - 2);
  1815. },
  1816. easeInQuint: function(t) {
  1817. return t * t * t * t * t;
  1818. },
  1819. easeOutQuint: function(t) {
  1820. return (t = t - 1) * t * t * t * t + 1;
  1821. },
  1822. easeInOutQuint: function(t) {
  1823. if ((t /= 0.5) < 1) {
  1824. return 0.5 * t * t * t * t * t;
  1825. }
  1826. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  1827. },
  1828. easeInSine: function(t) {
  1829. return -Math.cos(t * (Math.PI / 2)) + 1;
  1830. },
  1831. easeOutSine: function(t) {
  1832. return Math.sin(t * (Math.PI / 2));
  1833. },
  1834. easeInOutSine: function(t) {
  1835. return -0.5 * (Math.cos(Math.PI * t) - 1);
  1836. },
  1837. easeInExpo: function(t) {
  1838. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  1839. },
  1840. easeOutExpo: function(t) {
  1841. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  1842. },
  1843. easeInOutExpo: function(t) {
  1844. if (t === 0) {
  1845. return 0;
  1846. }
  1847. if (t === 1) {
  1848. return 1;
  1849. }
  1850. if ((t /= 0.5) < 1) {
  1851. return 0.5 * Math.pow(2, 10 * (t - 1));
  1852. }
  1853. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  1854. },
  1855. easeInCirc: function(t) {
  1856. if (t >= 1) {
  1857. return t;
  1858. }
  1859. return -(Math.sqrt(1 - t * t) - 1);
  1860. },
  1861. easeOutCirc: function(t) {
  1862. return Math.sqrt(1 - (t = t - 1) * t);
  1863. },
  1864. easeInOutCirc: function(t) {
  1865. if ((t /= 0.5) < 1) {
  1866. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  1867. }
  1868. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  1869. },
  1870. easeInElastic: function(t) {
  1871. var s = 1.70158;
  1872. var p = 0;
  1873. var a = 1;
  1874. if (t === 0) {
  1875. return 0;
  1876. }
  1877. if (t === 1) {
  1878. return 1;
  1879. }
  1880. if (!p) {
  1881. p = 0.3;
  1882. }
  1883. if (a < 1) {
  1884. a = 1;
  1885. s = p / 4;
  1886. } else {
  1887. s = p / (2 * Math.PI) * Math.asin(1 / a);
  1888. }
  1889. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  1890. },
  1891. easeOutElastic: function(t) {
  1892. var s = 1.70158;
  1893. var p = 0;
  1894. var a = 1;
  1895. if (t === 0) {
  1896. return 0;
  1897. }
  1898. if (t === 1) {
  1899. return 1;
  1900. }
  1901. if (!p) {
  1902. p = 0.3;
  1903. }
  1904. if (a < 1) {
  1905. a = 1;
  1906. s = p / 4;
  1907. } else {
  1908. s = p / (2 * Math.PI) * Math.asin(1 / a);
  1909. }
  1910. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  1911. },
  1912. easeInOutElastic: function(t) {
  1913. var s = 1.70158;
  1914. var p = 0;
  1915. var a = 1;
  1916. if (t === 0) {
  1917. return 0;
  1918. }
  1919. if ((t /= 0.5) === 2) {
  1920. return 1;
  1921. }
  1922. if (!p) {
  1923. p = 0.45;
  1924. }
  1925. if (a < 1) {
  1926. a = 1;
  1927. s = p / 4;
  1928. } else {
  1929. s = p / (2 * Math.PI) * Math.asin(1 / a);
  1930. }
  1931. if (t < 1) {
  1932. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  1933. }
  1934. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  1935. },
  1936. easeInBack: function(t) {
  1937. var s = 1.70158;
  1938. return t * t * ((s + 1) * t - s);
  1939. },
  1940. easeOutBack: function(t) {
  1941. var s = 1.70158;
  1942. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  1943. },
  1944. easeInOutBack: function(t) {
  1945. var s = 1.70158;
  1946. if ((t /= 0.5) < 1) {
  1947. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  1948. }
  1949. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  1950. },
  1951. easeInBounce: function(t) {
  1952. return 1 - effects.easeOutBounce(1 - t);
  1953. },
  1954. easeOutBounce: function(t) {
  1955. if (t < (1 / 2.75)) {
  1956. return 7.5625 * t * t;
  1957. }
  1958. if (t < (2 / 2.75)) {
  1959. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  1960. }
  1961. if (t < (2.5 / 2.75)) {
  1962. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  1963. }
  1964. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  1965. },
  1966. easeInOutBounce: function(t) {
  1967. if (t < 0.5) {
  1968. return effects.easeInBounce(t * 2) * 0.5;
  1969. }
  1970. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  1971. }
  1972. };
  1973. var helpers_easing = {
  1974. effects: effects
  1975. };
  1976. // DEPRECATIONS
  1977. /**
  1978. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  1979. * @function Chart.helpers.easingEffects
  1980. * @deprecated since version 2.7.0
  1981. * @todo remove at version 3
  1982. * @private
  1983. */
  1984. helpers_core.easingEffects = effects;
  1985. var PI = Math.PI;
  1986. var RAD_PER_DEG = PI / 180;
  1987. var DOUBLE_PI = PI * 2;
  1988. var HALF_PI = PI / 2;
  1989. var QUARTER_PI = PI / 4;
  1990. var TWO_THIRDS_PI = PI * 2 / 3;
  1991. /**
  1992. * @namespace Chart.helpers.canvas
  1993. */
  1994. var exports$1 = {
  1995. /**
  1996. * Clears the entire canvas associated to the given `chart`.
  1997. * @param {Chart} chart - The chart for which to clear the canvas.
  1998. */
  1999. clear: function(chart) {
  2000. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  2001. },
  2002. /**
  2003. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  2004. * given size (width, height) and the same `radius` for all corners.
  2005. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  2006. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  2007. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  2008. * @param {number} width - The rectangle's width.
  2009. * @param {number} height - The rectangle's height.
  2010. * @param {number} radius - The rounded amount (in pixels) for the four corners.
  2011. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  2012. */
  2013. roundedRect: function(ctx, x, y, width, height, radius) {
  2014. if (radius) {
  2015. var r = Math.min(radius, height / 2, width / 2);
  2016. var left = x + r;
  2017. var top = y + r;
  2018. var right = x + width - r;
  2019. var bottom = y + height - r;
  2020. ctx.moveTo(x, top);
  2021. if (left < right && top < bottom) {
  2022. ctx.arc(left, top, r, -PI, -HALF_PI);
  2023. ctx.arc(right, top, r, -HALF_PI, 0);
  2024. ctx.arc(right, bottom, r, 0, HALF_PI);
  2025. ctx.arc(left, bottom, r, HALF_PI, PI);
  2026. } else if (left < right) {
  2027. ctx.moveTo(left, y);
  2028. ctx.arc(right, top, r, -HALF_PI, HALF_PI);
  2029. ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
  2030. } else if (top < bottom) {
  2031. ctx.arc(left, top, r, -PI, 0);
  2032. ctx.arc(left, bottom, r, 0, PI);
  2033. } else {
  2034. ctx.arc(left, top, r, -PI, PI);
  2035. }
  2036. ctx.closePath();
  2037. ctx.moveTo(x, y);
  2038. } else {
  2039. ctx.rect(x, y, width, height);
  2040. }
  2041. },
  2042. drawPoint: function(ctx, style, radius, x, y, rotation) {
  2043. var type, xOffset, yOffset, size, cornerRadius;
  2044. var rad = (rotation || 0) * RAD_PER_DEG;
  2045. if (style && typeof style === 'object') {
  2046. type = style.toString();
  2047. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  2048. ctx.drawImage(style, x - style.width / 2, y - style.height / 2, style.width, style.height);
  2049. return;
  2050. }
  2051. }
  2052. if (isNaN(radius) || radius <= 0) {
  2053. return;
  2054. }
  2055. ctx.beginPath();
  2056. switch (style) {
  2057. // Default includes circle
  2058. default:
  2059. ctx.arc(x, y, radius, 0, DOUBLE_PI);
  2060. ctx.closePath();
  2061. break;
  2062. case 'triangle':
  2063. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2064. rad += TWO_THIRDS_PI;
  2065. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2066. rad += TWO_THIRDS_PI;
  2067. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2068. ctx.closePath();
  2069. break;
  2070. case 'rectRounded':
  2071. // NOTE: the rounded rect implementation changed to use `arc` instead of
  2072. // `quadraticCurveTo` since it generates better results when rect is
  2073. // almost a circle. 0.516 (instead of 0.5) produces results with visually
  2074. // closer proportion to the previous impl and it is inscribed in the
  2075. // circle with `radius`. For more details, see the following PRs:
  2076. // https://github.com/chartjs/Chart.js/issues/5597
  2077. // https://github.com/chartjs/Chart.js/issues/5858
  2078. cornerRadius = radius * 0.516;
  2079. size = radius - cornerRadius;
  2080. xOffset = Math.cos(rad + QUARTER_PI) * size;
  2081. yOffset = Math.sin(rad + QUARTER_PI) * size;
  2082. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  2083. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  2084. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  2085. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  2086. ctx.closePath();
  2087. break;
  2088. case 'rect':
  2089. if (!rotation) {
  2090. size = Math.SQRT1_2 * radius;
  2091. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  2092. break;
  2093. }
  2094. rad += QUARTER_PI;
  2095. /* falls through */
  2096. case 'rectRot':
  2097. xOffset = Math.cos(rad) * radius;
  2098. yOffset = Math.sin(rad) * radius;
  2099. ctx.moveTo(x - xOffset, y - yOffset);
  2100. ctx.lineTo(x + yOffset, y - xOffset);
  2101. ctx.lineTo(x + xOffset, y + yOffset);
  2102. ctx.lineTo(x - yOffset, y + xOffset);
  2103. ctx.closePath();
  2104. break;
  2105. case 'crossRot':
  2106. rad += QUARTER_PI;
  2107. /* falls through */
  2108. case 'cross':
  2109. xOffset = Math.cos(rad) * radius;
  2110. yOffset = Math.sin(rad) * radius;
  2111. ctx.moveTo(x - xOffset, y - yOffset);
  2112. ctx.lineTo(x + xOffset, y + yOffset);
  2113. ctx.moveTo(x + yOffset, y - xOffset);
  2114. ctx.lineTo(x - yOffset, y + xOffset);
  2115. break;
  2116. case 'star':
  2117. xOffset = Math.cos(rad) * radius;
  2118. yOffset = Math.sin(rad) * radius;
  2119. ctx.moveTo(x - xOffset, y - yOffset);
  2120. ctx.lineTo(x + xOffset, y + yOffset);
  2121. ctx.moveTo(x + yOffset, y - xOffset);
  2122. ctx.lineTo(x - yOffset, y + xOffset);
  2123. rad += QUARTER_PI;
  2124. xOffset = Math.cos(rad) * radius;
  2125. yOffset = Math.sin(rad) * radius;
  2126. ctx.moveTo(x - xOffset, y - yOffset);
  2127. ctx.lineTo(x + xOffset, y + yOffset);
  2128. ctx.moveTo(x + yOffset, y - xOffset);
  2129. ctx.lineTo(x - yOffset, y + xOffset);
  2130. break;
  2131. case 'line':
  2132. xOffset = Math.cos(rad) * radius;
  2133. yOffset = Math.sin(rad) * radius;
  2134. ctx.moveTo(x - xOffset, y - yOffset);
  2135. ctx.lineTo(x + xOffset, y + yOffset);
  2136. break;
  2137. case 'dash':
  2138. ctx.moveTo(x, y);
  2139. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  2140. break;
  2141. }
  2142. ctx.fill();
  2143. ctx.stroke();
  2144. },
  2145. /**
  2146. * Returns true if the point is inside the rectangle
  2147. * @param {object} point - The point to test
  2148. * @param {object} area - The rectangle
  2149. * @returns {boolean}
  2150. * @private
  2151. */
  2152. _isPointInArea: function(point, area) {
  2153. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  2154. return point.x > area.left - epsilon && point.x < area.right + epsilon &&
  2155. point.y > area.top - epsilon && point.y < area.bottom + epsilon;
  2156. },
  2157. clipArea: function(ctx, area) {
  2158. ctx.save();
  2159. ctx.beginPath();
  2160. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  2161. ctx.clip();
  2162. },
  2163. unclipArea: function(ctx) {
  2164. ctx.restore();
  2165. },
  2166. lineTo: function(ctx, previous, target, flip) {
  2167. var stepped = target.steppedLine;
  2168. if (stepped) {
  2169. if (stepped === 'middle') {
  2170. var midpoint = (previous.x + target.x) / 2.0;
  2171. ctx.lineTo(midpoint, flip ? target.y : previous.y);
  2172. ctx.lineTo(midpoint, flip ? previous.y : target.y);
  2173. } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
  2174. ctx.lineTo(previous.x, target.y);
  2175. } else {
  2176. ctx.lineTo(target.x, previous.y);
  2177. }
  2178. ctx.lineTo(target.x, target.y);
  2179. return;
  2180. }
  2181. if (!target.tension) {
  2182. ctx.lineTo(target.x, target.y);
  2183. return;
  2184. }
  2185. ctx.bezierCurveTo(
  2186. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  2187. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  2188. flip ? target.controlPointNextX : target.controlPointPreviousX,
  2189. flip ? target.controlPointNextY : target.controlPointPreviousY,
  2190. target.x,
  2191. target.y);
  2192. }
  2193. };
  2194. var helpers_canvas = exports$1;
  2195. // DEPRECATIONS
  2196. /**
  2197. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  2198. * @namespace Chart.helpers.clear
  2199. * @deprecated since version 2.7.0
  2200. * @todo remove at version 3
  2201. * @private
  2202. */
  2203. helpers_core.clear = exports$1.clear;
  2204. /**
  2205. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  2206. * @namespace Chart.helpers.drawRoundedRectangle
  2207. * @deprecated since version 2.7.0
  2208. * @todo remove at version 3
  2209. * @private
  2210. */
  2211. helpers_core.drawRoundedRectangle = function(ctx) {
  2212. ctx.beginPath();
  2213. exports$1.roundedRect.apply(exports$1, arguments);
  2214. };
  2215. var defaults = {
  2216. /**
  2217. * @private
  2218. */
  2219. _set: function(scope, values) {
  2220. return helpers_core.merge(this[scope] || (this[scope] = {}), values);
  2221. }
  2222. };
  2223. defaults._set('global', {
  2224. defaultColor: 'rgba(0,0,0,0.1)',
  2225. defaultFontColor: '#666',
  2226. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  2227. defaultFontSize: 12,
  2228. defaultFontStyle: 'normal',
  2229. defaultLineHeight: 1.2,
  2230. showLines: true
  2231. });
  2232. var core_defaults = defaults;
  2233. var valueOrDefault = helpers_core.valueOrDefault;
  2234. /**
  2235. * Converts the given font object into a CSS font string.
  2236. * @param {object} font - A font object.
  2237. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
  2238. * @private
  2239. */
  2240. function toFontString(font) {
  2241. if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
  2242. return null;
  2243. }
  2244. return (font.style ? font.style + ' ' : '')
  2245. + (font.weight ? font.weight + ' ' : '')
  2246. + font.size + 'px '
  2247. + font.family;
  2248. }
  2249. /**
  2250. * @alias Chart.helpers.options
  2251. * @namespace
  2252. */
  2253. var helpers_options = {
  2254. /**
  2255. * Converts the given line height `value` in pixels for a specific font `size`.
  2256. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  2257. * @param {number} size - The font size (in pixels) used to resolve relative `value`.
  2258. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
  2259. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  2260. * @since 2.7.0
  2261. */
  2262. toLineHeight: function(value, size) {
  2263. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  2264. if (!matches || matches[1] === 'normal') {
  2265. return size * 1.2;
  2266. }
  2267. value = +matches[2];
  2268. switch (matches[3]) {
  2269. case 'px':
  2270. return value;
  2271. case '%':
  2272. value /= 100;
  2273. break;
  2274. default:
  2275. break;
  2276. }
  2277. return size * value;
  2278. },
  2279. /**
  2280. * Converts the given value into a padding object with pre-computed width/height.
  2281. * @param {number|object} value - If a number, set the value to all TRBL component,
  2282. * else, if and object, use defined properties and sets undefined ones to 0.
  2283. * @returns {object} The padding values (top, right, bottom, left, width, height)
  2284. * @since 2.7.0
  2285. */
  2286. toPadding: function(value) {
  2287. var t, r, b, l;
  2288. if (helpers_core.isObject(value)) {
  2289. t = +value.top || 0;
  2290. r = +value.right || 0;
  2291. b = +value.bottom || 0;
  2292. l = +value.left || 0;
  2293. } else {
  2294. t = r = b = l = +value || 0;
  2295. }
  2296. return {
  2297. top: t,
  2298. right: r,
  2299. bottom: b,
  2300. left: l,
  2301. height: t + b,
  2302. width: l + r
  2303. };
  2304. },
  2305. /**
  2306. * Parses font options and returns the font object.
  2307. * @param {object} options - A object that contains font options to be parsed.
  2308. * @return {object} The font object.
  2309. * @todo Support font.* options and renamed to toFont().
  2310. * @private
  2311. */
  2312. _parseFont: function(options) {
  2313. var globalDefaults = core_defaults.global;
  2314. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  2315. var font = {
  2316. family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
  2317. lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
  2318. size: size,
  2319. style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
  2320. weight: null,
  2321. string: ''
  2322. };
  2323. font.string = toFontString(font);
  2324. return font;
  2325. },
  2326. /**
  2327. * Evaluates the given `inputs` sequentially and returns the first defined value.
  2328. * @param {Array} inputs - An array of values, falling back to the last value.
  2329. * @param {object} [context] - If defined and the current value is a function, the value
  2330. * is called with `context` as first argument and the result becomes the new input.
  2331. * @param {number} [index] - If defined and the current value is an array, the value
  2332. * at `index` become the new input.
  2333. * @since 2.7.0
  2334. */
  2335. resolve: function(inputs, context, index) {
  2336. var i, ilen, value;
  2337. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  2338. value = inputs[i];
  2339. if (value === undefined) {
  2340. continue;
  2341. }
  2342. if (context !== undefined && typeof value === 'function') {
  2343. value = value(context);
  2344. }
  2345. if (index !== undefined && helpers_core.isArray(value)) {
  2346. value = value[index];
  2347. }
  2348. if (value !== undefined) {
  2349. return value;
  2350. }
  2351. }
  2352. }
  2353. };
  2354. var helpers$1 = helpers_core;
  2355. var easing = helpers_easing;
  2356. var canvas = helpers_canvas;
  2357. var options = helpers_options;
  2358. helpers$1.easing = easing;
  2359. helpers$1.canvas = canvas;
  2360. helpers$1.options = options;
  2361. function interpolate(start, view, model, ease) {
  2362. var keys = Object.keys(model);
  2363. var i, ilen, key, actual, origin, target, type, c0, c1;
  2364. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  2365. key = keys[i];
  2366. target = model[key];
  2367. // if a value is added to the model after pivot() has been called, the view
  2368. // doesn't contain it, so let's initialize the view to the target value.
  2369. if (!view.hasOwnProperty(key)) {
  2370. view[key] = target;
  2371. }
  2372. actual = view[key];
  2373. if (actual === target || key[0] === '_') {
  2374. continue;
  2375. }
  2376. if (!start.hasOwnProperty(key)) {
  2377. start[key] = actual;
  2378. }
  2379. origin = start[key];
  2380. type = typeof target;
  2381. if (type === typeof origin) {
  2382. if (type === 'string') {
  2383. c0 = chartjsColor(origin);
  2384. if (c0.valid) {
  2385. c1 = chartjsColor(target);
  2386. if (c1.valid) {
  2387. view[key] = c1.mix(c0, ease).rgbString();
  2388. continue;
  2389. }
  2390. }
  2391. } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
  2392. view[key] = origin + (target - origin) * ease;
  2393. continue;
  2394. }
  2395. }
  2396. view[key] = target;
  2397. }
  2398. }
  2399. var Element = function(configuration) {
  2400. helpers$1.extend(this, configuration);
  2401. this.initialize.apply(this, arguments);
  2402. };
  2403. helpers$1.extend(Element.prototype, {
  2404. initialize: function() {
  2405. this.hidden = false;
  2406. },
  2407. pivot: function() {
  2408. var me = this;
  2409. if (!me._view) {
  2410. me._view = helpers$1.clone(me._model);
  2411. }
  2412. me._start = {};
  2413. return me;
  2414. },
  2415. transition: function(ease) {
  2416. var me = this;
  2417. var model = me._model;
  2418. var start = me._start;
  2419. var view = me._view;
  2420. // No animation -> No Transition
  2421. if (!model || ease === 1) {
  2422. me._view = model;
  2423. me._start = null;
  2424. return me;
  2425. }
  2426. if (!view) {
  2427. view = me._view = {};
  2428. }
  2429. if (!start) {
  2430. start = me._start = {};
  2431. }
  2432. interpolate(start, view, model, ease);
  2433. return me;
  2434. },
  2435. tooltipPosition: function() {
  2436. return {
  2437. x: this._model.x,
  2438. y: this._model.y
  2439. };
  2440. },
  2441. hasValue: function() {
  2442. return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
  2443. }
  2444. });
  2445. Element.extend = helpers$1.inherits;
  2446. var core_element = Element;
  2447. var exports$2 = core_element.extend({
  2448. chart: null, // the animation associated chart instance
  2449. currentStep: 0, // the current animation step
  2450. numSteps: 60, // default number of steps
  2451. easing: '', // the easing to use for this animation
  2452. render: null, // render function used by the animation service
  2453. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  2454. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  2455. });
  2456. var core_animation = exports$2;
  2457. // DEPRECATIONS
  2458. /**
  2459. * Provided for backward compatibility, use Chart.Animation instead
  2460. * @prop Chart.Animation#animationObject
  2461. * @deprecated since version 2.6.0
  2462. * @todo remove at version 3
  2463. */
  2464. Object.defineProperty(exports$2.prototype, 'animationObject', {
  2465. get: function() {
  2466. return this;
  2467. }
  2468. });
  2469. /**
  2470. * Provided for backward compatibility, use Chart.Animation#chart instead
  2471. * @prop Chart.Animation#chartInstance
  2472. * @deprecated since version 2.6.0
  2473. * @todo remove at version 3
  2474. */
  2475. Object.defineProperty(exports$2.prototype, 'chartInstance', {
  2476. get: function() {
  2477. return this.chart;
  2478. },
  2479. set: function(value) {
  2480. this.chart = value;
  2481. }
  2482. });
  2483. core_defaults._set('global', {
  2484. animation: {
  2485. duration: 1000,
  2486. easing: 'easeOutQuart',
  2487. onProgress: helpers$1.noop,
  2488. onComplete: helpers$1.noop
  2489. }
  2490. });
  2491. var core_animations = {
  2492. animations: [],
  2493. request: null,
  2494. /**
  2495. * @param {Chart} chart - The chart to animate.
  2496. * @param {Chart.Animation} animation - The animation that we will animate.
  2497. * @param {number} duration - The animation duration in ms.
  2498. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  2499. */
  2500. addAnimation: function(chart, animation, duration, lazy) {
  2501. var animations = this.animations;
  2502. var i, ilen;
  2503. animation.chart = chart;
  2504. animation.startTime = Date.now();
  2505. animation.duration = duration;
  2506. if (!lazy) {
  2507. chart.animating = true;
  2508. }
  2509. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  2510. if (animations[i].chart === chart) {
  2511. animations[i] = animation;
  2512. return;
  2513. }
  2514. }
  2515. animations.push(animation);
  2516. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  2517. if (animations.length === 1) {
  2518. this.requestAnimationFrame();
  2519. }
  2520. },
  2521. cancelAnimation: function(chart) {
  2522. var index = helpers$1.findIndex(this.animations, function(animation) {
  2523. return animation.chart === chart;
  2524. });
  2525. if (index !== -1) {
  2526. this.animations.splice(index, 1);
  2527. chart.animating = false;
  2528. }
  2529. },
  2530. requestAnimationFrame: function() {
  2531. var me = this;
  2532. if (me.request === null) {
  2533. // Skip animation frame requests until the active one is executed.
  2534. // This can happen when processing mouse events, e.g. 'mousemove'
  2535. // and 'mouseout' events will trigger multiple renders.
  2536. me.request = helpers$1.requestAnimFrame.call(window, function() {
  2537. me.request = null;
  2538. me.startDigest();
  2539. });
  2540. }
  2541. },
  2542. /**
  2543. * @private
  2544. */
  2545. startDigest: function() {
  2546. var me = this;
  2547. me.advance();
  2548. // Do we have more stuff to animate?
  2549. if (me.animations.length > 0) {
  2550. me.requestAnimationFrame();
  2551. }
  2552. },
  2553. /**
  2554. * @private
  2555. */
  2556. advance: function() {
  2557. var animations = this.animations;
  2558. var animation, chart, numSteps, nextStep;
  2559. var i = 0;
  2560. // 1 animation per chart, so we are looping charts here
  2561. while (i < animations.length) {
  2562. animation = animations[i];
  2563. chart = animation.chart;
  2564. numSteps = animation.numSteps;
  2565. // Make sure that currentStep starts at 1
  2566. // https://github.com/chartjs/Chart.js/issues/6104
  2567. nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
  2568. animation.currentStep = Math.min(nextStep, numSteps);
  2569. helpers$1.callback(animation.render, [chart, animation], chart);
  2570. helpers$1.callback(animation.onAnimationProgress, [animation], chart);
  2571. if (animation.currentStep >= numSteps) {
  2572. helpers$1.callback(animation.onAnimationComplete, [animation], chart);
  2573. chart.animating = false;
  2574. animations.splice(i, 1);
  2575. } else {
  2576. ++i;
  2577. }
  2578. }
  2579. }
  2580. };
  2581. var resolve = helpers$1.options.resolve;
  2582. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  2583. /**
  2584. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  2585. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  2586. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  2587. */
  2588. function listenArrayEvents(array, listener) {
  2589. if (array._chartjs) {
  2590. array._chartjs.listeners.push(listener);
  2591. return;
  2592. }
  2593. Object.defineProperty(array, '_chartjs', {
  2594. configurable: true,
  2595. enumerable: false,
  2596. value: {
  2597. listeners: [listener]
  2598. }
  2599. });
  2600. arrayEvents.forEach(function(key) {
  2601. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  2602. var base = array[key];
  2603. Object.defineProperty(array, key, {
  2604. configurable: true,
  2605. enumerable: false,
  2606. value: function() {
  2607. var args = Array.prototype.slice.call(arguments);
  2608. var res = base.apply(this, args);
  2609. helpers$1.each(array._chartjs.listeners, function(object) {
  2610. if (typeof object[method] === 'function') {
  2611. object[method].apply(object, args);
  2612. }
  2613. });
  2614. return res;
  2615. }
  2616. });
  2617. });
  2618. }
  2619. /**
  2620. * Removes the given array event listener and cleanup extra attached properties (such as
  2621. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  2622. */
  2623. function unlistenArrayEvents(array, listener) {
  2624. var stub = array._chartjs;
  2625. if (!stub) {
  2626. return;
  2627. }
  2628. var listeners = stub.listeners;
  2629. var index = listeners.indexOf(listener);
  2630. if (index !== -1) {
  2631. listeners.splice(index, 1);
  2632. }
  2633. if (listeners.length > 0) {
  2634. return;
  2635. }
  2636. arrayEvents.forEach(function(key) {
  2637. delete array[key];
  2638. });
  2639. delete array._chartjs;
  2640. }
  2641. // Base class for all dataset controllers (line, bar, etc)
  2642. var DatasetController = function(chart, datasetIndex) {
  2643. this.initialize(chart, datasetIndex);
  2644. };
  2645. helpers$1.extend(DatasetController.prototype, {
  2646. /**
  2647. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  2648. * @type {Chart.core.element}
  2649. */
  2650. datasetElementType: null,
  2651. /**
  2652. * Element type used to generate a meta data (e.g. Chart.element.Point).
  2653. * @type {Chart.core.element}
  2654. */
  2655. dataElementType: null,
  2656. initialize: function(chart, datasetIndex) {
  2657. var me = this;
  2658. me.chart = chart;
  2659. me.index = datasetIndex;
  2660. me.linkScales();
  2661. me.addElements();
  2662. },
  2663. updateIndex: function(datasetIndex) {
  2664. this.index = datasetIndex;
  2665. },
  2666. linkScales: function() {
  2667. var me = this;
  2668. var meta = me.getMeta();
  2669. var dataset = me.getDataset();
  2670. if (meta.xAxisID === null || !(meta.xAxisID in me.chart.scales)) {
  2671. meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id;
  2672. }
  2673. if (meta.yAxisID === null || !(meta.yAxisID in me.chart.scales)) {
  2674. meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id;
  2675. }
  2676. },
  2677. getDataset: function() {
  2678. return this.chart.data.datasets[this.index];
  2679. },
  2680. getMeta: function() {
  2681. return this.chart.getDatasetMeta(this.index);
  2682. },
  2683. getScaleForId: function(scaleID) {
  2684. return this.chart.scales[scaleID];
  2685. },
  2686. /**
  2687. * @private
  2688. */
  2689. _getValueScaleId: function() {
  2690. return this.getMeta().yAxisID;
  2691. },
  2692. /**
  2693. * @private
  2694. */
  2695. _getIndexScaleId: function() {
  2696. return this.getMeta().xAxisID;
  2697. },
  2698. /**
  2699. * @private
  2700. */
  2701. _getValueScale: function() {
  2702. return this.getScaleForId(this._getValueScaleId());
  2703. },
  2704. /**
  2705. * @private
  2706. */
  2707. _getIndexScale: function() {
  2708. return this.getScaleForId(this._getIndexScaleId());
  2709. },
  2710. reset: function() {
  2711. this.update(true);
  2712. },
  2713. /**
  2714. * @private
  2715. */
  2716. destroy: function() {
  2717. if (this._data) {
  2718. unlistenArrayEvents(this._data, this);
  2719. }
  2720. },
  2721. createMetaDataset: function() {
  2722. var me = this;
  2723. var type = me.datasetElementType;
  2724. return type && new type({
  2725. _chart: me.chart,
  2726. _datasetIndex: me.index
  2727. });
  2728. },
  2729. createMetaData: function(index) {
  2730. var me = this;
  2731. var type = me.dataElementType;
  2732. return type && new type({
  2733. _chart: me.chart,
  2734. _datasetIndex: me.index,
  2735. _index: index
  2736. });
  2737. },
  2738. addElements: function() {
  2739. var me = this;
  2740. var meta = me.getMeta();
  2741. var data = me.getDataset().data || [];
  2742. var metaData = meta.data;
  2743. var i, ilen;
  2744. for (i = 0, ilen = data.length; i < ilen; ++i) {
  2745. metaData[i] = metaData[i] || me.createMetaData(i);
  2746. }
  2747. meta.dataset = meta.dataset || me.createMetaDataset();
  2748. },
  2749. addElementAndReset: function(index) {
  2750. var element = this.createMetaData(index);
  2751. this.getMeta().data.splice(index, 0, element);
  2752. this.updateElement(element, index, true);
  2753. },
  2754. buildOrUpdateElements: function() {
  2755. var me = this;
  2756. var dataset = me.getDataset();
  2757. var data = dataset.data || (dataset.data = []);
  2758. // In order to correctly handle data addition/deletion animation (an thus simulate
  2759. // real-time charts), we need to monitor these data modifications and synchronize
  2760. // the internal meta data accordingly.
  2761. if (me._data !== data) {
  2762. if (me._data) {
  2763. // This case happens when the user replaced the data array instance.
  2764. unlistenArrayEvents(me._data, me);
  2765. }
  2766. if (data && Object.isExtensible(data)) {
  2767. listenArrayEvents(data, me);
  2768. }
  2769. me._data = data;
  2770. }
  2771. // Re-sync meta data in case the user replaced the data array or if we missed
  2772. // any updates and so make sure that we handle number of datapoints changing.
  2773. me.resyncElements();
  2774. },
  2775. update: helpers$1.noop,
  2776. transition: function(easingValue) {
  2777. var meta = this.getMeta();
  2778. var elements = meta.data || [];
  2779. var ilen = elements.length;
  2780. var i = 0;
  2781. for (; i < ilen; ++i) {
  2782. elements[i].transition(easingValue);
  2783. }
  2784. if (meta.dataset) {
  2785. meta.dataset.transition(easingValue);
  2786. }
  2787. },
  2788. draw: function() {
  2789. var meta = this.getMeta();
  2790. var elements = meta.data || [];
  2791. var ilen = elements.length;
  2792. var i = 0;
  2793. if (meta.dataset) {
  2794. meta.dataset.draw();
  2795. }
  2796. for (; i < ilen; ++i) {
  2797. elements[i].draw();
  2798. }
  2799. },
  2800. removeHoverStyle: function(element) {
  2801. helpers$1.merge(element._model, element.$previousStyle || {});
  2802. delete element.$previousStyle;
  2803. },
  2804. setHoverStyle: function(element) {
  2805. var dataset = this.chart.data.datasets[element._datasetIndex];
  2806. var index = element._index;
  2807. var custom = element.custom || {};
  2808. var model = element._model;
  2809. var getHoverColor = helpers$1.getHoverColor;
  2810. element.$previousStyle = {
  2811. backgroundColor: model.backgroundColor,
  2812. borderColor: model.borderColor,
  2813. borderWidth: model.borderWidth
  2814. };
  2815. model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
  2816. model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
  2817. model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
  2818. },
  2819. /**
  2820. * @private
  2821. */
  2822. resyncElements: function() {
  2823. var me = this;
  2824. var meta = me.getMeta();
  2825. var data = me.getDataset().data;
  2826. var numMeta = meta.data.length;
  2827. var numData = data.length;
  2828. if (numData < numMeta) {
  2829. meta.data.splice(numData, numMeta - numData);
  2830. } else if (numData > numMeta) {
  2831. me.insertElements(numMeta, numData - numMeta);
  2832. }
  2833. },
  2834. /**
  2835. * @private
  2836. */
  2837. insertElements: function(start, count) {
  2838. for (var i = 0; i < count; ++i) {
  2839. this.addElementAndReset(start + i);
  2840. }
  2841. },
  2842. /**
  2843. * @private
  2844. */
  2845. onDataPush: function() {
  2846. var count = arguments.length;
  2847. this.insertElements(this.getDataset().data.length - count, count);
  2848. },
  2849. /**
  2850. * @private
  2851. */
  2852. onDataPop: function() {
  2853. this.getMeta().data.pop();
  2854. },
  2855. /**
  2856. * @private
  2857. */
  2858. onDataShift: function() {
  2859. this.getMeta().data.shift();
  2860. },
  2861. /**
  2862. * @private
  2863. */
  2864. onDataSplice: function(start, count) {
  2865. this.getMeta().data.splice(start, count);
  2866. this.insertElements(start, arguments.length - 2);
  2867. },
  2868. /**
  2869. * @private
  2870. */
  2871. onDataUnshift: function() {
  2872. this.insertElements(0, arguments.length);
  2873. }
  2874. });
  2875. DatasetController.extend = helpers$1.inherits;
  2876. var core_datasetController = DatasetController;
  2877. core_defaults._set('global', {
  2878. elements: {
  2879. arc: {
  2880. backgroundColor: core_defaults.global.defaultColor,
  2881. borderColor: '#fff',
  2882. borderWidth: 2,
  2883. borderAlign: 'center'
  2884. }
  2885. }
  2886. });
  2887. var element_arc = core_element.extend({
  2888. inLabelRange: function(mouseX) {
  2889. var vm = this._view;
  2890. if (vm) {
  2891. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  2892. }
  2893. return false;
  2894. },
  2895. inRange: function(chartX, chartY) {
  2896. var vm = this._view;
  2897. if (vm) {
  2898. var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
  2899. var angle = pointRelativePosition.angle;
  2900. var distance = pointRelativePosition.distance;
  2901. // Sanitise angle range
  2902. var startAngle = vm.startAngle;
  2903. var endAngle = vm.endAngle;
  2904. while (endAngle < startAngle) {
  2905. endAngle += 2.0 * Math.PI;
  2906. }
  2907. while (angle > endAngle) {
  2908. angle -= 2.0 * Math.PI;
  2909. }
  2910. while (angle < startAngle) {
  2911. angle += 2.0 * Math.PI;
  2912. }
  2913. // Check if within the range of the open/close angle
  2914. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  2915. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  2916. return (betweenAngles && withinRadius);
  2917. }
  2918. return false;
  2919. },
  2920. getCenterPoint: function() {
  2921. var vm = this._view;
  2922. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  2923. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  2924. return {
  2925. x: vm.x + Math.cos(halfAngle) * halfRadius,
  2926. y: vm.y + Math.sin(halfAngle) * halfRadius
  2927. };
  2928. },
  2929. getArea: function() {
  2930. var vm = this._view;
  2931. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  2932. },
  2933. tooltipPosition: function() {
  2934. var vm = this._view;
  2935. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  2936. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  2937. return {
  2938. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  2939. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  2940. };
  2941. },
  2942. draw: function() {
  2943. var ctx = this._chart.ctx;
  2944. var vm = this._view;
  2945. var sA = vm.startAngle;
  2946. var eA = vm.endAngle;
  2947. var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
  2948. var angleMargin;
  2949. ctx.save();
  2950. ctx.beginPath();
  2951. ctx.arc(vm.x, vm.y, Math.max(vm.outerRadius - pixelMargin, 0), sA, eA);
  2952. ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
  2953. ctx.closePath();
  2954. ctx.fillStyle = vm.backgroundColor;
  2955. ctx.fill();
  2956. if (vm.borderWidth) {
  2957. if (vm.borderAlign === 'inner') {
  2958. // Draw an inner border by cliping the arc and drawing a double-width border
  2959. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  2960. ctx.beginPath();
  2961. angleMargin = pixelMargin / vm.outerRadius;
  2962. ctx.arc(vm.x, vm.y, vm.outerRadius, sA - angleMargin, eA + angleMargin);
  2963. if (vm.innerRadius > pixelMargin) {
  2964. angleMargin = pixelMargin / vm.innerRadius;
  2965. ctx.arc(vm.x, vm.y, vm.innerRadius - pixelMargin, eA + angleMargin, sA - angleMargin, true);
  2966. } else {
  2967. ctx.arc(vm.x, vm.y, pixelMargin, eA + Math.PI / 2, sA - Math.PI / 2);
  2968. }
  2969. ctx.closePath();
  2970. ctx.clip();
  2971. ctx.beginPath();
  2972. ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA);
  2973. ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true);
  2974. ctx.closePath();
  2975. ctx.lineWidth = vm.borderWidth * 2;
  2976. ctx.lineJoin = 'round';
  2977. } else {
  2978. ctx.lineWidth = vm.borderWidth;
  2979. ctx.lineJoin = 'bevel';
  2980. }
  2981. ctx.strokeStyle = vm.borderColor;
  2982. ctx.stroke();
  2983. }
  2984. ctx.restore();
  2985. }
  2986. });
  2987. var valueOrDefault$1 = helpers$1.valueOrDefault;
  2988. var defaultColor = core_defaults.global.defaultColor;
  2989. core_defaults._set('global', {
  2990. elements: {
  2991. line: {
  2992. tension: 0.4,
  2993. backgroundColor: defaultColor,
  2994. borderWidth: 3,
  2995. borderColor: defaultColor,
  2996. borderCapStyle: 'butt',
  2997. borderDash: [],
  2998. borderDashOffset: 0.0,
  2999. borderJoinStyle: 'miter',
  3000. capBezierPoints: true,
  3001. fill: true, // do we fill in the area between the line and its base axis
  3002. }
  3003. }
  3004. });
  3005. var element_line = core_element.extend({
  3006. draw: function() {
  3007. var me = this;
  3008. var vm = me._view;
  3009. var ctx = me._chart.ctx;
  3010. var spanGaps = vm.spanGaps;
  3011. var points = me._children.slice(); // clone array
  3012. var globalDefaults = core_defaults.global;
  3013. var globalOptionLineElements = globalDefaults.elements.line;
  3014. var lastDrawnIndex = -1;
  3015. var index, current, previous, currentVM;
  3016. // If we are looping, adding the first point again
  3017. if (me._loop && points.length) {
  3018. points.push(points[0]);
  3019. }
  3020. ctx.save();
  3021. // Stroke Line Options
  3022. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  3023. // IE 9 and 10 do not support line dash
  3024. if (ctx.setLineDash) {
  3025. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  3026. }
  3027. ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
  3028. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  3029. ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
  3030. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  3031. // Stroke Line
  3032. ctx.beginPath();
  3033. lastDrawnIndex = -1;
  3034. for (index = 0; index < points.length; ++index) {
  3035. current = points[index];
  3036. previous = helpers$1.previousItem(points, index);
  3037. currentVM = current._view;
  3038. // First point moves to it's starting position no matter what
  3039. if (index === 0) {
  3040. if (!currentVM.skip) {
  3041. ctx.moveTo(currentVM.x, currentVM.y);
  3042. lastDrawnIndex = index;
  3043. }
  3044. } else {
  3045. previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex];
  3046. if (!currentVM.skip) {
  3047. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  3048. // There was a gap and this is the first point after the gap
  3049. ctx.moveTo(currentVM.x, currentVM.y);
  3050. } else {
  3051. // Line to next point
  3052. helpers$1.canvas.lineTo(ctx, previous._view, current._view);
  3053. }
  3054. lastDrawnIndex = index;
  3055. }
  3056. }
  3057. }
  3058. ctx.stroke();
  3059. ctx.restore();
  3060. }
  3061. });
  3062. var valueOrDefault$2 = helpers$1.valueOrDefault;
  3063. var defaultColor$1 = core_defaults.global.defaultColor;
  3064. core_defaults._set('global', {
  3065. elements: {
  3066. point: {
  3067. radius: 3,
  3068. pointStyle: 'circle',
  3069. backgroundColor: defaultColor$1,
  3070. borderColor: defaultColor$1,
  3071. borderWidth: 1,
  3072. // Hover
  3073. hitRadius: 1,
  3074. hoverRadius: 4,
  3075. hoverBorderWidth: 1
  3076. }
  3077. }
  3078. });
  3079. function xRange(mouseX) {
  3080. var vm = this._view;
  3081. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  3082. }
  3083. function yRange(mouseY) {
  3084. var vm = this._view;
  3085. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  3086. }
  3087. var element_point = core_element.extend({
  3088. inRange: function(mouseX, mouseY) {
  3089. var vm = this._view;
  3090. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  3091. },
  3092. inLabelRange: xRange,
  3093. inXRange: xRange,
  3094. inYRange: yRange,
  3095. getCenterPoint: function() {
  3096. var vm = this._view;
  3097. return {
  3098. x: vm.x,
  3099. y: vm.y
  3100. };
  3101. },
  3102. getArea: function() {
  3103. return Math.PI * Math.pow(this._view.radius, 2);
  3104. },
  3105. tooltipPosition: function() {
  3106. var vm = this._view;
  3107. return {
  3108. x: vm.x,
  3109. y: vm.y,
  3110. padding: vm.radius + vm.borderWidth
  3111. };
  3112. },
  3113. draw: function(chartArea) {
  3114. var vm = this._view;
  3115. var ctx = this._chart.ctx;
  3116. var pointStyle = vm.pointStyle;
  3117. var rotation = vm.rotation;
  3118. var radius = vm.radius;
  3119. var x = vm.x;
  3120. var y = vm.y;
  3121. var globalDefaults = core_defaults.global;
  3122. var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
  3123. if (vm.skip) {
  3124. return;
  3125. }
  3126. // Clipping for Points.
  3127. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
  3128. ctx.strokeStyle = vm.borderColor || defaultColor;
  3129. ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
  3130. ctx.fillStyle = vm.backgroundColor || defaultColor;
  3131. helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  3132. }
  3133. }
  3134. });
  3135. var defaultColor$2 = core_defaults.global.defaultColor;
  3136. core_defaults._set('global', {
  3137. elements: {
  3138. rectangle: {
  3139. backgroundColor: defaultColor$2,
  3140. borderColor: defaultColor$2,
  3141. borderSkipped: 'bottom',
  3142. borderWidth: 0
  3143. }
  3144. }
  3145. });
  3146. function isVertical(vm) {
  3147. return vm && vm.width !== undefined;
  3148. }
  3149. /**
  3150. * Helper function to get the bounds of the bar regardless of the orientation
  3151. * @param bar {Chart.Element.Rectangle} the bar
  3152. * @return {Bounds} bounds of the bar
  3153. * @private
  3154. */
  3155. function getBarBounds(vm) {
  3156. var x1, x2, y1, y2, half;
  3157. if (isVertical(vm)) {
  3158. half = vm.width / 2;
  3159. x1 = vm.x - half;
  3160. x2 = vm.x + half;
  3161. y1 = Math.min(vm.y, vm.base);
  3162. y2 = Math.max(vm.y, vm.base);
  3163. } else {
  3164. half = vm.height / 2;
  3165. x1 = Math.min(vm.x, vm.base);
  3166. x2 = Math.max(vm.x, vm.base);
  3167. y1 = vm.y - half;
  3168. y2 = vm.y + half;
  3169. }
  3170. return {
  3171. left: x1,
  3172. top: y1,
  3173. right: x2,
  3174. bottom: y2
  3175. };
  3176. }
  3177. function swap(orig, v1, v2) {
  3178. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  3179. }
  3180. function parseBorderSkipped(vm) {
  3181. var edge = vm.borderSkipped;
  3182. var res = {};
  3183. if (!edge) {
  3184. return res;
  3185. }
  3186. if (vm.horizontal) {
  3187. if (vm.base > vm.x) {
  3188. edge = swap(edge, 'left', 'right');
  3189. }
  3190. } else if (vm.base < vm.y) {
  3191. edge = swap(edge, 'bottom', 'top');
  3192. }
  3193. res[edge] = true;
  3194. return res;
  3195. }
  3196. function parseBorderWidth(vm, maxW, maxH) {
  3197. var value = vm.borderWidth;
  3198. var skip = parseBorderSkipped(vm);
  3199. var t, r, b, l;
  3200. if (helpers$1.isObject(value)) {
  3201. t = +value.top || 0;
  3202. r = +value.right || 0;
  3203. b = +value.bottom || 0;
  3204. l = +value.left || 0;
  3205. } else {
  3206. t = r = b = l = +value || 0;
  3207. }
  3208. return {
  3209. t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
  3210. r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
  3211. b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
  3212. l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
  3213. };
  3214. }
  3215. function boundingRects(vm) {
  3216. var bounds = getBarBounds(vm);
  3217. var width = bounds.right - bounds.left;
  3218. var height = bounds.bottom - bounds.top;
  3219. var border = parseBorderWidth(vm, width / 2, height / 2);
  3220. return {
  3221. outer: {
  3222. x: bounds.left,
  3223. y: bounds.top,
  3224. w: width,
  3225. h: height
  3226. },
  3227. inner: {
  3228. x: bounds.left + border.l,
  3229. y: bounds.top + border.t,
  3230. w: width - border.l - border.r,
  3231. h: height - border.t - border.b
  3232. }
  3233. };
  3234. }
  3235. function inRange(vm, x, y) {
  3236. var skipX = x === null;
  3237. var skipY = y === null;
  3238. var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
  3239. return bounds
  3240. && (skipX || x >= bounds.left && x <= bounds.right)
  3241. && (skipY || y >= bounds.top && y <= bounds.bottom);
  3242. }
  3243. var element_rectangle = core_element.extend({
  3244. draw: function() {
  3245. var ctx = this._chart.ctx;
  3246. var vm = this._view;
  3247. var rects = boundingRects(vm);
  3248. var outer = rects.outer;
  3249. var inner = rects.inner;
  3250. ctx.fillStyle = vm.backgroundColor;
  3251. ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
  3252. if (outer.w === inner.w && outer.h === inner.h) {
  3253. return;
  3254. }
  3255. ctx.save();
  3256. ctx.beginPath();
  3257. ctx.rect(outer.x, outer.y, outer.w, outer.h);
  3258. ctx.clip();
  3259. ctx.fillStyle = vm.borderColor;
  3260. ctx.rect(inner.x, inner.y, inner.w, inner.h);
  3261. ctx.fill('evenodd');
  3262. ctx.restore();
  3263. },
  3264. height: function() {
  3265. var vm = this._view;
  3266. return vm.base - vm.y;
  3267. },
  3268. inRange: function(mouseX, mouseY) {
  3269. return inRange(this._view, mouseX, mouseY);
  3270. },
  3271. inLabelRange: function(mouseX, mouseY) {
  3272. var vm = this._view;
  3273. return isVertical(vm)
  3274. ? inRange(vm, mouseX, null)
  3275. : inRange(vm, null, mouseY);
  3276. },
  3277. inXRange: function(mouseX) {
  3278. return inRange(this._view, mouseX, null);
  3279. },
  3280. inYRange: function(mouseY) {
  3281. return inRange(this._view, null, mouseY);
  3282. },
  3283. getCenterPoint: function() {
  3284. var vm = this._view;
  3285. var x, y;
  3286. if (isVertical(vm)) {
  3287. x = vm.x;
  3288. y = (vm.y + vm.base) / 2;
  3289. } else {
  3290. x = (vm.x + vm.base) / 2;
  3291. y = vm.y;
  3292. }
  3293. return {x: x, y: y};
  3294. },
  3295. getArea: function() {
  3296. var vm = this._view;
  3297. return isVertical(vm)
  3298. ? vm.width * Math.abs(vm.y - vm.base)
  3299. : vm.height * Math.abs(vm.x - vm.base);
  3300. },
  3301. tooltipPosition: function() {
  3302. var vm = this._view;
  3303. return {
  3304. x: vm.x,
  3305. y: vm.y
  3306. };
  3307. }
  3308. });
  3309. var elements = {};
  3310. var Arc = element_arc;
  3311. var Line = element_line;
  3312. var Point = element_point;
  3313. var Rectangle = element_rectangle;
  3314. elements.Arc = Arc;
  3315. elements.Line = Line;
  3316. elements.Point = Point;
  3317. elements.Rectangle = Rectangle;
  3318. var resolve$1 = helpers$1.options.resolve;
  3319. core_defaults._set('bar', {
  3320. hover: {
  3321. mode: 'label'
  3322. },
  3323. scales: {
  3324. xAxes: [{
  3325. type: 'category',
  3326. categoryPercentage: 0.8,
  3327. barPercentage: 0.9,
  3328. offset: true,
  3329. gridLines: {
  3330. offsetGridLines: true
  3331. }
  3332. }],
  3333. yAxes: [{
  3334. type: 'linear'
  3335. }]
  3336. }
  3337. });
  3338. /**
  3339. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  3340. * @private
  3341. */
  3342. function computeMinSampleSize(scale, pixels) {
  3343. var min = scale.isHorizontal() ? scale.width : scale.height;
  3344. var ticks = scale.getTicks();
  3345. var prev, curr, i, ilen;
  3346. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  3347. min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
  3348. }
  3349. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  3350. curr = scale.getPixelForTick(i);
  3351. min = i > 0 ? Math.min(min, curr - prev) : min;
  3352. prev = curr;
  3353. }
  3354. return min;
  3355. }
  3356. /**
  3357. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  3358. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  3359. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  3360. * @private
  3361. */
  3362. function computeFitCategoryTraits(index, ruler, options) {
  3363. var thickness = options.barThickness;
  3364. var count = ruler.stackCount;
  3365. var curr = ruler.pixels[index];
  3366. var size, ratio;
  3367. if (helpers$1.isNullOrUndef(thickness)) {
  3368. size = ruler.min * options.categoryPercentage;
  3369. ratio = options.barPercentage;
  3370. } else {
  3371. // When bar thickness is enforced, category and bar percentages are ignored.
  3372. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  3373. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  3374. size = thickness * count;
  3375. ratio = 1;
  3376. }
  3377. return {
  3378. chunk: size / count,
  3379. ratio: ratio,
  3380. start: curr - (size / 2)
  3381. };
  3382. }
  3383. /**
  3384. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  3385. * percentage options are 1), based on the previous and following categories. This mode
  3386. * generates bars with different widths when data are not evenly spaced.
  3387. * @private
  3388. */
  3389. function computeFlexCategoryTraits(index, ruler, options) {
  3390. var pixels = ruler.pixels;
  3391. var curr = pixels[index];
  3392. var prev = index > 0 ? pixels[index - 1] : null;
  3393. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  3394. var percent = options.categoryPercentage;
  3395. var start, size;
  3396. if (prev === null) {
  3397. // first data: its size is double based on the next point or,
  3398. // if it's also the last data, we use the scale size.
  3399. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  3400. }
  3401. if (next === null) {
  3402. // last data: its size is also double based on the previous point.
  3403. next = curr + curr - prev;
  3404. }
  3405. start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  3406. size = Math.abs(next - prev) / 2 * percent;
  3407. return {
  3408. chunk: size / ruler.stackCount,
  3409. ratio: options.barPercentage,
  3410. start: start
  3411. };
  3412. }
  3413. var controller_bar = core_datasetController.extend({
  3414. dataElementType: elements.Rectangle,
  3415. initialize: function() {
  3416. var me = this;
  3417. var meta;
  3418. core_datasetController.prototype.initialize.apply(me, arguments);
  3419. meta = me.getMeta();
  3420. meta.stack = me.getDataset().stack;
  3421. meta.bar = true;
  3422. },
  3423. update: function(reset) {
  3424. var me = this;
  3425. var rects = me.getMeta().data;
  3426. var i, ilen;
  3427. me._ruler = me.getRuler();
  3428. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  3429. me.updateElement(rects[i], i, reset);
  3430. }
  3431. },
  3432. updateElement: function(rectangle, index, reset) {
  3433. var me = this;
  3434. var meta = me.getMeta();
  3435. var dataset = me.getDataset();
  3436. var options = me._resolveElementOptions(rectangle, index);
  3437. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  3438. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  3439. rectangle._datasetIndex = me.index;
  3440. rectangle._index = index;
  3441. rectangle._model = {
  3442. backgroundColor: options.backgroundColor,
  3443. borderColor: options.borderColor,
  3444. borderSkipped: options.borderSkipped,
  3445. borderWidth: options.borderWidth,
  3446. datasetLabel: dataset.label,
  3447. label: me.chart.data.labels[index]
  3448. };
  3449. me._updateElementGeometry(rectangle, index, reset);
  3450. rectangle.pivot();
  3451. },
  3452. /**
  3453. * @private
  3454. */
  3455. _updateElementGeometry: function(rectangle, index, reset) {
  3456. var me = this;
  3457. var model = rectangle._model;
  3458. var vscale = me._getValueScale();
  3459. var base = vscale.getBasePixel();
  3460. var horizontal = vscale.isHorizontal();
  3461. var ruler = me._ruler || me.getRuler();
  3462. var vpixels = me.calculateBarValuePixels(me.index, index);
  3463. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler);
  3464. model.horizontal = horizontal;
  3465. model.base = reset ? base : vpixels.base;
  3466. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  3467. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  3468. model.height = horizontal ? ipixels.size : undefined;
  3469. model.width = horizontal ? undefined : ipixels.size;
  3470. },
  3471. /**
  3472. * Returns the stacks based on groups and bar visibility.
  3473. * @param {number} [last] - The dataset index
  3474. * @returns {string[]} The list of stack IDs
  3475. * @private
  3476. */
  3477. _getStacks: function(last) {
  3478. var me = this;
  3479. var chart = me.chart;
  3480. var scale = me._getIndexScale();
  3481. var stacked = scale.options.stacked;
  3482. var ilen = last === undefined ? chart.data.datasets.length : last + 1;
  3483. var stacks = [];
  3484. var i, meta;
  3485. for (i = 0; i < ilen; ++i) {
  3486. meta = chart.getDatasetMeta(i);
  3487. if (meta.bar && chart.isDatasetVisible(i) &&
  3488. (stacked === false ||
  3489. (stacked === true && stacks.indexOf(meta.stack) === -1) ||
  3490. (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) {
  3491. stacks.push(meta.stack);
  3492. }
  3493. }
  3494. return stacks;
  3495. },
  3496. /**
  3497. * Returns the effective number of stacks based on groups and bar visibility.
  3498. * @private
  3499. */
  3500. getStackCount: function() {
  3501. return this._getStacks().length;
  3502. },
  3503. /**
  3504. * Returns the stack index for the given dataset based on groups and bar visibility.
  3505. * @param {number} [datasetIndex] - The dataset index
  3506. * @param {string} [name] - The stack name to find
  3507. * @returns {number} The stack index
  3508. * @private
  3509. */
  3510. getStackIndex: function(datasetIndex, name) {
  3511. var stacks = this._getStacks(datasetIndex);
  3512. var index = (name !== undefined)
  3513. ? stacks.indexOf(name)
  3514. : -1; // indexOf returns -1 if element is not present
  3515. return (index === -1)
  3516. ? stacks.length - 1
  3517. : index;
  3518. },
  3519. /**
  3520. * @private
  3521. */
  3522. getRuler: function() {
  3523. var me = this;
  3524. var scale = me._getIndexScale();
  3525. var stackCount = me.getStackCount();
  3526. var datasetIndex = me.index;
  3527. var isHorizontal = scale.isHorizontal();
  3528. var start = isHorizontal ? scale.left : scale.top;
  3529. var end = start + (isHorizontal ? scale.width : scale.height);
  3530. var pixels = [];
  3531. var i, ilen, min;
  3532. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  3533. pixels.push(scale.getPixelForValue(null, i, datasetIndex));
  3534. }
  3535. min = helpers$1.isNullOrUndef(scale.options.barThickness)
  3536. ? computeMinSampleSize(scale, pixels)
  3537. : -1;
  3538. return {
  3539. min: min,
  3540. pixels: pixels,
  3541. start: start,
  3542. end: end,
  3543. stackCount: stackCount,
  3544. scale: scale
  3545. };
  3546. },
  3547. /**
  3548. * Note: pixel values are not clamped to the scale area.
  3549. * @private
  3550. */
  3551. calculateBarValuePixels: function(datasetIndex, index) {
  3552. var me = this;
  3553. var chart = me.chart;
  3554. var meta = me.getMeta();
  3555. var scale = me._getValueScale();
  3556. var isHorizontal = scale.isHorizontal();
  3557. var datasets = chart.data.datasets;
  3558. var value = +scale.getRightValue(datasets[datasetIndex].data[index]);
  3559. var minBarLength = scale.options.minBarLength;
  3560. var stacked = scale.options.stacked;
  3561. var stack = meta.stack;
  3562. var start = 0;
  3563. var i, imeta, ivalue, base, head, size;
  3564. if (stacked || (stacked === undefined && stack !== undefined)) {
  3565. for (i = 0; i < datasetIndex; ++i) {
  3566. imeta = chart.getDatasetMeta(i);
  3567. if (imeta.bar &&
  3568. imeta.stack === stack &&
  3569. imeta.controller._getValueScaleId() === scale.id &&
  3570. chart.isDatasetVisible(i)) {
  3571. ivalue = +scale.getRightValue(datasets[i].data[index]);
  3572. if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) {
  3573. start += ivalue;
  3574. }
  3575. }
  3576. }
  3577. }
  3578. base = scale.getPixelForValue(start);
  3579. head = scale.getPixelForValue(start + value);
  3580. size = head - base;
  3581. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  3582. size = minBarLength;
  3583. if (value >= 0 && !isHorizontal || value < 0 && isHorizontal) {
  3584. head = base - minBarLength;
  3585. } else {
  3586. head = base + minBarLength;
  3587. }
  3588. }
  3589. return {
  3590. size: size,
  3591. base: base,
  3592. head: head,
  3593. center: head + size / 2
  3594. };
  3595. },
  3596. /**
  3597. * @private
  3598. */
  3599. calculateBarIndexPixels: function(datasetIndex, index, ruler) {
  3600. var me = this;
  3601. var options = ruler.scale.options;
  3602. var range = options.barThickness === 'flex'
  3603. ? computeFlexCategoryTraits(index, ruler, options)
  3604. : computeFitCategoryTraits(index, ruler, options);
  3605. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  3606. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  3607. var size = Math.min(
  3608. helpers$1.valueOrDefault(options.maxBarThickness, Infinity),
  3609. range.chunk * range.ratio);
  3610. return {
  3611. base: center - size / 2,
  3612. head: center + size / 2,
  3613. center: center,
  3614. size: size
  3615. };
  3616. },
  3617. draw: function() {
  3618. var me = this;
  3619. var chart = me.chart;
  3620. var scale = me._getValueScale();
  3621. var rects = me.getMeta().data;
  3622. var dataset = me.getDataset();
  3623. var ilen = rects.length;
  3624. var i = 0;
  3625. helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
  3626. for (; i < ilen; ++i) {
  3627. if (!isNaN(scale.getRightValue(dataset.data[i]))) {
  3628. rects[i].draw();
  3629. }
  3630. }
  3631. helpers$1.canvas.unclipArea(chart.ctx);
  3632. },
  3633. /**
  3634. * @private
  3635. */
  3636. _resolveElementOptions: function(rectangle, index) {
  3637. var me = this;
  3638. var chart = me.chart;
  3639. var datasets = chart.data.datasets;
  3640. var dataset = datasets[me.index];
  3641. var custom = rectangle.custom || {};
  3642. var options = chart.options.elements.rectangle;
  3643. var values = {};
  3644. var i, ilen, key;
  3645. // Scriptable options
  3646. var context = {
  3647. chart: chart,
  3648. dataIndex: index,
  3649. dataset: dataset,
  3650. datasetIndex: me.index
  3651. };
  3652. var keys = [
  3653. 'backgroundColor',
  3654. 'borderColor',
  3655. 'borderSkipped',
  3656. 'borderWidth'
  3657. ];
  3658. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3659. key = keys[i];
  3660. values[key] = resolve$1([
  3661. custom[key],
  3662. dataset[key],
  3663. options[key]
  3664. ], context, index);
  3665. }
  3666. return values;
  3667. }
  3668. });
  3669. var valueOrDefault$3 = helpers$1.valueOrDefault;
  3670. var resolve$2 = helpers$1.options.resolve;
  3671. core_defaults._set('bubble', {
  3672. hover: {
  3673. mode: 'single'
  3674. },
  3675. scales: {
  3676. xAxes: [{
  3677. type: 'linear', // bubble should probably use a linear scale by default
  3678. position: 'bottom',
  3679. id: 'x-axis-0' // need an ID so datasets can reference the scale
  3680. }],
  3681. yAxes: [{
  3682. type: 'linear',
  3683. position: 'left',
  3684. id: 'y-axis-0'
  3685. }]
  3686. },
  3687. tooltips: {
  3688. callbacks: {
  3689. title: function() {
  3690. // Title doesn't make sense for scatter since we format the data as a point
  3691. return '';
  3692. },
  3693. label: function(item, data) {
  3694. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  3695. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  3696. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  3697. }
  3698. }
  3699. }
  3700. });
  3701. var controller_bubble = core_datasetController.extend({
  3702. /**
  3703. * @protected
  3704. */
  3705. dataElementType: elements.Point,
  3706. /**
  3707. * @protected
  3708. */
  3709. update: function(reset) {
  3710. var me = this;
  3711. var meta = me.getMeta();
  3712. var points = meta.data;
  3713. // Update Points
  3714. helpers$1.each(points, function(point, index) {
  3715. me.updateElement(point, index, reset);
  3716. });
  3717. },
  3718. /**
  3719. * @protected
  3720. */
  3721. updateElement: function(point, index, reset) {
  3722. var me = this;
  3723. var meta = me.getMeta();
  3724. var custom = point.custom || {};
  3725. var xScale = me.getScaleForId(meta.xAxisID);
  3726. var yScale = me.getScaleForId(meta.yAxisID);
  3727. var options = me._resolveElementOptions(point, index);
  3728. var data = me.getDataset().data[index];
  3729. var dsIndex = me.index;
  3730. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  3731. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  3732. point._xScale = xScale;
  3733. point._yScale = yScale;
  3734. point._options = options;
  3735. point._datasetIndex = dsIndex;
  3736. point._index = index;
  3737. point._model = {
  3738. backgroundColor: options.backgroundColor,
  3739. borderColor: options.borderColor,
  3740. borderWidth: options.borderWidth,
  3741. hitRadius: options.hitRadius,
  3742. pointStyle: options.pointStyle,
  3743. rotation: options.rotation,
  3744. radius: reset ? 0 : options.radius,
  3745. skip: custom.skip || isNaN(x) || isNaN(y),
  3746. x: x,
  3747. y: y,
  3748. };
  3749. point.pivot();
  3750. },
  3751. /**
  3752. * @protected
  3753. */
  3754. setHoverStyle: function(point) {
  3755. var model = point._model;
  3756. var options = point._options;
  3757. var getHoverColor = helpers$1.getHoverColor;
  3758. point.$previousStyle = {
  3759. backgroundColor: model.backgroundColor,
  3760. borderColor: model.borderColor,
  3761. borderWidth: model.borderWidth,
  3762. radius: model.radius
  3763. };
  3764. model.backgroundColor = valueOrDefault$3(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  3765. model.borderColor = valueOrDefault$3(options.hoverBorderColor, getHoverColor(options.borderColor));
  3766. model.borderWidth = valueOrDefault$3(options.hoverBorderWidth, options.borderWidth);
  3767. model.radius = options.radius + options.hoverRadius;
  3768. },
  3769. /**
  3770. * @private
  3771. */
  3772. _resolveElementOptions: function(point, index) {
  3773. var me = this;
  3774. var chart = me.chart;
  3775. var datasets = chart.data.datasets;
  3776. var dataset = datasets[me.index];
  3777. var custom = point.custom || {};
  3778. var options = chart.options.elements.point;
  3779. var data = dataset.data[index];
  3780. var values = {};
  3781. var i, ilen, key;
  3782. // Scriptable options
  3783. var context = {
  3784. chart: chart,
  3785. dataIndex: index,
  3786. dataset: dataset,
  3787. datasetIndex: me.index
  3788. };
  3789. var keys = [
  3790. 'backgroundColor',
  3791. 'borderColor',
  3792. 'borderWidth',
  3793. 'hoverBackgroundColor',
  3794. 'hoverBorderColor',
  3795. 'hoverBorderWidth',
  3796. 'hoverRadius',
  3797. 'hitRadius',
  3798. 'pointStyle',
  3799. 'rotation'
  3800. ];
  3801. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3802. key = keys[i];
  3803. values[key] = resolve$2([
  3804. custom[key],
  3805. dataset[key],
  3806. options[key]
  3807. ], context, index);
  3808. }
  3809. // Custom radius resolution
  3810. values.radius = resolve$2([
  3811. custom.radius,
  3812. data ? data.r : undefined,
  3813. dataset.radius,
  3814. options.radius
  3815. ], context, index);
  3816. return values;
  3817. }
  3818. });
  3819. var resolve$3 = helpers$1.options.resolve;
  3820. var valueOrDefault$4 = helpers$1.valueOrDefault;
  3821. core_defaults._set('doughnut', {
  3822. animation: {
  3823. // Boolean - Whether we animate the rotation of the Doughnut
  3824. animateRotate: true,
  3825. // Boolean - Whether we animate scaling the Doughnut from the centre
  3826. animateScale: false
  3827. },
  3828. hover: {
  3829. mode: 'single'
  3830. },
  3831. legendCallback: function(chart) {
  3832. var text = [];
  3833. text.push('<ul class="' + chart.id + '-legend">');
  3834. var data = chart.data;
  3835. var datasets = data.datasets;
  3836. var labels = data.labels;
  3837. if (datasets.length) {
  3838. for (var i = 0; i < datasets[0].data.length; ++i) {
  3839. text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
  3840. if (labels[i]) {
  3841. text.push(labels[i]);
  3842. }
  3843. text.push('</li>');
  3844. }
  3845. }
  3846. text.push('</ul>');
  3847. return text.join('');
  3848. },
  3849. legend: {
  3850. labels: {
  3851. generateLabels: function(chart) {
  3852. var data = chart.data;
  3853. if (data.labels.length && data.datasets.length) {
  3854. return data.labels.map(function(label, i) {
  3855. var meta = chart.getDatasetMeta(0);
  3856. var ds = data.datasets[0];
  3857. var arc = meta.data[i];
  3858. var custom = arc && arc.custom || {};
  3859. var arcOpts = chart.options.elements.arc;
  3860. var fill = resolve$3([custom.backgroundColor, ds.backgroundColor, arcOpts.backgroundColor], undefined, i);
  3861. var stroke = resolve$3([custom.borderColor, ds.borderColor, arcOpts.borderColor], undefined, i);
  3862. var bw = resolve$3([custom.borderWidth, ds.borderWidth, arcOpts.borderWidth], undefined, i);
  3863. return {
  3864. text: label,
  3865. fillStyle: fill,
  3866. strokeStyle: stroke,
  3867. lineWidth: bw,
  3868. hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
  3869. // Extra data used for toggling the correct item
  3870. index: i
  3871. };
  3872. });
  3873. }
  3874. return [];
  3875. }
  3876. },
  3877. onClick: function(e, legendItem) {
  3878. var index = legendItem.index;
  3879. var chart = this.chart;
  3880. var i, ilen, meta;
  3881. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  3882. meta = chart.getDatasetMeta(i);
  3883. // toggle visibility of index if exists
  3884. if (meta.data[index]) {
  3885. meta.data[index].hidden = !meta.data[index].hidden;
  3886. }
  3887. }
  3888. chart.update();
  3889. }
  3890. },
  3891. // The percentage of the chart that we cut out of the middle.
  3892. cutoutPercentage: 50,
  3893. // The rotation of the chart, where the first data arc begins.
  3894. rotation: Math.PI * -0.5,
  3895. // The total circumference of the chart.
  3896. circumference: Math.PI * 2.0,
  3897. // Need to override these to give a nice default
  3898. tooltips: {
  3899. callbacks: {
  3900. title: function() {
  3901. return '';
  3902. },
  3903. label: function(tooltipItem, data) {
  3904. var dataLabel = data.labels[tooltipItem.index];
  3905. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  3906. if (helpers$1.isArray(dataLabel)) {
  3907. // show value on first line of multiline label
  3908. // need to clone because we are changing the value
  3909. dataLabel = dataLabel.slice();
  3910. dataLabel[0] += value;
  3911. } else {
  3912. dataLabel += value;
  3913. }
  3914. return dataLabel;
  3915. }
  3916. }
  3917. }
  3918. });
  3919. var controller_doughnut = core_datasetController.extend({
  3920. dataElementType: elements.Arc,
  3921. linkScales: helpers$1.noop,
  3922. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  3923. getRingIndex: function(datasetIndex) {
  3924. var ringIndex = 0;
  3925. for (var j = 0; j < datasetIndex; ++j) {
  3926. if (this.chart.isDatasetVisible(j)) {
  3927. ++ringIndex;
  3928. }
  3929. }
  3930. return ringIndex;
  3931. },
  3932. update: function(reset) {
  3933. var me = this;
  3934. var chart = me.chart;
  3935. var chartArea = chart.chartArea;
  3936. var opts = chart.options;
  3937. var availableWidth = chartArea.right - chartArea.left;
  3938. var availableHeight = chartArea.bottom - chartArea.top;
  3939. var minSize = Math.min(availableWidth, availableHeight);
  3940. var offset = {x: 0, y: 0};
  3941. var meta = me.getMeta();
  3942. var arcs = meta.data;
  3943. var cutoutPercentage = opts.cutoutPercentage;
  3944. var circumference = opts.circumference;
  3945. var chartWeight = me._getRingWeight(me.index);
  3946. var i, ilen;
  3947. // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc
  3948. if (circumference < Math.PI * 2.0) {
  3949. var startAngle = opts.rotation % (Math.PI * 2.0);
  3950. startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0);
  3951. var endAngle = startAngle + circumference;
  3952. var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)};
  3953. var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)};
  3954. var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle);
  3955. var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle);
  3956. var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle);
  3957. var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle);
  3958. var cutout = cutoutPercentage / 100.0;
  3959. var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))};
  3960. var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))};
  3961. var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5};
  3962. minSize = Math.min(availableWidth / size.width, availableHeight / size.height);
  3963. offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5};
  3964. }
  3965. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  3966. arcs[i]._options = me._resolveElementOptions(arcs[i], i);
  3967. }
  3968. chart.borderWidth = me.getMaxBorderWidth();
  3969. chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0);
  3970. chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0);
  3971. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
  3972. chart.offsetX = offset.x * chart.outerRadius;
  3973. chart.offsetY = offset.y * chart.outerRadius;
  3974. meta.total = me.calculateTotal();
  3975. me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
  3976. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
  3977. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  3978. me.updateElement(arcs[i], i, reset);
  3979. }
  3980. },
  3981. updateElement: function(arc, index, reset) {
  3982. var me = this;
  3983. var chart = me.chart;
  3984. var chartArea = chart.chartArea;
  3985. var opts = chart.options;
  3986. var animationOpts = opts.animation;
  3987. var centerX = (chartArea.left + chartArea.right) / 2;
  3988. var centerY = (chartArea.top + chartArea.bottom) / 2;
  3989. var startAngle = opts.rotation; // non reset case handled later
  3990. var endAngle = opts.rotation; // non reset case handled later
  3991. var dataset = me.getDataset();
  3992. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI));
  3993. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  3994. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  3995. var options = arc._options || {};
  3996. helpers$1.extend(arc, {
  3997. // Utility
  3998. _datasetIndex: me.index,
  3999. _index: index,
  4000. // Desired view properties
  4001. _model: {
  4002. backgroundColor: options.backgroundColor,
  4003. borderColor: options.borderColor,
  4004. borderWidth: options.borderWidth,
  4005. borderAlign: options.borderAlign,
  4006. x: centerX + chart.offsetX,
  4007. y: centerY + chart.offsetY,
  4008. startAngle: startAngle,
  4009. endAngle: endAngle,
  4010. circumference: circumference,
  4011. outerRadius: outerRadius,
  4012. innerRadius: innerRadius,
  4013. label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  4014. }
  4015. });
  4016. var model = arc._model;
  4017. // Set correct angles if not resetting
  4018. if (!reset || !animationOpts.animateRotate) {
  4019. if (index === 0) {
  4020. model.startAngle = opts.rotation;
  4021. } else {
  4022. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  4023. }
  4024. model.endAngle = model.startAngle + model.circumference;
  4025. }
  4026. arc.pivot();
  4027. },
  4028. calculateTotal: function() {
  4029. var dataset = this.getDataset();
  4030. var meta = this.getMeta();
  4031. var total = 0;
  4032. var value;
  4033. helpers$1.each(meta.data, function(element, index) {
  4034. value = dataset.data[index];
  4035. if (!isNaN(value) && !element.hidden) {
  4036. total += Math.abs(value);
  4037. }
  4038. });
  4039. /* if (total === 0) {
  4040. total = NaN;
  4041. }*/
  4042. return total;
  4043. },
  4044. calculateCircumference: function(value) {
  4045. var total = this.getMeta().total;
  4046. if (total > 0 && !isNaN(value)) {
  4047. return (Math.PI * 2.0) * (Math.abs(value) / total);
  4048. }
  4049. return 0;
  4050. },
  4051. // gets the max border or hover width to properly scale pie charts
  4052. getMaxBorderWidth: function(arcs) {
  4053. var me = this;
  4054. var max = 0;
  4055. var chart = me.chart;
  4056. var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
  4057. if (!arcs) {
  4058. // Find the outmost visible dataset
  4059. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  4060. if (chart.isDatasetVisible(i)) {
  4061. meta = chart.getDatasetMeta(i);
  4062. arcs = meta.data;
  4063. if (i !== me.index) {
  4064. controller = meta.controller;
  4065. }
  4066. break;
  4067. }
  4068. }
  4069. }
  4070. if (!arcs) {
  4071. return 0;
  4072. }
  4073. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4074. arc = arcs[i];
  4075. options = controller ? controller._resolveElementOptions(arc, i) : arc._options;
  4076. if (options.borderAlign !== 'inner') {
  4077. borderWidth = options.borderWidth;
  4078. hoverWidth = options.hoverBorderWidth;
  4079. max = borderWidth > max ? borderWidth : max;
  4080. max = hoverWidth > max ? hoverWidth : max;
  4081. }
  4082. }
  4083. return max;
  4084. },
  4085. /**
  4086. * @protected
  4087. */
  4088. setHoverStyle: function(arc) {
  4089. var model = arc._model;
  4090. var options = arc._options;
  4091. var getHoverColor = helpers$1.getHoverColor;
  4092. arc.$previousStyle = {
  4093. backgroundColor: model.backgroundColor,
  4094. borderColor: model.borderColor,
  4095. borderWidth: model.borderWidth,
  4096. };
  4097. model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4098. model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
  4099. model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
  4100. },
  4101. /**
  4102. * @private
  4103. */
  4104. _resolveElementOptions: function(arc, index) {
  4105. var me = this;
  4106. var chart = me.chart;
  4107. var dataset = me.getDataset();
  4108. var custom = arc.custom || {};
  4109. var options = chart.options.elements.arc;
  4110. var values = {};
  4111. var i, ilen, key;
  4112. // Scriptable options
  4113. var context = {
  4114. chart: chart,
  4115. dataIndex: index,
  4116. dataset: dataset,
  4117. datasetIndex: me.index
  4118. };
  4119. var keys = [
  4120. 'backgroundColor',
  4121. 'borderColor',
  4122. 'borderWidth',
  4123. 'borderAlign',
  4124. 'hoverBackgroundColor',
  4125. 'hoverBorderColor',
  4126. 'hoverBorderWidth',
  4127. ];
  4128. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4129. key = keys[i];
  4130. values[key] = resolve$3([
  4131. custom[key],
  4132. dataset[key],
  4133. options[key]
  4134. ], context, index);
  4135. }
  4136. return values;
  4137. },
  4138. /**
  4139. * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
  4140. * @private
  4141. */
  4142. _getRingWeightOffset: function(datasetIndex) {
  4143. var ringWeightOffset = 0;
  4144. for (var i = 0; i < datasetIndex; ++i) {
  4145. if (this.chart.isDatasetVisible(i)) {
  4146. ringWeightOffset += this._getRingWeight(i);
  4147. }
  4148. }
  4149. return ringWeightOffset;
  4150. },
  4151. /**
  4152. * @private
  4153. */
  4154. _getRingWeight: function(dataSetIndex) {
  4155. return Math.max(valueOrDefault$4(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
  4156. },
  4157. /**
  4158. * Returns the sum of all visibile data set weights. This value can be 0.
  4159. * @private
  4160. */
  4161. _getVisibleDatasetWeightTotal: function() {
  4162. return this._getRingWeightOffset(this.chart.data.datasets.length);
  4163. }
  4164. });
  4165. core_defaults._set('horizontalBar', {
  4166. hover: {
  4167. mode: 'index',
  4168. axis: 'y'
  4169. },
  4170. scales: {
  4171. xAxes: [{
  4172. type: 'linear',
  4173. position: 'bottom'
  4174. }],
  4175. yAxes: [{
  4176. type: 'category',
  4177. position: 'left',
  4178. categoryPercentage: 0.8,
  4179. barPercentage: 0.9,
  4180. offset: true,
  4181. gridLines: {
  4182. offsetGridLines: true
  4183. }
  4184. }]
  4185. },
  4186. elements: {
  4187. rectangle: {
  4188. borderSkipped: 'left'
  4189. }
  4190. },
  4191. tooltips: {
  4192. mode: 'index',
  4193. axis: 'y'
  4194. }
  4195. });
  4196. var controller_horizontalBar = controller_bar.extend({
  4197. /**
  4198. * @private
  4199. */
  4200. _getValueScaleId: function() {
  4201. return this.getMeta().xAxisID;
  4202. },
  4203. /**
  4204. * @private
  4205. */
  4206. _getIndexScaleId: function() {
  4207. return this.getMeta().yAxisID;
  4208. }
  4209. });
  4210. var valueOrDefault$5 = helpers$1.valueOrDefault;
  4211. var resolve$4 = helpers$1.options.resolve;
  4212. var isPointInArea = helpers$1.canvas._isPointInArea;
  4213. core_defaults._set('line', {
  4214. showLines: true,
  4215. spanGaps: false,
  4216. hover: {
  4217. mode: 'label'
  4218. },
  4219. scales: {
  4220. xAxes: [{
  4221. type: 'category',
  4222. id: 'x-axis-0'
  4223. }],
  4224. yAxes: [{
  4225. type: 'linear',
  4226. id: 'y-axis-0'
  4227. }]
  4228. }
  4229. });
  4230. function lineEnabled(dataset, options) {
  4231. return valueOrDefault$5(dataset.showLine, options.showLines);
  4232. }
  4233. var controller_line = core_datasetController.extend({
  4234. datasetElementType: elements.Line,
  4235. dataElementType: elements.Point,
  4236. update: function(reset) {
  4237. var me = this;
  4238. var meta = me.getMeta();
  4239. var line = meta.dataset;
  4240. var points = meta.data || [];
  4241. var scale = me.getScaleForId(meta.yAxisID);
  4242. var dataset = me.getDataset();
  4243. var showLine = lineEnabled(dataset, me.chart.options);
  4244. var i, ilen;
  4245. // Update Line
  4246. if (showLine) {
  4247. // Compatibility: If the properties are defined with only the old name, use those values
  4248. if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
  4249. dataset.lineTension = dataset.tension;
  4250. }
  4251. // Utility
  4252. line._scale = scale;
  4253. line._datasetIndex = me.index;
  4254. // Data
  4255. line._children = points;
  4256. // Model
  4257. line._model = me._resolveLineOptions(line);
  4258. line.pivot();
  4259. }
  4260. // Update Points
  4261. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4262. me.updateElement(points[i], i, reset);
  4263. }
  4264. if (showLine && line._model.tension !== 0) {
  4265. me.updateBezierControlPoints();
  4266. }
  4267. // Now pivot the point for animation
  4268. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4269. points[i].pivot();
  4270. }
  4271. },
  4272. updateElement: function(point, index, reset) {
  4273. var me = this;
  4274. var meta = me.getMeta();
  4275. var custom = point.custom || {};
  4276. var dataset = me.getDataset();
  4277. var datasetIndex = me.index;
  4278. var value = dataset.data[index];
  4279. var yScale = me.getScaleForId(meta.yAxisID);
  4280. var xScale = me.getScaleForId(meta.xAxisID);
  4281. var lineModel = meta.dataset._model;
  4282. var x, y;
  4283. var options = me._resolvePointOptions(point, index);
  4284. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  4285. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  4286. // Utility
  4287. point._xScale = xScale;
  4288. point._yScale = yScale;
  4289. point._options = options;
  4290. point._datasetIndex = datasetIndex;
  4291. point._index = index;
  4292. // Desired view properties
  4293. point._model = {
  4294. x: x,
  4295. y: y,
  4296. skip: custom.skip || isNaN(x) || isNaN(y),
  4297. // Appearance
  4298. radius: options.radius,
  4299. pointStyle: options.pointStyle,
  4300. rotation: options.rotation,
  4301. backgroundColor: options.backgroundColor,
  4302. borderColor: options.borderColor,
  4303. borderWidth: options.borderWidth,
  4304. tension: valueOrDefault$5(custom.tension, lineModel ? lineModel.tension : 0),
  4305. steppedLine: lineModel ? lineModel.steppedLine : false,
  4306. // Tooltip
  4307. hitRadius: options.hitRadius
  4308. };
  4309. },
  4310. /**
  4311. * @private
  4312. */
  4313. _resolvePointOptions: function(element, index) {
  4314. var me = this;
  4315. var chart = me.chart;
  4316. var dataset = chart.data.datasets[me.index];
  4317. var custom = element.custom || {};
  4318. var options = chart.options.elements.point;
  4319. var values = {};
  4320. var i, ilen, key;
  4321. // Scriptable options
  4322. var context = {
  4323. chart: chart,
  4324. dataIndex: index,
  4325. dataset: dataset,
  4326. datasetIndex: me.index
  4327. };
  4328. var ELEMENT_OPTIONS = {
  4329. backgroundColor: 'pointBackgroundColor',
  4330. borderColor: 'pointBorderColor',
  4331. borderWidth: 'pointBorderWidth',
  4332. hitRadius: 'pointHitRadius',
  4333. hoverBackgroundColor: 'pointHoverBackgroundColor',
  4334. hoverBorderColor: 'pointHoverBorderColor',
  4335. hoverBorderWidth: 'pointHoverBorderWidth',
  4336. hoverRadius: 'pointHoverRadius',
  4337. pointStyle: 'pointStyle',
  4338. radius: 'pointRadius',
  4339. rotation: 'pointRotation'
  4340. };
  4341. var keys = Object.keys(ELEMENT_OPTIONS);
  4342. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4343. key = keys[i];
  4344. values[key] = resolve$4([
  4345. custom[key],
  4346. dataset[ELEMENT_OPTIONS[key]],
  4347. dataset[key],
  4348. options[key]
  4349. ], context, index);
  4350. }
  4351. return values;
  4352. },
  4353. /**
  4354. * @private
  4355. */
  4356. _resolveLineOptions: function(element) {
  4357. var me = this;
  4358. var chart = me.chart;
  4359. var dataset = chart.data.datasets[me.index];
  4360. var custom = element.custom || {};
  4361. var options = chart.options;
  4362. var elementOptions = options.elements.line;
  4363. var values = {};
  4364. var i, ilen, key;
  4365. var keys = [
  4366. 'backgroundColor',
  4367. 'borderWidth',
  4368. 'borderColor',
  4369. 'borderCapStyle',
  4370. 'borderDash',
  4371. 'borderDashOffset',
  4372. 'borderJoinStyle',
  4373. 'fill',
  4374. 'cubicInterpolationMode'
  4375. ];
  4376. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4377. key = keys[i];
  4378. values[key] = resolve$4([
  4379. custom[key],
  4380. dataset[key],
  4381. elementOptions[key]
  4382. ]);
  4383. }
  4384. // The default behavior of lines is to break at null values, according
  4385. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  4386. // This option gives lines the ability to span gaps
  4387. values.spanGaps = valueOrDefault$5(dataset.spanGaps, options.spanGaps);
  4388. values.tension = valueOrDefault$5(dataset.lineTension, elementOptions.tension);
  4389. values.steppedLine = resolve$4([custom.steppedLine, dataset.steppedLine, elementOptions.stepped]);
  4390. return values;
  4391. },
  4392. calculatePointY: function(value, index, datasetIndex) {
  4393. var me = this;
  4394. var chart = me.chart;
  4395. var meta = me.getMeta();
  4396. var yScale = me.getScaleForId(meta.yAxisID);
  4397. var sumPos = 0;
  4398. var sumNeg = 0;
  4399. var i, ds, dsMeta;
  4400. if (yScale.options.stacked) {
  4401. for (i = 0; i < datasetIndex; i++) {
  4402. ds = chart.data.datasets[i];
  4403. dsMeta = chart.getDatasetMeta(i);
  4404. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) {
  4405. var stackedRightValue = Number(yScale.getRightValue(ds.data[index]));
  4406. if (stackedRightValue < 0) {
  4407. sumNeg += stackedRightValue || 0;
  4408. } else {
  4409. sumPos += stackedRightValue || 0;
  4410. }
  4411. }
  4412. }
  4413. var rightValue = Number(yScale.getRightValue(value));
  4414. if (rightValue < 0) {
  4415. return yScale.getPixelForValue(sumNeg + rightValue);
  4416. }
  4417. return yScale.getPixelForValue(sumPos + rightValue);
  4418. }
  4419. return yScale.getPixelForValue(value);
  4420. },
  4421. updateBezierControlPoints: function() {
  4422. var me = this;
  4423. var chart = me.chart;
  4424. var meta = me.getMeta();
  4425. var lineModel = meta.dataset._model;
  4426. var area = chart.chartArea;
  4427. var points = meta.data || [];
  4428. var i, ilen, model, controlPoints;
  4429. // Only consider points that are drawn in case the spanGaps option is used
  4430. if (lineModel.spanGaps) {
  4431. points = points.filter(function(pt) {
  4432. return !pt._model.skip;
  4433. });
  4434. }
  4435. function capControlPoint(pt, min, max) {
  4436. return Math.max(Math.min(pt, max), min);
  4437. }
  4438. if (lineModel.cubicInterpolationMode === 'monotone') {
  4439. helpers$1.splineCurveMonotone(points);
  4440. } else {
  4441. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4442. model = points[i]._model;
  4443. controlPoints = helpers$1.splineCurve(
  4444. helpers$1.previousItem(points, i)._model,
  4445. model,
  4446. helpers$1.nextItem(points, i)._model,
  4447. lineModel.tension
  4448. );
  4449. model.controlPointPreviousX = controlPoints.previous.x;
  4450. model.controlPointPreviousY = controlPoints.previous.y;
  4451. model.controlPointNextX = controlPoints.next.x;
  4452. model.controlPointNextY = controlPoints.next.y;
  4453. }
  4454. }
  4455. if (chart.options.elements.line.capBezierPoints) {
  4456. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4457. model = points[i]._model;
  4458. if (isPointInArea(model, area)) {
  4459. if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
  4460. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  4461. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  4462. }
  4463. if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
  4464. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  4465. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  4466. }
  4467. }
  4468. }
  4469. }
  4470. },
  4471. draw: function() {
  4472. var me = this;
  4473. var chart = me.chart;
  4474. var meta = me.getMeta();
  4475. var points = meta.data || [];
  4476. var area = chart.chartArea;
  4477. var ilen = points.length;
  4478. var halfBorderWidth;
  4479. var i = 0;
  4480. if (lineEnabled(me.getDataset(), chart.options)) {
  4481. halfBorderWidth = (meta.dataset._model.borderWidth || 0) / 2;
  4482. helpers$1.canvas.clipArea(chart.ctx, {
  4483. left: area.left,
  4484. right: area.right,
  4485. top: area.top - halfBorderWidth,
  4486. bottom: area.bottom + halfBorderWidth
  4487. });
  4488. meta.dataset.draw();
  4489. helpers$1.canvas.unclipArea(chart.ctx);
  4490. }
  4491. // Draw the points
  4492. for (; i < ilen; ++i) {
  4493. points[i].draw(area);
  4494. }
  4495. },
  4496. /**
  4497. * @protected
  4498. */
  4499. setHoverStyle: function(point) {
  4500. var model = point._model;
  4501. var options = point._options;
  4502. var getHoverColor = helpers$1.getHoverColor;
  4503. point.$previousStyle = {
  4504. backgroundColor: model.backgroundColor,
  4505. borderColor: model.borderColor,
  4506. borderWidth: model.borderWidth,
  4507. radius: model.radius
  4508. };
  4509. model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4510. model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
  4511. model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
  4512. model.radius = valueOrDefault$5(options.hoverRadius, options.radius);
  4513. },
  4514. });
  4515. var resolve$5 = helpers$1.options.resolve;
  4516. core_defaults._set('polarArea', {
  4517. scale: {
  4518. type: 'radialLinear',
  4519. angleLines: {
  4520. display: false
  4521. },
  4522. gridLines: {
  4523. circular: true
  4524. },
  4525. pointLabels: {
  4526. display: false
  4527. },
  4528. ticks: {
  4529. beginAtZero: true
  4530. }
  4531. },
  4532. // Boolean - Whether to animate the rotation of the chart
  4533. animation: {
  4534. animateRotate: true,
  4535. animateScale: true
  4536. },
  4537. startAngle: -0.5 * Math.PI,
  4538. legendCallback: function(chart) {
  4539. var text = [];
  4540. text.push('<ul class="' + chart.id + '-legend">');
  4541. var data = chart.data;
  4542. var datasets = data.datasets;
  4543. var labels = data.labels;
  4544. if (datasets.length) {
  4545. for (var i = 0; i < datasets[0].data.length; ++i) {
  4546. text.push('<li><span style="background-color:' + datasets[0].backgroundColor[i] + '"></span>');
  4547. if (labels[i]) {
  4548. text.push(labels[i]);
  4549. }
  4550. text.push('</li>');
  4551. }
  4552. }
  4553. text.push('</ul>');
  4554. return text.join('');
  4555. },
  4556. legend: {
  4557. labels: {
  4558. generateLabels: function(chart) {
  4559. var data = chart.data;
  4560. if (data.labels.length && data.datasets.length) {
  4561. return data.labels.map(function(label, i) {
  4562. var meta = chart.getDatasetMeta(0);
  4563. var ds = data.datasets[0];
  4564. var arc = meta.data[i];
  4565. var custom = arc.custom || {};
  4566. var arcOpts = chart.options.elements.arc;
  4567. var fill = resolve$5([custom.backgroundColor, ds.backgroundColor, arcOpts.backgroundColor], undefined, i);
  4568. var stroke = resolve$5([custom.borderColor, ds.borderColor, arcOpts.borderColor], undefined, i);
  4569. var bw = resolve$5([custom.borderWidth, ds.borderWidth, arcOpts.borderWidth], undefined, i);
  4570. return {
  4571. text: label,
  4572. fillStyle: fill,
  4573. strokeStyle: stroke,
  4574. lineWidth: bw,
  4575. hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
  4576. // Extra data used for toggling the correct item
  4577. index: i
  4578. };
  4579. });
  4580. }
  4581. return [];
  4582. }
  4583. },
  4584. onClick: function(e, legendItem) {
  4585. var index = legendItem.index;
  4586. var chart = this.chart;
  4587. var i, ilen, meta;
  4588. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  4589. meta = chart.getDatasetMeta(i);
  4590. meta.data[index].hidden = !meta.data[index].hidden;
  4591. }
  4592. chart.update();
  4593. }
  4594. },
  4595. // Need to override these to give a nice default
  4596. tooltips: {
  4597. callbacks: {
  4598. title: function() {
  4599. return '';
  4600. },
  4601. label: function(item, data) {
  4602. return data.labels[item.index] + ': ' + item.yLabel;
  4603. }
  4604. }
  4605. }
  4606. });
  4607. var controller_polarArea = core_datasetController.extend({
  4608. dataElementType: elements.Arc,
  4609. linkScales: helpers$1.noop,
  4610. update: function(reset) {
  4611. var me = this;
  4612. var dataset = me.getDataset();
  4613. var meta = me.getMeta();
  4614. var start = me.chart.options.startAngle || 0;
  4615. var starts = me._starts = [];
  4616. var angles = me._angles = [];
  4617. var arcs = meta.data;
  4618. var i, ilen, angle;
  4619. me._updateRadius();
  4620. meta.count = me.countVisibleElements();
  4621. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  4622. starts[i] = start;
  4623. angle = me._computeAngle(i);
  4624. angles[i] = angle;
  4625. start += angle;
  4626. }
  4627. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4628. arcs[i]._options = me._resolveElementOptions(arcs[i], i);
  4629. me.updateElement(arcs[i], i, reset);
  4630. }
  4631. },
  4632. /**
  4633. * @private
  4634. */
  4635. _updateRadius: function() {
  4636. var me = this;
  4637. var chart = me.chart;
  4638. var chartArea = chart.chartArea;
  4639. var opts = chart.options;
  4640. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  4641. chart.outerRadius = Math.max(minSize / 2, 0);
  4642. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  4643. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  4644. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  4645. me.innerRadius = me.outerRadius - chart.radiusLength;
  4646. },
  4647. updateElement: function(arc, index, reset) {
  4648. var me = this;
  4649. var chart = me.chart;
  4650. var dataset = me.getDataset();
  4651. var opts = chart.options;
  4652. var animationOpts = opts.animation;
  4653. var scale = chart.scale;
  4654. var labels = chart.data.labels;
  4655. var centerX = scale.xCenter;
  4656. var centerY = scale.yCenter;
  4657. // var negHalfPI = -0.5 * Math.PI;
  4658. var datasetStartAngle = opts.startAngle;
  4659. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  4660. var startAngle = me._starts[index];
  4661. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  4662. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  4663. var options = arc._options || {};
  4664. helpers$1.extend(arc, {
  4665. // Utility
  4666. _datasetIndex: me.index,
  4667. _index: index,
  4668. _scale: scale,
  4669. // Desired view properties
  4670. _model: {
  4671. backgroundColor: options.backgroundColor,
  4672. borderColor: options.borderColor,
  4673. borderWidth: options.borderWidth,
  4674. borderAlign: options.borderAlign,
  4675. x: centerX,
  4676. y: centerY,
  4677. innerRadius: 0,
  4678. outerRadius: reset ? resetRadius : distance,
  4679. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  4680. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  4681. label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
  4682. }
  4683. });
  4684. arc.pivot();
  4685. },
  4686. countVisibleElements: function() {
  4687. var dataset = this.getDataset();
  4688. var meta = this.getMeta();
  4689. var count = 0;
  4690. helpers$1.each(meta.data, function(element, index) {
  4691. if (!isNaN(dataset.data[index]) && !element.hidden) {
  4692. count++;
  4693. }
  4694. });
  4695. return count;
  4696. },
  4697. /**
  4698. * @protected
  4699. */
  4700. setHoverStyle: function(arc) {
  4701. var model = arc._model;
  4702. var options = arc._options;
  4703. var getHoverColor = helpers$1.getHoverColor;
  4704. var valueOrDefault = helpers$1.valueOrDefault;
  4705. arc.$previousStyle = {
  4706. backgroundColor: model.backgroundColor,
  4707. borderColor: model.borderColor,
  4708. borderWidth: model.borderWidth,
  4709. };
  4710. model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4711. model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
  4712. model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  4713. },
  4714. /**
  4715. * @private
  4716. */
  4717. _resolveElementOptions: function(arc, index) {
  4718. var me = this;
  4719. var chart = me.chart;
  4720. var dataset = me.getDataset();
  4721. var custom = arc.custom || {};
  4722. var options = chart.options.elements.arc;
  4723. var values = {};
  4724. var i, ilen, key;
  4725. // Scriptable options
  4726. var context = {
  4727. chart: chart,
  4728. dataIndex: index,
  4729. dataset: dataset,
  4730. datasetIndex: me.index
  4731. };
  4732. var keys = [
  4733. 'backgroundColor',
  4734. 'borderColor',
  4735. 'borderWidth',
  4736. 'borderAlign',
  4737. 'hoverBackgroundColor',
  4738. 'hoverBorderColor',
  4739. 'hoverBorderWidth',
  4740. ];
  4741. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4742. key = keys[i];
  4743. values[key] = resolve$5([
  4744. custom[key],
  4745. dataset[key],
  4746. options[key]
  4747. ], context, index);
  4748. }
  4749. return values;
  4750. },
  4751. /**
  4752. * @private
  4753. */
  4754. _computeAngle: function(index) {
  4755. var me = this;
  4756. var count = this.getMeta().count;
  4757. var dataset = me.getDataset();
  4758. var meta = me.getMeta();
  4759. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  4760. return 0;
  4761. }
  4762. // Scriptable options
  4763. var context = {
  4764. chart: me.chart,
  4765. dataIndex: index,
  4766. dataset: dataset,
  4767. datasetIndex: me.index
  4768. };
  4769. return resolve$5([
  4770. me.chart.options.elements.arc.angle,
  4771. (2 * Math.PI) / count
  4772. ], context, index);
  4773. }
  4774. });
  4775. core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
  4776. core_defaults._set('pie', {
  4777. cutoutPercentage: 0
  4778. });
  4779. // Pie charts are Doughnut chart with different defaults
  4780. var controller_pie = controller_doughnut;
  4781. var valueOrDefault$6 = helpers$1.valueOrDefault;
  4782. var resolve$6 = helpers$1.options.resolve;
  4783. core_defaults._set('radar', {
  4784. scale: {
  4785. type: 'radialLinear'
  4786. },
  4787. elements: {
  4788. line: {
  4789. tension: 0 // no bezier in radar
  4790. }
  4791. }
  4792. });
  4793. var controller_radar = core_datasetController.extend({
  4794. datasetElementType: elements.Line,
  4795. dataElementType: elements.Point,
  4796. linkScales: helpers$1.noop,
  4797. update: function(reset) {
  4798. var me = this;
  4799. var meta = me.getMeta();
  4800. var line = meta.dataset;
  4801. var points = meta.data || [];
  4802. var scale = me.chart.scale;
  4803. var dataset = me.getDataset();
  4804. var i, ilen;
  4805. // Compatibility: If the properties are defined with only the old name, use those values
  4806. if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) {
  4807. dataset.lineTension = dataset.tension;
  4808. }
  4809. // Utility
  4810. line._scale = scale;
  4811. line._datasetIndex = me.index;
  4812. // Data
  4813. line._children = points;
  4814. line._loop = true;
  4815. // Model
  4816. line._model = me._resolveLineOptions(line);
  4817. line.pivot();
  4818. // Update Points
  4819. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4820. me.updateElement(points[i], i, reset);
  4821. }
  4822. // Update bezier control points
  4823. me.updateBezierControlPoints();
  4824. // Now pivot the point for animation
  4825. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4826. points[i].pivot();
  4827. }
  4828. },
  4829. updateElement: function(point, index, reset) {
  4830. var me = this;
  4831. var custom = point.custom || {};
  4832. var dataset = me.getDataset();
  4833. var scale = me.chart.scale;
  4834. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  4835. var options = me._resolvePointOptions(point, index);
  4836. var lineModel = me.getMeta().dataset._model;
  4837. var x = reset ? scale.xCenter : pointPosition.x;
  4838. var y = reset ? scale.yCenter : pointPosition.y;
  4839. // Utility
  4840. point._scale = scale;
  4841. point._options = options;
  4842. point._datasetIndex = me.index;
  4843. point._index = index;
  4844. // Desired view properties
  4845. point._model = {
  4846. x: x, // value not used in dataset scale, but we want a consistent API between scales
  4847. y: y,
  4848. skip: custom.skip || isNaN(x) || isNaN(y),
  4849. // Appearance
  4850. radius: options.radius,
  4851. pointStyle: options.pointStyle,
  4852. rotation: options.rotation,
  4853. backgroundColor: options.backgroundColor,
  4854. borderColor: options.borderColor,
  4855. borderWidth: options.borderWidth,
  4856. tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0),
  4857. // Tooltip
  4858. hitRadius: options.hitRadius
  4859. };
  4860. },
  4861. /**
  4862. * @private
  4863. */
  4864. _resolvePointOptions: function(element, index) {
  4865. var me = this;
  4866. var chart = me.chart;
  4867. var dataset = chart.data.datasets[me.index];
  4868. var custom = element.custom || {};
  4869. var options = chart.options.elements.point;
  4870. var values = {};
  4871. var i, ilen, key;
  4872. // Scriptable options
  4873. var context = {
  4874. chart: chart,
  4875. dataIndex: index,
  4876. dataset: dataset,
  4877. datasetIndex: me.index
  4878. };
  4879. var ELEMENT_OPTIONS = {
  4880. backgroundColor: 'pointBackgroundColor',
  4881. borderColor: 'pointBorderColor',
  4882. borderWidth: 'pointBorderWidth',
  4883. hitRadius: 'pointHitRadius',
  4884. hoverBackgroundColor: 'pointHoverBackgroundColor',
  4885. hoverBorderColor: 'pointHoverBorderColor',
  4886. hoverBorderWidth: 'pointHoverBorderWidth',
  4887. hoverRadius: 'pointHoverRadius',
  4888. pointStyle: 'pointStyle',
  4889. radius: 'pointRadius',
  4890. rotation: 'pointRotation'
  4891. };
  4892. var keys = Object.keys(ELEMENT_OPTIONS);
  4893. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4894. key = keys[i];
  4895. values[key] = resolve$6([
  4896. custom[key],
  4897. dataset[ELEMENT_OPTIONS[key]],
  4898. dataset[key],
  4899. options[key]
  4900. ], context, index);
  4901. }
  4902. return values;
  4903. },
  4904. /**
  4905. * @private
  4906. */
  4907. _resolveLineOptions: function(element) {
  4908. var me = this;
  4909. var chart = me.chart;
  4910. var dataset = chart.data.datasets[me.index];
  4911. var custom = element.custom || {};
  4912. var options = chart.options.elements.line;
  4913. var values = {};
  4914. var i, ilen, key;
  4915. var keys = [
  4916. 'backgroundColor',
  4917. 'borderWidth',
  4918. 'borderColor',
  4919. 'borderCapStyle',
  4920. 'borderDash',
  4921. 'borderDashOffset',
  4922. 'borderJoinStyle',
  4923. 'fill'
  4924. ];
  4925. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  4926. key = keys[i];
  4927. values[key] = resolve$6([
  4928. custom[key],
  4929. dataset[key],
  4930. options[key]
  4931. ]);
  4932. }
  4933. values.tension = valueOrDefault$6(dataset.lineTension, options.tension);
  4934. return values;
  4935. },
  4936. updateBezierControlPoints: function() {
  4937. var me = this;
  4938. var meta = me.getMeta();
  4939. var area = me.chart.chartArea;
  4940. var points = meta.data || [];
  4941. var i, ilen, model, controlPoints;
  4942. function capControlPoint(pt, min, max) {
  4943. return Math.max(Math.min(pt, max), min);
  4944. }
  4945. for (i = 0, ilen = points.length; i < ilen; ++i) {
  4946. model = points[i]._model;
  4947. controlPoints = helpers$1.splineCurve(
  4948. helpers$1.previousItem(points, i, true)._model,
  4949. model,
  4950. helpers$1.nextItem(points, i, true)._model,
  4951. model.tension
  4952. );
  4953. // Prevent the bezier going outside of the bounds of the graph
  4954. model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
  4955. model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
  4956. model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
  4957. model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
  4958. }
  4959. },
  4960. setHoverStyle: function(point) {
  4961. var model = point._model;
  4962. var options = point._options;
  4963. var getHoverColor = helpers$1.getHoverColor;
  4964. point.$previousStyle = {
  4965. backgroundColor: model.backgroundColor,
  4966. borderColor: model.borderColor,
  4967. borderWidth: model.borderWidth,
  4968. radius: model.radius
  4969. };
  4970. model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4971. model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));
  4972. model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);
  4973. model.radius = valueOrDefault$6(options.hoverRadius, options.radius);
  4974. }
  4975. });
  4976. core_defaults._set('scatter', {
  4977. hover: {
  4978. mode: 'single'
  4979. },
  4980. scales: {
  4981. xAxes: [{
  4982. id: 'x-axis-1', // need an ID so datasets can reference the scale
  4983. type: 'linear', // scatter should not use a category axis
  4984. position: 'bottom'
  4985. }],
  4986. yAxes: [{
  4987. id: 'y-axis-1',
  4988. type: 'linear',
  4989. position: 'left'
  4990. }]
  4991. },
  4992. showLines: false,
  4993. tooltips: {
  4994. callbacks: {
  4995. title: function() {
  4996. return ''; // doesn't make sense for scatter since data are formatted as a point
  4997. },
  4998. label: function(item) {
  4999. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  5000. }
  5001. }
  5002. }
  5003. });
  5004. // Scatter charts use line controllers
  5005. var controller_scatter = controller_line;
  5006. // NOTE export a map in which the key represents the controller type, not
  5007. // the class, and so must be CamelCase in order to be correctly retrieved
  5008. // by the controller in core.controller.js (`controllers[meta.type]`).
  5009. var controllers = {
  5010. bar: controller_bar,
  5011. bubble: controller_bubble,
  5012. doughnut: controller_doughnut,
  5013. horizontalBar: controller_horizontalBar,
  5014. line: controller_line,
  5015. polarArea: controller_polarArea,
  5016. pie: controller_pie,
  5017. radar: controller_radar,
  5018. scatter: controller_scatter
  5019. };
  5020. /**
  5021. * Helper function to get relative position for an event
  5022. * @param {Event|IEvent} event - The event to get the position for
  5023. * @param {Chart} chart - The chart
  5024. * @returns {object} the event position
  5025. */
  5026. function getRelativePosition(e, chart) {
  5027. if (e.native) {
  5028. return {
  5029. x: e.x,
  5030. y: e.y
  5031. };
  5032. }
  5033. return helpers$1.getRelativePosition(e, chart);
  5034. }
  5035. /**
  5036. * Helper function to traverse all of the visible elements in the chart
  5037. * @param {Chart} chart - the chart
  5038. * @param {function} handler - the callback to execute for each visible item
  5039. */
  5040. function parseVisibleItems(chart, handler) {
  5041. var datasets = chart.data.datasets;
  5042. var meta, i, j, ilen, jlen;
  5043. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  5044. if (!chart.isDatasetVisible(i)) {
  5045. continue;
  5046. }
  5047. meta = chart.getDatasetMeta(i);
  5048. for (j = 0, jlen = meta.data.length; j < jlen; ++j) {
  5049. var element = meta.data[j];
  5050. if (!element._view.skip) {
  5051. handler(element);
  5052. }
  5053. }
  5054. }
  5055. }
  5056. /**
  5057. * Helper function to get the items that intersect the event position
  5058. * @param {ChartElement[]} items - elements to filter
  5059. * @param {object} position - the point to be nearest to
  5060. * @return {ChartElement[]} the nearest items
  5061. */
  5062. function getIntersectItems(chart, position) {
  5063. var elements = [];
  5064. parseVisibleItems(chart, function(element) {
  5065. if (element.inRange(position.x, position.y)) {
  5066. elements.push(element);
  5067. }
  5068. });
  5069. return elements;
  5070. }
  5071. /**
  5072. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  5073. * @param {Chart} chart - the chart to look at elements from
  5074. * @param {object} position - the point to be nearest to
  5075. * @param {boolean} intersect - if true, only consider items that intersect the position
  5076. * @param {function} distanceMetric - function to provide the distance between points
  5077. * @return {ChartElement[]} the nearest items
  5078. */
  5079. function getNearestItems(chart, position, intersect, distanceMetric) {
  5080. var minDistance = Number.POSITIVE_INFINITY;
  5081. var nearestItems = [];
  5082. parseVisibleItems(chart, function(element) {
  5083. if (intersect && !element.inRange(position.x, position.y)) {
  5084. return;
  5085. }
  5086. var center = element.getCenterPoint();
  5087. var distance = distanceMetric(position, center);
  5088. if (distance < minDistance) {
  5089. nearestItems = [element];
  5090. minDistance = distance;
  5091. } else if (distance === minDistance) {
  5092. // Can have multiple items at the same distance in which case we sort by size
  5093. nearestItems.push(element);
  5094. }
  5095. });
  5096. return nearestItems;
  5097. }
  5098. /**
  5099. * Get a distance metric function for two points based on the
  5100. * axis mode setting
  5101. * @param {string} axis - the axis mode. x|y|xy
  5102. */
  5103. function getDistanceMetricForAxis(axis) {
  5104. var useX = axis.indexOf('x') !== -1;
  5105. var useY = axis.indexOf('y') !== -1;
  5106. return function(pt1, pt2) {
  5107. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  5108. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  5109. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  5110. };
  5111. }
  5112. function indexMode(chart, e, options) {
  5113. var position = getRelativePosition(e, chart);
  5114. // Default axis for index mode is 'x' to match old behaviour
  5115. options.axis = options.axis || 'x';
  5116. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5117. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5118. var elements = [];
  5119. if (!items.length) {
  5120. return [];
  5121. }
  5122. chart.data.datasets.forEach(function(dataset, datasetIndex) {
  5123. if (chart.isDatasetVisible(datasetIndex)) {
  5124. var meta = chart.getDatasetMeta(datasetIndex);
  5125. var element = meta.data[items[0]._index];
  5126. // don't count items that are skipped (null data)
  5127. if (element && !element._view.skip) {
  5128. elements.push(element);
  5129. }
  5130. }
  5131. });
  5132. return elements;
  5133. }
  5134. /**
  5135. * @interface IInteractionOptions
  5136. */
  5137. /**
  5138. * If true, only consider items that intersect the point
  5139. * @name IInterfaceOptions#boolean
  5140. * @type Boolean
  5141. */
  5142. /**
  5143. * Contains interaction related functions
  5144. * @namespace Chart.Interaction
  5145. */
  5146. var core_interaction = {
  5147. // Helper function for different modes
  5148. modes: {
  5149. single: function(chart, e) {
  5150. var position = getRelativePosition(e, chart);
  5151. var elements = [];
  5152. parseVisibleItems(chart, function(element) {
  5153. if (element.inRange(position.x, position.y)) {
  5154. elements.push(element);
  5155. return elements;
  5156. }
  5157. });
  5158. return elements.slice(0, 1);
  5159. },
  5160. /**
  5161. * @function Chart.Interaction.modes.label
  5162. * @deprecated since version 2.4.0
  5163. * @todo remove at version 3
  5164. * @private
  5165. */
  5166. label: indexMode,
  5167. /**
  5168. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  5169. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  5170. * @function Chart.Interaction.modes.index
  5171. * @since v2.4.0
  5172. * @param {Chart} chart - the chart we are returning items from
  5173. * @param {Event} e - the event we are find things at
  5174. * @param {IInteractionOptions} options - options to use during interaction
  5175. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5176. */
  5177. index: indexMode,
  5178. /**
  5179. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  5180. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  5181. * @function Chart.Interaction.modes.dataset
  5182. * @param {Chart} chart - the chart we are returning items from
  5183. * @param {Event} e - the event we are find things at
  5184. * @param {IInteractionOptions} options - options to use during interaction
  5185. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5186. */
  5187. dataset: function(chart, e, options) {
  5188. var position = getRelativePosition(e, chart);
  5189. options.axis = options.axis || 'xy';
  5190. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5191. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5192. if (items.length > 0) {
  5193. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  5194. }
  5195. return items;
  5196. },
  5197. /**
  5198. * @function Chart.Interaction.modes.x-axis
  5199. * @deprecated since version 2.4.0. Use index mode and intersect == true
  5200. * @todo remove at version 3
  5201. * @private
  5202. */
  5203. 'x-axis': function(chart, e) {
  5204. return indexMode(chart, e, {intersect: false});
  5205. },
  5206. /**
  5207. * Point mode returns all elements that hit test based on the event position
  5208. * of the event
  5209. * @function Chart.Interaction.modes.intersect
  5210. * @param {Chart} chart - the chart we are returning items from
  5211. * @param {Event} e - the event we are find things at
  5212. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5213. */
  5214. point: function(chart, e) {
  5215. var position = getRelativePosition(e, chart);
  5216. return getIntersectItems(chart, position);
  5217. },
  5218. /**
  5219. * nearest mode returns the element closest to the point
  5220. * @function Chart.Interaction.modes.intersect
  5221. * @param {Chart} chart - the chart we are returning items from
  5222. * @param {Event} e - the event we are find things at
  5223. * @param {IInteractionOptions} options - options to use
  5224. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5225. */
  5226. nearest: function(chart, e, options) {
  5227. var position = getRelativePosition(e, chart);
  5228. options.axis = options.axis || 'xy';
  5229. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5230. return getNearestItems(chart, position, options.intersect, distanceMetric);
  5231. },
  5232. /**
  5233. * x mode returns the elements that hit-test at the current x coordinate
  5234. * @function Chart.Interaction.modes.x
  5235. * @param {Chart} chart - the chart we are returning items from
  5236. * @param {Event} e - the event we are find things at
  5237. * @param {IInteractionOptions} options - options to use
  5238. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5239. */
  5240. x: function(chart, e, options) {
  5241. var position = getRelativePosition(e, chart);
  5242. var items = [];
  5243. var intersectsItem = false;
  5244. parseVisibleItems(chart, function(element) {
  5245. if (element.inXRange(position.x)) {
  5246. items.push(element);
  5247. }
  5248. if (element.inRange(position.x, position.y)) {
  5249. intersectsItem = true;
  5250. }
  5251. });
  5252. // If we want to trigger on an intersect and we don't have any items
  5253. // that intersect the position, return nothing
  5254. if (options.intersect && !intersectsItem) {
  5255. items = [];
  5256. }
  5257. return items;
  5258. },
  5259. /**
  5260. * y mode returns the elements that hit-test at the current y coordinate
  5261. * @function Chart.Interaction.modes.y
  5262. * @param {Chart} chart - the chart we are returning items from
  5263. * @param {Event} e - the event we are find things at
  5264. * @param {IInteractionOptions} options - options to use
  5265. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5266. */
  5267. y: function(chart, e, options) {
  5268. var position = getRelativePosition(e, chart);
  5269. var items = [];
  5270. var intersectsItem = false;
  5271. parseVisibleItems(chart, function(element) {
  5272. if (element.inYRange(position.y)) {
  5273. items.push(element);
  5274. }
  5275. if (element.inRange(position.x, position.y)) {
  5276. intersectsItem = true;
  5277. }
  5278. });
  5279. // If we want to trigger on an intersect and we don't have any items
  5280. // that intersect the position, return nothing
  5281. if (options.intersect && !intersectsItem) {
  5282. items = [];
  5283. }
  5284. return items;
  5285. }
  5286. }
  5287. };
  5288. function filterByPosition(array, position) {
  5289. return helpers$1.where(array, function(v) {
  5290. return v.position === position;
  5291. });
  5292. }
  5293. function sortByWeight(array, reverse) {
  5294. array.forEach(function(v, i) {
  5295. v._tmpIndex_ = i;
  5296. return v;
  5297. });
  5298. array.sort(function(a, b) {
  5299. var v0 = reverse ? b : a;
  5300. var v1 = reverse ? a : b;
  5301. return v0.weight === v1.weight ?
  5302. v0._tmpIndex_ - v1._tmpIndex_ :
  5303. v0.weight - v1.weight;
  5304. });
  5305. array.forEach(function(v) {
  5306. delete v._tmpIndex_;
  5307. });
  5308. }
  5309. function findMaxPadding(boxes) {
  5310. var top = 0;
  5311. var left = 0;
  5312. var bottom = 0;
  5313. var right = 0;
  5314. helpers$1.each(boxes, function(box) {
  5315. if (box.getPadding) {
  5316. var boxPadding = box.getPadding();
  5317. top = Math.max(top, boxPadding.top);
  5318. left = Math.max(left, boxPadding.left);
  5319. bottom = Math.max(bottom, boxPadding.bottom);
  5320. right = Math.max(right, boxPadding.right);
  5321. }
  5322. });
  5323. return {
  5324. top: top,
  5325. left: left,
  5326. bottom: bottom,
  5327. right: right
  5328. };
  5329. }
  5330. function addSizeByPosition(boxes, size) {
  5331. helpers$1.each(boxes, function(box) {
  5332. size[box.position] += box.isHorizontal() ? box.height : box.width;
  5333. });
  5334. }
  5335. core_defaults._set('global', {
  5336. layout: {
  5337. padding: {
  5338. top: 0,
  5339. right: 0,
  5340. bottom: 0,
  5341. left: 0
  5342. }
  5343. }
  5344. });
  5345. /**
  5346. * @interface ILayoutItem
  5347. * @prop {string} position - The position of the item in the chart layout. Possible values are
  5348. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  5349. * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  5350. * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  5351. * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  5352. * @prop {function} update - Takes two parameters: width and height. Returns size of item
  5353. * @prop {function} getPadding - Returns an object with padding on the edges
  5354. * @prop {number} width - Width of item. Must be valid after update()
  5355. * @prop {number} height - Height of item. Must be valid after update()
  5356. * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
  5357. * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
  5358. * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
  5359. * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  5360. */
  5361. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  5362. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  5363. // It is this service's responsibility of carrying out that layout.
  5364. var core_layouts = {
  5365. defaults: {},
  5366. /**
  5367. * Register a box to a chart.
  5368. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  5369. * @param {Chart} chart - the chart to use
  5370. * @param {ILayoutItem} item - the item to add to be layed out
  5371. */
  5372. addBox: function(chart, item) {
  5373. if (!chart.boxes) {
  5374. chart.boxes = [];
  5375. }
  5376. // initialize item with default values
  5377. item.fullWidth = item.fullWidth || false;
  5378. item.position = item.position || 'top';
  5379. item.weight = item.weight || 0;
  5380. chart.boxes.push(item);
  5381. },
  5382. /**
  5383. * Remove a layoutItem from a chart
  5384. * @param {Chart} chart - the chart to remove the box from
  5385. * @param {ILayoutItem} layoutItem - the item to remove from the layout
  5386. */
  5387. removeBox: function(chart, layoutItem) {
  5388. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  5389. if (index !== -1) {
  5390. chart.boxes.splice(index, 1);
  5391. }
  5392. },
  5393. /**
  5394. * Sets (or updates) options on the given `item`.
  5395. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  5396. * @param {ILayoutItem} item - the item to configure with the given options
  5397. * @param {object} options - the new item options.
  5398. */
  5399. configure: function(chart, item, options) {
  5400. var props = ['fullWidth', 'position', 'weight'];
  5401. var ilen = props.length;
  5402. var i = 0;
  5403. var prop;
  5404. for (; i < ilen; ++i) {
  5405. prop = props[i];
  5406. if (options.hasOwnProperty(prop)) {
  5407. item[prop] = options[prop];
  5408. }
  5409. }
  5410. },
  5411. /**
  5412. * Fits boxes of the given chart into the given size by having each box measure itself
  5413. * then running a fitting algorithm
  5414. * @param {Chart} chart - the chart
  5415. * @param {number} width - the width to fit into
  5416. * @param {number} height - the height to fit into
  5417. */
  5418. update: function(chart, width, height) {
  5419. if (!chart) {
  5420. return;
  5421. }
  5422. var layoutOptions = chart.options.layout || {};
  5423. var padding = helpers$1.options.toPadding(layoutOptions.padding);
  5424. var leftPadding = padding.left;
  5425. var rightPadding = padding.right;
  5426. var topPadding = padding.top;
  5427. var bottomPadding = padding.bottom;
  5428. var leftBoxes = filterByPosition(chart.boxes, 'left');
  5429. var rightBoxes = filterByPosition(chart.boxes, 'right');
  5430. var topBoxes = filterByPosition(chart.boxes, 'top');
  5431. var bottomBoxes = filterByPosition(chart.boxes, 'bottom');
  5432. var chartAreaBoxes = filterByPosition(chart.boxes, 'chartArea');
  5433. // Sort boxes by weight. A higher weight is further away from the chart area
  5434. sortByWeight(leftBoxes, true);
  5435. sortByWeight(rightBoxes, false);
  5436. sortByWeight(topBoxes, true);
  5437. sortByWeight(bottomBoxes, false);
  5438. var verticalBoxes = leftBoxes.concat(rightBoxes);
  5439. var horizontalBoxes = topBoxes.concat(bottomBoxes);
  5440. var outerBoxes = verticalBoxes.concat(horizontalBoxes);
  5441. // Essentially we now have any number of boxes on each of the 4 sides.
  5442. // Our canvas looks like the following.
  5443. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  5444. // B1 is the bottom axis
  5445. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  5446. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  5447. // an error will be thrown.
  5448. //
  5449. // |----------------------------------------------------|
  5450. // | T1 (Full Width) |
  5451. // |----------------------------------------------------|
  5452. // | | | T2 | |
  5453. // | |----|-------------------------------------|----|
  5454. // | | | C1 | | C2 | |
  5455. // | | |----| |----| |
  5456. // | | | | |
  5457. // | L1 | L2 | ChartArea (C0) | R1 |
  5458. // | | | | |
  5459. // | | |----| |----| |
  5460. // | | | C3 | | C4 | |
  5461. // | |----|-------------------------------------|----|
  5462. // | | | B1 | |
  5463. // |----------------------------------------------------|
  5464. // | B2 (Full Width) |
  5465. // |----------------------------------------------------|
  5466. //
  5467. // What we do to find the best sizing, we do the following
  5468. // 1. Determine the minimum size of the chart area.
  5469. // 2. Split the remaining width equally between each vertical axis
  5470. // 3. Split the remaining height equally between each horizontal axis
  5471. // 4. Give each layout the maximum size it can be. The layout will return it's minimum size
  5472. // 5. Adjust the sizes of each axis based on it's minimum reported size.
  5473. // 6. Refit each axis
  5474. // 7. Position each axis in the final location
  5475. // 8. Tell the chart the final location of the chart area
  5476. // 9. Tell any axes that overlay the chart area the positions of the chart area
  5477. // Step 1
  5478. var chartWidth = width - leftPadding - rightPadding;
  5479. var chartHeight = height - topPadding - bottomPadding;
  5480. var chartAreaWidth = chartWidth / 2; // min 50%
  5481. // Step 2
  5482. var verticalBoxWidth = (width - chartAreaWidth) / verticalBoxes.length;
  5483. // Step 3
  5484. // TODO re-limit horizontal axis height (this limit has affected only padding calculation since PR 1837)
  5485. // var horizontalBoxHeight = (height - chartAreaHeight) / horizontalBoxes.length;
  5486. // Step 4
  5487. var maxChartAreaWidth = chartWidth;
  5488. var maxChartAreaHeight = chartHeight;
  5489. var outerBoxSizes = {top: topPadding, left: leftPadding, bottom: bottomPadding, right: rightPadding};
  5490. var minBoxSizes = [];
  5491. var maxPadding;
  5492. function getMinimumBoxSize(box) {
  5493. var minSize;
  5494. var isHorizontal = box.isHorizontal();
  5495. if (isHorizontal) {
  5496. minSize = box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2);
  5497. maxChartAreaHeight -= minSize.height;
  5498. } else {
  5499. minSize = box.update(verticalBoxWidth, maxChartAreaHeight);
  5500. maxChartAreaWidth -= minSize.width;
  5501. }
  5502. minBoxSizes.push({
  5503. horizontal: isHorizontal,
  5504. width: minSize.width,
  5505. box: box,
  5506. });
  5507. }
  5508. helpers$1.each(outerBoxes, getMinimumBoxSize);
  5509. // If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478)
  5510. maxPadding = findMaxPadding(outerBoxes);
  5511. // At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could
  5512. // be if the axes are drawn at their minimum sizes.
  5513. // Steps 5 & 6
  5514. // Function to fit a box
  5515. function fitBox(box) {
  5516. var minBoxSize = helpers$1.findNextWhere(minBoxSizes, function(minBox) {
  5517. return minBox.box === box;
  5518. });
  5519. if (minBoxSize) {
  5520. if (minBoxSize.horizontal) {
  5521. var scaleMargin = {
  5522. left: Math.max(outerBoxSizes.left, maxPadding.left),
  5523. right: Math.max(outerBoxSizes.right, maxPadding.right),
  5524. top: 0,
  5525. bottom: 0
  5526. };
  5527. // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends
  5528. // on the margin. Sometimes they need to increase in size slightly
  5529. box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin);
  5530. } else {
  5531. box.update(minBoxSize.width, maxChartAreaHeight);
  5532. }
  5533. }
  5534. }
  5535. // Update, and calculate the left and right margins for the horizontal boxes
  5536. helpers$1.each(verticalBoxes, fitBox);
  5537. addSizeByPosition(verticalBoxes, outerBoxSizes);
  5538. // Set the Left and Right margins for the horizontal boxes
  5539. helpers$1.each(horizontalBoxes, fitBox);
  5540. addSizeByPosition(horizontalBoxes, outerBoxSizes);
  5541. function finalFitVerticalBox(box) {
  5542. var minBoxSize = helpers$1.findNextWhere(minBoxSizes, function(minSize) {
  5543. return minSize.box === box;
  5544. });
  5545. var scaleMargin = {
  5546. left: 0,
  5547. right: 0,
  5548. top: outerBoxSizes.top,
  5549. bottom: outerBoxSizes.bottom
  5550. };
  5551. if (minBoxSize) {
  5552. box.update(minBoxSize.width, maxChartAreaHeight, scaleMargin);
  5553. }
  5554. }
  5555. // Let the left layout know the final margin
  5556. helpers$1.each(verticalBoxes, finalFitVerticalBox);
  5557. // Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance)
  5558. outerBoxSizes = {top: topPadding, left: leftPadding, bottom: bottomPadding, right: rightPadding};
  5559. addSizeByPosition(outerBoxes, outerBoxSizes);
  5560. // We may be adding some padding to account for rotated x axis labels
  5561. var leftPaddingAddition = Math.max(maxPadding.left - outerBoxSizes.left, 0);
  5562. outerBoxSizes.left += leftPaddingAddition;
  5563. outerBoxSizes.right += Math.max(maxPadding.right - outerBoxSizes.right, 0);
  5564. var topPaddingAddition = Math.max(maxPadding.top - outerBoxSizes.top, 0);
  5565. outerBoxSizes.top += topPaddingAddition;
  5566. outerBoxSizes.bottom += Math.max(maxPadding.bottom - outerBoxSizes.bottom, 0);
  5567. // Figure out if our chart area changed. This would occur if the dataset layout label rotation
  5568. // changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do
  5569. // without calling `fit` again
  5570. var newMaxChartAreaHeight = height - outerBoxSizes.top - outerBoxSizes.bottom;
  5571. var newMaxChartAreaWidth = width - outerBoxSizes.left - outerBoxSizes.right;
  5572. if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) {
  5573. helpers$1.each(verticalBoxes, function(box) {
  5574. box.height = newMaxChartAreaHeight;
  5575. });
  5576. helpers$1.each(horizontalBoxes, function(box) {
  5577. if (!box.fullWidth) {
  5578. box.width = newMaxChartAreaWidth;
  5579. }
  5580. });
  5581. maxChartAreaHeight = newMaxChartAreaHeight;
  5582. maxChartAreaWidth = newMaxChartAreaWidth;
  5583. }
  5584. // Step 7 - Position the boxes
  5585. var left = leftPadding + leftPaddingAddition;
  5586. var top = topPadding + topPaddingAddition;
  5587. function placeBox(box) {
  5588. if (box.isHorizontal()) {
  5589. box.left = box.fullWidth ? leftPadding : outerBoxSizes.left;
  5590. box.right = box.fullWidth ? width - rightPadding : outerBoxSizes.left + maxChartAreaWidth;
  5591. box.top = top;
  5592. box.bottom = top + box.height;
  5593. // Move to next point
  5594. top = box.bottom;
  5595. } else {
  5596. box.left = left;
  5597. box.right = left + box.width;
  5598. box.top = outerBoxSizes.top;
  5599. box.bottom = outerBoxSizes.top + maxChartAreaHeight;
  5600. // Move to next point
  5601. left = box.right;
  5602. }
  5603. }
  5604. helpers$1.each(leftBoxes.concat(topBoxes), placeBox);
  5605. // Account for chart width and height
  5606. left += maxChartAreaWidth;
  5607. top += maxChartAreaHeight;
  5608. helpers$1.each(rightBoxes, placeBox);
  5609. helpers$1.each(bottomBoxes, placeBox);
  5610. // Step 8
  5611. chart.chartArea = {
  5612. left: outerBoxSizes.left,
  5613. top: outerBoxSizes.top,
  5614. right: outerBoxSizes.left + maxChartAreaWidth,
  5615. bottom: outerBoxSizes.top + maxChartAreaHeight
  5616. };
  5617. // Step 9
  5618. helpers$1.each(chartAreaBoxes, function(box) {
  5619. box.left = chart.chartArea.left;
  5620. box.top = chart.chartArea.top;
  5621. box.right = chart.chartArea.right;
  5622. box.bottom = chart.chartArea.bottom;
  5623. box.update(maxChartAreaWidth, maxChartAreaHeight);
  5624. });
  5625. }
  5626. };
  5627. /**
  5628. * Platform fallback implementation (minimal).
  5629. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  5630. */
  5631. var platform_basic = {
  5632. acquireContext: function(item) {
  5633. if (item && item.canvas) {
  5634. // Support for any object associated to a canvas (including a context2d)
  5635. item = item.canvas;
  5636. }
  5637. return item && item.getContext('2d') || null;
  5638. }
  5639. };
  5640. 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";
  5641. var platform_dom$1 = /*#__PURE__*/Object.freeze({
  5642. default: platform_dom
  5643. });
  5644. function getCjsExportFromNamespace (n) {
  5645. return n && n.default || n;
  5646. }
  5647. var stylesheet = getCjsExportFromNamespace(platform_dom$1);
  5648. var EXPANDO_KEY = '$chartjs';
  5649. var CSS_PREFIX = 'chartjs-';
  5650. var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';
  5651. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  5652. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  5653. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  5654. /**
  5655. * DOM event types -> Chart.js event types.
  5656. * Note: only events with different types are mapped.
  5657. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  5658. */
  5659. var EVENT_TYPES = {
  5660. touchstart: 'mousedown',
  5661. touchmove: 'mousemove',
  5662. touchend: 'mouseup',
  5663. pointerenter: 'mouseenter',
  5664. pointerdown: 'mousedown',
  5665. pointermove: 'mousemove',
  5666. pointerup: 'mouseup',
  5667. pointerleave: 'mouseout',
  5668. pointerout: 'mouseout'
  5669. };
  5670. /**
  5671. * The "used" size is the final value of a dimension property after all calculations have
  5672. * been performed. This method uses the computed style of `element` but returns undefined
  5673. * if the computed style is not expressed in pixels. That can happen in some cases where
  5674. * `element` has a size relative to its parent and this last one is not yet displayed,
  5675. * for example because of `display: none` on a parent node.
  5676. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  5677. * @returns {number} Size in pixels or undefined if unknown.
  5678. */
  5679. function readUsedSize(element, property) {
  5680. var value = helpers$1.getStyle(element, property);
  5681. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  5682. return matches ? Number(matches[1]) : undefined;
  5683. }
  5684. /**
  5685. * Initializes the canvas style and render size without modifying the canvas display size,
  5686. * since responsiveness is handled by the controller.resize() method. The config is used
  5687. * to determine the aspect ratio to apply in case no explicit height has been specified.
  5688. */
  5689. function initCanvas(canvas, config) {
  5690. var style = canvas.style;
  5691. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  5692. // returns null or '' if no explicit value has been set to the canvas attribute.
  5693. var renderHeight = canvas.getAttribute('height');
  5694. var renderWidth = canvas.getAttribute('width');
  5695. // Chart.js modifies some canvas values that we want to restore on destroy
  5696. canvas[EXPANDO_KEY] = {
  5697. initial: {
  5698. height: renderHeight,
  5699. width: renderWidth,
  5700. style: {
  5701. display: style.display,
  5702. height: style.height,
  5703. width: style.width
  5704. }
  5705. }
  5706. };
  5707. // Force canvas to display as block to avoid extra space caused by inline
  5708. // elements, which would interfere with the responsive resize process.
  5709. // https://github.com/chartjs/Chart.js/issues/2538
  5710. style.display = style.display || 'block';
  5711. if (renderWidth === null || renderWidth === '') {
  5712. var displayWidth = readUsedSize(canvas, 'width');
  5713. if (displayWidth !== undefined) {
  5714. canvas.width = displayWidth;
  5715. }
  5716. }
  5717. if (renderHeight === null || renderHeight === '') {
  5718. if (canvas.style.height === '') {
  5719. // If no explicit render height and style height, let's apply the aspect ratio,
  5720. // which one can be specified by the user but also by charts as default option
  5721. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  5722. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  5723. } else {
  5724. var displayHeight = readUsedSize(canvas, 'height');
  5725. if (displayWidth !== undefined) {
  5726. canvas.height = displayHeight;
  5727. }
  5728. }
  5729. }
  5730. return canvas;
  5731. }
  5732. /**
  5733. * Detects support for options object argument in addEventListener.
  5734. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  5735. * @private
  5736. */
  5737. var supportsEventListenerOptions = (function() {
  5738. var supports = false;
  5739. try {
  5740. var options = Object.defineProperty({}, 'passive', {
  5741. // eslint-disable-next-line getter-return
  5742. get: function() {
  5743. supports = true;
  5744. }
  5745. });
  5746. window.addEventListener('e', null, options);
  5747. } catch (e) {
  5748. // continue regardless of error
  5749. }
  5750. return supports;
  5751. }());
  5752. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  5753. // https://github.com/chartjs/Chart.js/issues/4287
  5754. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  5755. function addListener(node, type, listener) {
  5756. node.addEventListener(type, listener, eventListenerOptions);
  5757. }
  5758. function removeListener(node, type, listener) {
  5759. node.removeEventListener(type, listener, eventListenerOptions);
  5760. }
  5761. function createEvent(type, chart, x, y, nativeEvent) {
  5762. return {
  5763. type: type,
  5764. chart: chart,
  5765. native: nativeEvent || null,
  5766. x: x !== undefined ? x : null,
  5767. y: y !== undefined ? y : null,
  5768. };
  5769. }
  5770. function fromNativeEvent(event, chart) {
  5771. var type = EVENT_TYPES[event.type] || event.type;
  5772. var pos = helpers$1.getRelativePosition(event, chart);
  5773. return createEvent(type, chart, pos.x, pos.y, event);
  5774. }
  5775. function throttled(fn, thisArg) {
  5776. var ticking = false;
  5777. var args = [];
  5778. return function() {
  5779. args = Array.prototype.slice.call(arguments);
  5780. thisArg = thisArg || this;
  5781. if (!ticking) {
  5782. ticking = true;
  5783. helpers$1.requestAnimFrame.call(window, function() {
  5784. ticking = false;
  5785. fn.apply(thisArg, args);
  5786. });
  5787. }
  5788. };
  5789. }
  5790. function createDiv(cls) {
  5791. var el = document.createElement('div');
  5792. el.className = cls || '';
  5793. return el;
  5794. }
  5795. // Implementation based on https://github.com/marcj/css-element-queries
  5796. function createResizer(handler) {
  5797. var maxSize = 1000000;
  5798. // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
  5799. // https://github.com/chartjs/Chart.js/issues/5902
  5800. var resizer = createDiv(CSS_SIZE_MONITOR);
  5801. var expand = createDiv(CSS_SIZE_MONITOR + '-expand');
  5802. var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');
  5803. expand.appendChild(createDiv());
  5804. shrink.appendChild(createDiv());
  5805. resizer.appendChild(expand);
  5806. resizer.appendChild(shrink);
  5807. resizer._reset = function() {
  5808. expand.scrollLeft = maxSize;
  5809. expand.scrollTop = maxSize;
  5810. shrink.scrollLeft = maxSize;
  5811. shrink.scrollTop = maxSize;
  5812. };
  5813. var onScroll = function() {
  5814. resizer._reset();
  5815. handler();
  5816. };
  5817. addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  5818. addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  5819. return resizer;
  5820. }
  5821. // https://davidwalsh.name/detect-node-insertion
  5822. function watchForRender(node, handler) {
  5823. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  5824. var proxy = expando.renderProxy = function(e) {
  5825. if (e.animationName === CSS_RENDER_ANIMATION) {
  5826. handler();
  5827. }
  5828. };
  5829. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  5830. addListener(node, type, proxy);
  5831. });
  5832. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  5833. // is removed then added back immediately (same animation frame?). Accessing the
  5834. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  5835. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  5836. // https://github.com/chartjs/Chart.js/issues/4737
  5837. expando.reflow = !!node.offsetParent;
  5838. node.classList.add(CSS_RENDER_MONITOR);
  5839. }
  5840. function unwatchForRender(node) {
  5841. var expando = node[EXPANDO_KEY] || {};
  5842. var proxy = expando.renderProxy;
  5843. if (proxy) {
  5844. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  5845. removeListener(node, type, proxy);
  5846. });
  5847. delete expando.renderProxy;
  5848. }
  5849. node.classList.remove(CSS_RENDER_MONITOR);
  5850. }
  5851. function addResizeListener(node, listener, chart) {
  5852. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  5853. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  5854. var resizer = expando.resizer = createResizer(throttled(function() {
  5855. if (expando.resizer) {
  5856. var container = chart.options.maintainAspectRatio && node.parentNode;
  5857. var w = container ? container.clientWidth : 0;
  5858. listener(createEvent('resize', chart));
  5859. if (container && container.clientWidth < w && chart.canvas) {
  5860. // If the container size shrank during chart resize, let's assume
  5861. // scrollbar appeared. So we resize again with the scrollbar visible -
  5862. // effectively making chart smaller and the scrollbar hidden again.
  5863. // Because we are inside `throttled`, and currently `ticking`, scroll
  5864. // events are ignored during this whole 2 resize process.
  5865. // If we assumed wrong and something else happened, we are resizing
  5866. // twice in a frame (potential performance issue)
  5867. listener(createEvent('resize', chart));
  5868. }
  5869. }
  5870. }));
  5871. // The resizer needs to be attached to the node parent, so we first need to be
  5872. // sure that `node` is attached to the DOM before injecting the resizer element.
  5873. watchForRender(node, function() {
  5874. if (expando.resizer) {
  5875. var container = node.parentNode;
  5876. if (container && container !== resizer.parentNode) {
  5877. container.insertBefore(resizer, container.firstChild);
  5878. }
  5879. // The container size might have changed, let's reset the resizer state.
  5880. resizer._reset();
  5881. }
  5882. });
  5883. }
  5884. function removeResizeListener(node) {
  5885. var expando = node[EXPANDO_KEY] || {};
  5886. var resizer = expando.resizer;
  5887. delete expando.resizer;
  5888. unwatchForRender(node);
  5889. if (resizer && resizer.parentNode) {
  5890. resizer.parentNode.removeChild(resizer);
  5891. }
  5892. }
  5893. function injectCSS(platform, css) {
  5894. // https://stackoverflow.com/q/3922139
  5895. var style = platform._style || document.createElement('style');
  5896. if (!platform._style) {
  5897. platform._style = style;
  5898. css = '/* Chart.js */\n' + css;
  5899. style.setAttribute('type', 'text/css');
  5900. document.getElementsByTagName('head')[0].appendChild(style);
  5901. }
  5902. style.appendChild(document.createTextNode(css));
  5903. }
  5904. var platform_dom$2 = {
  5905. /**
  5906. * When `true`, prevents the automatic injection of the stylesheet required to
  5907. * correctly detect when the chart is added to the DOM and then resized. This
  5908. * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)
  5909. * to be manually imported to make this library compatible with any CSP.
  5910. * See https://github.com/chartjs/Chart.js/issues/5208
  5911. */
  5912. disableCSSInjection: false,
  5913. /**
  5914. * This property holds whether this platform is enabled for the current environment.
  5915. * Currently used by platform.js to select the proper implementation.
  5916. * @private
  5917. */
  5918. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  5919. /**
  5920. * @private
  5921. */
  5922. _ensureLoaded: function() {
  5923. if (this._loaded) {
  5924. return;
  5925. }
  5926. this._loaded = true;
  5927. // https://github.com/chartjs/Chart.js/issues/5208
  5928. if (!this.disableCSSInjection) {
  5929. injectCSS(this, stylesheet);
  5930. }
  5931. },
  5932. acquireContext: function(item, config) {
  5933. if (typeof item === 'string') {
  5934. item = document.getElementById(item);
  5935. } else if (item.length) {
  5936. // Support for array based queries (such as jQuery)
  5937. item = item[0];
  5938. }
  5939. if (item && item.canvas) {
  5940. // Support for any object associated to a canvas (including a context2d)
  5941. item = item.canvas;
  5942. }
  5943. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  5944. // method, for example: https://github.com/kkapsner/CanvasBlocker
  5945. // https://github.com/chartjs/Chart.js/issues/2807
  5946. var context = item && item.getContext && item.getContext('2d');
  5947. // Load platform resources on first chart creation, to make possible to change
  5948. // platform options after importing the library (e.g. `disableCSSInjection`).
  5949. this._ensureLoaded();
  5950. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  5951. // inside an iframe or when running in a protected environment. We could guess the
  5952. // types from their toString() value but let's keep things flexible and assume it's
  5953. // a sufficient condition if the item has a context2D which has item as `canvas`.
  5954. // https://github.com/chartjs/Chart.js/issues/3887
  5955. // https://github.com/chartjs/Chart.js/issues/4102
  5956. // https://github.com/chartjs/Chart.js/issues/4152
  5957. if (context && context.canvas === item) {
  5958. initCanvas(item, config);
  5959. return context;
  5960. }
  5961. return null;
  5962. },
  5963. releaseContext: function(context) {
  5964. var canvas = context.canvas;
  5965. if (!canvas[EXPANDO_KEY]) {
  5966. return;
  5967. }
  5968. var initial = canvas[EXPANDO_KEY].initial;
  5969. ['height', 'width'].forEach(function(prop) {
  5970. var value = initial[prop];
  5971. if (helpers$1.isNullOrUndef(value)) {
  5972. canvas.removeAttribute(prop);
  5973. } else {
  5974. canvas.setAttribute(prop, value);
  5975. }
  5976. });
  5977. helpers$1.each(initial.style || {}, function(value, key) {
  5978. canvas.style[key] = value;
  5979. });
  5980. // The canvas render size might have been changed (and thus the state stack discarded),
  5981. // we can't use save() and restore() to restore the initial state. So make sure that at
  5982. // least the canvas context is reset to the default state by setting the canvas width.
  5983. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  5984. // eslint-disable-next-line no-self-assign
  5985. canvas.width = canvas.width;
  5986. delete canvas[EXPANDO_KEY];
  5987. },
  5988. addEventListener: function(chart, type, listener) {
  5989. var canvas = chart.canvas;
  5990. if (type === 'resize') {
  5991. // Note: the resize event is not supported on all browsers.
  5992. addResizeListener(canvas, listener, chart);
  5993. return;
  5994. }
  5995. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  5996. var proxies = expando.proxies || (expando.proxies = {});
  5997. var proxy = proxies[chart.id + '_' + type] = function(event) {
  5998. listener(fromNativeEvent(event, chart));
  5999. };
  6000. addListener(canvas, type, proxy);
  6001. },
  6002. removeEventListener: function(chart, type, listener) {
  6003. var canvas = chart.canvas;
  6004. if (type === 'resize') {
  6005. // Note: the resize event is not supported on all browsers.
  6006. removeResizeListener(canvas);
  6007. return;
  6008. }
  6009. var expando = listener[EXPANDO_KEY] || {};
  6010. var proxies = expando.proxies || {};
  6011. var proxy = proxies[chart.id + '_' + type];
  6012. if (!proxy) {
  6013. return;
  6014. }
  6015. removeListener(canvas, type, proxy);
  6016. }
  6017. };
  6018. // DEPRECATIONS
  6019. /**
  6020. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  6021. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6022. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  6023. * @function Chart.helpers.addEvent
  6024. * @deprecated since version 2.7.0
  6025. * @todo remove at version 3
  6026. * @private
  6027. */
  6028. helpers$1.addEvent = addListener;
  6029. /**
  6030. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  6031. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6032. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  6033. * @function Chart.helpers.removeEvent
  6034. * @deprecated since version 2.7.0
  6035. * @todo remove at version 3
  6036. * @private
  6037. */
  6038. helpers$1.removeEvent = removeListener;
  6039. // @TODO Make possible to select another platform at build time.
  6040. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;
  6041. /**
  6042. * @namespace Chart.platform
  6043. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  6044. * @since 2.4.0
  6045. */
  6046. var platform = helpers$1.extend({
  6047. /**
  6048. * @since 2.7.0
  6049. */
  6050. initialize: function() {},
  6051. /**
  6052. * Called at chart construction time, returns a context2d instance implementing
  6053. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  6054. * @param {*} item - The native item from which to acquire context (platform specific)
  6055. * @param {object} options - The chart options
  6056. * @returns {CanvasRenderingContext2D} context2d instance
  6057. */
  6058. acquireContext: function() {},
  6059. /**
  6060. * Called at chart destruction time, releases any resources associated to the context
  6061. * previously returned by the acquireContext() method.
  6062. * @param {CanvasRenderingContext2D} context - The context2d instance
  6063. * @returns {boolean} true if the method succeeded, else false
  6064. */
  6065. releaseContext: function() {},
  6066. /**
  6067. * Registers the specified listener on the given chart.
  6068. * @param {Chart} chart - Chart from which to listen for event
  6069. * @param {string} type - The ({@link IEvent}) type to listen for
  6070. * @param {function} listener - Receives a notification (an object that implements
  6071. * the {@link IEvent} interface) when an event of the specified type occurs.
  6072. */
  6073. addEventListener: function() {},
  6074. /**
  6075. * Removes the specified listener previously registered with addEventListener.
  6076. * @param {Chart} chart - Chart from which to remove the listener
  6077. * @param {string} type - The ({@link IEvent}) type to remove
  6078. * @param {function} listener - The listener function to remove from the event target.
  6079. */
  6080. removeEventListener: function() {}
  6081. }, implementation);
  6082. core_defaults._set('global', {
  6083. plugins: {}
  6084. });
  6085. /**
  6086. * The plugin service singleton
  6087. * @namespace Chart.plugins
  6088. * @since 2.1.0
  6089. */
  6090. var core_plugins = {
  6091. /**
  6092. * Globally registered plugins.
  6093. * @private
  6094. */
  6095. _plugins: [],
  6096. /**
  6097. * This identifier is used to invalidate the descriptors cache attached to each chart
  6098. * when a global plugin is registered or unregistered. In this case, the cache ID is
  6099. * incremented and descriptors are regenerated during following API calls.
  6100. * @private
  6101. */
  6102. _cacheId: 0,
  6103. /**
  6104. * Registers the given plugin(s) if not already registered.
  6105. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6106. */
  6107. register: function(plugins) {
  6108. var p = this._plugins;
  6109. ([]).concat(plugins).forEach(function(plugin) {
  6110. if (p.indexOf(plugin) === -1) {
  6111. p.push(plugin);
  6112. }
  6113. });
  6114. this._cacheId++;
  6115. },
  6116. /**
  6117. * Unregisters the given plugin(s) only if registered.
  6118. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6119. */
  6120. unregister: function(plugins) {
  6121. var p = this._plugins;
  6122. ([]).concat(plugins).forEach(function(plugin) {
  6123. var idx = p.indexOf(plugin);
  6124. if (idx !== -1) {
  6125. p.splice(idx, 1);
  6126. }
  6127. });
  6128. this._cacheId++;
  6129. },
  6130. /**
  6131. * Remove all registered plugins.
  6132. * @since 2.1.5
  6133. */
  6134. clear: function() {
  6135. this._plugins = [];
  6136. this._cacheId++;
  6137. },
  6138. /**
  6139. * Returns the number of registered plugins?
  6140. * @returns {number}
  6141. * @since 2.1.5
  6142. */
  6143. count: function() {
  6144. return this._plugins.length;
  6145. },
  6146. /**
  6147. * Returns all registered plugin instances.
  6148. * @returns {IPlugin[]} array of plugin objects.
  6149. * @since 2.1.5
  6150. */
  6151. getAll: function() {
  6152. return this._plugins;
  6153. },
  6154. /**
  6155. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  6156. * This method immediately returns as soon as a plugin explicitly returns false. The
  6157. * returned value can be used, for instance, to interrupt the current action.
  6158. * @param {Chart} chart - The chart instance for which plugins should be called.
  6159. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  6160. * @param {Array} [args] - Extra arguments to apply to the hook call.
  6161. * @returns {boolean} false if any of the plugins return false, else returns true.
  6162. */
  6163. notify: function(chart, hook, args) {
  6164. var descriptors = this.descriptors(chart);
  6165. var ilen = descriptors.length;
  6166. var i, descriptor, plugin, params, method;
  6167. for (i = 0; i < ilen; ++i) {
  6168. descriptor = descriptors[i];
  6169. plugin = descriptor.plugin;
  6170. method = plugin[hook];
  6171. if (typeof method === 'function') {
  6172. params = [chart].concat(args || []);
  6173. params.push(descriptor.options);
  6174. if (method.apply(plugin, params) === false) {
  6175. return false;
  6176. }
  6177. }
  6178. }
  6179. return true;
  6180. },
  6181. /**
  6182. * Returns descriptors of enabled plugins for the given chart.
  6183. * @returns {object[]} [{ plugin, options }]
  6184. * @private
  6185. */
  6186. descriptors: function(chart) {
  6187. var cache = chart.$plugins || (chart.$plugins = {});
  6188. if (cache.id === this._cacheId) {
  6189. return cache.descriptors;
  6190. }
  6191. var plugins = [];
  6192. var descriptors = [];
  6193. var config = (chart && chart.config) || {};
  6194. var options = (config.options && config.options.plugins) || {};
  6195. this._plugins.concat(config.plugins || []).forEach(function(plugin) {
  6196. var idx = plugins.indexOf(plugin);
  6197. if (idx !== -1) {
  6198. return;
  6199. }
  6200. var id = plugin.id;
  6201. var opts = options[id];
  6202. if (opts === false) {
  6203. return;
  6204. }
  6205. if (opts === true) {
  6206. opts = helpers$1.clone(core_defaults.global.plugins[id]);
  6207. }
  6208. plugins.push(plugin);
  6209. descriptors.push({
  6210. plugin: plugin,
  6211. options: opts || {}
  6212. });
  6213. });
  6214. cache.descriptors = descriptors;
  6215. cache.id = this._cacheId;
  6216. return descriptors;
  6217. },
  6218. /**
  6219. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  6220. * but in some cases, this reference can be changed by the user when updating options.
  6221. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  6222. * @private
  6223. */
  6224. _invalidate: function(chart) {
  6225. delete chart.$plugins;
  6226. }
  6227. };
  6228. var core_scaleService = {
  6229. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  6230. // use the new chart options to grab the correct scale
  6231. constructors: {},
  6232. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  6233. // old browsers
  6234. // Scale config defaults
  6235. defaults: {},
  6236. registerScaleType: function(type, scaleConstructor, scaleDefaults) {
  6237. this.constructors[type] = scaleConstructor;
  6238. this.defaults[type] = helpers$1.clone(scaleDefaults);
  6239. },
  6240. getScaleConstructor: function(type) {
  6241. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  6242. },
  6243. getScaleDefaults: function(type) {
  6244. // Return the scale defaults merged with the global settings so that we always use the latest ones
  6245. return this.defaults.hasOwnProperty(type) ? helpers$1.merge({}, [core_defaults.scale, this.defaults[type]]) : {};
  6246. },
  6247. updateScaleDefaults: function(type, additions) {
  6248. var me = this;
  6249. if (me.defaults.hasOwnProperty(type)) {
  6250. me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
  6251. }
  6252. },
  6253. addScalesToLayout: function(chart) {
  6254. // Adds each scale to the chart.boxes array to be sized accordingly
  6255. helpers$1.each(chart.scales, function(scale) {
  6256. // Set ILayoutItem parameters for backwards compatibility
  6257. scale.fullWidth = scale.options.fullWidth;
  6258. scale.position = scale.options.position;
  6259. scale.weight = scale.options.weight;
  6260. core_layouts.addBox(chart, scale);
  6261. });
  6262. }
  6263. };
  6264. var valueOrDefault$7 = helpers$1.valueOrDefault;
  6265. core_defaults._set('global', {
  6266. tooltips: {
  6267. enabled: true,
  6268. custom: null,
  6269. mode: 'nearest',
  6270. position: 'average',
  6271. intersect: true,
  6272. backgroundColor: 'rgba(0,0,0,0.8)',
  6273. titleFontStyle: 'bold',
  6274. titleSpacing: 2,
  6275. titleMarginBottom: 6,
  6276. titleFontColor: '#fff',
  6277. titleAlign: 'left',
  6278. bodySpacing: 2,
  6279. bodyFontColor: '#fff',
  6280. bodyAlign: 'left',
  6281. footerFontStyle: 'bold',
  6282. footerSpacing: 2,
  6283. footerMarginTop: 6,
  6284. footerFontColor: '#fff',
  6285. footerAlign: 'left',
  6286. yPadding: 6,
  6287. xPadding: 6,
  6288. caretPadding: 2,
  6289. caretSize: 5,
  6290. cornerRadius: 6,
  6291. multiKeyBackground: '#fff',
  6292. displayColors: true,
  6293. borderColor: 'rgba(0,0,0,0)',
  6294. borderWidth: 0,
  6295. callbacks: {
  6296. // Args are: (tooltipItems, data)
  6297. beforeTitle: helpers$1.noop,
  6298. title: function(tooltipItems, data) {
  6299. var title = '';
  6300. var labels = data.labels;
  6301. var labelCount = labels ? labels.length : 0;
  6302. if (tooltipItems.length > 0) {
  6303. var item = tooltipItems[0];
  6304. if (item.label) {
  6305. title = item.label;
  6306. } else if (item.xLabel) {
  6307. title = item.xLabel;
  6308. } else if (labelCount > 0 && item.index < labelCount) {
  6309. title = labels[item.index];
  6310. }
  6311. }
  6312. return title;
  6313. },
  6314. afterTitle: helpers$1.noop,
  6315. // Args are: (tooltipItems, data)
  6316. beforeBody: helpers$1.noop,
  6317. // Args are: (tooltipItem, data)
  6318. beforeLabel: helpers$1.noop,
  6319. label: function(tooltipItem, data) {
  6320. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  6321. if (label) {
  6322. label += ': ';
  6323. }
  6324. if (!helpers$1.isNullOrUndef(tooltipItem.value)) {
  6325. label += tooltipItem.value;
  6326. } else {
  6327. label += tooltipItem.yLabel;
  6328. }
  6329. return label;
  6330. },
  6331. labelColor: function(tooltipItem, chart) {
  6332. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  6333. var activeElement = meta.data[tooltipItem.index];
  6334. var view = activeElement._view;
  6335. return {
  6336. borderColor: view.borderColor,
  6337. backgroundColor: view.backgroundColor
  6338. };
  6339. },
  6340. labelTextColor: function() {
  6341. return this._options.bodyFontColor;
  6342. },
  6343. afterLabel: helpers$1.noop,
  6344. // Args are: (tooltipItems, data)
  6345. afterBody: helpers$1.noop,
  6346. // Args are: (tooltipItems, data)
  6347. beforeFooter: helpers$1.noop,
  6348. footer: helpers$1.noop,
  6349. afterFooter: helpers$1.noop
  6350. }
  6351. }
  6352. });
  6353. var positioners = {
  6354. /**
  6355. * Average mode places the tooltip at the average position of the elements shown
  6356. * @function Chart.Tooltip.positioners.average
  6357. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  6358. * @returns {object} tooltip position
  6359. */
  6360. average: function(elements) {
  6361. if (!elements.length) {
  6362. return false;
  6363. }
  6364. var i, len;
  6365. var x = 0;
  6366. var y = 0;
  6367. var count = 0;
  6368. for (i = 0, len = elements.length; i < len; ++i) {
  6369. var el = elements[i];
  6370. if (el && el.hasValue()) {
  6371. var pos = el.tooltipPosition();
  6372. x += pos.x;
  6373. y += pos.y;
  6374. ++count;
  6375. }
  6376. }
  6377. return {
  6378. x: x / count,
  6379. y: y / count
  6380. };
  6381. },
  6382. /**
  6383. * Gets the tooltip position nearest of the item nearest to the event position
  6384. * @function Chart.Tooltip.positioners.nearest
  6385. * @param elements {Chart.Element[]} the tooltip elements
  6386. * @param eventPosition {object} the position of the event in canvas coordinates
  6387. * @returns {object} the tooltip position
  6388. */
  6389. nearest: function(elements, eventPosition) {
  6390. var x = eventPosition.x;
  6391. var y = eventPosition.y;
  6392. var minDistance = Number.POSITIVE_INFINITY;
  6393. var i, len, nearestElement;
  6394. for (i = 0, len = elements.length; i < len; ++i) {
  6395. var el = elements[i];
  6396. if (el && el.hasValue()) {
  6397. var center = el.getCenterPoint();
  6398. var d = helpers$1.distanceBetweenPoints(eventPosition, center);
  6399. if (d < minDistance) {
  6400. minDistance = d;
  6401. nearestElement = el;
  6402. }
  6403. }
  6404. }
  6405. if (nearestElement) {
  6406. var tp = nearestElement.tooltipPosition();
  6407. x = tp.x;
  6408. y = tp.y;
  6409. }
  6410. return {
  6411. x: x,
  6412. y: y
  6413. };
  6414. }
  6415. };
  6416. // Helper to push or concat based on if the 2nd parameter is an array or not
  6417. function pushOrConcat(base, toPush) {
  6418. if (toPush) {
  6419. if (helpers$1.isArray(toPush)) {
  6420. // base = base.concat(toPush);
  6421. Array.prototype.push.apply(base, toPush);
  6422. } else {
  6423. base.push(toPush);
  6424. }
  6425. }
  6426. return base;
  6427. }
  6428. /**
  6429. * Returns array of strings split by newline
  6430. * @param {string} value - The value to split by newline.
  6431. * @returns {string[]} value if newline present - Returned from String split() method
  6432. * @function
  6433. */
  6434. function splitNewlines(str) {
  6435. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  6436. return str.split('\n');
  6437. }
  6438. return str;
  6439. }
  6440. /**
  6441. * Private helper to create a tooltip item model
  6442. * @param element - the chart element (point, arc, bar) to create the tooltip item for
  6443. * @return new tooltip item
  6444. */
  6445. function createTooltipItem(element) {
  6446. var xScale = element._xScale;
  6447. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  6448. var index = element._index;
  6449. var datasetIndex = element._datasetIndex;
  6450. var controller = element._chart.getDatasetMeta(datasetIndex).controller;
  6451. var indexScale = controller._getIndexScale();
  6452. var valueScale = controller._getValueScale();
  6453. return {
  6454. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  6455. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  6456. label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',
  6457. value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',
  6458. index: index,
  6459. datasetIndex: datasetIndex,
  6460. x: element._model.x,
  6461. y: element._model.y
  6462. };
  6463. }
  6464. /**
  6465. * Helper to get the reset model for the tooltip
  6466. * @param tooltipOpts {object} the tooltip options
  6467. */
  6468. function getBaseModel(tooltipOpts) {
  6469. var globalDefaults = core_defaults.global;
  6470. return {
  6471. // Positioning
  6472. xPadding: tooltipOpts.xPadding,
  6473. yPadding: tooltipOpts.yPadding,
  6474. xAlign: tooltipOpts.xAlign,
  6475. yAlign: tooltipOpts.yAlign,
  6476. // Body
  6477. bodyFontColor: tooltipOpts.bodyFontColor,
  6478. _bodyFontFamily: valueOrDefault$7(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  6479. _bodyFontStyle: valueOrDefault$7(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  6480. _bodyAlign: tooltipOpts.bodyAlign,
  6481. bodyFontSize: valueOrDefault$7(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  6482. bodySpacing: tooltipOpts.bodySpacing,
  6483. // Title
  6484. titleFontColor: tooltipOpts.titleFontColor,
  6485. _titleFontFamily: valueOrDefault$7(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  6486. _titleFontStyle: valueOrDefault$7(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  6487. titleFontSize: valueOrDefault$7(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  6488. _titleAlign: tooltipOpts.titleAlign,
  6489. titleSpacing: tooltipOpts.titleSpacing,
  6490. titleMarginBottom: tooltipOpts.titleMarginBottom,
  6491. // Footer
  6492. footerFontColor: tooltipOpts.footerFontColor,
  6493. _footerFontFamily: valueOrDefault$7(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  6494. _footerFontStyle: valueOrDefault$7(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  6495. footerFontSize: valueOrDefault$7(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  6496. _footerAlign: tooltipOpts.footerAlign,
  6497. footerSpacing: tooltipOpts.footerSpacing,
  6498. footerMarginTop: tooltipOpts.footerMarginTop,
  6499. // Appearance
  6500. caretSize: tooltipOpts.caretSize,
  6501. cornerRadius: tooltipOpts.cornerRadius,
  6502. backgroundColor: tooltipOpts.backgroundColor,
  6503. opacity: 0,
  6504. legendColorBackground: tooltipOpts.multiKeyBackground,
  6505. displayColors: tooltipOpts.displayColors,
  6506. borderColor: tooltipOpts.borderColor,
  6507. borderWidth: tooltipOpts.borderWidth
  6508. };
  6509. }
  6510. /**
  6511. * Get the size of the tooltip
  6512. */
  6513. function getTooltipSize(tooltip, model) {
  6514. var ctx = tooltip._chart.ctx;
  6515. var height = model.yPadding * 2; // Tooltip Padding
  6516. var width = 0;
  6517. // Count of all lines in the body
  6518. var body = model.body;
  6519. var combinedBodyLength = body.reduce(function(count, bodyItem) {
  6520. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  6521. }, 0);
  6522. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  6523. var titleLineCount = model.title.length;
  6524. var footerLineCount = model.footer.length;
  6525. var titleFontSize = model.titleFontSize;
  6526. var bodyFontSize = model.bodyFontSize;
  6527. var footerFontSize = model.footerFontSize;
  6528. height += titleLineCount * titleFontSize; // Title Lines
  6529. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  6530. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  6531. height += combinedBodyLength * bodyFontSize; // Body Lines
  6532. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  6533. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  6534. height += footerLineCount * (footerFontSize); // Footer Lines
  6535. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  6536. // Title width
  6537. var widthPadding = 0;
  6538. var maxLineWidth = function(line) {
  6539. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  6540. };
  6541. ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  6542. helpers$1.each(model.title, maxLineWidth);
  6543. // Body width
  6544. ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  6545. helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  6546. // Body lines may include some extra width due to the color box
  6547. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  6548. helpers$1.each(body, function(bodyItem) {
  6549. helpers$1.each(bodyItem.before, maxLineWidth);
  6550. helpers$1.each(bodyItem.lines, maxLineWidth);
  6551. helpers$1.each(bodyItem.after, maxLineWidth);
  6552. });
  6553. // Reset back to 0
  6554. widthPadding = 0;
  6555. // Footer width
  6556. ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  6557. helpers$1.each(model.footer, maxLineWidth);
  6558. // Add padding
  6559. width += 2 * model.xPadding;
  6560. return {
  6561. width: width,
  6562. height: height
  6563. };
  6564. }
  6565. /**
  6566. * Helper to get the alignment of a tooltip given the size
  6567. */
  6568. function determineAlignment(tooltip, size) {
  6569. var model = tooltip._model;
  6570. var chart = tooltip._chart;
  6571. var chartArea = tooltip._chart.chartArea;
  6572. var xAlign = 'center';
  6573. var yAlign = 'center';
  6574. if (model.y < size.height) {
  6575. yAlign = 'top';
  6576. } else if (model.y > (chart.height - size.height)) {
  6577. yAlign = 'bottom';
  6578. }
  6579. var lf, rf; // functions to determine left, right alignment
  6580. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  6581. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  6582. var midX = (chartArea.left + chartArea.right) / 2;
  6583. var midY = (chartArea.top + chartArea.bottom) / 2;
  6584. if (yAlign === 'center') {
  6585. lf = function(x) {
  6586. return x <= midX;
  6587. };
  6588. rf = function(x) {
  6589. return x > midX;
  6590. };
  6591. } else {
  6592. lf = function(x) {
  6593. return x <= (size.width / 2);
  6594. };
  6595. rf = function(x) {
  6596. return x >= (chart.width - (size.width / 2));
  6597. };
  6598. }
  6599. olf = function(x) {
  6600. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  6601. };
  6602. orf = function(x) {
  6603. return x - size.width - model.caretSize - model.caretPadding < 0;
  6604. };
  6605. yf = function(y) {
  6606. return y <= midY ? 'top' : 'bottom';
  6607. };
  6608. if (lf(model.x)) {
  6609. xAlign = 'left';
  6610. // Is tooltip too wide and goes over the right side of the chart.?
  6611. if (olf(model.x)) {
  6612. xAlign = 'center';
  6613. yAlign = yf(model.y);
  6614. }
  6615. } else if (rf(model.x)) {
  6616. xAlign = 'right';
  6617. // Is tooltip too wide and goes outside left edge of canvas?
  6618. if (orf(model.x)) {
  6619. xAlign = 'center';
  6620. yAlign = yf(model.y);
  6621. }
  6622. }
  6623. var opts = tooltip._options;
  6624. return {
  6625. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  6626. yAlign: opts.yAlign ? opts.yAlign : yAlign
  6627. };
  6628. }
  6629. /**
  6630. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  6631. */
  6632. function getBackgroundPoint(vm, size, alignment, chart) {
  6633. // Background Position
  6634. var x = vm.x;
  6635. var y = vm.y;
  6636. var caretSize = vm.caretSize;
  6637. var caretPadding = vm.caretPadding;
  6638. var cornerRadius = vm.cornerRadius;
  6639. var xAlign = alignment.xAlign;
  6640. var yAlign = alignment.yAlign;
  6641. var paddingAndSize = caretSize + caretPadding;
  6642. var radiusAndPadding = cornerRadius + caretPadding;
  6643. if (xAlign === 'right') {
  6644. x -= size.width;
  6645. } else if (xAlign === 'center') {
  6646. x -= (size.width / 2);
  6647. if (x + size.width > chart.width) {
  6648. x = chart.width - size.width;
  6649. }
  6650. if (x < 0) {
  6651. x = 0;
  6652. }
  6653. }
  6654. if (yAlign === 'top') {
  6655. y += paddingAndSize;
  6656. } else if (yAlign === 'bottom') {
  6657. y -= size.height + paddingAndSize;
  6658. } else {
  6659. y -= (size.height / 2);
  6660. }
  6661. if (yAlign === 'center') {
  6662. if (xAlign === 'left') {
  6663. x += paddingAndSize;
  6664. } else if (xAlign === 'right') {
  6665. x -= paddingAndSize;
  6666. }
  6667. } else if (xAlign === 'left') {
  6668. x -= radiusAndPadding;
  6669. } else if (xAlign === 'right') {
  6670. x += radiusAndPadding;
  6671. }
  6672. return {
  6673. x: x,
  6674. y: y
  6675. };
  6676. }
  6677. function getAlignedX(vm, align) {
  6678. return align === 'center'
  6679. ? vm.x + vm.width / 2
  6680. : align === 'right'
  6681. ? vm.x + vm.width - vm.xPadding
  6682. : vm.x + vm.xPadding;
  6683. }
  6684. /**
  6685. * Helper to build before and after body lines
  6686. */
  6687. function getBeforeAfterBodyLines(callback) {
  6688. return pushOrConcat([], splitNewlines(callback));
  6689. }
  6690. var exports$3 = core_element.extend({
  6691. initialize: function() {
  6692. this._model = getBaseModel(this._options);
  6693. this._lastActive = [];
  6694. },
  6695. // Get the title
  6696. // Args are: (tooltipItem, data)
  6697. getTitle: function() {
  6698. var me = this;
  6699. var opts = me._options;
  6700. var callbacks = opts.callbacks;
  6701. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  6702. var title = callbacks.title.apply(me, arguments);
  6703. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  6704. var lines = [];
  6705. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  6706. lines = pushOrConcat(lines, splitNewlines(title));
  6707. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  6708. return lines;
  6709. },
  6710. // Args are: (tooltipItem, data)
  6711. getBeforeBody: function() {
  6712. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  6713. },
  6714. // Args are: (tooltipItem, data)
  6715. getBody: function(tooltipItems, data) {
  6716. var me = this;
  6717. var callbacks = me._options.callbacks;
  6718. var bodyItems = [];
  6719. helpers$1.each(tooltipItems, function(tooltipItem) {
  6720. var bodyItem = {
  6721. before: [],
  6722. lines: [],
  6723. after: []
  6724. };
  6725. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  6726. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  6727. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  6728. bodyItems.push(bodyItem);
  6729. });
  6730. return bodyItems;
  6731. },
  6732. // Args are: (tooltipItem, data)
  6733. getAfterBody: function() {
  6734. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  6735. },
  6736. // Get the footer and beforeFooter and afterFooter lines
  6737. // Args are: (tooltipItem, data)
  6738. getFooter: function() {
  6739. var me = this;
  6740. var callbacks = me._options.callbacks;
  6741. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  6742. var footer = callbacks.footer.apply(me, arguments);
  6743. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  6744. var lines = [];
  6745. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  6746. lines = pushOrConcat(lines, splitNewlines(footer));
  6747. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  6748. return lines;
  6749. },
  6750. update: function(changed) {
  6751. var me = this;
  6752. var opts = me._options;
  6753. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  6754. // 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
  6755. // which breaks any animations.
  6756. var existingModel = me._model;
  6757. var model = me._model = getBaseModel(opts);
  6758. var active = me._active;
  6759. var data = me._data;
  6760. // In the case where active.length === 0 we need to keep these at existing values for good animations
  6761. var alignment = {
  6762. xAlign: existingModel.xAlign,
  6763. yAlign: existingModel.yAlign
  6764. };
  6765. var backgroundPoint = {
  6766. x: existingModel.x,
  6767. y: existingModel.y
  6768. };
  6769. var tooltipSize = {
  6770. width: existingModel.width,
  6771. height: existingModel.height
  6772. };
  6773. var tooltipPosition = {
  6774. x: existingModel.caretX,
  6775. y: existingModel.caretY
  6776. };
  6777. var i, len;
  6778. if (active.length) {
  6779. model.opacity = 1;
  6780. var labelColors = [];
  6781. var labelTextColors = [];
  6782. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  6783. var tooltipItems = [];
  6784. for (i = 0, len = active.length; i < len; ++i) {
  6785. tooltipItems.push(createTooltipItem(active[i]));
  6786. }
  6787. // If the user provided a filter function, use it to modify the tooltip items
  6788. if (opts.filter) {
  6789. tooltipItems = tooltipItems.filter(function(a) {
  6790. return opts.filter(a, data);
  6791. });
  6792. }
  6793. // If the user provided a sorting function, use it to modify the tooltip items
  6794. if (opts.itemSort) {
  6795. tooltipItems = tooltipItems.sort(function(a, b) {
  6796. return opts.itemSort(a, b, data);
  6797. });
  6798. }
  6799. // Determine colors for boxes
  6800. helpers$1.each(tooltipItems, function(tooltipItem) {
  6801. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  6802. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  6803. });
  6804. // Build the Text Lines
  6805. model.title = me.getTitle(tooltipItems, data);
  6806. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  6807. model.body = me.getBody(tooltipItems, data);
  6808. model.afterBody = me.getAfterBody(tooltipItems, data);
  6809. model.footer = me.getFooter(tooltipItems, data);
  6810. // Initial positioning and colors
  6811. model.x = tooltipPosition.x;
  6812. model.y = tooltipPosition.y;
  6813. model.caretPadding = opts.caretPadding;
  6814. model.labelColors = labelColors;
  6815. model.labelTextColors = labelTextColors;
  6816. // data points
  6817. model.dataPoints = tooltipItems;
  6818. // We need to determine alignment of the tooltip
  6819. tooltipSize = getTooltipSize(this, model);
  6820. alignment = determineAlignment(this, tooltipSize);
  6821. // Final Size and Position
  6822. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  6823. } else {
  6824. model.opacity = 0;
  6825. }
  6826. model.xAlign = alignment.xAlign;
  6827. model.yAlign = alignment.yAlign;
  6828. model.x = backgroundPoint.x;
  6829. model.y = backgroundPoint.y;
  6830. model.width = tooltipSize.width;
  6831. model.height = tooltipSize.height;
  6832. // Point where the caret on the tooltip points to
  6833. model.caretX = tooltipPosition.x;
  6834. model.caretY = tooltipPosition.y;
  6835. me._model = model;
  6836. if (changed && opts.custom) {
  6837. opts.custom.call(me, model);
  6838. }
  6839. return me;
  6840. },
  6841. drawCaret: function(tooltipPoint, size) {
  6842. var ctx = this._chart.ctx;
  6843. var vm = this._view;
  6844. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  6845. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  6846. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  6847. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  6848. },
  6849. getCaretPosition: function(tooltipPoint, size, vm) {
  6850. var x1, x2, x3, y1, y2, y3;
  6851. var caretSize = vm.caretSize;
  6852. var cornerRadius = vm.cornerRadius;
  6853. var xAlign = vm.xAlign;
  6854. var yAlign = vm.yAlign;
  6855. var ptX = tooltipPoint.x;
  6856. var ptY = tooltipPoint.y;
  6857. var width = size.width;
  6858. var height = size.height;
  6859. if (yAlign === 'center') {
  6860. y2 = ptY + (height / 2);
  6861. if (xAlign === 'left') {
  6862. x1 = ptX;
  6863. x2 = x1 - caretSize;
  6864. x3 = x1;
  6865. y1 = y2 + caretSize;
  6866. y3 = y2 - caretSize;
  6867. } else {
  6868. x1 = ptX + width;
  6869. x2 = x1 + caretSize;
  6870. x3 = x1;
  6871. y1 = y2 - caretSize;
  6872. y3 = y2 + caretSize;
  6873. }
  6874. } else {
  6875. if (xAlign === 'left') {
  6876. x2 = ptX + cornerRadius + (caretSize);
  6877. x1 = x2 - caretSize;
  6878. x3 = x2 + caretSize;
  6879. } else if (xAlign === 'right') {
  6880. x2 = ptX + width - cornerRadius - caretSize;
  6881. x1 = x2 - caretSize;
  6882. x3 = x2 + caretSize;
  6883. } else {
  6884. x2 = vm.caretX;
  6885. x1 = x2 - caretSize;
  6886. x3 = x2 + caretSize;
  6887. }
  6888. if (yAlign === 'top') {
  6889. y1 = ptY;
  6890. y2 = y1 - caretSize;
  6891. y3 = y1;
  6892. } else {
  6893. y1 = ptY + height;
  6894. y2 = y1 + caretSize;
  6895. y3 = y1;
  6896. // invert drawing order
  6897. var tmp = x3;
  6898. x3 = x1;
  6899. x1 = tmp;
  6900. }
  6901. }
  6902. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  6903. },
  6904. drawTitle: function(pt, vm, ctx) {
  6905. var title = vm.title;
  6906. if (title.length) {
  6907. pt.x = getAlignedX(vm, vm._titleAlign);
  6908. ctx.textAlign = vm._titleAlign;
  6909. ctx.textBaseline = 'top';
  6910. var titleFontSize = vm.titleFontSize;
  6911. var titleSpacing = vm.titleSpacing;
  6912. ctx.fillStyle = vm.titleFontColor;
  6913. ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  6914. var i, len;
  6915. for (i = 0, len = title.length; i < len; ++i) {
  6916. ctx.fillText(title[i], pt.x, pt.y);
  6917. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  6918. if (i + 1 === title.length) {
  6919. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  6920. }
  6921. }
  6922. }
  6923. },
  6924. drawBody: function(pt, vm, ctx) {
  6925. var bodyFontSize = vm.bodyFontSize;
  6926. var bodySpacing = vm.bodySpacing;
  6927. var bodyAlign = vm._bodyAlign;
  6928. var body = vm.body;
  6929. var drawColorBoxes = vm.displayColors;
  6930. var labelColors = vm.labelColors;
  6931. var xLinePadding = 0;
  6932. var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
  6933. var textColor;
  6934. ctx.textAlign = bodyAlign;
  6935. ctx.textBaseline = 'top';
  6936. ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  6937. pt.x = getAlignedX(vm, bodyAlign);
  6938. // Before Body
  6939. var fillLineOfText = function(line) {
  6940. ctx.fillText(line, pt.x + xLinePadding, pt.y);
  6941. pt.y += bodyFontSize + bodySpacing;
  6942. };
  6943. // Before body lines
  6944. ctx.fillStyle = vm.bodyFontColor;
  6945. helpers$1.each(vm.beforeBody, fillLineOfText);
  6946. xLinePadding = drawColorBoxes && bodyAlign !== 'right'
  6947. ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
  6948. : 0;
  6949. // Draw body lines now
  6950. helpers$1.each(body, function(bodyItem, i) {
  6951. textColor = vm.labelTextColors[i];
  6952. ctx.fillStyle = textColor;
  6953. helpers$1.each(bodyItem.before, fillLineOfText);
  6954. helpers$1.each(bodyItem.lines, function(line) {
  6955. // Draw Legend-like boxes if needed
  6956. if (drawColorBoxes) {
  6957. // Fill a white rect so that colours merge nicely if the opacity is < 1
  6958. ctx.fillStyle = vm.legendColorBackground;
  6959. ctx.fillRect(colorX, pt.y, bodyFontSize, bodyFontSize);
  6960. // Border
  6961. ctx.lineWidth = 1;
  6962. ctx.strokeStyle = labelColors[i].borderColor;
  6963. ctx.strokeRect(colorX, pt.y, bodyFontSize, bodyFontSize);
  6964. // Inner square
  6965. ctx.fillStyle = labelColors[i].backgroundColor;
  6966. ctx.fillRect(colorX + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  6967. ctx.fillStyle = textColor;
  6968. }
  6969. fillLineOfText(line);
  6970. });
  6971. helpers$1.each(bodyItem.after, fillLineOfText);
  6972. });
  6973. // Reset back to 0 for after body
  6974. xLinePadding = 0;
  6975. // After body lines
  6976. helpers$1.each(vm.afterBody, fillLineOfText);
  6977. pt.y -= bodySpacing; // Remove last body spacing
  6978. },
  6979. drawFooter: function(pt, vm, ctx) {
  6980. var footer = vm.footer;
  6981. if (footer.length) {
  6982. pt.x = getAlignedX(vm, vm._footerAlign);
  6983. pt.y += vm.footerMarginTop;
  6984. ctx.textAlign = vm._footerAlign;
  6985. ctx.textBaseline = 'top';
  6986. ctx.fillStyle = vm.footerFontColor;
  6987. ctx.font = helpers$1.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  6988. helpers$1.each(footer, function(line) {
  6989. ctx.fillText(line, pt.x, pt.y);
  6990. pt.y += vm.footerFontSize + vm.footerSpacing;
  6991. });
  6992. }
  6993. },
  6994. drawBackground: function(pt, vm, ctx, tooltipSize) {
  6995. ctx.fillStyle = vm.backgroundColor;
  6996. ctx.strokeStyle = vm.borderColor;
  6997. ctx.lineWidth = vm.borderWidth;
  6998. var xAlign = vm.xAlign;
  6999. var yAlign = vm.yAlign;
  7000. var x = pt.x;
  7001. var y = pt.y;
  7002. var width = tooltipSize.width;
  7003. var height = tooltipSize.height;
  7004. var radius = vm.cornerRadius;
  7005. ctx.beginPath();
  7006. ctx.moveTo(x + radius, y);
  7007. if (yAlign === 'top') {
  7008. this.drawCaret(pt, tooltipSize);
  7009. }
  7010. ctx.lineTo(x + width - radius, y);
  7011. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  7012. if (yAlign === 'center' && xAlign === 'right') {
  7013. this.drawCaret(pt, tooltipSize);
  7014. }
  7015. ctx.lineTo(x + width, y + height - radius);
  7016. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  7017. if (yAlign === 'bottom') {
  7018. this.drawCaret(pt, tooltipSize);
  7019. }
  7020. ctx.lineTo(x + radius, y + height);
  7021. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  7022. if (yAlign === 'center' && xAlign === 'left') {
  7023. this.drawCaret(pt, tooltipSize);
  7024. }
  7025. ctx.lineTo(x, y + radius);
  7026. ctx.quadraticCurveTo(x, y, x + radius, y);
  7027. ctx.closePath();
  7028. ctx.fill();
  7029. if (vm.borderWidth > 0) {
  7030. ctx.stroke();
  7031. }
  7032. },
  7033. draw: function() {
  7034. var ctx = this._chart.ctx;
  7035. var vm = this._view;
  7036. if (vm.opacity === 0) {
  7037. return;
  7038. }
  7039. var tooltipSize = {
  7040. width: vm.width,
  7041. height: vm.height
  7042. };
  7043. var pt = {
  7044. x: vm.x,
  7045. y: vm.y
  7046. };
  7047. // IE11/Edge does not like very small opacities, so snap to 0
  7048. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  7049. // Truthy/falsey value for empty tooltip
  7050. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  7051. if (this._options.enabled && hasTooltipContent) {
  7052. ctx.save();
  7053. ctx.globalAlpha = opacity;
  7054. // Draw Background
  7055. this.drawBackground(pt, vm, ctx, tooltipSize);
  7056. // Draw Title, Body, and Footer
  7057. pt.y += vm.yPadding;
  7058. // Titles
  7059. this.drawTitle(pt, vm, ctx);
  7060. // Body
  7061. this.drawBody(pt, vm, ctx);
  7062. // Footer
  7063. this.drawFooter(pt, vm, ctx);
  7064. ctx.restore();
  7065. }
  7066. },
  7067. /**
  7068. * Handle an event
  7069. * @private
  7070. * @param {IEvent} event - The event to handle
  7071. * @returns {boolean} true if the tooltip changed
  7072. */
  7073. handleEvent: function(e) {
  7074. var me = this;
  7075. var options = me._options;
  7076. var changed = false;
  7077. me._lastActive = me._lastActive || [];
  7078. // Find Active Elements for tooltips
  7079. if (e.type === 'mouseout') {
  7080. me._active = [];
  7081. } else {
  7082. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  7083. }
  7084. // Remember Last Actives
  7085. changed = !helpers$1.arrayEquals(me._active, me._lastActive);
  7086. // Only handle target event on tooltip change
  7087. if (changed) {
  7088. me._lastActive = me._active;
  7089. if (options.enabled || options.custom) {
  7090. me._eventPosition = {
  7091. x: e.x,
  7092. y: e.y
  7093. };
  7094. me.update(true);
  7095. me.pivot();
  7096. }
  7097. }
  7098. return changed;
  7099. }
  7100. });
  7101. /**
  7102. * @namespace Chart.Tooltip.positioners
  7103. */
  7104. var positioners_1 = positioners;
  7105. var core_tooltip = exports$3;
  7106. core_tooltip.positioners = positioners_1;
  7107. var valueOrDefault$8 = helpers$1.valueOrDefault;
  7108. core_defaults._set('global', {
  7109. elements: {},
  7110. events: [
  7111. 'mousemove',
  7112. 'mouseout',
  7113. 'click',
  7114. 'touchstart',
  7115. 'touchmove'
  7116. ],
  7117. hover: {
  7118. onHover: null,
  7119. mode: 'nearest',
  7120. intersect: true,
  7121. animationDuration: 400
  7122. },
  7123. onClick: null,
  7124. maintainAspectRatio: true,
  7125. responsive: true,
  7126. responsiveAnimationDuration: 0
  7127. });
  7128. /**
  7129. * Recursively merge the given config objects representing the `scales` option
  7130. * by incorporating scale defaults in `xAxes` and `yAxes` array items, then
  7131. * returns a deep copy of the result, thus doesn't alter inputs.
  7132. */
  7133. function mergeScaleConfig(/* config objects ... */) {
  7134. return helpers$1.merge({}, [].slice.call(arguments), {
  7135. merger: function(key, target, source, options) {
  7136. if (key === 'xAxes' || key === 'yAxes') {
  7137. var slen = source[key].length;
  7138. var i, type, scale;
  7139. if (!target[key]) {
  7140. target[key] = [];
  7141. }
  7142. for (i = 0; i < slen; ++i) {
  7143. scale = source[key][i];
  7144. type = valueOrDefault$8(scale.type, key === 'xAxes' ? 'category' : 'linear');
  7145. if (i >= target[key].length) {
  7146. target[key].push({});
  7147. }
  7148. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  7149. // new/untyped scale or type changed: let's apply the new defaults
  7150. // then merge source scale to correctly overwrite the defaults.
  7151. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
  7152. } else {
  7153. // scales type are the same
  7154. helpers$1.merge(target[key][i], scale);
  7155. }
  7156. }
  7157. } else {
  7158. helpers$1._merger(key, target, source, options);
  7159. }
  7160. }
  7161. });
  7162. }
  7163. /**
  7164. * Recursively merge the given config objects as the root options by handling
  7165. * default scale options for the `scales` and `scale` properties, then returns
  7166. * a deep copy of the result, thus doesn't alter inputs.
  7167. */
  7168. function mergeConfig(/* config objects ... */) {
  7169. return helpers$1.merge({}, [].slice.call(arguments), {
  7170. merger: function(key, target, source, options) {
  7171. var tval = target[key] || {};
  7172. var sval = source[key];
  7173. if (key === 'scales') {
  7174. // scale config merging is complex. Add our own function here for that
  7175. target[key] = mergeScaleConfig(tval, sval);
  7176. } else if (key === 'scale') {
  7177. // used in polar area & radar charts since there is only one scale
  7178. target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
  7179. } else {
  7180. helpers$1._merger(key, target, source, options);
  7181. }
  7182. }
  7183. });
  7184. }
  7185. function initConfig(config) {
  7186. config = config || {};
  7187. // Do NOT use mergeConfig for the data object because this method merges arrays
  7188. // and so would change references to labels and datasets, preventing data updates.
  7189. var data = config.data = config.data || {};
  7190. data.datasets = data.datasets || [];
  7191. data.labels = data.labels || [];
  7192. config.options = mergeConfig(
  7193. core_defaults.global,
  7194. core_defaults[config.type],
  7195. config.options || {});
  7196. return config;
  7197. }
  7198. function updateConfig(chart) {
  7199. var newOptions = chart.options;
  7200. helpers$1.each(chart.scales, function(scale) {
  7201. core_layouts.removeBox(chart, scale);
  7202. });
  7203. newOptions = mergeConfig(
  7204. core_defaults.global,
  7205. core_defaults[chart.config.type],
  7206. newOptions);
  7207. chart.options = chart.config.options = newOptions;
  7208. chart.ensureScalesHaveIDs();
  7209. chart.buildOrUpdateScales();
  7210. // Tooltip
  7211. chart.tooltip._options = newOptions.tooltips;
  7212. chart.tooltip.initialize();
  7213. }
  7214. function positionIsHorizontal(position) {
  7215. return position === 'top' || position === 'bottom';
  7216. }
  7217. var Chart = function(item, config) {
  7218. this.construct(item, config);
  7219. return this;
  7220. };
  7221. helpers$1.extend(Chart.prototype, /** @lends Chart */ {
  7222. /**
  7223. * @private
  7224. */
  7225. construct: function(item, config) {
  7226. var me = this;
  7227. config = initConfig(config);
  7228. var context = platform.acquireContext(item, config);
  7229. var canvas = context && context.canvas;
  7230. var height = canvas && canvas.height;
  7231. var width = canvas && canvas.width;
  7232. me.id = helpers$1.uid();
  7233. me.ctx = context;
  7234. me.canvas = canvas;
  7235. me.config = config;
  7236. me.width = width;
  7237. me.height = height;
  7238. me.aspectRatio = height ? width / height : null;
  7239. me.options = config.options;
  7240. me._bufferedRender = false;
  7241. /**
  7242. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  7243. * the "instance" still need to be defined since it might be called from plugins.
  7244. * @prop Chart#chart
  7245. * @deprecated since version 2.6.0
  7246. * @todo remove at version 3
  7247. * @private
  7248. */
  7249. me.chart = me;
  7250. me.controller = me; // chart.chart.controller #inception
  7251. // Add the chart instance to the global namespace
  7252. Chart.instances[me.id] = me;
  7253. // Define alias to the config data: `chart.data === chart.config.data`
  7254. Object.defineProperty(me, 'data', {
  7255. get: function() {
  7256. return me.config.data;
  7257. },
  7258. set: function(value) {
  7259. me.config.data = value;
  7260. }
  7261. });
  7262. if (!context || !canvas) {
  7263. // The given item is not a compatible context2d element, let's return before finalizing
  7264. // the chart initialization but after setting basic chart / controller properties that
  7265. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  7266. // https://github.com/chartjs/Chart.js/issues/2807
  7267. console.error("Failed to create chart: can't acquire context from the given item");
  7268. return;
  7269. }
  7270. me.initialize();
  7271. me.update();
  7272. },
  7273. /**
  7274. * @private
  7275. */
  7276. initialize: function() {
  7277. var me = this;
  7278. // Before init plugin notification
  7279. core_plugins.notify(me, 'beforeInit');
  7280. helpers$1.retinaScale(me, me.options.devicePixelRatio);
  7281. me.bindEvents();
  7282. if (me.options.responsive) {
  7283. // Initial resize before chart draws (must be silent to preserve initial animations).
  7284. me.resize(true);
  7285. }
  7286. // Make sure scales have IDs and are built before we build any controllers.
  7287. me.ensureScalesHaveIDs();
  7288. me.buildOrUpdateScales();
  7289. me.initToolTip();
  7290. // After init plugin notification
  7291. core_plugins.notify(me, 'afterInit');
  7292. return me;
  7293. },
  7294. clear: function() {
  7295. helpers$1.canvas.clear(this);
  7296. return this;
  7297. },
  7298. stop: function() {
  7299. // Stops any current animation loop occurring
  7300. core_animations.cancelAnimation(this);
  7301. return this;
  7302. },
  7303. resize: function(silent) {
  7304. var me = this;
  7305. var options = me.options;
  7306. var canvas = me.canvas;
  7307. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  7308. // the canvas render width and height will be casted to integers so make sure that
  7309. // the canvas display style uses the same integer values to avoid blurring effect.
  7310. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  7311. var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
  7312. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
  7313. if (me.width === newWidth && me.height === newHeight) {
  7314. return;
  7315. }
  7316. canvas.width = me.width = newWidth;
  7317. canvas.height = me.height = newHeight;
  7318. canvas.style.width = newWidth + 'px';
  7319. canvas.style.height = newHeight + 'px';
  7320. helpers$1.retinaScale(me, options.devicePixelRatio);
  7321. if (!silent) {
  7322. // Notify any plugins about the resize
  7323. var newSize = {width: newWidth, height: newHeight};
  7324. core_plugins.notify(me, 'resize', [newSize]);
  7325. // Notify of resize
  7326. if (options.onResize) {
  7327. options.onResize(me, newSize);
  7328. }
  7329. me.stop();
  7330. me.update({
  7331. duration: options.responsiveAnimationDuration
  7332. });
  7333. }
  7334. },
  7335. ensureScalesHaveIDs: function() {
  7336. var options = this.options;
  7337. var scalesOptions = options.scales || {};
  7338. var scaleOptions = options.scale;
  7339. helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {
  7340. xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index);
  7341. });
  7342. helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {
  7343. yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index);
  7344. });
  7345. if (scaleOptions) {
  7346. scaleOptions.id = scaleOptions.id || 'scale';
  7347. }
  7348. },
  7349. /**
  7350. * Builds a map of scale ID to scale object for future lookup.
  7351. */
  7352. buildOrUpdateScales: function() {
  7353. var me = this;
  7354. var options = me.options;
  7355. var scales = me.scales || {};
  7356. var items = [];
  7357. var updated = Object.keys(scales).reduce(function(obj, id) {
  7358. obj[id] = false;
  7359. return obj;
  7360. }, {});
  7361. if (options.scales) {
  7362. items = items.concat(
  7363. (options.scales.xAxes || []).map(function(xAxisOptions) {
  7364. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  7365. }),
  7366. (options.scales.yAxes || []).map(function(yAxisOptions) {
  7367. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  7368. })
  7369. );
  7370. }
  7371. if (options.scale) {
  7372. items.push({
  7373. options: options.scale,
  7374. dtype: 'radialLinear',
  7375. isDefault: true,
  7376. dposition: 'chartArea'
  7377. });
  7378. }
  7379. helpers$1.each(items, function(item) {
  7380. var scaleOptions = item.options;
  7381. var id = scaleOptions.id;
  7382. var scaleType = valueOrDefault$8(scaleOptions.type, item.dtype);
  7383. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  7384. scaleOptions.position = item.dposition;
  7385. }
  7386. updated[id] = true;
  7387. var scale = null;
  7388. if (id in scales && scales[id].type === scaleType) {
  7389. scale = scales[id];
  7390. scale.options = scaleOptions;
  7391. scale.ctx = me.ctx;
  7392. scale.chart = me;
  7393. } else {
  7394. var scaleClass = core_scaleService.getScaleConstructor(scaleType);
  7395. if (!scaleClass) {
  7396. return;
  7397. }
  7398. scale = new scaleClass({
  7399. id: id,
  7400. type: scaleType,
  7401. options: scaleOptions,
  7402. ctx: me.ctx,
  7403. chart: me
  7404. });
  7405. scales[scale.id] = scale;
  7406. }
  7407. scale.mergeTicksOptions();
  7408. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  7409. // and consider it as a regular scale part of the "scales"" map only! This would
  7410. // make the logic easier and remove some useless? custom code.
  7411. if (item.isDefault) {
  7412. me.scale = scale;
  7413. }
  7414. });
  7415. // clear up discarded scales
  7416. helpers$1.each(updated, function(hasUpdated, id) {
  7417. if (!hasUpdated) {
  7418. delete scales[id];
  7419. }
  7420. });
  7421. me.scales = scales;
  7422. core_scaleService.addScalesToLayout(this);
  7423. },
  7424. buildOrUpdateControllers: function() {
  7425. var me = this;
  7426. var newControllers = [];
  7427. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  7428. var meta = me.getDatasetMeta(datasetIndex);
  7429. var type = dataset.type || me.config.type;
  7430. if (meta.type && meta.type !== type) {
  7431. me.destroyDatasetMeta(datasetIndex);
  7432. meta = me.getDatasetMeta(datasetIndex);
  7433. }
  7434. meta.type = type;
  7435. if (meta.controller) {
  7436. meta.controller.updateIndex(datasetIndex);
  7437. meta.controller.linkScales();
  7438. } else {
  7439. var ControllerClass = controllers[meta.type];
  7440. if (ControllerClass === undefined) {
  7441. throw new Error('"' + meta.type + '" is not a chart type.');
  7442. }
  7443. meta.controller = new ControllerClass(me, datasetIndex);
  7444. newControllers.push(meta.controller);
  7445. }
  7446. }, me);
  7447. return newControllers;
  7448. },
  7449. /**
  7450. * Reset the elements of all datasets
  7451. * @private
  7452. */
  7453. resetElements: function() {
  7454. var me = this;
  7455. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  7456. me.getDatasetMeta(datasetIndex).controller.reset();
  7457. }, me);
  7458. },
  7459. /**
  7460. * Resets the chart back to it's state before the initial animation
  7461. */
  7462. reset: function() {
  7463. this.resetElements();
  7464. this.tooltip.initialize();
  7465. },
  7466. update: function(config) {
  7467. var me = this;
  7468. if (!config || typeof config !== 'object') {
  7469. // backwards compatibility
  7470. config = {
  7471. duration: config,
  7472. lazy: arguments[1]
  7473. };
  7474. }
  7475. updateConfig(me);
  7476. // plugins options references might have change, let's invalidate the cache
  7477. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  7478. core_plugins._invalidate(me);
  7479. if (core_plugins.notify(me, 'beforeUpdate') === false) {
  7480. return;
  7481. }
  7482. // In case the entire data object changed
  7483. me.tooltip._data = me.data;
  7484. // Make sure dataset controllers are updated and new controllers are reset
  7485. var newControllers = me.buildOrUpdateControllers();
  7486. // Make sure all dataset controllers have correct meta data counts
  7487. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  7488. me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements();
  7489. }, me);
  7490. me.updateLayout();
  7491. // Can only reset the new controllers after the scales have been updated
  7492. if (me.options.animation && me.options.animation.duration) {
  7493. helpers$1.each(newControllers, function(controller) {
  7494. controller.reset();
  7495. });
  7496. }
  7497. me.updateDatasets();
  7498. // Need to reset tooltip in case it is displayed with elements that are removed
  7499. // after update.
  7500. me.tooltip.initialize();
  7501. // Last active contains items that were previously in the tooltip.
  7502. // When we reset the tooltip, we need to clear it
  7503. me.lastActive = [];
  7504. // Do this before render so that any plugins that need final scale updates can use it
  7505. core_plugins.notify(me, 'afterUpdate');
  7506. if (me._bufferedRender) {
  7507. me._bufferedRequest = {
  7508. duration: config.duration,
  7509. easing: config.easing,
  7510. lazy: config.lazy
  7511. };
  7512. } else {
  7513. me.render(config);
  7514. }
  7515. },
  7516. /**
  7517. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  7518. * hook, in which case, plugins will not be called on `afterLayout`.
  7519. * @private
  7520. */
  7521. updateLayout: function() {
  7522. var me = this;
  7523. if (core_plugins.notify(me, 'beforeLayout') === false) {
  7524. return;
  7525. }
  7526. core_layouts.update(this, this.width, this.height);
  7527. /**
  7528. * Provided for backward compatibility, use `afterLayout` instead.
  7529. * @method IPlugin#afterScaleUpdate
  7530. * @deprecated since version 2.5.0
  7531. * @todo remove at version 3
  7532. * @private
  7533. */
  7534. core_plugins.notify(me, 'afterScaleUpdate');
  7535. core_plugins.notify(me, 'afterLayout');
  7536. },
  7537. /**
  7538. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  7539. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  7540. * @private
  7541. */
  7542. updateDatasets: function() {
  7543. var me = this;
  7544. if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  7545. return;
  7546. }
  7547. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  7548. me.updateDataset(i);
  7549. }
  7550. core_plugins.notify(me, 'afterDatasetsUpdate');
  7551. },
  7552. /**
  7553. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  7554. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  7555. * @private
  7556. */
  7557. updateDataset: function(index) {
  7558. var me = this;
  7559. var meta = me.getDatasetMeta(index);
  7560. var args = {
  7561. meta: meta,
  7562. index: index
  7563. };
  7564. if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  7565. return;
  7566. }
  7567. meta.controller.update();
  7568. core_plugins.notify(me, 'afterDatasetUpdate', [args]);
  7569. },
  7570. render: function(config) {
  7571. var me = this;
  7572. if (!config || typeof config !== 'object') {
  7573. // backwards compatibility
  7574. config = {
  7575. duration: config,
  7576. lazy: arguments[1]
  7577. };
  7578. }
  7579. var animationOptions = me.options.animation;
  7580. var duration = valueOrDefault$8(config.duration, animationOptions && animationOptions.duration);
  7581. var lazy = config.lazy;
  7582. if (core_plugins.notify(me, 'beforeRender') === false) {
  7583. return;
  7584. }
  7585. var onComplete = function(animation) {
  7586. core_plugins.notify(me, 'afterRender');
  7587. helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
  7588. };
  7589. if (animationOptions && duration) {
  7590. var animation = new core_animation({
  7591. numSteps: duration / 16.66, // 60 fps
  7592. easing: config.easing || animationOptions.easing,
  7593. render: function(chart, animationObject) {
  7594. var easingFunction = helpers$1.easing.effects[animationObject.easing];
  7595. var currentStep = animationObject.currentStep;
  7596. var stepDecimal = currentStep / animationObject.numSteps;
  7597. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  7598. },
  7599. onAnimationProgress: animationOptions.onProgress,
  7600. onAnimationComplete: onComplete
  7601. });
  7602. core_animations.addAnimation(me, animation, duration, lazy);
  7603. } else {
  7604. me.draw();
  7605. // See https://github.com/chartjs/Chart.js/issues/3781
  7606. onComplete(new core_animation({numSteps: 0, chart: me}));
  7607. }
  7608. return me;
  7609. },
  7610. draw: function(easingValue) {
  7611. var me = this;
  7612. me.clear();
  7613. if (helpers$1.isNullOrUndef(easingValue)) {
  7614. easingValue = 1;
  7615. }
  7616. me.transition(easingValue);
  7617. if (me.width <= 0 || me.height <= 0) {
  7618. return;
  7619. }
  7620. if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  7621. return;
  7622. }
  7623. // Draw all the scales
  7624. helpers$1.each(me.boxes, function(box) {
  7625. box.draw(me.chartArea);
  7626. }, me);
  7627. me.drawDatasets(easingValue);
  7628. me._drawTooltip(easingValue);
  7629. core_plugins.notify(me, 'afterDraw', [easingValue]);
  7630. },
  7631. /**
  7632. * @private
  7633. */
  7634. transition: function(easingValue) {
  7635. var me = this;
  7636. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  7637. if (me.isDatasetVisible(i)) {
  7638. me.getDatasetMeta(i).controller.transition(easingValue);
  7639. }
  7640. }
  7641. me.tooltip.transition(easingValue);
  7642. },
  7643. /**
  7644. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  7645. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  7646. * @private
  7647. */
  7648. drawDatasets: function(easingValue) {
  7649. var me = this;
  7650. if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  7651. return;
  7652. }
  7653. // Draw datasets reversed to support proper line stacking
  7654. for (var i = (me.data.datasets || []).length - 1; i >= 0; --i) {
  7655. if (me.isDatasetVisible(i)) {
  7656. me.drawDataset(i, easingValue);
  7657. }
  7658. }
  7659. core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  7660. },
  7661. /**
  7662. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  7663. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  7664. * @private
  7665. */
  7666. drawDataset: function(index, easingValue) {
  7667. var me = this;
  7668. var meta = me.getDatasetMeta(index);
  7669. var args = {
  7670. meta: meta,
  7671. index: index,
  7672. easingValue: easingValue
  7673. };
  7674. if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  7675. return;
  7676. }
  7677. meta.controller.draw(easingValue);
  7678. core_plugins.notify(me, 'afterDatasetDraw', [args]);
  7679. },
  7680. /**
  7681. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  7682. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  7683. * @private
  7684. */
  7685. _drawTooltip: function(easingValue) {
  7686. var me = this;
  7687. var tooltip = me.tooltip;
  7688. var args = {
  7689. tooltip: tooltip,
  7690. easingValue: easingValue
  7691. };
  7692. if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  7693. return;
  7694. }
  7695. tooltip.draw();
  7696. core_plugins.notify(me, 'afterTooltipDraw', [args]);
  7697. },
  7698. /**
  7699. * Get the single element that was clicked on
  7700. * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  7701. */
  7702. getElementAtEvent: function(e) {
  7703. return core_interaction.modes.single(this, e);
  7704. },
  7705. getElementsAtEvent: function(e) {
  7706. return core_interaction.modes.label(this, e, {intersect: true});
  7707. },
  7708. getElementsAtXAxis: function(e) {
  7709. return core_interaction.modes['x-axis'](this, e, {intersect: true});
  7710. },
  7711. getElementsAtEventForMode: function(e, mode, options) {
  7712. var method = core_interaction.modes[mode];
  7713. if (typeof method === 'function') {
  7714. return method(this, e, options);
  7715. }
  7716. return [];
  7717. },
  7718. getDatasetAtEvent: function(e) {
  7719. return core_interaction.modes.dataset(this, e, {intersect: true});
  7720. },
  7721. getDatasetMeta: function(datasetIndex) {
  7722. var me = this;
  7723. var dataset = me.data.datasets[datasetIndex];
  7724. if (!dataset._meta) {
  7725. dataset._meta = {};
  7726. }
  7727. var meta = dataset._meta[me.id];
  7728. if (!meta) {
  7729. meta = dataset._meta[me.id] = {
  7730. type: null,
  7731. data: [],
  7732. dataset: null,
  7733. controller: null,
  7734. hidden: null, // See isDatasetVisible() comment
  7735. xAxisID: null,
  7736. yAxisID: null
  7737. };
  7738. }
  7739. return meta;
  7740. },
  7741. getVisibleDatasetCount: function() {
  7742. var count = 0;
  7743. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  7744. if (this.isDatasetVisible(i)) {
  7745. count++;
  7746. }
  7747. }
  7748. return count;
  7749. },
  7750. isDatasetVisible: function(datasetIndex) {
  7751. var meta = this.getDatasetMeta(datasetIndex);
  7752. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  7753. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  7754. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  7755. },
  7756. generateLegend: function() {
  7757. return this.options.legendCallback(this);
  7758. },
  7759. /**
  7760. * @private
  7761. */
  7762. destroyDatasetMeta: function(datasetIndex) {
  7763. var id = this.id;
  7764. var dataset = this.data.datasets[datasetIndex];
  7765. var meta = dataset._meta && dataset._meta[id];
  7766. if (meta) {
  7767. meta.controller.destroy();
  7768. delete dataset._meta[id];
  7769. }
  7770. },
  7771. destroy: function() {
  7772. var me = this;
  7773. var canvas = me.canvas;
  7774. var i, ilen;
  7775. me.stop();
  7776. // dataset controllers need to cleanup associated data
  7777. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  7778. me.destroyDatasetMeta(i);
  7779. }
  7780. if (canvas) {
  7781. me.unbindEvents();
  7782. helpers$1.canvas.clear(me);
  7783. platform.releaseContext(me.ctx);
  7784. me.canvas = null;
  7785. me.ctx = null;
  7786. }
  7787. core_plugins.notify(me, 'destroy');
  7788. delete Chart.instances[me.id];
  7789. },
  7790. toBase64Image: function() {
  7791. return this.canvas.toDataURL.apply(this.canvas, arguments);
  7792. },
  7793. initToolTip: function() {
  7794. var me = this;
  7795. me.tooltip = new core_tooltip({
  7796. _chart: me,
  7797. _chartInstance: me, // deprecated, backward compatibility
  7798. _data: me.data,
  7799. _options: me.options.tooltips
  7800. }, me);
  7801. },
  7802. /**
  7803. * @private
  7804. */
  7805. bindEvents: function() {
  7806. var me = this;
  7807. var listeners = me._listeners = {};
  7808. var listener = function() {
  7809. me.eventHandler.apply(me, arguments);
  7810. };
  7811. helpers$1.each(me.options.events, function(type) {
  7812. platform.addEventListener(me, type, listener);
  7813. listeners[type] = listener;
  7814. });
  7815. // Elements used to detect size change should not be injected for non responsive charts.
  7816. // See https://github.com/chartjs/Chart.js/issues/2210
  7817. if (me.options.responsive) {
  7818. listener = function() {
  7819. me.resize();
  7820. };
  7821. platform.addEventListener(me, 'resize', listener);
  7822. listeners.resize = listener;
  7823. }
  7824. },
  7825. /**
  7826. * @private
  7827. */
  7828. unbindEvents: function() {
  7829. var me = this;
  7830. var listeners = me._listeners;
  7831. if (!listeners) {
  7832. return;
  7833. }
  7834. delete me._listeners;
  7835. helpers$1.each(listeners, function(listener, type) {
  7836. platform.removeEventListener(me, type, listener);
  7837. });
  7838. },
  7839. updateHoverStyle: function(elements, mode, enabled) {
  7840. var method = enabled ? 'setHoverStyle' : 'removeHoverStyle';
  7841. var element, i, ilen;
  7842. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  7843. element = elements[i];
  7844. if (element) {
  7845. this.getDatasetMeta(element._datasetIndex).controller[method](element);
  7846. }
  7847. }
  7848. },
  7849. /**
  7850. * @private
  7851. */
  7852. eventHandler: function(e) {
  7853. var me = this;
  7854. var tooltip = me.tooltip;
  7855. if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
  7856. return;
  7857. }
  7858. // Buffer any update calls so that renders do not occur
  7859. me._bufferedRender = true;
  7860. me._bufferedRequest = null;
  7861. var changed = me.handleEvent(e);
  7862. // for smooth tooltip animations issue #4989
  7863. // the tooltip should be the source of change
  7864. // Animation check workaround:
  7865. // tooltip._start will be null when tooltip isn't animating
  7866. if (tooltip) {
  7867. changed = tooltip._start
  7868. ? tooltip.handleEvent(e)
  7869. : changed | tooltip.handleEvent(e);
  7870. }
  7871. core_plugins.notify(me, 'afterEvent', [e]);
  7872. var bufferedRequest = me._bufferedRequest;
  7873. if (bufferedRequest) {
  7874. // If we have an update that was triggered, we need to do a normal render
  7875. me.render(bufferedRequest);
  7876. } else if (changed && !me.animating) {
  7877. // If entering, leaving, or changing elements, animate the change via pivot
  7878. me.stop();
  7879. // We only need to render at this point. Updating will cause scales to be
  7880. // recomputed generating flicker & using more memory than necessary.
  7881. me.render({
  7882. duration: me.options.hover.animationDuration,
  7883. lazy: true
  7884. });
  7885. }
  7886. me._bufferedRender = false;
  7887. me._bufferedRequest = null;
  7888. return me;
  7889. },
  7890. /**
  7891. * Handle an event
  7892. * @private
  7893. * @param {IEvent} event the event to handle
  7894. * @return {boolean} true if the chart needs to re-render
  7895. */
  7896. handleEvent: function(e) {
  7897. var me = this;
  7898. var options = me.options || {};
  7899. var hoverOptions = options.hover;
  7900. var changed = false;
  7901. me.lastActive = me.lastActive || [];
  7902. // Find Active Elements for hover and tooltips
  7903. if (e.type === 'mouseout') {
  7904. me.active = [];
  7905. } else {
  7906. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  7907. }
  7908. // Invoke onHover hook
  7909. // Need to call with native event here to not break backwards compatibility
  7910. helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  7911. if (e.type === 'mouseup' || e.type === 'click') {
  7912. if (options.onClick) {
  7913. // Use e.native here for backwards compatibility
  7914. options.onClick.call(me, e.native, me.active);
  7915. }
  7916. }
  7917. // Remove styling for last active (even if it may still be active)
  7918. if (me.lastActive.length) {
  7919. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  7920. }
  7921. // Built in hover styling
  7922. if (me.active.length && hoverOptions.mode) {
  7923. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  7924. }
  7925. changed = !helpers$1.arrayEquals(me.active, me.lastActive);
  7926. // Remember Last Actives
  7927. me.lastActive = me.active;
  7928. return changed;
  7929. }
  7930. });
  7931. /**
  7932. * NOTE(SB) We actually don't use this container anymore but we need to keep it
  7933. * for backward compatibility. Though, it can still be useful for plugins that
  7934. * would need to work on multiple charts?!
  7935. */
  7936. Chart.instances = {};
  7937. var core_controller = Chart;
  7938. // DEPRECATIONS
  7939. /**
  7940. * Provided for backward compatibility, use Chart instead.
  7941. * @class Chart.Controller
  7942. * @deprecated since version 2.6
  7943. * @todo remove at version 3
  7944. * @private
  7945. */
  7946. Chart.Controller = Chart;
  7947. /**
  7948. * Provided for backward compatibility, not available anymore.
  7949. * @namespace Chart
  7950. * @deprecated since version 2.8
  7951. * @todo remove at version 3
  7952. * @private
  7953. */
  7954. Chart.types = {};
  7955. /**
  7956. * Provided for backward compatibility, not available anymore.
  7957. * @namespace Chart.helpers.configMerge
  7958. * @deprecated since version 2.8.0
  7959. * @todo remove at version 3
  7960. * @private
  7961. */
  7962. helpers$1.configMerge = mergeConfig;
  7963. /**
  7964. * Provided for backward compatibility, not available anymore.
  7965. * @namespace Chart.helpers.scaleMerge
  7966. * @deprecated since version 2.8.0
  7967. * @todo remove at version 3
  7968. * @private
  7969. */
  7970. helpers$1.scaleMerge = mergeScaleConfig;
  7971. var core_helpers = function() {
  7972. // -- Basic js utility methods
  7973. helpers$1.where = function(collection, filterCallback) {
  7974. if (helpers$1.isArray(collection) && Array.prototype.filter) {
  7975. return collection.filter(filterCallback);
  7976. }
  7977. var filtered = [];
  7978. helpers$1.each(collection, function(item) {
  7979. if (filterCallback(item)) {
  7980. filtered.push(item);
  7981. }
  7982. });
  7983. return filtered;
  7984. };
  7985. helpers$1.findIndex = Array.prototype.findIndex ?
  7986. function(array, callback, scope) {
  7987. return array.findIndex(callback, scope);
  7988. } :
  7989. function(array, callback, scope) {
  7990. scope = scope === undefined ? array : scope;
  7991. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  7992. if (callback.call(scope, array[i], i, array)) {
  7993. return i;
  7994. }
  7995. }
  7996. return -1;
  7997. };
  7998. helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
  7999. // Default to start of the array
  8000. if (helpers$1.isNullOrUndef(startIndex)) {
  8001. startIndex = -1;
  8002. }
  8003. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  8004. var currentItem = arrayToSearch[i];
  8005. if (filterCallback(currentItem)) {
  8006. return currentItem;
  8007. }
  8008. }
  8009. };
  8010. helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
  8011. // Default to end of the array
  8012. if (helpers$1.isNullOrUndef(startIndex)) {
  8013. startIndex = arrayToSearch.length;
  8014. }
  8015. for (var i = startIndex - 1; i >= 0; i--) {
  8016. var currentItem = arrayToSearch[i];
  8017. if (filterCallback(currentItem)) {
  8018. return currentItem;
  8019. }
  8020. }
  8021. };
  8022. // -- Math methods
  8023. helpers$1.isNumber = function(n) {
  8024. return !isNaN(parseFloat(n)) && isFinite(n);
  8025. };
  8026. helpers$1.almostEquals = function(x, y, epsilon) {
  8027. return Math.abs(x - y) < epsilon;
  8028. };
  8029. helpers$1.almostWhole = function(x, epsilon) {
  8030. var rounded = Math.round(x);
  8031. return (((rounded - epsilon) < x) && ((rounded + epsilon) > x));
  8032. };
  8033. helpers$1.max = function(array) {
  8034. return array.reduce(function(max, value) {
  8035. if (!isNaN(value)) {
  8036. return Math.max(max, value);
  8037. }
  8038. return max;
  8039. }, Number.NEGATIVE_INFINITY);
  8040. };
  8041. helpers$1.min = function(array) {
  8042. return array.reduce(function(min, value) {
  8043. if (!isNaN(value)) {
  8044. return Math.min(min, value);
  8045. }
  8046. return min;
  8047. }, Number.POSITIVE_INFINITY);
  8048. };
  8049. helpers$1.sign = Math.sign ?
  8050. function(x) {
  8051. return Math.sign(x);
  8052. } :
  8053. function(x) {
  8054. x = +x; // convert to a number
  8055. if (x === 0 || isNaN(x)) {
  8056. return x;
  8057. }
  8058. return x > 0 ? 1 : -1;
  8059. };
  8060. helpers$1.log10 = Math.log10 ?
  8061. function(x) {
  8062. return Math.log10(x);
  8063. } :
  8064. function(x) {
  8065. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  8066. // Check for whole powers of 10,
  8067. // which due to floating point rounding error should be corrected.
  8068. var powerOf10 = Math.round(exponent);
  8069. var isPowerOf10 = x === Math.pow(10, powerOf10);
  8070. return isPowerOf10 ? powerOf10 : exponent;
  8071. };
  8072. helpers$1.toRadians = function(degrees) {
  8073. return degrees * (Math.PI / 180);
  8074. };
  8075. helpers$1.toDegrees = function(radians) {
  8076. return radians * (180 / Math.PI);
  8077. };
  8078. /**
  8079. * Returns the number of decimal places
  8080. * i.e. the number of digits after the decimal point, of the value of this Number.
  8081. * @param {number} x - A number.
  8082. * @returns {number} The number of decimal places.
  8083. * @private
  8084. */
  8085. helpers$1._decimalPlaces = function(x) {
  8086. if (!helpers$1.isFinite(x)) {
  8087. return;
  8088. }
  8089. var e = 1;
  8090. var p = 0;
  8091. while (Math.round(x * e) / e !== x) {
  8092. e *= 10;
  8093. p++;
  8094. }
  8095. return p;
  8096. };
  8097. // Gets the angle from vertical upright to the point about a centre.
  8098. helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {
  8099. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  8100. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  8101. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  8102. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  8103. if (angle < (-0.5 * Math.PI)) {
  8104. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  8105. }
  8106. return {
  8107. angle: angle,
  8108. distance: radialDistanceFromCenter
  8109. };
  8110. };
  8111. helpers$1.distanceBetweenPoints = function(pt1, pt2) {
  8112. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  8113. };
  8114. /**
  8115. * Provided for backward compatibility, not available anymore
  8116. * @function Chart.helpers.aliasPixel
  8117. * @deprecated since version 2.8.0
  8118. * @todo remove at version 3
  8119. */
  8120. helpers$1.aliasPixel = function(pixelWidth) {
  8121. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  8122. };
  8123. /**
  8124. * Returns the aligned pixel value to avoid anti-aliasing blur
  8125. * @param {Chart} chart - The chart instance.
  8126. * @param {number} pixel - A pixel value.
  8127. * @param {number} width - The width of the element.
  8128. * @returns {number} The aligned pixel value.
  8129. * @private
  8130. */
  8131. helpers$1._alignPixel = function(chart, pixel, width) {
  8132. var devicePixelRatio = chart.currentDevicePixelRatio;
  8133. var halfWidth = width / 2;
  8134. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  8135. };
  8136. helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
  8137. // Props to Rob Spencer at scaled innovation for his post on splining between points
  8138. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  8139. // This function must also respect "skipped" points
  8140. var previous = firstPoint.skip ? middlePoint : firstPoint;
  8141. var current = middlePoint;
  8142. var next = afterPoint.skip ? middlePoint : afterPoint;
  8143. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  8144. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  8145. var s01 = d01 / (d01 + d12);
  8146. var s12 = d12 / (d01 + d12);
  8147. // If all points are the same, s01 & s02 will be inf
  8148. s01 = isNaN(s01) ? 0 : s01;
  8149. s12 = isNaN(s12) ? 0 : s12;
  8150. var fa = t * s01; // scaling factor for triangle Ta
  8151. var fb = t * s12;
  8152. return {
  8153. previous: {
  8154. x: current.x - fa * (next.x - previous.x),
  8155. y: current.y - fa * (next.y - previous.y)
  8156. },
  8157. next: {
  8158. x: current.x + fb * (next.x - previous.x),
  8159. y: current.y + fb * (next.y - previous.y)
  8160. }
  8161. };
  8162. };
  8163. helpers$1.EPSILON = Number.EPSILON || 1e-14;
  8164. helpers$1.splineCurveMonotone = function(points) {
  8165. // This function calculates Bézier control points in a similar way than |splineCurve|,
  8166. // but preserves monotonicity of the provided data and ensures no local extremums are added
  8167. // between the dataset discrete points due to the interpolation.
  8168. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  8169. var pointsWithTangents = (points || []).map(function(point) {
  8170. return {
  8171. model: point._model,
  8172. deltaK: 0,
  8173. mK: 0
  8174. };
  8175. });
  8176. // Calculate slopes (deltaK) and initialize tangents (mK)
  8177. var pointsLen = pointsWithTangents.length;
  8178. var i, pointBefore, pointCurrent, pointAfter;
  8179. for (i = 0; i < pointsLen; ++i) {
  8180. pointCurrent = pointsWithTangents[i];
  8181. if (pointCurrent.model.skip) {
  8182. continue;
  8183. }
  8184. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8185. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8186. if (pointAfter && !pointAfter.model.skip) {
  8187. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  8188. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  8189. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  8190. }
  8191. if (!pointBefore || pointBefore.model.skip) {
  8192. pointCurrent.mK = pointCurrent.deltaK;
  8193. } else if (!pointAfter || pointAfter.model.skip) {
  8194. pointCurrent.mK = pointBefore.deltaK;
  8195. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  8196. pointCurrent.mK = 0;
  8197. } else {
  8198. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  8199. }
  8200. }
  8201. // Adjust tangents to ensure monotonic properties
  8202. var alphaK, betaK, tauK, squaredMagnitude;
  8203. for (i = 0; i < pointsLen - 1; ++i) {
  8204. pointCurrent = pointsWithTangents[i];
  8205. pointAfter = pointsWithTangents[i + 1];
  8206. if (pointCurrent.model.skip || pointAfter.model.skip) {
  8207. continue;
  8208. }
  8209. if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  8210. pointCurrent.mK = pointAfter.mK = 0;
  8211. continue;
  8212. }
  8213. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  8214. betaK = pointAfter.mK / pointCurrent.deltaK;
  8215. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  8216. if (squaredMagnitude <= 9) {
  8217. continue;
  8218. }
  8219. tauK = 3 / Math.sqrt(squaredMagnitude);
  8220. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  8221. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  8222. }
  8223. // Compute control points
  8224. var deltaX;
  8225. for (i = 0; i < pointsLen; ++i) {
  8226. pointCurrent = pointsWithTangents[i];
  8227. if (pointCurrent.model.skip) {
  8228. continue;
  8229. }
  8230. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8231. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8232. if (pointBefore && !pointBefore.model.skip) {
  8233. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  8234. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  8235. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  8236. }
  8237. if (pointAfter && !pointAfter.model.skip) {
  8238. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  8239. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  8240. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  8241. }
  8242. }
  8243. };
  8244. helpers$1.nextItem = function(collection, index, loop) {
  8245. if (loop) {
  8246. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  8247. }
  8248. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  8249. };
  8250. helpers$1.previousItem = function(collection, index, loop) {
  8251. if (loop) {
  8252. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  8253. }
  8254. return index <= 0 ? collection[0] : collection[index - 1];
  8255. };
  8256. // Implementation of the nice number algorithm used in determining where axis labels will go
  8257. helpers$1.niceNum = function(range, round) {
  8258. var exponent = Math.floor(helpers$1.log10(range));
  8259. var fraction = range / Math.pow(10, exponent);
  8260. var niceFraction;
  8261. if (round) {
  8262. if (fraction < 1.5) {
  8263. niceFraction = 1;
  8264. } else if (fraction < 3) {
  8265. niceFraction = 2;
  8266. } else if (fraction < 7) {
  8267. niceFraction = 5;
  8268. } else {
  8269. niceFraction = 10;
  8270. }
  8271. } else if (fraction <= 1.0) {
  8272. niceFraction = 1;
  8273. } else if (fraction <= 2) {
  8274. niceFraction = 2;
  8275. } else if (fraction <= 5) {
  8276. niceFraction = 5;
  8277. } else {
  8278. niceFraction = 10;
  8279. }
  8280. return niceFraction * Math.pow(10, exponent);
  8281. };
  8282. // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  8283. helpers$1.requestAnimFrame = (function() {
  8284. if (typeof window === 'undefined') {
  8285. return function(callback) {
  8286. callback();
  8287. };
  8288. }
  8289. return window.requestAnimationFrame ||
  8290. window.webkitRequestAnimationFrame ||
  8291. window.mozRequestAnimationFrame ||
  8292. window.oRequestAnimationFrame ||
  8293. window.msRequestAnimationFrame ||
  8294. function(callback) {
  8295. return window.setTimeout(callback, 1000 / 60);
  8296. };
  8297. }());
  8298. // -- DOM methods
  8299. helpers$1.getRelativePosition = function(evt, chart) {
  8300. var mouseX, mouseY;
  8301. var e = evt.originalEvent || evt;
  8302. var canvas = evt.target || evt.srcElement;
  8303. var boundingRect = canvas.getBoundingClientRect();
  8304. var touches = e.touches;
  8305. if (touches && touches.length > 0) {
  8306. mouseX = touches[0].clientX;
  8307. mouseY = touches[0].clientY;
  8308. } else {
  8309. mouseX = e.clientX;
  8310. mouseY = e.clientY;
  8311. }
  8312. // Scale mouse coordinates into canvas coordinates
  8313. // by following the pattern laid out by 'jerryj' in the comments of
  8314. // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  8315. var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
  8316. var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
  8317. var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
  8318. var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
  8319. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  8320. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  8321. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  8322. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  8323. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  8324. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  8325. return {
  8326. x: mouseX,
  8327. y: mouseY
  8328. };
  8329. };
  8330. // Private helper function to convert max-width/max-height values that may be percentages into a number
  8331. function parseMaxStyle(styleValue, node, parentProperty) {
  8332. var valueInPixels;
  8333. if (typeof styleValue === 'string') {
  8334. valueInPixels = parseInt(styleValue, 10);
  8335. if (styleValue.indexOf('%') !== -1) {
  8336. // percentage * size in dimension
  8337. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  8338. }
  8339. } else {
  8340. valueInPixels = styleValue;
  8341. }
  8342. return valueInPixels;
  8343. }
  8344. /**
  8345. * Returns if the given value contains an effective constraint.
  8346. * @private
  8347. */
  8348. function isConstrainedValue(value) {
  8349. return value !== undefined && value !== null && value !== 'none';
  8350. }
  8351. /**
  8352. * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
  8353. * @param {HTMLElement} domNode - the node to check the constraint on
  8354. * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
  8355. * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
  8356. * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
  8357. */
  8358. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  8359. var view = document.defaultView;
  8360. var parentNode = helpers$1._getParentNode(domNode);
  8361. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  8362. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  8363. var hasCNode = isConstrainedValue(constrainedNode);
  8364. var hasCContainer = isConstrainedValue(constrainedContainer);
  8365. var infinity = Number.POSITIVE_INFINITY;
  8366. if (hasCNode || hasCContainer) {
  8367. return Math.min(
  8368. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  8369. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  8370. }
  8371. return 'none';
  8372. }
  8373. // returns Number or undefined if no constraint
  8374. helpers$1.getConstraintWidth = function(domNode) {
  8375. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  8376. };
  8377. // returns Number or undefined if no constraint
  8378. helpers$1.getConstraintHeight = function(domNode) {
  8379. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  8380. };
  8381. /**
  8382. * @private
  8383. */
  8384. helpers$1._calculatePadding = function(container, padding, parentDimension) {
  8385. padding = helpers$1.getStyle(container, padding);
  8386. return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
  8387. };
  8388. /**
  8389. * @private
  8390. */
  8391. helpers$1._getParentNode = function(domNode) {
  8392. var parent = domNode.parentNode;
  8393. if (parent && parent.toString() === '[object ShadowRoot]') {
  8394. parent = parent.host;
  8395. }
  8396. return parent;
  8397. };
  8398. helpers$1.getMaximumWidth = function(domNode) {
  8399. var container = helpers$1._getParentNode(domNode);
  8400. if (!container) {
  8401. return domNode.clientWidth;
  8402. }
  8403. var clientWidth = container.clientWidth;
  8404. var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
  8405. var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
  8406. var w = clientWidth - paddingLeft - paddingRight;
  8407. var cw = helpers$1.getConstraintWidth(domNode);
  8408. return isNaN(cw) ? w : Math.min(w, cw);
  8409. };
  8410. helpers$1.getMaximumHeight = function(domNode) {
  8411. var container = helpers$1._getParentNode(domNode);
  8412. if (!container) {
  8413. return domNode.clientHeight;
  8414. }
  8415. var clientHeight = container.clientHeight;
  8416. var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
  8417. var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
  8418. var h = clientHeight - paddingTop - paddingBottom;
  8419. var ch = helpers$1.getConstraintHeight(domNode);
  8420. return isNaN(ch) ? h : Math.min(h, ch);
  8421. };
  8422. helpers$1.getStyle = function(el, property) {
  8423. return el.currentStyle ?
  8424. el.currentStyle[property] :
  8425. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  8426. };
  8427. helpers$1.retinaScale = function(chart, forceRatio) {
  8428. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  8429. if (pixelRatio === 1) {
  8430. return;
  8431. }
  8432. var canvas = chart.canvas;
  8433. var height = chart.height;
  8434. var width = chart.width;
  8435. canvas.height = height * pixelRatio;
  8436. canvas.width = width * pixelRatio;
  8437. chart.ctx.scale(pixelRatio, pixelRatio);
  8438. // If no style has been set on the canvas, the render size is used as display size,
  8439. // making the chart visually bigger, so let's enforce it to the "correct" values.
  8440. // See https://github.com/chartjs/Chart.js/issues/3575
  8441. if (!canvas.style.height && !canvas.style.width) {
  8442. canvas.style.height = height + 'px';
  8443. canvas.style.width = width + 'px';
  8444. }
  8445. };
  8446. // -- Canvas methods
  8447. helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {
  8448. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  8449. };
  8450. helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {
  8451. cache = cache || {};
  8452. var data = cache.data = cache.data || {};
  8453. var gc = cache.garbageCollect = cache.garbageCollect || [];
  8454. if (cache.font !== font) {
  8455. data = cache.data = {};
  8456. gc = cache.garbageCollect = [];
  8457. cache.font = font;
  8458. }
  8459. ctx.font = font;
  8460. var longest = 0;
  8461. helpers$1.each(arrayOfThings, function(thing) {
  8462. // Undefined strings and arrays should not be measured
  8463. if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
  8464. longest = helpers$1.measureText(ctx, data, gc, longest, thing);
  8465. } else if (helpers$1.isArray(thing)) {
  8466. // if it is an array lets measure each element
  8467. // to do maybe simplify this function a bit so we can do this more recursively?
  8468. helpers$1.each(thing, function(nestedThing) {
  8469. // Undefined strings and arrays should not be measured
  8470. if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
  8471. longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
  8472. }
  8473. });
  8474. }
  8475. });
  8476. var gcLen = gc.length / 2;
  8477. if (gcLen > arrayOfThings.length) {
  8478. for (var i = 0; i < gcLen; i++) {
  8479. delete data[gc[i]];
  8480. }
  8481. gc.splice(0, gcLen);
  8482. }
  8483. return longest;
  8484. };
  8485. helpers$1.measureText = function(ctx, data, gc, longest, string) {
  8486. var textWidth = data[string];
  8487. if (!textWidth) {
  8488. textWidth = data[string] = ctx.measureText(string).width;
  8489. gc.push(string);
  8490. }
  8491. if (textWidth > longest) {
  8492. longest = textWidth;
  8493. }
  8494. return longest;
  8495. };
  8496. helpers$1.numberOfLabelLines = function(arrayOfThings) {
  8497. var numberOfLines = 1;
  8498. helpers$1.each(arrayOfThings, function(thing) {
  8499. if (helpers$1.isArray(thing)) {
  8500. if (thing.length > numberOfLines) {
  8501. numberOfLines = thing.length;
  8502. }
  8503. }
  8504. });
  8505. return numberOfLines;
  8506. };
  8507. helpers$1.color = !chartjsColor ?
  8508. function(value) {
  8509. console.error('Color.js not found!');
  8510. return value;
  8511. } :
  8512. function(value) {
  8513. /* global CanvasGradient */
  8514. if (value instanceof CanvasGradient) {
  8515. value = core_defaults.global.defaultColor;
  8516. }
  8517. return chartjsColor(value);
  8518. };
  8519. helpers$1.getHoverColor = function(colorValue) {
  8520. /* global CanvasPattern */
  8521. return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
  8522. colorValue :
  8523. helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  8524. };
  8525. };
  8526. function abstract() {
  8527. throw new Error(
  8528. 'This method is not implemented: either no adapter can ' +
  8529. 'be found or an incomplete integration was provided.'
  8530. );
  8531. }
  8532. /**
  8533. * Date adapter (current used by the time scale)
  8534. * @namespace Chart._adapters._date
  8535. * @memberof Chart._adapters
  8536. * @private
  8537. */
  8538. /**
  8539. * Currently supported unit string values.
  8540. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
  8541. * @memberof Chart._adapters._date
  8542. * @name Unit
  8543. */
  8544. /**
  8545. * @class
  8546. */
  8547. function DateAdapter(options) {
  8548. this.options = options || {};
  8549. }
  8550. helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
  8551. /**
  8552. * Returns a map of time formats for the supported formatting units defined
  8553. * in Unit as well as 'datetime' representing a detailed date/time string.
  8554. * @returns {{string: string}}
  8555. */
  8556. formats: abstract,
  8557. /**
  8558. * Parses the given `value` and return the associated timestamp.
  8559. * @param {any} value - the value to parse (usually comes from the data)
  8560. * @param {string} [format] - the expected data format
  8561. * @returns {(number|null)}
  8562. * @function
  8563. */
  8564. parse: abstract,
  8565. /**
  8566. * Returns the formatted date in the specified `format` for a given `timestamp`.
  8567. * @param {number} timestamp - the timestamp to format
  8568. * @param {string} format - the date/time token
  8569. * @return {string}
  8570. * @function
  8571. */
  8572. format: abstract,
  8573. /**
  8574. * Adds the specified `amount` of `unit` to the given `timestamp`.
  8575. * @param {number} timestamp - the input timestamp
  8576. * @param {number} amount - the amount to add
  8577. * @param {Unit} unit - the unit as string
  8578. * @return {number}
  8579. * @function
  8580. */
  8581. add: abstract,
  8582. /**
  8583. * Returns the number of `unit` between the given timestamps.
  8584. * @param {number} max - the input timestamp (reference)
  8585. * @param {number} min - the timestamp to substract
  8586. * @param {Unit} unit - the unit as string
  8587. * @return {number}
  8588. * @function
  8589. */
  8590. diff: abstract,
  8591. /**
  8592. * Returns start of `unit` for the given `timestamp`.
  8593. * @param {number} timestamp - the input timestamp
  8594. * @param {Unit} unit - the unit as string
  8595. * @param {number} [weekday] - the ISO day of the week with 1 being Monday
  8596. * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
  8597. * @function
  8598. */
  8599. startOf: abstract,
  8600. /**
  8601. * Returns end of `unit` for the given `timestamp`.
  8602. * @param {number} timestamp - the input timestamp
  8603. * @param {Unit} unit - the unit as string
  8604. * @function
  8605. */
  8606. endOf: abstract,
  8607. // DEPRECATIONS
  8608. /**
  8609. * Provided for backward compatibility for scale.getValueForPixel(),
  8610. * this method should be overridden only by the moment adapter.
  8611. * @deprecated since version 2.8.0
  8612. * @todo remove at version 3
  8613. * @private
  8614. */
  8615. _create: function(value) {
  8616. return value;
  8617. }
  8618. });
  8619. DateAdapter.override = function(members) {
  8620. helpers$1.extend(DateAdapter.prototype, members);
  8621. };
  8622. var _date = DateAdapter;
  8623. var core_adapters = {
  8624. _date: _date
  8625. };
  8626. /**
  8627. * Namespace to hold static tick generation functions
  8628. * @namespace Chart.Ticks
  8629. */
  8630. var core_ticks = {
  8631. /**
  8632. * Namespace to hold formatters for different types of ticks
  8633. * @namespace Chart.Ticks.formatters
  8634. */
  8635. formatters: {
  8636. /**
  8637. * Formatter for value labels
  8638. * @method Chart.Ticks.formatters.values
  8639. * @param value the value to display
  8640. * @return {string|string[]} the label to display
  8641. */
  8642. values: function(value) {
  8643. return helpers$1.isArray(value) ? value : '' + value;
  8644. },
  8645. /**
  8646. * Formatter for linear numeric ticks
  8647. * @method Chart.Ticks.formatters.linear
  8648. * @param tickValue {number} the value to be formatted
  8649. * @param index {number} the position of the tickValue parameter in the ticks array
  8650. * @param ticks {number[]} the list of ticks being converted
  8651. * @return {string} string representation of the tickValue parameter
  8652. */
  8653. linear: function(tickValue, index, ticks) {
  8654. // If we have lots of ticks, don't use the ones
  8655. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  8656. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  8657. if (Math.abs(delta) > 1) {
  8658. if (tickValue !== Math.floor(tickValue)) {
  8659. // not an integer
  8660. delta = tickValue - Math.floor(tickValue);
  8661. }
  8662. }
  8663. var logDelta = helpers$1.log10(Math.abs(delta));
  8664. var tickString = '';
  8665. if (tickValue !== 0) {
  8666. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  8667. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  8668. var logTick = helpers$1.log10(Math.abs(tickValue));
  8669. tickString = tickValue.toExponential(Math.floor(logTick) - Math.floor(logDelta));
  8670. } else {
  8671. var numDecimal = -1 * Math.floor(logDelta);
  8672. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  8673. tickString = tickValue.toFixed(numDecimal);
  8674. }
  8675. } else {
  8676. tickString = '0'; // never show decimal places for 0
  8677. }
  8678. return tickString;
  8679. },
  8680. logarithmic: function(tickValue, index, ticks) {
  8681. var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
  8682. if (tickValue === 0) {
  8683. return '0';
  8684. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  8685. return tickValue.toExponential();
  8686. }
  8687. return '';
  8688. }
  8689. }
  8690. };
  8691. var valueOrDefault$9 = helpers$1.valueOrDefault;
  8692. var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
  8693. core_defaults._set('scale', {
  8694. display: true,
  8695. position: 'left',
  8696. offset: false,
  8697. // grid line settings
  8698. gridLines: {
  8699. display: true,
  8700. color: 'rgba(0, 0, 0, 0.1)',
  8701. lineWidth: 1,
  8702. drawBorder: true,
  8703. drawOnChartArea: true,
  8704. drawTicks: true,
  8705. tickMarkLength: 10,
  8706. zeroLineWidth: 1,
  8707. zeroLineColor: 'rgba(0,0,0,0.25)',
  8708. zeroLineBorderDash: [],
  8709. zeroLineBorderDashOffset: 0.0,
  8710. offsetGridLines: false,
  8711. borderDash: [],
  8712. borderDashOffset: 0.0
  8713. },
  8714. // scale label
  8715. scaleLabel: {
  8716. // display property
  8717. display: false,
  8718. // actual label
  8719. labelString: '',
  8720. // top/bottom padding
  8721. padding: {
  8722. top: 4,
  8723. bottom: 4
  8724. }
  8725. },
  8726. // label settings
  8727. ticks: {
  8728. beginAtZero: false,
  8729. minRotation: 0,
  8730. maxRotation: 50,
  8731. mirror: false,
  8732. padding: 0,
  8733. reverse: false,
  8734. display: true,
  8735. autoSkip: true,
  8736. autoSkipPadding: 0,
  8737. labelOffset: 0,
  8738. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  8739. callback: core_ticks.formatters.values,
  8740. minor: {},
  8741. major: {}
  8742. }
  8743. });
  8744. function labelsFromTicks(ticks) {
  8745. var labels = [];
  8746. var i, ilen;
  8747. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  8748. labels.push(ticks[i].label);
  8749. }
  8750. return labels;
  8751. }
  8752. function getPixelForGridLine(scale, index, offsetGridLines) {
  8753. var lineValue = scale.getPixelForTick(index);
  8754. if (offsetGridLines) {
  8755. if (scale.getTicks().length === 1) {
  8756. lineValue -= scale.isHorizontal() ?
  8757. Math.max(lineValue - scale.left, scale.right - lineValue) :
  8758. Math.max(lineValue - scale.top, scale.bottom - lineValue);
  8759. } else if (index === 0) {
  8760. lineValue -= (scale.getPixelForTick(1) - lineValue) / 2;
  8761. } else {
  8762. lineValue -= (lineValue - scale.getPixelForTick(index - 1)) / 2;
  8763. }
  8764. }
  8765. return lineValue;
  8766. }
  8767. function computeTextSize(context, tick, font) {
  8768. return helpers$1.isArray(tick) ?
  8769. helpers$1.longestText(context, font, tick) :
  8770. context.measureText(tick).width;
  8771. }
  8772. var core_scale = core_element.extend({
  8773. /**
  8774. * Get the padding needed for the scale
  8775. * @method getPadding
  8776. * @private
  8777. * @returns {Padding} the necessary padding
  8778. */
  8779. getPadding: function() {
  8780. var me = this;
  8781. return {
  8782. left: me.paddingLeft || 0,
  8783. top: me.paddingTop || 0,
  8784. right: me.paddingRight || 0,
  8785. bottom: me.paddingBottom || 0
  8786. };
  8787. },
  8788. /**
  8789. * Returns the scale tick objects ({label, major})
  8790. * @since 2.7
  8791. */
  8792. getTicks: function() {
  8793. return this._ticks;
  8794. },
  8795. // These methods are ordered by lifecyle. Utilities then follow.
  8796. // Any function defined here is inherited by all scale types.
  8797. // Any function can be extended by the scale type
  8798. mergeTicksOptions: function() {
  8799. var ticks = this.options.ticks;
  8800. if (ticks.minor === false) {
  8801. ticks.minor = {
  8802. display: false
  8803. };
  8804. }
  8805. if (ticks.major === false) {
  8806. ticks.major = {
  8807. display: false
  8808. };
  8809. }
  8810. for (var key in ticks) {
  8811. if (key !== 'major' && key !== 'minor') {
  8812. if (typeof ticks.minor[key] === 'undefined') {
  8813. ticks.minor[key] = ticks[key];
  8814. }
  8815. if (typeof ticks.major[key] === 'undefined') {
  8816. ticks.major[key] = ticks[key];
  8817. }
  8818. }
  8819. }
  8820. },
  8821. beforeUpdate: function() {
  8822. helpers$1.callback(this.options.beforeUpdate, [this]);
  8823. },
  8824. update: function(maxWidth, maxHeight, margins) {
  8825. var me = this;
  8826. var i, ilen, labels, label, ticks, tick;
  8827. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  8828. me.beforeUpdate();
  8829. // Absorb the master measurements
  8830. me.maxWidth = maxWidth;
  8831. me.maxHeight = maxHeight;
  8832. me.margins = helpers$1.extend({
  8833. left: 0,
  8834. right: 0,
  8835. top: 0,
  8836. bottom: 0
  8837. }, margins);
  8838. me._maxLabelLines = 0;
  8839. me.longestLabelWidth = 0;
  8840. me.longestTextCache = me.longestTextCache || {};
  8841. // Dimensions
  8842. me.beforeSetDimensions();
  8843. me.setDimensions();
  8844. me.afterSetDimensions();
  8845. // Data min/max
  8846. me.beforeDataLimits();
  8847. me.determineDataLimits();
  8848. me.afterDataLimits();
  8849. // Ticks - `this.ticks` is now DEPRECATED!
  8850. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  8851. // and must not be accessed directly from outside this class. `this.ticks` being
  8852. // around for long time and not marked as private, we can't change its structure
  8853. // without unexpected breaking changes. If you need to access the scale ticks,
  8854. // use scale.getTicks() instead.
  8855. me.beforeBuildTicks();
  8856. // New implementations should return an array of objects but for BACKWARD COMPAT,
  8857. // we still support no return (`this.ticks` internally set by calling this method).
  8858. ticks = me.buildTicks() || [];
  8859. // Allow modification of ticks in callback.
  8860. ticks = me.afterBuildTicks(ticks) || ticks;
  8861. me.beforeTickToLabelConversion();
  8862. // New implementations should return the formatted tick labels but for BACKWARD
  8863. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  8864. // this method and supposed to contain only string values).
  8865. labels = me.convertTicksToLabels(ticks) || me.ticks;
  8866. me.afterTickToLabelConversion();
  8867. me.ticks = labels; // BACKWARD COMPATIBILITY
  8868. // IMPORTANT: from this point, we consider that `this.ticks` will NEVER change!
  8869. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  8870. for (i = 0, ilen = labels.length; i < ilen; ++i) {
  8871. label = labels[i];
  8872. tick = ticks[i];
  8873. if (!tick) {
  8874. ticks.push(tick = {
  8875. label: label,
  8876. major: false
  8877. });
  8878. } else {
  8879. tick.label = label;
  8880. }
  8881. }
  8882. me._ticks = ticks;
  8883. // Tick Rotation
  8884. me.beforeCalculateTickRotation();
  8885. me.calculateTickRotation();
  8886. me.afterCalculateTickRotation();
  8887. // Fit
  8888. me.beforeFit();
  8889. me.fit();
  8890. me.afterFit();
  8891. //
  8892. me.afterUpdate();
  8893. return me.minSize;
  8894. },
  8895. afterUpdate: function() {
  8896. helpers$1.callback(this.options.afterUpdate, [this]);
  8897. },
  8898. //
  8899. beforeSetDimensions: function() {
  8900. helpers$1.callback(this.options.beforeSetDimensions, [this]);
  8901. },
  8902. setDimensions: function() {
  8903. var me = this;
  8904. // Set the unconstrained dimension before label rotation
  8905. if (me.isHorizontal()) {
  8906. // Reset position before calculating rotation
  8907. me.width = me.maxWidth;
  8908. me.left = 0;
  8909. me.right = me.width;
  8910. } else {
  8911. me.height = me.maxHeight;
  8912. // Reset position before calculating rotation
  8913. me.top = 0;
  8914. me.bottom = me.height;
  8915. }
  8916. // Reset padding
  8917. me.paddingLeft = 0;
  8918. me.paddingTop = 0;
  8919. me.paddingRight = 0;
  8920. me.paddingBottom = 0;
  8921. },
  8922. afterSetDimensions: function() {
  8923. helpers$1.callback(this.options.afterSetDimensions, [this]);
  8924. },
  8925. // Data limits
  8926. beforeDataLimits: function() {
  8927. helpers$1.callback(this.options.beforeDataLimits, [this]);
  8928. },
  8929. determineDataLimits: helpers$1.noop,
  8930. afterDataLimits: function() {
  8931. helpers$1.callback(this.options.afterDataLimits, [this]);
  8932. },
  8933. //
  8934. beforeBuildTicks: function() {
  8935. helpers$1.callback(this.options.beforeBuildTicks, [this]);
  8936. },
  8937. buildTicks: helpers$1.noop,
  8938. afterBuildTicks: function(ticks) {
  8939. var me = this;
  8940. // ticks is empty for old axis implementations here
  8941. if (helpers$1.isArray(ticks) && ticks.length) {
  8942. return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
  8943. }
  8944. // Support old implementations (that modified `this.ticks` directly in buildTicks)
  8945. me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
  8946. return ticks;
  8947. },
  8948. beforeTickToLabelConversion: function() {
  8949. helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
  8950. },
  8951. convertTicksToLabels: function() {
  8952. var me = this;
  8953. // Convert ticks to strings
  8954. var tickOpts = me.options.ticks;
  8955. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  8956. },
  8957. afterTickToLabelConversion: function() {
  8958. helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
  8959. },
  8960. //
  8961. beforeCalculateTickRotation: function() {
  8962. helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
  8963. },
  8964. calculateTickRotation: function() {
  8965. var me = this;
  8966. var context = me.ctx;
  8967. var tickOpts = me.options.ticks;
  8968. var labels = labelsFromTicks(me._ticks);
  8969. // Get the width of each grid by calculating the difference
  8970. // between x offsets between 0 and 1.
  8971. var tickFont = helpers$1.options._parseFont(tickOpts);
  8972. context.font = tickFont.string;
  8973. var labelRotation = tickOpts.minRotation || 0;
  8974. if (labels.length && me.options.display && me.isHorizontal()) {
  8975. var originalLabelWidth = helpers$1.longestText(context, tickFont.string, labels, me.longestTextCache);
  8976. var labelWidth = originalLabelWidth;
  8977. var cosRotation, sinRotation;
  8978. // Allow 3 pixels x2 padding either side for label readability
  8979. var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6;
  8980. // Max label rotation can be set or default to 90 - also act as a loop counter
  8981. while (labelWidth > tickWidth && labelRotation < tickOpts.maxRotation) {
  8982. var angleRadians = helpers$1.toRadians(labelRotation);
  8983. cosRotation = Math.cos(angleRadians);
  8984. sinRotation = Math.sin(angleRadians);
  8985. if (sinRotation * originalLabelWidth > me.maxHeight) {
  8986. // go back one step
  8987. labelRotation--;
  8988. break;
  8989. }
  8990. labelRotation++;
  8991. labelWidth = cosRotation * originalLabelWidth;
  8992. }
  8993. }
  8994. me.labelRotation = labelRotation;
  8995. },
  8996. afterCalculateTickRotation: function() {
  8997. helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
  8998. },
  8999. //
  9000. beforeFit: function() {
  9001. helpers$1.callback(this.options.beforeFit, [this]);
  9002. },
  9003. fit: function() {
  9004. var me = this;
  9005. // Reset
  9006. var minSize = me.minSize = {
  9007. width: 0,
  9008. height: 0
  9009. };
  9010. var labels = labelsFromTicks(me._ticks);
  9011. var opts = me.options;
  9012. var tickOpts = opts.ticks;
  9013. var scaleLabelOpts = opts.scaleLabel;
  9014. var gridLineOpts = opts.gridLines;
  9015. var display = me._isVisible();
  9016. var position = opts.position;
  9017. var isHorizontal = me.isHorizontal();
  9018. var parseFont = helpers$1.options._parseFont;
  9019. var tickFont = parseFont(tickOpts);
  9020. var tickMarkLength = opts.gridLines.tickMarkLength;
  9021. // Width
  9022. if (isHorizontal) {
  9023. // subtract the margins to line up with the chartArea if we are a full width scale
  9024. minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth;
  9025. } else {
  9026. minSize.width = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
  9027. }
  9028. // height
  9029. if (isHorizontal) {
  9030. minSize.height = display && gridLineOpts.drawTicks ? tickMarkLength : 0;
  9031. } else {
  9032. minSize.height = me.maxHeight; // fill all the height
  9033. }
  9034. // Are we showing a title for the scale?
  9035. if (scaleLabelOpts.display && display) {
  9036. var scaleLabelFont = parseFont(scaleLabelOpts);
  9037. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabelOpts.padding);
  9038. var deltaHeight = scaleLabelFont.lineHeight + scaleLabelPadding.height;
  9039. if (isHorizontal) {
  9040. minSize.height += deltaHeight;
  9041. } else {
  9042. minSize.width += deltaHeight;
  9043. }
  9044. }
  9045. // Don't bother fitting the ticks if we are not showing the labels
  9046. if (tickOpts.display && display) {
  9047. var largestTextWidth = helpers$1.longestText(me.ctx, tickFont.string, labels, me.longestTextCache);
  9048. var tallestLabelHeightInLines = helpers$1.numberOfLabelLines(labels);
  9049. var lineSpace = tickFont.size * 0.5;
  9050. var tickPadding = me.options.ticks.padding;
  9051. // Store max number of lines and widest label for _autoSkip
  9052. me._maxLabelLines = tallestLabelHeightInLines;
  9053. me.longestLabelWidth = largestTextWidth;
  9054. if (isHorizontal) {
  9055. var angleRadians = helpers$1.toRadians(me.labelRotation);
  9056. var cosRotation = Math.cos(angleRadians);
  9057. var sinRotation = Math.sin(angleRadians);
  9058. // TODO - improve this calculation
  9059. var labelHeight = (sinRotation * largestTextWidth)
  9060. + (tickFont.lineHeight * tallestLabelHeightInLines)
  9061. + lineSpace; // padding
  9062. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  9063. me.ctx.font = tickFont.string;
  9064. var firstLabelWidth = computeTextSize(me.ctx, labels[0], tickFont.string);
  9065. var lastLabelWidth = computeTextSize(me.ctx, labels[labels.length - 1], tickFont.string);
  9066. var offsetLeft = me.getPixelForTick(0) - me.left;
  9067. var offsetRight = me.right - me.getPixelForTick(labels.length - 1);
  9068. var paddingLeft, paddingRight;
  9069. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  9070. // which means that the right padding is dominated by the font height
  9071. if (me.labelRotation !== 0) {
  9072. paddingLeft = position === 'bottom' ? (cosRotation * firstLabelWidth) : (cosRotation * lineSpace);
  9073. paddingRight = position === 'bottom' ? (cosRotation * lineSpace) : (cosRotation * lastLabelWidth);
  9074. } else {
  9075. paddingLeft = firstLabelWidth / 2;
  9076. paddingRight = lastLabelWidth / 2;
  9077. }
  9078. me.paddingLeft = Math.max(paddingLeft - offsetLeft, 0) + 3; // add 3 px to move away from canvas edges
  9079. me.paddingRight = Math.max(paddingRight - offsetRight, 0) + 3;
  9080. } else {
  9081. // A vertical axis is more constrained by the width. Labels are the
  9082. // dominant factor here, so get that length first and account for padding
  9083. if (tickOpts.mirror) {
  9084. largestTextWidth = 0;
  9085. } else {
  9086. // use lineSpace for consistency with horizontal axis
  9087. // tickPadding is not implemented for horizontal
  9088. largestTextWidth += tickPadding + lineSpace;
  9089. }
  9090. minSize.width = Math.min(me.maxWidth, minSize.width + largestTextWidth);
  9091. me.paddingTop = tickFont.size / 2;
  9092. me.paddingBottom = tickFont.size / 2;
  9093. }
  9094. }
  9095. me.handleMargins();
  9096. me.width = minSize.width;
  9097. me.height = minSize.height;
  9098. },
  9099. /**
  9100. * Handle margins and padding interactions
  9101. * @private
  9102. */
  9103. handleMargins: function() {
  9104. var me = this;
  9105. if (me.margins) {
  9106. me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0);
  9107. me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0);
  9108. me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0);
  9109. me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0);
  9110. }
  9111. },
  9112. afterFit: function() {
  9113. helpers$1.callback(this.options.afterFit, [this]);
  9114. },
  9115. // Shared Methods
  9116. isHorizontal: function() {
  9117. return this.options.position === 'top' || this.options.position === 'bottom';
  9118. },
  9119. isFullWidth: function() {
  9120. return (this.options.fullWidth);
  9121. },
  9122. // 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
  9123. getRightValue: function(rawValue) {
  9124. // Null and undefined values first
  9125. if (helpers$1.isNullOrUndef(rawValue)) {
  9126. return NaN;
  9127. }
  9128. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  9129. if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
  9130. return NaN;
  9131. }
  9132. // If it is in fact an object, dive in one more level
  9133. if (rawValue) {
  9134. if (this.isHorizontal()) {
  9135. if (rawValue.x !== undefined) {
  9136. return this.getRightValue(rawValue.x);
  9137. }
  9138. } else if (rawValue.y !== undefined) {
  9139. return this.getRightValue(rawValue.y);
  9140. }
  9141. }
  9142. // Value is good, return it
  9143. return rawValue;
  9144. },
  9145. /**
  9146. * Used to get the value to display in the tooltip for the data at the given index
  9147. * @param index
  9148. * @param datasetIndex
  9149. */
  9150. getLabelForIndex: helpers$1.noop,
  9151. /**
  9152. * Returns the location of the given data point. Value can either be an index or a numerical value
  9153. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9154. * @param value
  9155. * @param index
  9156. * @param datasetIndex
  9157. */
  9158. getPixelForValue: helpers$1.noop,
  9159. /**
  9160. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  9161. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9162. * @param pixel
  9163. */
  9164. getValueForPixel: helpers$1.noop,
  9165. /**
  9166. * Returns the location of the tick at the given index
  9167. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9168. */
  9169. getPixelForTick: function(index) {
  9170. var me = this;
  9171. var offset = me.options.offset;
  9172. if (me.isHorizontal()) {
  9173. var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
  9174. var tickWidth = innerWidth / Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
  9175. var pixel = (tickWidth * index) + me.paddingLeft;
  9176. if (offset) {
  9177. pixel += tickWidth / 2;
  9178. }
  9179. var finalVal = me.left + pixel;
  9180. finalVal += me.isFullWidth() ? me.margins.left : 0;
  9181. return finalVal;
  9182. }
  9183. var innerHeight = me.height - (me.paddingTop + me.paddingBottom);
  9184. return me.top + (index * (innerHeight / (me._ticks.length - 1)));
  9185. },
  9186. /**
  9187. * Utility for getting the pixel location of a percentage of scale
  9188. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9189. */
  9190. getPixelForDecimal: function(decimal) {
  9191. var me = this;
  9192. if (me.isHorizontal()) {
  9193. var innerWidth = me.width - (me.paddingLeft + me.paddingRight);
  9194. var valueOffset = (innerWidth * decimal) + me.paddingLeft;
  9195. var finalVal = me.left + valueOffset;
  9196. finalVal += me.isFullWidth() ? me.margins.left : 0;
  9197. return finalVal;
  9198. }
  9199. return me.top + (decimal * me.height);
  9200. },
  9201. /**
  9202. * Returns the pixel for the minimum chart value
  9203. * The coordinate (0, 0) is at the upper-left corner of the canvas
  9204. */
  9205. getBasePixel: function() {
  9206. return this.getPixelForValue(this.getBaseValue());
  9207. },
  9208. getBaseValue: function() {
  9209. var me = this;
  9210. var min = me.min;
  9211. var max = me.max;
  9212. return me.beginAtZero ? 0 :
  9213. min < 0 && max < 0 ? max :
  9214. min > 0 && max > 0 ? min :
  9215. 0;
  9216. },
  9217. /**
  9218. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  9219. * @private
  9220. */
  9221. _autoSkip: function(ticks) {
  9222. var me = this;
  9223. var isHorizontal = me.isHorizontal();
  9224. var optionTicks = me.options.ticks.minor;
  9225. var tickCount = ticks.length;
  9226. var skipRatio = false;
  9227. var maxTicks = optionTicks.maxTicksLimit;
  9228. // Total space needed to display all ticks. First and last ticks are
  9229. // drawn as their center at end of axis, so tickCount-1
  9230. var ticksLength = me._tickSize() * (tickCount - 1);
  9231. // Axis length
  9232. var axisLength = isHorizontal
  9233. ? me.width - (me.paddingLeft + me.paddingRight)
  9234. : me.height - (me.paddingTop + me.PaddingBottom);
  9235. var result = [];
  9236. var i, tick;
  9237. if (ticksLength > axisLength) {
  9238. skipRatio = 1 + Math.floor(ticksLength / axisLength);
  9239. }
  9240. // if they defined a max number of optionTicks,
  9241. // increase skipRatio until that number is met
  9242. if (tickCount > maxTicks) {
  9243. skipRatio = Math.max(skipRatio, 1 + Math.floor(tickCount / maxTicks));
  9244. }
  9245. for (i = 0; i < tickCount; i++) {
  9246. tick = ticks[i];
  9247. if (skipRatio > 1 && i % skipRatio > 0) {
  9248. // leave tick in place but make sure it's not displayed (#4635)
  9249. delete tick.label;
  9250. }
  9251. result.push(tick);
  9252. }
  9253. return result;
  9254. },
  9255. /**
  9256. * @private
  9257. */
  9258. _tickSize: function() {
  9259. var me = this;
  9260. var isHorizontal = me.isHorizontal();
  9261. var optionTicks = me.options.ticks.minor;
  9262. // Calculate space needed by label in axis direction.
  9263. var rot = helpers$1.toRadians(me.labelRotation);
  9264. var cos = Math.abs(Math.cos(rot));
  9265. var sin = Math.abs(Math.sin(rot));
  9266. var padding = optionTicks.autoSkipPadding || 0;
  9267. var w = (me.longestLabelWidth + padding) || 0;
  9268. var tickFont = helpers$1.options._parseFont(optionTicks);
  9269. var h = (me._maxLabelLines * tickFont.lineHeight + padding) || 0;
  9270. // Calculate space needed for 1 tick in axis direction.
  9271. return isHorizontal
  9272. ? h * cos > w * sin ? w / cos : h / sin
  9273. : h * sin < w * cos ? h / cos : w / sin;
  9274. },
  9275. /**
  9276. * @private
  9277. */
  9278. _isVisible: function() {
  9279. var me = this;
  9280. var chart = me.chart;
  9281. var display = me.options.display;
  9282. var i, ilen, meta;
  9283. if (display !== 'auto') {
  9284. return !!display;
  9285. }
  9286. // When 'auto', the scale is visible if at least one associated dataset is visible.
  9287. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  9288. if (chart.isDatasetVisible(i)) {
  9289. meta = chart.getDatasetMeta(i);
  9290. if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
  9291. return true;
  9292. }
  9293. }
  9294. }
  9295. return false;
  9296. },
  9297. /**
  9298. * Actually draw the scale on the canvas
  9299. * @param {object} chartArea - the area of the chart to draw full grid lines on
  9300. */
  9301. draw: function(chartArea) {
  9302. var me = this;
  9303. var options = me.options;
  9304. if (!me._isVisible()) {
  9305. return;
  9306. }
  9307. var chart = me.chart;
  9308. var context = me.ctx;
  9309. var globalDefaults = core_defaults.global;
  9310. var defaultFontColor = globalDefaults.defaultFontColor;
  9311. var optionTicks = options.ticks.minor;
  9312. var optionMajorTicks = options.ticks.major || optionTicks;
  9313. var gridLines = options.gridLines;
  9314. var scaleLabel = options.scaleLabel;
  9315. var position = options.position;
  9316. var isRotated = me.labelRotation !== 0;
  9317. var isMirrored = optionTicks.mirror;
  9318. var isHorizontal = me.isHorizontal();
  9319. var parseFont = helpers$1.options._parseFont;
  9320. var ticks = optionTicks.display && optionTicks.autoSkip ? me._autoSkip(me.getTicks()) : me.getTicks();
  9321. var tickFontColor = valueOrDefault$9(optionTicks.fontColor, defaultFontColor);
  9322. var tickFont = parseFont(optionTicks);
  9323. var lineHeight = tickFont.lineHeight;
  9324. var majorTickFontColor = valueOrDefault$9(optionMajorTicks.fontColor, defaultFontColor);
  9325. var majorTickFont = parseFont(optionMajorTicks);
  9326. var tickPadding = optionTicks.padding;
  9327. var labelOffset = optionTicks.labelOffset;
  9328. var tl = gridLines.drawTicks ? gridLines.tickMarkLength : 0;
  9329. var scaleLabelFontColor = valueOrDefault$9(scaleLabel.fontColor, defaultFontColor);
  9330. var scaleLabelFont = parseFont(scaleLabel);
  9331. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
  9332. var labelRotationRadians = helpers$1.toRadians(me.labelRotation);
  9333. var itemsToDraw = [];
  9334. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  9335. var alignPixel = helpers$1._alignPixel;
  9336. var borderValue, tickStart, tickEnd;
  9337. if (position === 'top') {
  9338. borderValue = alignPixel(chart, me.bottom, axisWidth);
  9339. tickStart = me.bottom - tl;
  9340. tickEnd = borderValue - axisWidth / 2;
  9341. } else if (position === 'bottom') {
  9342. borderValue = alignPixel(chart, me.top, axisWidth);
  9343. tickStart = borderValue + axisWidth / 2;
  9344. tickEnd = me.top + tl;
  9345. } else if (position === 'left') {
  9346. borderValue = alignPixel(chart, me.right, axisWidth);
  9347. tickStart = me.right - tl;
  9348. tickEnd = borderValue - axisWidth / 2;
  9349. } else {
  9350. borderValue = alignPixel(chart, me.left, axisWidth);
  9351. tickStart = borderValue + axisWidth / 2;
  9352. tickEnd = me.left + tl;
  9353. }
  9354. var epsilon = 0.0000001; // 0.0000001 is margin in pixels for Accumulated error.
  9355. helpers$1.each(ticks, function(tick, index) {
  9356. // autoskipper skipped this tick (#4635)
  9357. if (helpers$1.isNullOrUndef(tick.label)) {
  9358. return;
  9359. }
  9360. var label = tick.label;
  9361. var lineWidth, lineColor, borderDash, borderDashOffset;
  9362. if (index === me.zeroLineIndex && options.offset === gridLines.offsetGridLines) {
  9363. // Draw the first index specially
  9364. lineWidth = gridLines.zeroLineWidth;
  9365. lineColor = gridLines.zeroLineColor;
  9366. borderDash = gridLines.zeroLineBorderDash || [];
  9367. borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
  9368. } else {
  9369. lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, index);
  9370. lineColor = valueAtIndexOrDefault(gridLines.color, index);
  9371. borderDash = gridLines.borderDash || [];
  9372. borderDashOffset = gridLines.borderDashOffset || 0.0;
  9373. }
  9374. // Common properties
  9375. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY, textOffset, textAlign;
  9376. var labelCount = helpers$1.isArray(label) ? label.length : 1;
  9377. var lineValue = getPixelForGridLine(me, index, gridLines.offsetGridLines);
  9378. if (isHorizontal) {
  9379. var labelYOffset = tl + tickPadding;
  9380. if (lineValue < me.left - epsilon) {
  9381. lineColor = 'rgba(0,0,0,0)';
  9382. }
  9383. tx1 = tx2 = x1 = x2 = alignPixel(chart, lineValue, lineWidth);
  9384. ty1 = tickStart;
  9385. ty2 = tickEnd;
  9386. labelX = me.getPixelForTick(index) + labelOffset; // x values for optionTicks (need to consider offsetLabel option)
  9387. if (position === 'top') {
  9388. y1 = alignPixel(chart, chartArea.top, axisWidth) + axisWidth / 2;
  9389. y2 = chartArea.bottom;
  9390. textOffset = ((!isRotated ? 0.5 : 1) - labelCount) * lineHeight;
  9391. textAlign = !isRotated ? 'center' : 'left';
  9392. labelY = me.bottom - labelYOffset;
  9393. } else {
  9394. y1 = chartArea.top;
  9395. y2 = alignPixel(chart, chartArea.bottom, axisWidth) - axisWidth / 2;
  9396. textOffset = (!isRotated ? 0.5 : 0) * lineHeight;
  9397. textAlign = !isRotated ? 'center' : 'right';
  9398. labelY = me.top + labelYOffset;
  9399. }
  9400. } else {
  9401. var labelXOffset = (isMirrored ? 0 : tl) + tickPadding;
  9402. if (lineValue < me.top - epsilon) {
  9403. lineColor = 'rgba(0,0,0,0)';
  9404. }
  9405. tx1 = tickStart;
  9406. tx2 = tickEnd;
  9407. ty1 = ty2 = y1 = y2 = alignPixel(chart, lineValue, lineWidth);
  9408. labelY = me.getPixelForTick(index) + labelOffset;
  9409. textOffset = (1 - labelCount) * lineHeight / 2;
  9410. if (position === 'left') {
  9411. x1 = alignPixel(chart, chartArea.left, axisWidth) + axisWidth / 2;
  9412. x2 = chartArea.right;
  9413. textAlign = isMirrored ? 'left' : 'right';
  9414. labelX = me.right - labelXOffset;
  9415. } else {
  9416. x1 = chartArea.left;
  9417. x2 = alignPixel(chart, chartArea.right, axisWidth) - axisWidth / 2;
  9418. textAlign = isMirrored ? 'right' : 'left';
  9419. labelX = me.left + labelXOffset;
  9420. }
  9421. }
  9422. itemsToDraw.push({
  9423. tx1: tx1,
  9424. ty1: ty1,
  9425. tx2: tx2,
  9426. ty2: ty2,
  9427. x1: x1,
  9428. y1: y1,
  9429. x2: x2,
  9430. y2: y2,
  9431. labelX: labelX,
  9432. labelY: labelY,
  9433. glWidth: lineWidth,
  9434. glColor: lineColor,
  9435. glBorderDash: borderDash,
  9436. glBorderDashOffset: borderDashOffset,
  9437. rotation: -1 * labelRotationRadians,
  9438. label: label,
  9439. major: tick.major,
  9440. textOffset: textOffset,
  9441. textAlign: textAlign
  9442. });
  9443. });
  9444. // Draw all of the tick labels, tick marks, and grid lines at the correct places
  9445. helpers$1.each(itemsToDraw, function(itemToDraw) {
  9446. var glWidth = itemToDraw.glWidth;
  9447. var glColor = itemToDraw.glColor;
  9448. if (gridLines.display && glWidth && glColor) {
  9449. context.save();
  9450. context.lineWidth = glWidth;
  9451. context.strokeStyle = glColor;
  9452. if (context.setLineDash) {
  9453. context.setLineDash(itemToDraw.glBorderDash);
  9454. context.lineDashOffset = itemToDraw.glBorderDashOffset;
  9455. }
  9456. context.beginPath();
  9457. if (gridLines.drawTicks) {
  9458. context.moveTo(itemToDraw.tx1, itemToDraw.ty1);
  9459. context.lineTo(itemToDraw.tx2, itemToDraw.ty2);
  9460. }
  9461. if (gridLines.drawOnChartArea) {
  9462. context.moveTo(itemToDraw.x1, itemToDraw.y1);
  9463. context.lineTo(itemToDraw.x2, itemToDraw.y2);
  9464. }
  9465. context.stroke();
  9466. context.restore();
  9467. }
  9468. if (optionTicks.display) {
  9469. // Make sure we draw text in the correct color and font
  9470. context.save();
  9471. context.translate(itemToDraw.labelX, itemToDraw.labelY);
  9472. context.rotate(itemToDraw.rotation);
  9473. context.font = itemToDraw.major ? majorTickFont.string : tickFont.string;
  9474. context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor;
  9475. context.textBaseline = 'middle';
  9476. context.textAlign = itemToDraw.textAlign;
  9477. var label = itemToDraw.label;
  9478. var y = itemToDraw.textOffset;
  9479. if (helpers$1.isArray(label)) {
  9480. for (var i = 0; i < label.length; ++i) {
  9481. // We just make sure the multiline element is a string here..
  9482. context.fillText('' + label[i], 0, y);
  9483. y += lineHeight;
  9484. }
  9485. } else {
  9486. context.fillText(label, 0, y);
  9487. }
  9488. context.restore();
  9489. }
  9490. });
  9491. if (scaleLabel.display) {
  9492. // Draw the scale label
  9493. var scaleLabelX;
  9494. var scaleLabelY;
  9495. var rotation = 0;
  9496. var halfLineHeight = scaleLabelFont.lineHeight / 2;
  9497. if (isHorizontal) {
  9498. scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width
  9499. scaleLabelY = position === 'bottom'
  9500. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  9501. : me.top + halfLineHeight + scaleLabelPadding.top;
  9502. } else {
  9503. var isLeft = position === 'left';
  9504. scaleLabelX = isLeft
  9505. ? me.left + halfLineHeight + scaleLabelPadding.top
  9506. : me.right - halfLineHeight - scaleLabelPadding.top;
  9507. scaleLabelY = me.top + ((me.bottom - me.top) / 2);
  9508. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  9509. }
  9510. context.save();
  9511. context.translate(scaleLabelX, scaleLabelY);
  9512. context.rotate(rotation);
  9513. context.textAlign = 'center';
  9514. context.textBaseline = 'middle';
  9515. context.fillStyle = scaleLabelFontColor; // render in correct colour
  9516. context.font = scaleLabelFont.string;
  9517. context.fillText(scaleLabel.labelString, 0, 0);
  9518. context.restore();
  9519. }
  9520. if (axisWidth) {
  9521. // Draw the line at the edge of the axis
  9522. var firstLineWidth = axisWidth;
  9523. var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, ticks.length - 1, 0);
  9524. var x1, x2, y1, y2;
  9525. if (isHorizontal) {
  9526. x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
  9527. x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  9528. y1 = y2 = borderValue;
  9529. } else {
  9530. y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
  9531. y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  9532. x1 = x2 = borderValue;
  9533. }
  9534. context.lineWidth = axisWidth;
  9535. context.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
  9536. context.beginPath();
  9537. context.moveTo(x1, y1);
  9538. context.lineTo(x2, y2);
  9539. context.stroke();
  9540. }
  9541. }
  9542. });
  9543. var defaultConfig = {
  9544. position: 'bottom'
  9545. };
  9546. var scale_category = core_scale.extend({
  9547. /**
  9548. * Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those
  9549. * else fall back to data.labels
  9550. * @private
  9551. */
  9552. getLabels: function() {
  9553. var data = this.chart.data;
  9554. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels;
  9555. },
  9556. determineDataLimits: function() {
  9557. var me = this;
  9558. var labels = me.getLabels();
  9559. me.minIndex = 0;
  9560. me.maxIndex = labels.length - 1;
  9561. var findIndex;
  9562. if (me.options.ticks.min !== undefined) {
  9563. // user specified min value
  9564. findIndex = labels.indexOf(me.options.ticks.min);
  9565. me.minIndex = findIndex !== -1 ? findIndex : me.minIndex;
  9566. }
  9567. if (me.options.ticks.max !== undefined) {
  9568. // user specified max value
  9569. findIndex = labels.indexOf(me.options.ticks.max);
  9570. me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex;
  9571. }
  9572. me.min = labels[me.minIndex];
  9573. me.max = labels[me.maxIndex];
  9574. },
  9575. buildTicks: function() {
  9576. var me = this;
  9577. var labels = me.getLabels();
  9578. // If we are viewing some subset of labels, slice the original array
  9579. me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1);
  9580. },
  9581. getLabelForIndex: function(index, datasetIndex) {
  9582. var me = this;
  9583. var chart = me.chart;
  9584. if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {
  9585. return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);
  9586. }
  9587. return me.ticks[index - me.minIndex];
  9588. },
  9589. // Used to get data value locations. Value can either be an index or a numerical value
  9590. getPixelForValue: function(value, index) {
  9591. var me = this;
  9592. var offset = me.options.offset;
  9593. // 1 is added because we need the length but we have the indexes
  9594. var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - (offset ? 0 : 1)), 1);
  9595. // If value is a data object, then index is the index in the data array,
  9596. // not the index of the scale. We need to change that.
  9597. var valueCategory;
  9598. if (value !== undefined && value !== null) {
  9599. valueCategory = me.isHorizontal() ? value.x : value.y;
  9600. }
  9601. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  9602. var labels = me.getLabels();
  9603. value = valueCategory || value;
  9604. var idx = labels.indexOf(value);
  9605. index = idx !== -1 ? idx : index;
  9606. }
  9607. if (me.isHorizontal()) {
  9608. var valueWidth = me.width / offsetAmt;
  9609. var widthOffset = (valueWidth * (index - me.minIndex));
  9610. if (offset) {
  9611. widthOffset += (valueWidth / 2);
  9612. }
  9613. return me.left + widthOffset;
  9614. }
  9615. var valueHeight = me.height / offsetAmt;
  9616. var heightOffset = (valueHeight * (index - me.minIndex));
  9617. if (offset) {
  9618. heightOffset += (valueHeight / 2);
  9619. }
  9620. return me.top + heightOffset;
  9621. },
  9622. getPixelForTick: function(index) {
  9623. return this.getPixelForValue(this.ticks[index], index + this.minIndex, null);
  9624. },
  9625. getValueForPixel: function(pixel) {
  9626. var me = this;
  9627. var offset = me.options.offset;
  9628. var value;
  9629. var offsetAmt = Math.max((me._ticks.length - (offset ? 0 : 1)), 1);
  9630. var horz = me.isHorizontal();
  9631. var valueDimension = (horz ? me.width : me.height) / offsetAmt;
  9632. pixel -= horz ? me.left : me.top;
  9633. if (offset) {
  9634. pixel -= (valueDimension / 2);
  9635. }
  9636. if (pixel <= 0) {
  9637. value = 0;
  9638. } else {
  9639. value = Math.round(pixel / valueDimension);
  9640. }
  9641. return value + me.minIndex;
  9642. },
  9643. getBasePixel: function() {
  9644. return this.bottom;
  9645. }
  9646. });
  9647. // INTERNAL: static default options, registered in src/index.js
  9648. var _defaults = defaultConfig;
  9649. scale_category._defaults = _defaults;
  9650. var noop = helpers$1.noop;
  9651. var isNullOrUndef = helpers$1.isNullOrUndef;
  9652. /**
  9653. * Generate a set of linear ticks
  9654. * @param generationOptions the options used to generate the ticks
  9655. * @param dataRange the range of the data
  9656. * @returns {number[]} array of tick values
  9657. */
  9658. function generateTicks(generationOptions, dataRange) {
  9659. var ticks = [];
  9660. // To get a "nice" value for the tick spacing, we will use the appropriately named
  9661. // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  9662. // for details.
  9663. var MIN_SPACING = 1e-14;
  9664. var stepSize = generationOptions.stepSize;
  9665. var unit = stepSize || 1;
  9666. var maxNumSpaces = generationOptions.maxTicks - 1;
  9667. var min = generationOptions.min;
  9668. var max = generationOptions.max;
  9669. var precision = generationOptions.precision;
  9670. var rmin = dataRange.min;
  9671. var rmax = dataRange.max;
  9672. var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
  9673. var factor, niceMin, niceMax, numSpaces;
  9674. // Beyond MIN_SPACING floating point numbers being to lose precision
  9675. // such that we can't do the math necessary to generate ticks
  9676. if (spacing < MIN_SPACING && isNullOrUndef(min) && isNullOrUndef(max)) {
  9677. return [rmin, rmax];
  9678. }
  9679. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  9680. if (numSpaces > maxNumSpaces) {
  9681. // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
  9682. spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
  9683. }
  9684. if (stepSize || isNullOrUndef(precision)) {
  9685. // If a precision is not specified, calculate factor based on spacing
  9686. factor = Math.pow(10, helpers$1._decimalPlaces(spacing));
  9687. } else {
  9688. // If the user specified a precision, round to that number of decimal places
  9689. factor = Math.pow(10, precision);
  9690. spacing = Math.ceil(spacing * factor) / factor;
  9691. }
  9692. niceMin = Math.floor(rmin / spacing) * spacing;
  9693. niceMax = Math.ceil(rmax / spacing) * spacing;
  9694. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  9695. if (stepSize) {
  9696. // If very close to our whole number, use it.
  9697. if (!isNullOrUndef(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
  9698. niceMin = min;
  9699. }
  9700. if (!isNullOrUndef(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
  9701. niceMax = max;
  9702. }
  9703. }
  9704. numSpaces = (niceMax - niceMin) / spacing;
  9705. // If very close to our rounded value, use it.
  9706. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  9707. numSpaces = Math.round(numSpaces);
  9708. } else {
  9709. numSpaces = Math.ceil(numSpaces);
  9710. }
  9711. niceMin = Math.round(niceMin * factor) / factor;
  9712. niceMax = Math.round(niceMax * factor) / factor;
  9713. ticks.push(isNullOrUndef(min) ? niceMin : min);
  9714. for (var j = 1; j < numSpaces; ++j) {
  9715. ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
  9716. }
  9717. ticks.push(isNullOrUndef(max) ? niceMax : max);
  9718. return ticks;
  9719. }
  9720. var scale_linearbase = core_scale.extend({
  9721. getRightValue: function(value) {
  9722. if (typeof value === 'string') {
  9723. return +value;
  9724. }
  9725. return core_scale.prototype.getRightValue.call(this, value);
  9726. },
  9727. handleTickRangeOptions: function() {
  9728. var me = this;
  9729. var opts = me.options;
  9730. var tickOpts = opts.ticks;
  9731. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  9732. // do nothing since that would make the chart weird. If the user really wants a weird chart
  9733. // axis, they can manually override it
  9734. if (tickOpts.beginAtZero) {
  9735. var minSign = helpers$1.sign(me.min);
  9736. var maxSign = helpers$1.sign(me.max);
  9737. if (minSign < 0 && maxSign < 0) {
  9738. // move the top up to 0
  9739. me.max = 0;
  9740. } else if (minSign > 0 && maxSign > 0) {
  9741. // move the bottom down to 0
  9742. me.min = 0;
  9743. }
  9744. }
  9745. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  9746. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  9747. if (tickOpts.min !== undefined) {
  9748. me.min = tickOpts.min;
  9749. } else if (tickOpts.suggestedMin !== undefined) {
  9750. if (me.min === null) {
  9751. me.min = tickOpts.suggestedMin;
  9752. } else {
  9753. me.min = Math.min(me.min, tickOpts.suggestedMin);
  9754. }
  9755. }
  9756. if (tickOpts.max !== undefined) {
  9757. me.max = tickOpts.max;
  9758. } else if (tickOpts.suggestedMax !== undefined) {
  9759. if (me.max === null) {
  9760. me.max = tickOpts.suggestedMax;
  9761. } else {
  9762. me.max = Math.max(me.max, tickOpts.suggestedMax);
  9763. }
  9764. }
  9765. if (setMin !== setMax) {
  9766. // We set the min or the max but not both.
  9767. // So ensure that our range is good
  9768. // Inverted or 0 length range can happen when
  9769. // ticks.min is set, and no datasets are visible
  9770. if (me.min >= me.max) {
  9771. if (setMin) {
  9772. me.max = me.min + 1;
  9773. } else {
  9774. me.min = me.max - 1;
  9775. }
  9776. }
  9777. }
  9778. if (me.min === me.max) {
  9779. me.max++;
  9780. if (!tickOpts.beginAtZero) {
  9781. me.min--;
  9782. }
  9783. }
  9784. },
  9785. getTickLimit: function() {
  9786. var me = this;
  9787. var tickOpts = me.options.ticks;
  9788. var stepSize = tickOpts.stepSize;
  9789. var maxTicksLimit = tickOpts.maxTicksLimit;
  9790. var maxTicks;
  9791. if (stepSize) {
  9792. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  9793. } else {
  9794. maxTicks = me._computeTickLimit();
  9795. maxTicksLimit = maxTicksLimit || 11;
  9796. }
  9797. if (maxTicksLimit) {
  9798. maxTicks = Math.min(maxTicksLimit, maxTicks);
  9799. }
  9800. return maxTicks;
  9801. },
  9802. _computeTickLimit: function() {
  9803. return Number.POSITIVE_INFINITY;
  9804. },
  9805. handleDirectionalChanges: noop,
  9806. buildTicks: function() {
  9807. var me = this;
  9808. var opts = me.options;
  9809. var tickOpts = opts.ticks;
  9810. // Figure out what the max number of ticks we can support it is based on the size of
  9811. // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
  9812. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  9813. // the graph. Make sure we always have at least 2 ticks
  9814. var maxTicks = me.getTickLimit();
  9815. maxTicks = Math.max(2, maxTicks);
  9816. var numericGeneratorOptions = {
  9817. maxTicks: maxTicks,
  9818. min: tickOpts.min,
  9819. max: tickOpts.max,
  9820. precision: tickOpts.precision,
  9821. stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  9822. };
  9823. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  9824. me.handleDirectionalChanges();
  9825. // At this point, we need to update our max and min given the tick values since we have expanded the
  9826. // range of the scale
  9827. me.max = helpers$1.max(ticks);
  9828. me.min = helpers$1.min(ticks);
  9829. if (tickOpts.reverse) {
  9830. ticks.reverse();
  9831. me.start = me.max;
  9832. me.end = me.min;
  9833. } else {
  9834. me.start = me.min;
  9835. me.end = me.max;
  9836. }
  9837. },
  9838. convertTicksToLabels: function() {
  9839. var me = this;
  9840. me.ticksAsNumbers = me.ticks.slice();
  9841. me.zeroLineIndex = me.ticks.indexOf(0);
  9842. core_scale.prototype.convertTicksToLabels.call(me);
  9843. }
  9844. });
  9845. var defaultConfig$1 = {
  9846. position: 'left',
  9847. ticks: {
  9848. callback: core_ticks.formatters.linear
  9849. }
  9850. };
  9851. var scale_linear = scale_linearbase.extend({
  9852. determineDataLimits: function() {
  9853. var me = this;
  9854. var opts = me.options;
  9855. var chart = me.chart;
  9856. var data = chart.data;
  9857. var datasets = data.datasets;
  9858. var isHorizontal = me.isHorizontal();
  9859. var DEFAULT_MIN = 0;
  9860. var DEFAULT_MAX = 1;
  9861. function IDMatches(meta) {
  9862. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  9863. }
  9864. // First Calculate the range
  9865. me.min = null;
  9866. me.max = null;
  9867. var hasStacks = opts.stacked;
  9868. if (hasStacks === undefined) {
  9869. helpers$1.each(datasets, function(dataset, datasetIndex) {
  9870. if (hasStacks) {
  9871. return;
  9872. }
  9873. var meta = chart.getDatasetMeta(datasetIndex);
  9874. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  9875. meta.stack !== undefined) {
  9876. hasStacks = true;
  9877. }
  9878. });
  9879. }
  9880. if (opts.stacked || hasStacks) {
  9881. var valuesPerStack = {};
  9882. helpers$1.each(datasets, function(dataset, datasetIndex) {
  9883. var meta = chart.getDatasetMeta(datasetIndex);
  9884. var key = [
  9885. meta.type,
  9886. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  9887. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  9888. meta.stack
  9889. ].join('.');
  9890. if (valuesPerStack[key] === undefined) {
  9891. valuesPerStack[key] = {
  9892. positiveValues: [],
  9893. negativeValues: []
  9894. };
  9895. }
  9896. // Store these per type
  9897. var positiveValues = valuesPerStack[key].positiveValues;
  9898. var negativeValues = valuesPerStack[key].negativeValues;
  9899. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  9900. helpers$1.each(dataset.data, function(rawValue, index) {
  9901. var value = +me.getRightValue(rawValue);
  9902. if (isNaN(value) || meta.data[index].hidden) {
  9903. return;
  9904. }
  9905. positiveValues[index] = positiveValues[index] || 0;
  9906. negativeValues[index] = negativeValues[index] || 0;
  9907. if (opts.relativePoints) {
  9908. positiveValues[index] = 100;
  9909. } else if (value < 0) {
  9910. negativeValues[index] += value;
  9911. } else {
  9912. positiveValues[index] += value;
  9913. }
  9914. });
  9915. }
  9916. });
  9917. helpers$1.each(valuesPerStack, function(valuesForType) {
  9918. var values = valuesForType.positiveValues.concat(valuesForType.negativeValues);
  9919. var minVal = helpers$1.min(values);
  9920. var maxVal = helpers$1.max(values);
  9921. me.min = me.min === null ? minVal : Math.min(me.min, minVal);
  9922. me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
  9923. });
  9924. } else {
  9925. helpers$1.each(datasets, function(dataset, datasetIndex) {
  9926. var meta = chart.getDatasetMeta(datasetIndex);
  9927. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  9928. helpers$1.each(dataset.data, function(rawValue, index) {
  9929. var value = +me.getRightValue(rawValue);
  9930. if (isNaN(value) || meta.data[index].hidden) {
  9931. return;
  9932. }
  9933. if (me.min === null) {
  9934. me.min = value;
  9935. } else if (value < me.min) {
  9936. me.min = value;
  9937. }
  9938. if (me.max === null) {
  9939. me.max = value;
  9940. } else if (value > me.max) {
  9941. me.max = value;
  9942. }
  9943. });
  9944. }
  9945. });
  9946. }
  9947. me.min = isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  9948. me.max = isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  9949. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  9950. this.handleTickRangeOptions();
  9951. },
  9952. // Returns the maximum number of ticks based on the scale dimension
  9953. _computeTickLimit: function() {
  9954. var me = this;
  9955. var tickFont;
  9956. if (me.isHorizontal()) {
  9957. return Math.ceil(me.width / 40);
  9958. }
  9959. tickFont = helpers$1.options._parseFont(me.options.ticks);
  9960. return Math.ceil(me.height / tickFont.lineHeight);
  9961. },
  9962. // Called after the ticks are built. We need
  9963. handleDirectionalChanges: function() {
  9964. if (!this.isHorizontal()) {
  9965. // We are in a vertical orientation. The top value is the highest. So reverse the array
  9966. this.ticks.reverse();
  9967. }
  9968. },
  9969. getLabelForIndex: function(index, datasetIndex) {
  9970. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  9971. },
  9972. // Utils
  9973. getPixelForValue: function(value) {
  9974. // This must be called after fit has been run so that
  9975. // this.left, this.top, this.right, and this.bottom have been defined
  9976. var me = this;
  9977. var start = me.start;
  9978. var rightValue = +me.getRightValue(value);
  9979. var pixel;
  9980. var range = me.end - start;
  9981. if (me.isHorizontal()) {
  9982. pixel = me.left + (me.width / range * (rightValue - start));
  9983. } else {
  9984. pixel = me.bottom - (me.height / range * (rightValue - start));
  9985. }
  9986. return pixel;
  9987. },
  9988. getValueForPixel: function(pixel) {
  9989. var me = this;
  9990. var isHorizontal = me.isHorizontal();
  9991. var innerDimension = isHorizontal ? me.width : me.height;
  9992. var offset = (isHorizontal ? pixel - me.left : me.bottom - pixel) / innerDimension;
  9993. return me.start + ((me.end - me.start) * offset);
  9994. },
  9995. getPixelForTick: function(index) {
  9996. return this.getPixelForValue(this.ticksAsNumbers[index]);
  9997. }
  9998. });
  9999. // INTERNAL: static default options, registered in src/index.js
  10000. var _defaults$1 = defaultConfig$1;
  10001. scale_linear._defaults = _defaults$1;
  10002. var valueOrDefault$a = helpers$1.valueOrDefault;
  10003. /**
  10004. * Generate a set of logarithmic ticks
  10005. * @param generationOptions the options used to generate the ticks
  10006. * @param dataRange the range of the data
  10007. * @returns {number[]} array of tick values
  10008. */
  10009. function generateTicks$1(generationOptions, dataRange) {
  10010. var ticks = [];
  10011. var tickVal = valueOrDefault$a(generationOptions.min, Math.pow(10, Math.floor(helpers$1.log10(dataRange.min))));
  10012. var endExp = Math.floor(helpers$1.log10(dataRange.max));
  10013. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  10014. var exp, significand;
  10015. if (tickVal === 0) {
  10016. exp = Math.floor(helpers$1.log10(dataRange.minNotZero));
  10017. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  10018. ticks.push(tickVal);
  10019. tickVal = significand * Math.pow(10, exp);
  10020. } else {
  10021. exp = Math.floor(helpers$1.log10(tickVal));
  10022. significand = Math.floor(tickVal / Math.pow(10, exp));
  10023. }
  10024. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  10025. do {
  10026. ticks.push(tickVal);
  10027. ++significand;
  10028. if (significand === 10) {
  10029. significand = 1;
  10030. ++exp;
  10031. precision = exp >= 0 ? 1 : precision;
  10032. }
  10033. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  10034. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  10035. var lastTick = valueOrDefault$a(generationOptions.max, tickVal);
  10036. ticks.push(lastTick);
  10037. return ticks;
  10038. }
  10039. var defaultConfig$2 = {
  10040. position: 'left',
  10041. // label settings
  10042. ticks: {
  10043. callback: core_ticks.formatters.logarithmic
  10044. }
  10045. };
  10046. // TODO(v3): change this to positiveOrDefault
  10047. function nonNegativeOrDefault(value, defaultValue) {
  10048. return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;
  10049. }
  10050. var scale_logarithmic = core_scale.extend({
  10051. determineDataLimits: function() {
  10052. var me = this;
  10053. var opts = me.options;
  10054. var chart = me.chart;
  10055. var data = chart.data;
  10056. var datasets = data.datasets;
  10057. var isHorizontal = me.isHorizontal();
  10058. function IDMatches(meta) {
  10059. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  10060. }
  10061. // Calculate Range
  10062. me.min = null;
  10063. me.max = null;
  10064. me.minNotZero = null;
  10065. var hasStacks = opts.stacked;
  10066. if (hasStacks === undefined) {
  10067. helpers$1.each(datasets, function(dataset, datasetIndex) {
  10068. if (hasStacks) {
  10069. return;
  10070. }
  10071. var meta = chart.getDatasetMeta(datasetIndex);
  10072. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  10073. meta.stack !== undefined) {
  10074. hasStacks = true;
  10075. }
  10076. });
  10077. }
  10078. if (opts.stacked || hasStacks) {
  10079. var valuesPerStack = {};
  10080. helpers$1.each(datasets, function(dataset, datasetIndex) {
  10081. var meta = chart.getDatasetMeta(datasetIndex);
  10082. var key = [
  10083. meta.type,
  10084. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  10085. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  10086. meta.stack
  10087. ].join('.');
  10088. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  10089. if (valuesPerStack[key] === undefined) {
  10090. valuesPerStack[key] = [];
  10091. }
  10092. helpers$1.each(dataset.data, function(rawValue, index) {
  10093. var values = valuesPerStack[key];
  10094. var value = +me.getRightValue(rawValue);
  10095. // invalid, hidden and negative values are ignored
  10096. if (isNaN(value) || meta.data[index].hidden || value < 0) {
  10097. return;
  10098. }
  10099. values[index] = values[index] || 0;
  10100. values[index] += value;
  10101. });
  10102. }
  10103. });
  10104. helpers$1.each(valuesPerStack, function(valuesForType) {
  10105. if (valuesForType.length > 0) {
  10106. var minVal = helpers$1.min(valuesForType);
  10107. var maxVal = helpers$1.max(valuesForType);
  10108. me.min = me.min === null ? minVal : Math.min(me.min, minVal);
  10109. me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
  10110. }
  10111. });
  10112. } else {
  10113. helpers$1.each(datasets, function(dataset, datasetIndex) {
  10114. var meta = chart.getDatasetMeta(datasetIndex);
  10115. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  10116. helpers$1.each(dataset.data, function(rawValue, index) {
  10117. var value = +me.getRightValue(rawValue);
  10118. // invalid, hidden and negative values are ignored
  10119. if (isNaN(value) || meta.data[index].hidden || value < 0) {
  10120. return;
  10121. }
  10122. if (me.min === null) {
  10123. me.min = value;
  10124. } else if (value < me.min) {
  10125. me.min = value;
  10126. }
  10127. if (me.max === null) {
  10128. me.max = value;
  10129. } else if (value > me.max) {
  10130. me.max = value;
  10131. }
  10132. if (value !== 0 && (me.minNotZero === null || value < me.minNotZero)) {
  10133. me.minNotZero = value;
  10134. }
  10135. });
  10136. }
  10137. });
  10138. }
  10139. // Common base implementation to handle ticks.min, ticks.max
  10140. this.handleTickRangeOptions();
  10141. },
  10142. handleTickRangeOptions: function() {
  10143. var me = this;
  10144. var tickOpts = me.options.ticks;
  10145. var DEFAULT_MIN = 1;
  10146. var DEFAULT_MAX = 10;
  10147. me.min = nonNegativeOrDefault(tickOpts.min, me.min);
  10148. me.max = nonNegativeOrDefault(tickOpts.max, me.max);
  10149. if (me.min === me.max) {
  10150. if (me.min !== 0 && me.min !== null) {
  10151. me.min = Math.pow(10, Math.floor(helpers$1.log10(me.min)) - 1);
  10152. me.max = Math.pow(10, Math.floor(helpers$1.log10(me.max)) + 1);
  10153. } else {
  10154. me.min = DEFAULT_MIN;
  10155. me.max = DEFAULT_MAX;
  10156. }
  10157. }
  10158. if (me.min === null) {
  10159. me.min = Math.pow(10, Math.floor(helpers$1.log10(me.max)) - 1);
  10160. }
  10161. if (me.max === null) {
  10162. me.max = me.min !== 0
  10163. ? Math.pow(10, Math.floor(helpers$1.log10(me.min)) + 1)
  10164. : DEFAULT_MAX;
  10165. }
  10166. if (me.minNotZero === null) {
  10167. if (me.min > 0) {
  10168. me.minNotZero = me.min;
  10169. } else if (me.max < 1) {
  10170. me.minNotZero = Math.pow(10, Math.floor(helpers$1.log10(me.max)));
  10171. } else {
  10172. me.minNotZero = DEFAULT_MIN;
  10173. }
  10174. }
  10175. },
  10176. buildTicks: function() {
  10177. var me = this;
  10178. var tickOpts = me.options.ticks;
  10179. var reverse = !me.isHorizontal();
  10180. var generationOptions = {
  10181. min: nonNegativeOrDefault(tickOpts.min),
  10182. max: nonNegativeOrDefault(tickOpts.max)
  10183. };
  10184. var ticks = me.ticks = generateTicks$1(generationOptions, me);
  10185. // At this point, we need to update our max and min given the tick values since we have expanded the
  10186. // range of the scale
  10187. me.max = helpers$1.max(ticks);
  10188. me.min = helpers$1.min(ticks);
  10189. if (tickOpts.reverse) {
  10190. reverse = !reverse;
  10191. me.start = me.max;
  10192. me.end = me.min;
  10193. } else {
  10194. me.start = me.min;
  10195. me.end = me.max;
  10196. }
  10197. if (reverse) {
  10198. ticks.reverse();
  10199. }
  10200. },
  10201. convertTicksToLabels: function() {
  10202. this.tickValues = this.ticks.slice();
  10203. core_scale.prototype.convertTicksToLabels.call(this);
  10204. },
  10205. // Get the correct tooltip label
  10206. getLabelForIndex: function(index, datasetIndex) {
  10207. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  10208. },
  10209. getPixelForTick: function(index) {
  10210. return this.getPixelForValue(this.tickValues[index]);
  10211. },
  10212. /**
  10213. * Returns the value of the first tick.
  10214. * @param {number} value - The minimum not zero value.
  10215. * @return {number} The first tick value.
  10216. * @private
  10217. */
  10218. _getFirstTickValue: function(value) {
  10219. var exp = Math.floor(helpers$1.log10(value));
  10220. var significand = Math.floor(value / Math.pow(10, exp));
  10221. return significand * Math.pow(10, exp);
  10222. },
  10223. getPixelForValue: function(value) {
  10224. var me = this;
  10225. var tickOpts = me.options.ticks;
  10226. var reverse = tickOpts.reverse;
  10227. var log10 = helpers$1.log10;
  10228. var firstTickValue = me._getFirstTickValue(me.minNotZero);
  10229. var offset = 0;
  10230. var innerDimension, pixel, start, end, sign;
  10231. value = +me.getRightValue(value);
  10232. if (reverse) {
  10233. start = me.end;
  10234. end = me.start;
  10235. sign = -1;
  10236. } else {
  10237. start = me.start;
  10238. end = me.end;
  10239. sign = 1;
  10240. }
  10241. if (me.isHorizontal()) {
  10242. innerDimension = me.width;
  10243. pixel = reverse ? me.right : me.left;
  10244. } else {
  10245. innerDimension = me.height;
  10246. sign *= -1; // invert, since the upper-left corner of the canvas is at pixel (0, 0)
  10247. pixel = reverse ? me.top : me.bottom;
  10248. }
  10249. if (value !== start) {
  10250. if (start === 0) { // include zero tick
  10251. offset = valueOrDefault$a(tickOpts.fontSize, core_defaults.global.defaultFontSize);
  10252. innerDimension -= offset;
  10253. start = firstTickValue;
  10254. }
  10255. if (value !== 0) {
  10256. offset += innerDimension / (log10(end) - log10(start)) * (log10(value) - log10(start));
  10257. }
  10258. pixel += sign * offset;
  10259. }
  10260. return pixel;
  10261. },
  10262. getValueForPixel: function(pixel) {
  10263. var me = this;
  10264. var tickOpts = me.options.ticks;
  10265. var reverse = tickOpts.reverse;
  10266. var log10 = helpers$1.log10;
  10267. var firstTickValue = me._getFirstTickValue(me.minNotZero);
  10268. var innerDimension, start, end, value;
  10269. if (reverse) {
  10270. start = me.end;
  10271. end = me.start;
  10272. } else {
  10273. start = me.start;
  10274. end = me.end;
  10275. }
  10276. if (me.isHorizontal()) {
  10277. innerDimension = me.width;
  10278. value = reverse ? me.right - pixel : pixel - me.left;
  10279. } else {
  10280. innerDimension = me.height;
  10281. value = reverse ? pixel - me.top : me.bottom - pixel;
  10282. }
  10283. if (value !== start) {
  10284. if (start === 0) { // include zero tick
  10285. var offset = valueOrDefault$a(tickOpts.fontSize, core_defaults.global.defaultFontSize);
  10286. value -= offset;
  10287. innerDimension -= offset;
  10288. start = firstTickValue;
  10289. }
  10290. value *= log10(end) - log10(start);
  10291. value /= innerDimension;
  10292. value = Math.pow(10, log10(start) + value);
  10293. }
  10294. return value;
  10295. }
  10296. });
  10297. // INTERNAL: static default options, registered in src/index.js
  10298. var _defaults$2 = defaultConfig$2;
  10299. scale_logarithmic._defaults = _defaults$2;
  10300. var valueOrDefault$b = helpers$1.valueOrDefault;
  10301. var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
  10302. var resolve$7 = helpers$1.options.resolve;
  10303. var defaultConfig$3 = {
  10304. display: true,
  10305. // Boolean - Whether to animate scaling the chart from the centre
  10306. animate: true,
  10307. position: 'chartArea',
  10308. angleLines: {
  10309. display: true,
  10310. color: 'rgba(0, 0, 0, 0.1)',
  10311. lineWidth: 1,
  10312. borderDash: [],
  10313. borderDashOffset: 0.0
  10314. },
  10315. gridLines: {
  10316. circular: false
  10317. },
  10318. // label settings
  10319. ticks: {
  10320. // Boolean - Show a backdrop to the scale label
  10321. showLabelBackdrop: true,
  10322. // String - The colour of the label backdrop
  10323. backdropColor: 'rgba(255,255,255,0.75)',
  10324. // Number - The backdrop padding above & below the label in pixels
  10325. backdropPaddingY: 2,
  10326. // Number - The backdrop padding to the side of the label in pixels
  10327. backdropPaddingX: 2,
  10328. callback: core_ticks.formatters.linear
  10329. },
  10330. pointLabels: {
  10331. // Boolean - if true, show point labels
  10332. display: true,
  10333. // Number - Point label font size in pixels
  10334. fontSize: 10,
  10335. // Function - Used to convert point labels
  10336. callback: function(label) {
  10337. return label;
  10338. }
  10339. }
  10340. };
  10341. function getValueCount(scale) {
  10342. var opts = scale.options;
  10343. return opts.angleLines.display || opts.pointLabels.display ? scale.chart.data.labels.length : 0;
  10344. }
  10345. function getTickBackdropHeight(opts) {
  10346. var tickOpts = opts.ticks;
  10347. if (tickOpts.display && opts.display) {
  10348. return valueOrDefault$b(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
  10349. }
  10350. return 0;
  10351. }
  10352. function measureLabelSize(ctx, lineHeight, label) {
  10353. if (helpers$1.isArray(label)) {
  10354. return {
  10355. w: helpers$1.longestText(ctx, ctx.font, label),
  10356. h: label.length * lineHeight
  10357. };
  10358. }
  10359. return {
  10360. w: ctx.measureText(label).width,
  10361. h: lineHeight
  10362. };
  10363. }
  10364. function determineLimits(angle, pos, size, min, max) {
  10365. if (angle === min || angle === max) {
  10366. return {
  10367. start: pos - (size / 2),
  10368. end: pos + (size / 2)
  10369. };
  10370. } else if (angle < min || angle > max) {
  10371. return {
  10372. start: pos - size,
  10373. end: pos
  10374. };
  10375. }
  10376. return {
  10377. start: pos,
  10378. end: pos + size
  10379. };
  10380. }
  10381. /**
  10382. * Helper function to fit a radial linear scale with point labels
  10383. */
  10384. function fitWithPointLabels(scale) {
  10385. // Right, this is really confusing and there is a lot of maths going on here
  10386. // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  10387. //
  10388. // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  10389. //
  10390. // Solution:
  10391. //
  10392. // We assume the radius of the polygon is half the size of the canvas at first
  10393. // at each index we check if the text overlaps.
  10394. //
  10395. // Where it does, we store that angle and that index.
  10396. //
  10397. // After finding the largest index and angle we calculate how much we need to remove
  10398. // from the shape radius to move the point inwards by that x.
  10399. //
  10400. // We average the left and right distances to get the maximum shape radius that can fit in the box
  10401. // along with labels.
  10402. //
  10403. // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  10404. // on each side, removing that from the size, halving it and adding the left x protrusion width.
  10405. //
  10406. // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  10407. // and position it in the most space efficient manner
  10408. //
  10409. // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  10410. var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
  10411. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  10412. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  10413. var furthestLimits = {
  10414. l: 0,
  10415. r: scale.width,
  10416. t: 0,
  10417. b: scale.height - scale.paddingTop
  10418. };
  10419. var furthestAngles = {};
  10420. var i, textSize, pointPosition;
  10421. scale.ctx.font = plFont.string;
  10422. scale._pointLabelSizes = [];
  10423. var valueCount = getValueCount(scale);
  10424. for (i = 0; i < valueCount; i++) {
  10425. pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
  10426. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i] || '');
  10427. scale._pointLabelSizes[i] = textSize;
  10428. // Add quarter circle to make degree 0 mean top of circle
  10429. var angleRadians = scale.getIndexAngle(i);
  10430. var angle = helpers$1.toDegrees(angleRadians) % 360;
  10431. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  10432. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  10433. if (hLimits.start < furthestLimits.l) {
  10434. furthestLimits.l = hLimits.start;
  10435. furthestAngles.l = angleRadians;
  10436. }
  10437. if (hLimits.end > furthestLimits.r) {
  10438. furthestLimits.r = hLimits.end;
  10439. furthestAngles.r = angleRadians;
  10440. }
  10441. if (vLimits.start < furthestLimits.t) {
  10442. furthestLimits.t = vLimits.start;
  10443. furthestAngles.t = angleRadians;
  10444. }
  10445. if (vLimits.end > furthestLimits.b) {
  10446. furthestLimits.b = vLimits.end;
  10447. furthestAngles.b = angleRadians;
  10448. }
  10449. }
  10450. scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  10451. }
  10452. function getTextAlignForAngle(angle) {
  10453. if (angle === 0 || angle === 180) {
  10454. return 'center';
  10455. } else if (angle < 180) {
  10456. return 'left';
  10457. }
  10458. return 'right';
  10459. }
  10460. function fillText(ctx, text, position, lineHeight) {
  10461. var y = position.y + lineHeight / 2;
  10462. var i, ilen;
  10463. if (helpers$1.isArray(text)) {
  10464. for (i = 0, ilen = text.length; i < ilen; ++i) {
  10465. ctx.fillText(text[i], position.x, y);
  10466. y += lineHeight;
  10467. }
  10468. } else {
  10469. ctx.fillText(text, position.x, y);
  10470. }
  10471. }
  10472. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  10473. if (angle === 90 || angle === 270) {
  10474. position.y -= (textSize.h / 2);
  10475. } else if (angle > 270 || angle < 90) {
  10476. position.y -= textSize.h;
  10477. }
  10478. }
  10479. function drawPointLabels(scale) {
  10480. var ctx = scale.ctx;
  10481. var opts = scale.options;
  10482. var angleLineOpts = opts.angleLines;
  10483. var gridLineOpts = opts.gridLines;
  10484. var pointLabelOpts = opts.pointLabels;
  10485. var lineWidth = valueOrDefault$b(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
  10486. var lineColor = valueOrDefault$b(angleLineOpts.color, gridLineOpts.color);
  10487. var tickBackdropHeight = getTickBackdropHeight(opts);
  10488. ctx.save();
  10489. ctx.lineWidth = lineWidth;
  10490. ctx.strokeStyle = lineColor;
  10491. if (ctx.setLineDash) {
  10492. ctx.setLineDash(resolve$7([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
  10493. ctx.lineDashOffset = resolve$7([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
  10494. }
  10495. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  10496. // Point Label Font
  10497. var plFont = helpers$1.options._parseFont(pointLabelOpts);
  10498. ctx.font = plFont.string;
  10499. ctx.textBaseline = 'middle';
  10500. for (var i = getValueCount(scale) - 1; i >= 0; i--) {
  10501. if (angleLineOpts.display && lineWidth && lineColor) {
  10502. var outerPosition = scale.getPointPosition(i, outerDistance);
  10503. ctx.beginPath();
  10504. ctx.moveTo(scale.xCenter, scale.yCenter);
  10505. ctx.lineTo(outerPosition.x, outerPosition.y);
  10506. ctx.stroke();
  10507. }
  10508. if (pointLabelOpts.display) {
  10509. // Extra pixels out for some label spacing
  10510. var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  10511. var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
  10512. // Keep this in loop since we may support array properties here
  10513. var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
  10514. ctx.fillStyle = pointLabelFontColor;
  10515. var angleRadians = scale.getIndexAngle(i);
  10516. var angle = helpers$1.toDegrees(angleRadians);
  10517. ctx.textAlign = getTextAlignForAngle(angle);
  10518. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  10519. fillText(ctx, scale.pointLabels[i] || '', pointLabelPosition, plFont.lineHeight);
  10520. }
  10521. }
  10522. ctx.restore();
  10523. }
  10524. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  10525. var ctx = scale.ctx;
  10526. var circular = gridLineOpts.circular;
  10527. var valueCount = getValueCount(scale);
  10528. var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
  10529. var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
  10530. var pointPosition;
  10531. if ((!circular && !valueCount) || !lineColor || !lineWidth) {
  10532. return;
  10533. }
  10534. ctx.save();
  10535. ctx.strokeStyle = lineColor;
  10536. ctx.lineWidth = lineWidth;
  10537. if (ctx.setLineDash) {
  10538. ctx.setLineDash(gridLineOpts.borderDash || []);
  10539. ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
  10540. }
  10541. ctx.beginPath();
  10542. if (circular) {
  10543. // Draw circular arcs between the points
  10544. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  10545. } else {
  10546. // Draw straight lines connecting each index
  10547. pointPosition = scale.getPointPosition(0, radius);
  10548. ctx.moveTo(pointPosition.x, pointPosition.y);
  10549. for (var i = 1; i < valueCount; i++) {
  10550. pointPosition = scale.getPointPosition(i, radius);
  10551. ctx.lineTo(pointPosition.x, pointPosition.y);
  10552. }
  10553. }
  10554. ctx.closePath();
  10555. ctx.stroke();
  10556. ctx.restore();
  10557. }
  10558. function numberOrZero(param) {
  10559. return helpers$1.isNumber(param) ? param : 0;
  10560. }
  10561. var scale_radialLinear = scale_linearbase.extend({
  10562. setDimensions: function() {
  10563. var me = this;
  10564. // Set the unconstrained dimension before label rotation
  10565. me.width = me.maxWidth;
  10566. me.height = me.maxHeight;
  10567. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  10568. me.xCenter = Math.floor(me.width / 2);
  10569. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  10570. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  10571. },
  10572. determineDataLimits: function() {
  10573. var me = this;
  10574. var chart = me.chart;
  10575. var min = Number.POSITIVE_INFINITY;
  10576. var max = Number.NEGATIVE_INFINITY;
  10577. helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {
  10578. if (chart.isDatasetVisible(datasetIndex)) {
  10579. var meta = chart.getDatasetMeta(datasetIndex);
  10580. helpers$1.each(dataset.data, function(rawValue, index) {
  10581. var value = +me.getRightValue(rawValue);
  10582. if (isNaN(value) || meta.data[index].hidden) {
  10583. return;
  10584. }
  10585. min = Math.min(value, min);
  10586. max = Math.max(value, max);
  10587. });
  10588. }
  10589. });
  10590. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  10591. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  10592. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  10593. me.handleTickRangeOptions();
  10594. },
  10595. // Returns the maximum number of ticks based on the scale dimension
  10596. _computeTickLimit: function() {
  10597. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  10598. },
  10599. convertTicksToLabels: function() {
  10600. var me = this;
  10601. scale_linearbase.prototype.convertTicksToLabels.call(me);
  10602. // Point labels
  10603. me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me);
  10604. },
  10605. getLabelForIndex: function(index, datasetIndex) {
  10606. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  10607. },
  10608. fit: function() {
  10609. var me = this;
  10610. var opts = me.options;
  10611. if (opts.display && opts.pointLabels.display) {
  10612. fitWithPointLabels(me);
  10613. } else {
  10614. me.setCenterPoint(0, 0, 0, 0);
  10615. }
  10616. },
  10617. /**
  10618. * Set radius reductions and determine new radius and center point
  10619. * @private
  10620. */
  10621. setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
  10622. var me = this;
  10623. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  10624. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  10625. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  10626. var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  10627. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  10628. radiusReductionRight = numberOrZero(radiusReductionRight);
  10629. radiusReductionTop = numberOrZero(radiusReductionTop);
  10630. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  10631. me.drawingArea = Math.min(
  10632. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  10633. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  10634. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  10635. },
  10636. setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
  10637. var me = this;
  10638. var maxRight = me.width - rightMovement - me.drawingArea;
  10639. var maxLeft = leftMovement + me.drawingArea;
  10640. var maxTop = topMovement + me.drawingArea;
  10641. var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  10642. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  10643. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  10644. },
  10645. getIndexAngle: function(index) {
  10646. var angleMultiplier = (Math.PI * 2) / getValueCount(this);
  10647. var startAngle = this.chart.options && this.chart.options.startAngle ?
  10648. this.chart.options.startAngle :
  10649. 0;
  10650. var startAngleRadians = startAngle * Math.PI * 2 / 360;
  10651. // Start from the top instead of right, so remove a quarter of the circle
  10652. return index * angleMultiplier + startAngleRadians;
  10653. },
  10654. getDistanceFromCenterForValue: function(value) {
  10655. var me = this;
  10656. if (value === null) {
  10657. return 0; // null always in center
  10658. }
  10659. // Take into account half font size + the yPadding of the top value
  10660. var scalingFactor = me.drawingArea / (me.max - me.min);
  10661. if (me.options.ticks.reverse) {
  10662. return (me.max - value) * scalingFactor;
  10663. }
  10664. return (value - me.min) * scalingFactor;
  10665. },
  10666. getPointPosition: function(index, distanceFromCenter) {
  10667. var me = this;
  10668. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  10669. return {
  10670. x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
  10671. y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
  10672. };
  10673. },
  10674. getPointPositionForValue: function(index, value) {
  10675. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  10676. },
  10677. getBasePosition: function() {
  10678. var me = this;
  10679. var min = me.min;
  10680. var max = me.max;
  10681. return me.getPointPositionForValue(0,
  10682. me.beginAtZero ? 0 :
  10683. min < 0 && max < 0 ? max :
  10684. min > 0 && max > 0 ? min :
  10685. 0);
  10686. },
  10687. draw: function() {
  10688. var me = this;
  10689. var opts = me.options;
  10690. var gridLineOpts = opts.gridLines;
  10691. var tickOpts = opts.ticks;
  10692. if (opts.display) {
  10693. var ctx = me.ctx;
  10694. var startAngle = this.getIndexAngle(0);
  10695. var tickFont = helpers$1.options._parseFont(tickOpts);
  10696. if (opts.angleLines.display || opts.pointLabels.display) {
  10697. drawPointLabels(me);
  10698. }
  10699. helpers$1.each(me.ticks, function(label, index) {
  10700. // Don't draw a centre value (if it is minimum)
  10701. if (index > 0 || tickOpts.reverse) {
  10702. var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  10703. // Draw circular lines around the scale
  10704. if (gridLineOpts.display && index !== 0) {
  10705. drawRadiusLine(me, gridLineOpts, yCenterOffset, index);
  10706. }
  10707. if (tickOpts.display) {
  10708. var tickFontColor = valueOrDefault$b(tickOpts.fontColor, core_defaults.global.defaultFontColor);
  10709. ctx.font = tickFont.string;
  10710. ctx.save();
  10711. ctx.translate(me.xCenter, me.yCenter);
  10712. ctx.rotate(startAngle);
  10713. if (tickOpts.showLabelBackdrop) {
  10714. var labelWidth = ctx.measureText(label).width;
  10715. ctx.fillStyle = tickOpts.backdropColor;
  10716. ctx.fillRect(
  10717. -labelWidth / 2 - tickOpts.backdropPaddingX,
  10718. -yCenterOffset - tickFont.size / 2 - tickOpts.backdropPaddingY,
  10719. labelWidth + tickOpts.backdropPaddingX * 2,
  10720. tickFont.size + tickOpts.backdropPaddingY * 2
  10721. );
  10722. }
  10723. ctx.textAlign = 'center';
  10724. ctx.textBaseline = 'middle';
  10725. ctx.fillStyle = tickFontColor;
  10726. ctx.fillText(label, 0, -yCenterOffset);
  10727. ctx.restore();
  10728. }
  10729. }
  10730. });
  10731. }
  10732. }
  10733. });
  10734. // INTERNAL: static default options, registered in src/index.js
  10735. var _defaults$3 = defaultConfig$3;
  10736. scale_radialLinear._defaults = _defaults$3;
  10737. var valueOrDefault$c = helpers$1.valueOrDefault;
  10738. // Integer constants are from the ES6 spec.
  10739. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  10740. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  10741. var INTERVALS = {
  10742. millisecond: {
  10743. common: true,
  10744. size: 1,
  10745. steps: [1, 2, 5, 10, 20, 50, 100, 250, 500]
  10746. },
  10747. second: {
  10748. common: true,
  10749. size: 1000,
  10750. steps: [1, 2, 5, 10, 15, 30]
  10751. },
  10752. minute: {
  10753. common: true,
  10754. size: 60000,
  10755. steps: [1, 2, 5, 10, 15, 30]
  10756. },
  10757. hour: {
  10758. common: true,
  10759. size: 3600000,
  10760. steps: [1, 2, 3, 6, 12]
  10761. },
  10762. day: {
  10763. common: true,
  10764. size: 86400000,
  10765. steps: [1, 2, 5]
  10766. },
  10767. week: {
  10768. common: false,
  10769. size: 604800000,
  10770. steps: [1, 2, 3, 4]
  10771. },
  10772. month: {
  10773. common: true,
  10774. size: 2.628e9,
  10775. steps: [1, 2, 3]
  10776. },
  10777. quarter: {
  10778. common: false,
  10779. size: 7.884e9,
  10780. steps: [1, 2, 3, 4]
  10781. },
  10782. year: {
  10783. common: true,
  10784. size: 3.154e10
  10785. }
  10786. };
  10787. var UNITS = Object.keys(INTERVALS);
  10788. function sorter(a, b) {
  10789. return a - b;
  10790. }
  10791. function arrayUnique(items) {
  10792. var hash = {};
  10793. var out = [];
  10794. var i, ilen, item;
  10795. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10796. item = items[i];
  10797. if (!hash[item]) {
  10798. hash[item] = true;
  10799. out.push(item);
  10800. }
  10801. }
  10802. return out;
  10803. }
  10804. /**
  10805. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  10806. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  10807. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  10808. * extremity (left + width or top + height). Note that it would be more optimized to directly
  10809. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  10810. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  10811. *
  10812. * @param {number[]} timestamps - timestamps sorted from lowest to highest.
  10813. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
  10814. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  10815. * If 'series', timestamps will be positioned at the same distance from each other. In this
  10816. * case, only timestamps that break the time linearity are registered, meaning that in the
  10817. * best case, all timestamps are linear, the table contains only min and max.
  10818. */
  10819. function buildLookupTable(timestamps, min, max, distribution) {
  10820. if (distribution === 'linear' || !timestamps.length) {
  10821. return [
  10822. {time: min, pos: 0},
  10823. {time: max, pos: 1}
  10824. ];
  10825. }
  10826. var table = [];
  10827. var items = [min];
  10828. var i, ilen, prev, curr, next;
  10829. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  10830. curr = timestamps[i];
  10831. if (curr > min && curr < max) {
  10832. items.push(curr);
  10833. }
  10834. }
  10835. items.push(max);
  10836. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10837. next = items[i + 1];
  10838. prev = items[i - 1];
  10839. curr = items[i];
  10840. // only add points that breaks the scale linearity
  10841. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  10842. table.push({time: curr, pos: i / (ilen - 1)});
  10843. }
  10844. }
  10845. return table;
  10846. }
  10847. // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  10848. function lookup(table, key, value) {
  10849. var lo = 0;
  10850. var hi = table.length - 1;
  10851. var mid, i0, i1;
  10852. while (lo >= 0 && lo <= hi) {
  10853. mid = (lo + hi) >> 1;
  10854. i0 = table[mid - 1] || null;
  10855. i1 = table[mid];
  10856. if (!i0) {
  10857. // given value is outside table (before first item)
  10858. return {lo: null, hi: i1};
  10859. } else if (i1[key] < value) {
  10860. lo = mid + 1;
  10861. } else if (i0[key] > value) {
  10862. hi = mid - 1;
  10863. } else {
  10864. return {lo: i0, hi: i1};
  10865. }
  10866. }
  10867. // given value is outside table (after last item)
  10868. return {lo: i1, hi: null};
  10869. }
  10870. /**
  10871. * Linearly interpolates the given source `value` using the table items `skey` values and
  10872. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  10873. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  10874. * index [0, 1] or [n - 1, n] are used for the interpolation.
  10875. */
  10876. function interpolate$1(table, skey, sval, tkey) {
  10877. var range = lookup(table, skey, sval);
  10878. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  10879. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  10880. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  10881. var span = next[skey] - prev[skey];
  10882. var ratio = span ? (sval - prev[skey]) / span : 0;
  10883. var offset = (next[tkey] - prev[tkey]) * ratio;
  10884. return prev[tkey] + offset;
  10885. }
  10886. function toTimestamp(scale, input) {
  10887. var adapter = scale._adapter;
  10888. var options = scale.options.time;
  10889. var parser = options.parser;
  10890. var format = parser || options.format;
  10891. var value = input;
  10892. if (typeof parser === 'function') {
  10893. value = parser(value);
  10894. }
  10895. // Only parse if its not a timestamp already
  10896. if (!helpers$1.isFinite(value)) {
  10897. value = typeof format === 'string'
  10898. ? adapter.parse(value, format)
  10899. : adapter.parse(value);
  10900. }
  10901. if (value !== null) {
  10902. return +value;
  10903. }
  10904. // Labels are in an incompatible format and no `parser` has been provided.
  10905. // The user might still use the deprecated `format` option for parsing.
  10906. if (!parser && typeof format === 'function') {
  10907. value = format(input);
  10908. // `format` could return something else than a timestamp, if so, parse it
  10909. if (!helpers$1.isFinite(value)) {
  10910. value = adapter.parse(value);
  10911. }
  10912. }
  10913. return value;
  10914. }
  10915. function parse(scale, input) {
  10916. if (helpers$1.isNullOrUndef(input)) {
  10917. return null;
  10918. }
  10919. var options = scale.options.time;
  10920. var value = toTimestamp(scale, scale.getRightValue(input));
  10921. if (value === null) {
  10922. return value;
  10923. }
  10924. if (options.round) {
  10925. value = +scale._adapter.startOf(value, options.round);
  10926. }
  10927. return value;
  10928. }
  10929. /**
  10930. * Returns the number of unit to skip to be able to display up to `capacity` number of ticks
  10931. * in `unit` for the given `min` / `max` range and respecting the interval steps constraints.
  10932. */
  10933. function determineStepSize(min, max, unit, capacity) {
  10934. var range = max - min;
  10935. var interval = INTERVALS[unit];
  10936. var milliseconds = interval.size;
  10937. var steps = interval.steps;
  10938. var i, ilen, factor;
  10939. if (!steps) {
  10940. return Math.ceil(range / (capacity * milliseconds));
  10941. }
  10942. for (i = 0, ilen = steps.length; i < ilen; ++i) {
  10943. factor = steps[i];
  10944. if (Math.ceil(range / (milliseconds * factor)) <= capacity) {
  10945. break;
  10946. }
  10947. }
  10948. return factor;
  10949. }
  10950. /**
  10951. * Figures out what unit results in an appropriate number of auto-generated ticks
  10952. */
  10953. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  10954. var ilen = UNITS.length;
  10955. var i, interval, factor;
  10956. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  10957. interval = INTERVALS[UNITS[i]];
  10958. factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER;
  10959. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  10960. return UNITS[i];
  10961. }
  10962. }
  10963. return UNITS[ilen - 1];
  10964. }
  10965. /**
  10966. * Figures out what unit to format a set of ticks with
  10967. */
  10968. function determineUnitForFormatting(scale, ticks, minUnit, min, max) {
  10969. var ilen = UNITS.length;
  10970. var i, unit;
  10971. for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) {
  10972. unit = UNITS[i];
  10973. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= ticks.length) {
  10974. return unit;
  10975. }
  10976. }
  10977. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  10978. }
  10979. function determineMajorUnit(unit) {
  10980. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  10981. if (INTERVALS[UNITS[i]].common) {
  10982. return UNITS[i];
  10983. }
  10984. }
  10985. }
  10986. /**
  10987. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  10988. * `minor` unit, aligned on the `major` unit and using the given scale time `options`.
  10989. * Important: this method can return ticks outside the min and max range, it's the
  10990. * responsibility of the calling code to clamp values if needed.
  10991. */
  10992. function generate(scale, min, max, capacity) {
  10993. var adapter = scale._adapter;
  10994. var options = scale.options;
  10995. var timeOpts = options.time;
  10996. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  10997. var major = determineMajorUnit(minor);
  10998. var stepSize = valueOrDefault$c(timeOpts.stepSize, timeOpts.unitStepSize);
  10999. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  11000. var majorTicksEnabled = options.ticks.major.enabled;
  11001. var interval = INTERVALS[minor];
  11002. var first = min;
  11003. var last = max;
  11004. var ticks = [];
  11005. var time;
  11006. if (!stepSize) {
  11007. stepSize = determineStepSize(min, max, minor, capacity);
  11008. }
  11009. // For 'week' unit, handle the first day of week option
  11010. if (weekday) {
  11011. first = +adapter.startOf(first, 'isoWeek', weekday);
  11012. last = +adapter.startOf(last, 'isoWeek', weekday);
  11013. }
  11014. // Align first/last ticks on unit
  11015. first = +adapter.startOf(first, weekday ? 'day' : minor);
  11016. last = +adapter.startOf(last, weekday ? 'day' : minor);
  11017. // Make sure that the last tick include max
  11018. if (last < max) {
  11019. last = +adapter.add(last, 1, minor);
  11020. }
  11021. time = first;
  11022. if (majorTicksEnabled && major && !weekday && !timeOpts.round) {
  11023. // Align the first tick on the previous `minor` unit aligned on the `major` unit:
  11024. // we first aligned time on the previous `major` unit then add the number of full
  11025. // stepSize there is between first and the previous major time.
  11026. time = +adapter.startOf(time, major);
  11027. time = +adapter.add(time, ~~((first - time) / (interval.size * stepSize)) * stepSize, minor);
  11028. }
  11029. for (; time < last; time = +adapter.add(time, stepSize, minor)) {
  11030. ticks.push(+time);
  11031. }
  11032. ticks.push(+time);
  11033. return ticks;
  11034. }
  11035. /**
  11036. * Returns the start and end offsets from edges in the form of {start, end}
  11037. * where each value is a relative width to the scale and ranges between 0 and 1.
  11038. * They add extra margins on the both sides by scaling down the original scale.
  11039. * Offsets are added when the `offset` option is true.
  11040. */
  11041. function computeOffsets(table, ticks, min, max, options) {
  11042. var start = 0;
  11043. var end = 0;
  11044. var first, last;
  11045. if (options.offset && ticks.length) {
  11046. if (!options.time.min) {
  11047. first = interpolate$1(table, 'time', ticks[0], 'pos');
  11048. if (ticks.length === 1) {
  11049. start = 1 - first;
  11050. } else {
  11051. start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
  11052. }
  11053. }
  11054. if (!options.time.max) {
  11055. last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
  11056. if (ticks.length === 1) {
  11057. end = last;
  11058. } else {
  11059. end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
  11060. }
  11061. }
  11062. }
  11063. return {start: start, end: end};
  11064. }
  11065. function ticksFromTimestamps(scale, values, majorUnit) {
  11066. var ticks = [];
  11067. var i, ilen, value, major;
  11068. for (i = 0, ilen = values.length; i < ilen; ++i) {
  11069. value = values[i];
  11070. major = majorUnit ? value === +scale._adapter.startOf(value, majorUnit) : false;
  11071. ticks.push({
  11072. value: value,
  11073. major: major
  11074. });
  11075. }
  11076. return ticks;
  11077. }
  11078. var defaultConfig$4 = {
  11079. position: 'bottom',
  11080. /**
  11081. * Data distribution along the scale:
  11082. * - 'linear': data are spread according to their time (distances can vary),
  11083. * - 'series': data are spread at the same distance from each other.
  11084. * @see https://github.com/chartjs/Chart.js/pull/4507
  11085. * @since 2.7.0
  11086. */
  11087. distribution: 'linear',
  11088. /**
  11089. * Scale boundary strategy (bypassed by min/max time options)
  11090. * - `data`: make sure data are fully visible, ticks outside are removed
  11091. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  11092. * @see https://github.com/chartjs/Chart.js/pull/4556
  11093. * @since 2.7.0
  11094. */
  11095. bounds: 'data',
  11096. adapters: {},
  11097. time: {
  11098. 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
  11099. format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from https://momentjs.com/docs/#/parsing/string-format/
  11100. unit: false, // false == automatic or override with week, month, year, etc.
  11101. round: false, // none, or override with week, month, year, etc.
  11102. displayFormat: false, // DEPRECATED
  11103. isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
  11104. minUnit: 'millisecond',
  11105. displayFormats: {}
  11106. },
  11107. ticks: {
  11108. autoSkip: false,
  11109. /**
  11110. * Ticks generation input values:
  11111. * - 'auto': generates "optimal" ticks based on scale size and time options.
  11112. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  11113. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  11114. * @see https://github.com/chartjs/Chart.js/pull/4507
  11115. * @since 2.7.0
  11116. */
  11117. source: 'auto',
  11118. major: {
  11119. enabled: false
  11120. }
  11121. }
  11122. };
  11123. var scale_time = core_scale.extend({
  11124. initialize: function() {
  11125. this.mergeTicksOptions();
  11126. core_scale.prototype.initialize.call(this);
  11127. },
  11128. update: function() {
  11129. var me = this;
  11130. var options = me.options;
  11131. var time = options.time || (options.time = {});
  11132. var adapter = me._adapter = new core_adapters._date(options.adapters.date);
  11133. // DEPRECATIONS: output a message only one time per update
  11134. if (time.format) {
  11135. console.warn('options.time.format is deprecated and replaced by options.time.parser.');
  11136. }
  11137. // Backward compatibility: before introducing adapter, `displayFormats` was
  11138. // supposed to contain *all* unit/string pairs but this can't be resolved
  11139. // when loading the scale (adapters are loaded afterward), so let's populate
  11140. // missing formats on update
  11141. helpers$1.mergeIf(time.displayFormats, adapter.formats());
  11142. return core_scale.prototype.update.apply(me, arguments);
  11143. },
  11144. /**
  11145. * Allows data to be referenced via 't' attribute
  11146. */
  11147. getRightValue: function(rawValue) {
  11148. if (rawValue && rawValue.t !== undefined) {
  11149. rawValue = rawValue.t;
  11150. }
  11151. return core_scale.prototype.getRightValue.call(this, rawValue);
  11152. },
  11153. determineDataLimits: function() {
  11154. var me = this;
  11155. var chart = me.chart;
  11156. var adapter = me._adapter;
  11157. var timeOpts = me.options.time;
  11158. var unit = timeOpts.unit || 'day';
  11159. var min = MAX_INTEGER;
  11160. var max = MIN_INTEGER;
  11161. var timestamps = [];
  11162. var datasets = [];
  11163. var labels = [];
  11164. var i, j, ilen, jlen, data, timestamp;
  11165. var dataLabels = chart.data.labels || [];
  11166. // Convert labels to timestamps
  11167. for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
  11168. labels.push(parse(me, dataLabels[i]));
  11169. }
  11170. // Convert data to timestamps
  11171. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  11172. if (chart.isDatasetVisible(i)) {
  11173. data = chart.data.datasets[i].data;
  11174. // Let's consider that all data have the same format.
  11175. if (helpers$1.isObject(data[0])) {
  11176. datasets[i] = [];
  11177. for (j = 0, jlen = data.length; j < jlen; ++j) {
  11178. timestamp = parse(me, data[j]);
  11179. timestamps.push(timestamp);
  11180. datasets[i][j] = timestamp;
  11181. }
  11182. } else {
  11183. for (j = 0, jlen = labels.length; j < jlen; ++j) {
  11184. timestamps.push(labels[j]);
  11185. }
  11186. datasets[i] = labels.slice(0);
  11187. }
  11188. } else {
  11189. datasets[i] = [];
  11190. }
  11191. }
  11192. if (labels.length) {
  11193. // Sort labels **after** data have been converted
  11194. labels = arrayUnique(labels).sort(sorter);
  11195. min = Math.min(min, labels[0]);
  11196. max = Math.max(max, labels[labels.length - 1]);
  11197. }
  11198. if (timestamps.length) {
  11199. timestamps = arrayUnique(timestamps).sort(sorter);
  11200. min = Math.min(min, timestamps[0]);
  11201. max = Math.max(max, timestamps[timestamps.length - 1]);
  11202. }
  11203. min = parse(me, timeOpts.min) || min;
  11204. max = parse(me, timeOpts.max) || max;
  11205. // In case there is no valid min/max, set limits based on unit time option
  11206. min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
  11207. max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;
  11208. // Make sure that max is strictly higher than min (required by the lookup table)
  11209. me.min = Math.min(min, max);
  11210. me.max = Math.max(min + 1, max);
  11211. // PRIVATE
  11212. me._horizontal = me.isHorizontal();
  11213. me._table = [];
  11214. me._timestamps = {
  11215. data: timestamps,
  11216. datasets: datasets,
  11217. labels: labels
  11218. };
  11219. },
  11220. buildTicks: function() {
  11221. var me = this;
  11222. var min = me.min;
  11223. var max = me.max;
  11224. var options = me.options;
  11225. var timeOpts = options.time;
  11226. var timestamps = [];
  11227. var ticks = [];
  11228. var i, ilen, timestamp;
  11229. switch (options.ticks.source) {
  11230. case 'data':
  11231. timestamps = me._timestamps.data;
  11232. break;
  11233. case 'labels':
  11234. timestamps = me._timestamps.labels;
  11235. break;
  11236. case 'auto':
  11237. default:
  11238. timestamps = generate(me, min, max, me.getLabelCapacity(min), options);
  11239. }
  11240. if (options.bounds === 'ticks' && timestamps.length) {
  11241. min = timestamps[0];
  11242. max = timestamps[timestamps.length - 1];
  11243. }
  11244. // Enforce limits with user min/max options
  11245. min = parse(me, timeOpts.min) || min;
  11246. max = parse(me, timeOpts.max) || max;
  11247. // Remove ticks outside the min/max range
  11248. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  11249. timestamp = timestamps[i];
  11250. if (timestamp >= min && timestamp <= max) {
  11251. ticks.push(timestamp);
  11252. }
  11253. }
  11254. me.min = min;
  11255. me.max = max;
  11256. // PRIVATE
  11257. me._unit = timeOpts.unit || determineUnitForFormatting(me, ticks, timeOpts.minUnit, me.min, me.max);
  11258. me._majorUnit = determineMajorUnit(me._unit);
  11259. me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution);
  11260. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  11261. if (options.ticks.reverse) {
  11262. ticks.reverse();
  11263. }
  11264. return ticksFromTimestamps(me, ticks, me._majorUnit);
  11265. },
  11266. getLabelForIndex: function(index, datasetIndex) {
  11267. var me = this;
  11268. var adapter = me._adapter;
  11269. var data = me.chart.data;
  11270. var timeOpts = me.options.time;
  11271. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  11272. var value = data.datasets[datasetIndex].data[index];
  11273. if (helpers$1.isObject(value)) {
  11274. label = me.getRightValue(value);
  11275. }
  11276. if (timeOpts.tooltipFormat) {
  11277. return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
  11278. }
  11279. if (typeof label === 'string') {
  11280. return label;
  11281. }
  11282. return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
  11283. },
  11284. /**
  11285. * Function to format an individual tick mark
  11286. * @private
  11287. */
  11288. tickFormatFunction: function(time, index, ticks, format) {
  11289. var me = this;
  11290. var adapter = me._adapter;
  11291. var options = me.options;
  11292. var formats = options.time.displayFormats;
  11293. var minorFormat = formats[me._unit];
  11294. var majorUnit = me._majorUnit;
  11295. var majorFormat = formats[majorUnit];
  11296. var majorTime = +adapter.startOf(time, majorUnit);
  11297. var majorTickOpts = options.ticks.major;
  11298. var major = majorTickOpts.enabled && majorUnit && majorFormat && time === majorTime;
  11299. var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
  11300. var tickOpts = major ? majorTickOpts : options.ticks.minor;
  11301. var formatter = valueOrDefault$c(tickOpts.callback, tickOpts.userCallback);
  11302. return formatter ? formatter(label, index, ticks) : label;
  11303. },
  11304. convertTicksToLabels: function(ticks) {
  11305. var labels = [];
  11306. var i, ilen;
  11307. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  11308. labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
  11309. }
  11310. return labels;
  11311. },
  11312. /**
  11313. * @private
  11314. */
  11315. getPixelForOffset: function(time) {
  11316. var me = this;
  11317. var isReverse = me.options.ticks.reverse;
  11318. var size = me._horizontal ? me.width : me.height;
  11319. var start = me._horizontal ? isReverse ? me.right : me.left : isReverse ? me.bottom : me.top;
  11320. var pos = interpolate$1(me._table, 'time', time, 'pos');
  11321. var offset = size * (me._offsets.start + pos) / (me._offsets.start + 1 + me._offsets.end);
  11322. return isReverse ? start - offset : start + offset;
  11323. },
  11324. getPixelForValue: function(value, index, datasetIndex) {
  11325. var me = this;
  11326. var time = null;
  11327. if (index !== undefined && datasetIndex !== undefined) {
  11328. time = me._timestamps.datasets[datasetIndex][index];
  11329. }
  11330. if (time === null) {
  11331. time = parse(me, value);
  11332. }
  11333. if (time !== null) {
  11334. return me.getPixelForOffset(time);
  11335. }
  11336. },
  11337. getPixelForTick: function(index) {
  11338. var ticks = this.getTicks();
  11339. return index >= 0 && index < ticks.length ?
  11340. this.getPixelForOffset(ticks[index].value) :
  11341. null;
  11342. },
  11343. getValueForPixel: function(pixel) {
  11344. var me = this;
  11345. var size = me._horizontal ? me.width : me.height;
  11346. var start = me._horizontal ? me.left : me.top;
  11347. var pos = (size ? (pixel - start) / size : 0) * (me._offsets.start + 1 + me._offsets.start) - me._offsets.end;
  11348. var time = interpolate$1(me._table, 'pos', pos, 'time');
  11349. // DEPRECATION, we should return time directly
  11350. return me._adapter._create(time);
  11351. },
  11352. /**
  11353. * Crude approximation of what the label width might be
  11354. * @private
  11355. */
  11356. getLabelWidth: function(label) {
  11357. var me = this;
  11358. var ticksOpts = me.options.ticks;
  11359. var tickLabelWidth = me.ctx.measureText(label).width;
  11360. var angle = helpers$1.toRadians(ticksOpts.maxRotation);
  11361. var cosRotation = Math.cos(angle);
  11362. var sinRotation = Math.sin(angle);
  11363. var tickFontSize = valueOrDefault$c(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
  11364. return (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation);
  11365. },
  11366. /**
  11367. * @private
  11368. */
  11369. getLabelCapacity: function(exampleTime) {
  11370. var me = this;
  11371. // pick the longest format (milliseconds) for guestimation
  11372. var format = me.options.time.displayFormats.millisecond;
  11373. var exampleLabel = me.tickFormatFunction(exampleTime, 0, [], format);
  11374. var tickLabelWidth = me.getLabelWidth(exampleLabel);
  11375. var innerWidth = me.isHorizontal() ? me.width : me.height;
  11376. var capacity = Math.floor(innerWidth / tickLabelWidth);
  11377. return capacity > 0 ? capacity : 1;
  11378. }
  11379. });
  11380. // INTERNAL: static default options, registered in src/index.js
  11381. var _defaults$4 = defaultConfig$4;
  11382. scale_time._defaults = _defaults$4;
  11383. var scales = {
  11384. category: scale_category,
  11385. linear: scale_linear,
  11386. logarithmic: scale_logarithmic,
  11387. radialLinear: scale_radialLinear,
  11388. time: scale_time
  11389. };
  11390. var FORMATS = {
  11391. datetime: 'MMM D, YYYY, h:mm:ss a',
  11392. millisecond: 'h:mm:ss.SSS a',
  11393. second: 'h:mm:ss a',
  11394. minute: 'h:mm a',
  11395. hour: 'hA',
  11396. day: 'MMM D',
  11397. week: 'll',
  11398. month: 'MMM YYYY',
  11399. quarter: '[Q]Q - YYYY',
  11400. year: 'YYYY'
  11401. };
  11402. core_adapters._date.override(typeof moment === 'function' ? {
  11403. _id: 'moment', // DEBUG ONLY
  11404. formats: function() {
  11405. return FORMATS;
  11406. },
  11407. parse: function(value, format) {
  11408. if (typeof value === 'string' && typeof format === 'string') {
  11409. value = moment(value, format);
  11410. } else if (!(value instanceof moment)) {
  11411. value = moment(value);
  11412. }
  11413. return value.isValid() ? value.valueOf() : null;
  11414. },
  11415. format: function(time, format) {
  11416. return moment(time).format(format);
  11417. },
  11418. add: function(time, amount, unit) {
  11419. return moment(time).add(amount, unit).valueOf();
  11420. },
  11421. diff: function(max, min, unit) {
  11422. return moment.duration(moment(max).diff(moment(min))).as(unit);
  11423. },
  11424. startOf: function(time, unit, weekday) {
  11425. time = moment(time);
  11426. if (unit === 'isoWeek') {
  11427. return time.isoWeekday(weekday).valueOf();
  11428. }
  11429. return time.startOf(unit).valueOf();
  11430. },
  11431. endOf: function(time, unit) {
  11432. return moment(time).endOf(unit).valueOf();
  11433. },
  11434. // DEPRECATIONS
  11435. /**
  11436. * Provided for backward compatibility with scale.getValueForPixel().
  11437. * @deprecated since version 2.8.0
  11438. * @todo remove at version 3
  11439. * @private
  11440. */
  11441. _create: function(time) {
  11442. return moment(time);
  11443. },
  11444. } : {});
  11445. core_defaults._set('global', {
  11446. plugins: {
  11447. filler: {
  11448. propagate: true
  11449. }
  11450. }
  11451. });
  11452. var mappers = {
  11453. dataset: function(source) {
  11454. var index = source.fill;
  11455. var chart = source.chart;
  11456. var meta = chart.getDatasetMeta(index);
  11457. var visible = meta && chart.isDatasetVisible(index);
  11458. var points = (visible && meta.dataset._children) || [];
  11459. var length = points.length || 0;
  11460. return !length ? null : function(point, i) {
  11461. return (i < length && points[i]._view) || null;
  11462. };
  11463. },
  11464. boundary: function(source) {
  11465. var boundary = source.boundary;
  11466. var x = boundary ? boundary.x : null;
  11467. var y = boundary ? boundary.y : null;
  11468. return function(point) {
  11469. return {
  11470. x: x === null ? point.x : x,
  11471. y: y === null ? point.y : y,
  11472. };
  11473. };
  11474. }
  11475. };
  11476. // @todo if (fill[0] === '#')
  11477. function decodeFill(el, index, count) {
  11478. var model = el._model || {};
  11479. var fill = model.fill;
  11480. var target;
  11481. if (fill === undefined) {
  11482. fill = !!model.backgroundColor;
  11483. }
  11484. if (fill === false || fill === null) {
  11485. return false;
  11486. }
  11487. if (fill === true) {
  11488. return 'origin';
  11489. }
  11490. target = parseFloat(fill, 10);
  11491. if (isFinite(target) && Math.floor(target) === target) {
  11492. if (fill[0] === '-' || fill[0] === '+') {
  11493. target = index + target;
  11494. }
  11495. if (target === index || target < 0 || target >= count) {
  11496. return false;
  11497. }
  11498. return target;
  11499. }
  11500. switch (fill) {
  11501. // compatibility
  11502. case 'bottom':
  11503. return 'start';
  11504. case 'top':
  11505. return 'end';
  11506. case 'zero':
  11507. return 'origin';
  11508. // supported boundaries
  11509. case 'origin':
  11510. case 'start':
  11511. case 'end':
  11512. return fill;
  11513. // invalid fill values
  11514. default:
  11515. return false;
  11516. }
  11517. }
  11518. function computeBoundary(source) {
  11519. var model = source.el._model || {};
  11520. var scale = source.el._scale || {};
  11521. var fill = source.fill;
  11522. var target = null;
  11523. var horizontal;
  11524. if (isFinite(fill)) {
  11525. return null;
  11526. }
  11527. // Backward compatibility: until v3, we still need to support boundary values set on
  11528. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  11529. // controllers might still use it (e.g. the Smith chart).
  11530. if (fill === 'start') {
  11531. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  11532. } else if (fill === 'end') {
  11533. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  11534. } else if (model.scaleZero !== undefined) {
  11535. target = model.scaleZero;
  11536. } else if (scale.getBasePosition) {
  11537. target = scale.getBasePosition();
  11538. } else if (scale.getBasePixel) {
  11539. target = scale.getBasePixel();
  11540. }
  11541. if (target !== undefined && target !== null) {
  11542. if (target.x !== undefined && target.y !== undefined) {
  11543. return target;
  11544. }
  11545. if (helpers$1.isFinite(target)) {
  11546. horizontal = scale.isHorizontal();
  11547. return {
  11548. x: horizontal ? target : null,
  11549. y: horizontal ? null : target
  11550. };
  11551. }
  11552. }
  11553. return null;
  11554. }
  11555. function resolveTarget(sources, index, propagate) {
  11556. var source = sources[index];
  11557. var fill = source.fill;
  11558. var visited = [index];
  11559. var target;
  11560. if (!propagate) {
  11561. return fill;
  11562. }
  11563. while (fill !== false && visited.indexOf(fill) === -1) {
  11564. if (!isFinite(fill)) {
  11565. return fill;
  11566. }
  11567. target = sources[fill];
  11568. if (!target) {
  11569. return false;
  11570. }
  11571. if (target.visible) {
  11572. return fill;
  11573. }
  11574. visited.push(fill);
  11575. fill = target.fill;
  11576. }
  11577. return false;
  11578. }
  11579. function createMapper(source) {
  11580. var fill = source.fill;
  11581. var type = 'dataset';
  11582. if (fill === false) {
  11583. return null;
  11584. }
  11585. if (!isFinite(fill)) {
  11586. type = 'boundary';
  11587. }
  11588. return mappers[type](source);
  11589. }
  11590. function isDrawable(point) {
  11591. return point && !point.skip;
  11592. }
  11593. function drawArea(ctx, curve0, curve1, len0, len1) {
  11594. var i;
  11595. if (!len0 || !len1) {
  11596. return;
  11597. }
  11598. // building first area curve (normal)
  11599. ctx.moveTo(curve0[0].x, curve0[0].y);
  11600. for (i = 1; i < len0; ++i) {
  11601. helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  11602. }
  11603. // joining the two area curves
  11604. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  11605. // building opposite area curve (reverse)
  11606. for (i = len1 - 1; i > 0; --i) {
  11607. helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  11608. }
  11609. }
  11610. function doFill(ctx, points, mapper, view, color, loop) {
  11611. var count = points.length;
  11612. var span = view.spanGaps;
  11613. var curve0 = [];
  11614. var curve1 = [];
  11615. var len0 = 0;
  11616. var len1 = 0;
  11617. var i, ilen, index, p0, p1, d0, d1;
  11618. ctx.beginPath();
  11619. for (i = 0, ilen = (count + !!loop); i < ilen; ++i) {
  11620. index = i % count;
  11621. p0 = points[index]._view;
  11622. p1 = mapper(p0, index, view);
  11623. d0 = isDrawable(p0);
  11624. d1 = isDrawable(p1);
  11625. if (d0 && d1) {
  11626. len0 = curve0.push(p0);
  11627. len1 = curve1.push(p1);
  11628. } else if (len0 && len1) {
  11629. if (!span) {
  11630. drawArea(ctx, curve0, curve1, len0, len1);
  11631. len0 = len1 = 0;
  11632. curve0 = [];
  11633. curve1 = [];
  11634. } else {
  11635. if (d0) {
  11636. curve0.push(p0);
  11637. }
  11638. if (d1) {
  11639. curve1.push(p1);
  11640. }
  11641. }
  11642. }
  11643. }
  11644. drawArea(ctx, curve0, curve1, len0, len1);
  11645. ctx.closePath();
  11646. ctx.fillStyle = color;
  11647. ctx.fill();
  11648. }
  11649. var plugin_filler = {
  11650. id: 'filler',
  11651. afterDatasetsUpdate: function(chart, options) {
  11652. var count = (chart.data.datasets || []).length;
  11653. var propagate = options.propagate;
  11654. var sources = [];
  11655. var meta, i, el, source;
  11656. for (i = 0; i < count; ++i) {
  11657. meta = chart.getDatasetMeta(i);
  11658. el = meta.dataset;
  11659. source = null;
  11660. if (el && el._model && el instanceof elements.Line) {
  11661. source = {
  11662. visible: chart.isDatasetVisible(i),
  11663. fill: decodeFill(el, i, count),
  11664. chart: chart,
  11665. el: el
  11666. };
  11667. }
  11668. meta.$filler = source;
  11669. sources.push(source);
  11670. }
  11671. for (i = 0; i < count; ++i) {
  11672. source = sources[i];
  11673. if (!source) {
  11674. continue;
  11675. }
  11676. source.fill = resolveTarget(sources, i, propagate);
  11677. source.boundary = computeBoundary(source);
  11678. source.mapper = createMapper(source);
  11679. }
  11680. },
  11681. beforeDatasetDraw: function(chart, args) {
  11682. var meta = args.meta.$filler;
  11683. if (!meta) {
  11684. return;
  11685. }
  11686. var ctx = chart.ctx;
  11687. var el = meta.el;
  11688. var view = el._view;
  11689. var points = el._children || [];
  11690. var mapper = meta.mapper;
  11691. var color = view.backgroundColor || core_defaults.global.defaultColor;
  11692. if (mapper && color && points.length) {
  11693. helpers$1.canvas.clipArea(ctx, chart.chartArea);
  11694. doFill(ctx, points, mapper, view, color, el._loop);
  11695. helpers$1.canvas.unclipArea(ctx);
  11696. }
  11697. }
  11698. };
  11699. var noop$1 = helpers$1.noop;
  11700. var valueOrDefault$d = helpers$1.valueOrDefault;
  11701. core_defaults._set('global', {
  11702. legend: {
  11703. display: true,
  11704. position: 'top',
  11705. fullWidth: true,
  11706. reverse: false,
  11707. weight: 1000,
  11708. // a callback that will handle
  11709. onClick: function(e, legendItem) {
  11710. var index = legendItem.datasetIndex;
  11711. var ci = this.chart;
  11712. var meta = ci.getDatasetMeta(index);
  11713. // See controller.isDatasetVisible comment
  11714. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  11715. // We hid a dataset ... rerender the chart
  11716. ci.update();
  11717. },
  11718. onHover: null,
  11719. onLeave: null,
  11720. labels: {
  11721. boxWidth: 40,
  11722. padding: 10,
  11723. // Generates labels shown in the legend
  11724. // Valid properties to return:
  11725. // text : text to display
  11726. // fillStyle : fill of coloured box
  11727. // strokeStyle: stroke of coloured box
  11728. // hidden : if this legend item refers to a hidden item
  11729. // lineCap : cap style for line
  11730. // lineDash
  11731. // lineDashOffset :
  11732. // lineJoin :
  11733. // lineWidth :
  11734. generateLabels: function(chart) {
  11735. var data = chart.data;
  11736. return helpers$1.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {
  11737. return {
  11738. text: dataset.label,
  11739. fillStyle: (!helpers$1.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
  11740. hidden: !chart.isDatasetVisible(i),
  11741. lineCap: dataset.borderCapStyle,
  11742. lineDash: dataset.borderDash,
  11743. lineDashOffset: dataset.borderDashOffset,
  11744. lineJoin: dataset.borderJoinStyle,
  11745. lineWidth: dataset.borderWidth,
  11746. strokeStyle: dataset.borderColor,
  11747. pointStyle: dataset.pointStyle,
  11748. // Below is extra data used for toggling the datasets
  11749. datasetIndex: i
  11750. };
  11751. }, this) : [];
  11752. }
  11753. }
  11754. },
  11755. legendCallback: function(chart) {
  11756. var text = [];
  11757. text.push('<ul class="' + chart.id + '-legend">');
  11758. for (var i = 0; i < chart.data.datasets.length; i++) {
  11759. text.push('<li><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"></span>');
  11760. if (chart.data.datasets[i].label) {
  11761. text.push(chart.data.datasets[i].label);
  11762. }
  11763. text.push('</li>');
  11764. }
  11765. text.push('</ul>');
  11766. return text.join('');
  11767. }
  11768. });
  11769. /**
  11770. * Helper function to get the box width based on the usePointStyle option
  11771. * @param {object} labelopts - the label options on the legend
  11772. * @param {number} fontSize - the label font size
  11773. * @return {number} width of the color box area
  11774. */
  11775. function getBoxWidth(labelOpts, fontSize) {
  11776. return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
  11777. fontSize :
  11778. labelOpts.boxWidth;
  11779. }
  11780. /**
  11781. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  11782. */
  11783. var Legend = core_element.extend({
  11784. initialize: function(config) {
  11785. helpers$1.extend(this, config);
  11786. // Contains hit boxes for each dataset (in dataset order)
  11787. this.legendHitBoxes = [];
  11788. /**
  11789. * @private
  11790. */
  11791. this._hoveredItem = null;
  11792. // Are we in doughnut mode which has a different data type
  11793. this.doughnutMode = false;
  11794. },
  11795. // These methods are ordered by lifecycle. Utilities then follow.
  11796. // Any function defined here is inherited by all legend types.
  11797. // Any function can be extended by the legend type
  11798. beforeUpdate: noop$1,
  11799. update: function(maxWidth, maxHeight, margins) {
  11800. var me = this;
  11801. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  11802. me.beforeUpdate();
  11803. // Absorb the master measurements
  11804. me.maxWidth = maxWidth;
  11805. me.maxHeight = maxHeight;
  11806. me.margins = margins;
  11807. // Dimensions
  11808. me.beforeSetDimensions();
  11809. me.setDimensions();
  11810. me.afterSetDimensions();
  11811. // Labels
  11812. me.beforeBuildLabels();
  11813. me.buildLabels();
  11814. me.afterBuildLabels();
  11815. // Fit
  11816. me.beforeFit();
  11817. me.fit();
  11818. me.afterFit();
  11819. //
  11820. me.afterUpdate();
  11821. return me.minSize;
  11822. },
  11823. afterUpdate: noop$1,
  11824. //
  11825. beforeSetDimensions: noop$1,
  11826. setDimensions: function() {
  11827. var me = this;
  11828. // Set the unconstrained dimension before label rotation
  11829. if (me.isHorizontal()) {
  11830. // Reset position before calculating rotation
  11831. me.width = me.maxWidth;
  11832. me.left = 0;
  11833. me.right = me.width;
  11834. } else {
  11835. me.height = me.maxHeight;
  11836. // Reset position before calculating rotation
  11837. me.top = 0;
  11838. me.bottom = me.height;
  11839. }
  11840. // Reset padding
  11841. me.paddingLeft = 0;
  11842. me.paddingTop = 0;
  11843. me.paddingRight = 0;
  11844. me.paddingBottom = 0;
  11845. // Reset minSize
  11846. me.minSize = {
  11847. width: 0,
  11848. height: 0
  11849. };
  11850. },
  11851. afterSetDimensions: noop$1,
  11852. //
  11853. beforeBuildLabels: noop$1,
  11854. buildLabels: function() {
  11855. var me = this;
  11856. var labelOpts = me.options.labels || {};
  11857. var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
  11858. if (labelOpts.filter) {
  11859. legendItems = legendItems.filter(function(item) {
  11860. return labelOpts.filter(item, me.chart.data);
  11861. });
  11862. }
  11863. if (me.options.reverse) {
  11864. legendItems.reverse();
  11865. }
  11866. me.legendItems = legendItems;
  11867. },
  11868. afterBuildLabels: noop$1,
  11869. //
  11870. beforeFit: noop$1,
  11871. fit: function() {
  11872. var me = this;
  11873. var opts = me.options;
  11874. var labelOpts = opts.labels;
  11875. var display = opts.display;
  11876. var ctx = me.ctx;
  11877. var labelFont = helpers$1.options._parseFont(labelOpts);
  11878. var fontSize = labelFont.size;
  11879. // Reset hit boxes
  11880. var hitboxes = me.legendHitBoxes = [];
  11881. var minSize = me.minSize;
  11882. var isHorizontal = me.isHorizontal();
  11883. if (isHorizontal) {
  11884. minSize.width = me.maxWidth; // fill all the width
  11885. minSize.height = display ? 10 : 0;
  11886. } else {
  11887. minSize.width = display ? 10 : 0;
  11888. minSize.height = me.maxHeight; // fill all the height
  11889. }
  11890. // Increase sizes here
  11891. if (display) {
  11892. ctx.font = labelFont.string;
  11893. if (isHorizontal) {
  11894. // Labels
  11895. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  11896. var lineWidths = me.lineWidths = [0];
  11897. var totalHeight = 0;
  11898. ctx.textAlign = 'left';
  11899. ctx.textBaseline = 'top';
  11900. helpers$1.each(me.legendItems, function(legendItem, i) {
  11901. var boxWidth = getBoxWidth(labelOpts, fontSize);
  11902. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  11903. if (i === 0 || lineWidths[lineWidths.length - 1] + width + labelOpts.padding > minSize.width) {
  11904. totalHeight += fontSize + labelOpts.padding;
  11905. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = labelOpts.padding;
  11906. }
  11907. // Store the hitbox width and height here. Final position will be updated in `draw`
  11908. hitboxes[i] = {
  11909. left: 0,
  11910. top: 0,
  11911. width: width,
  11912. height: fontSize
  11913. };
  11914. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  11915. });
  11916. minSize.height += totalHeight;
  11917. } else {
  11918. var vPadding = labelOpts.padding;
  11919. var columnWidths = me.columnWidths = [];
  11920. var totalWidth = labelOpts.padding;
  11921. var currentColWidth = 0;
  11922. var currentColHeight = 0;
  11923. var itemHeight = fontSize + vPadding;
  11924. helpers$1.each(me.legendItems, function(legendItem, i) {
  11925. var boxWidth = getBoxWidth(labelOpts, fontSize);
  11926. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  11927. // If too tall, go to new column
  11928. if (i > 0 && currentColHeight + itemHeight > minSize.height - vPadding) {
  11929. totalWidth += currentColWidth + labelOpts.padding;
  11930. columnWidths.push(currentColWidth); // previous column width
  11931. currentColWidth = 0;
  11932. currentColHeight = 0;
  11933. }
  11934. // Get max width
  11935. currentColWidth = Math.max(currentColWidth, itemWidth);
  11936. currentColHeight += itemHeight;
  11937. // Store the hitbox width and height here. Final position will be updated in `draw`
  11938. hitboxes[i] = {
  11939. left: 0,
  11940. top: 0,
  11941. width: itemWidth,
  11942. height: fontSize
  11943. };
  11944. });
  11945. totalWidth += currentColWidth;
  11946. columnWidths.push(currentColWidth);
  11947. minSize.width += totalWidth;
  11948. }
  11949. }
  11950. me.width = minSize.width;
  11951. me.height = minSize.height;
  11952. },
  11953. afterFit: noop$1,
  11954. // Shared Methods
  11955. isHorizontal: function() {
  11956. return this.options.position === 'top' || this.options.position === 'bottom';
  11957. },
  11958. // Actually draw the legend on the canvas
  11959. draw: function() {
  11960. var me = this;
  11961. var opts = me.options;
  11962. var labelOpts = opts.labels;
  11963. var globalDefaults = core_defaults.global;
  11964. var defaultColor = globalDefaults.defaultColor;
  11965. var lineDefault = globalDefaults.elements.line;
  11966. var legendWidth = me.width;
  11967. var lineWidths = me.lineWidths;
  11968. if (opts.display) {
  11969. var ctx = me.ctx;
  11970. var fontColor = valueOrDefault$d(labelOpts.fontColor, globalDefaults.defaultFontColor);
  11971. var labelFont = helpers$1.options._parseFont(labelOpts);
  11972. var fontSize = labelFont.size;
  11973. var cursor;
  11974. // Canvas setup
  11975. ctx.textAlign = 'left';
  11976. ctx.textBaseline = 'middle';
  11977. ctx.lineWidth = 0.5;
  11978. ctx.strokeStyle = fontColor; // for strikethrough effect
  11979. ctx.fillStyle = fontColor; // render in correct colour
  11980. ctx.font = labelFont.string;
  11981. var boxWidth = getBoxWidth(labelOpts, fontSize);
  11982. var hitboxes = me.legendHitBoxes;
  11983. // current position
  11984. var drawLegendBox = function(x, y, legendItem) {
  11985. if (isNaN(boxWidth) || boxWidth <= 0) {
  11986. return;
  11987. }
  11988. // Set the ctx for the box
  11989. ctx.save();
  11990. var lineWidth = valueOrDefault$d(legendItem.lineWidth, lineDefault.borderWidth);
  11991. ctx.fillStyle = valueOrDefault$d(legendItem.fillStyle, defaultColor);
  11992. ctx.lineCap = valueOrDefault$d(legendItem.lineCap, lineDefault.borderCapStyle);
  11993. ctx.lineDashOffset = valueOrDefault$d(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  11994. ctx.lineJoin = valueOrDefault$d(legendItem.lineJoin, lineDefault.borderJoinStyle);
  11995. ctx.lineWidth = lineWidth;
  11996. ctx.strokeStyle = valueOrDefault$d(legendItem.strokeStyle, defaultColor);
  11997. if (ctx.setLineDash) {
  11998. // IE 9 and 10 do not support line dash
  11999. ctx.setLineDash(valueOrDefault$d(legendItem.lineDash, lineDefault.borderDash));
  12000. }
  12001. if (opts.labels && opts.labels.usePointStyle) {
  12002. // Recalculate x and y for drawPoint() because its expecting
  12003. // x and y to be center of figure (instead of top left)
  12004. var radius = boxWidth * Math.SQRT2 / 2;
  12005. var centerX = x + boxWidth / 2;
  12006. var centerY = y + fontSize / 2;
  12007. // Draw pointStyle as legend symbol
  12008. helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY);
  12009. } else {
  12010. // Draw box as legend symbol
  12011. if (lineWidth !== 0) {
  12012. ctx.strokeRect(x, y, boxWidth, fontSize);
  12013. }
  12014. ctx.fillRect(x, y, boxWidth, fontSize);
  12015. }
  12016. ctx.restore();
  12017. };
  12018. var fillText = function(x, y, legendItem, textWidth) {
  12019. var halfFontSize = fontSize / 2;
  12020. var xLeft = boxWidth + halfFontSize + x;
  12021. var yMiddle = y + halfFontSize;
  12022. ctx.fillText(legendItem.text, xLeft, yMiddle);
  12023. if (legendItem.hidden) {
  12024. // Strikethrough the text if hidden
  12025. ctx.beginPath();
  12026. ctx.lineWidth = 2;
  12027. ctx.moveTo(xLeft, yMiddle);
  12028. ctx.lineTo(xLeft + textWidth, yMiddle);
  12029. ctx.stroke();
  12030. }
  12031. };
  12032. // Horizontal
  12033. var isHorizontal = me.isHorizontal();
  12034. if (isHorizontal) {
  12035. cursor = {
  12036. x: me.left + ((legendWidth - lineWidths[0]) / 2) + labelOpts.padding,
  12037. y: me.top + labelOpts.padding,
  12038. line: 0
  12039. };
  12040. } else {
  12041. cursor = {
  12042. x: me.left + labelOpts.padding,
  12043. y: me.top + labelOpts.padding,
  12044. line: 0
  12045. };
  12046. }
  12047. var itemHeight = fontSize + labelOpts.padding;
  12048. helpers$1.each(me.legendItems, function(legendItem, i) {
  12049. var textWidth = ctx.measureText(legendItem.text).width;
  12050. var width = boxWidth + (fontSize / 2) + textWidth;
  12051. var x = cursor.x;
  12052. var y = cursor.y;
  12053. // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
  12054. // instead of me.right and me.bottom because me.width and me.height
  12055. // may have been changed since me.minSize was calculated
  12056. if (isHorizontal) {
  12057. if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
  12058. y = cursor.y += itemHeight;
  12059. cursor.line++;
  12060. x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2) + labelOpts.padding;
  12061. }
  12062. } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
  12063. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  12064. y = cursor.y = me.top + labelOpts.padding;
  12065. cursor.line++;
  12066. }
  12067. drawLegendBox(x, y, legendItem);
  12068. hitboxes[i].left = x;
  12069. hitboxes[i].top = y;
  12070. // Fill the actual label
  12071. fillText(x, y, legendItem, textWidth);
  12072. if (isHorizontal) {
  12073. cursor.x += width + labelOpts.padding;
  12074. } else {
  12075. cursor.y += itemHeight;
  12076. }
  12077. });
  12078. }
  12079. },
  12080. /**
  12081. * @private
  12082. */
  12083. _getLegendItemAt: function(x, y) {
  12084. var me = this;
  12085. var i, hitBox, lh;
  12086. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  12087. // See if we are touching one of the dataset boxes
  12088. lh = me.legendHitBoxes;
  12089. for (i = 0; i < lh.length; ++i) {
  12090. hitBox = lh[i];
  12091. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  12092. // Touching an element
  12093. return me.legendItems[i];
  12094. }
  12095. }
  12096. }
  12097. return null;
  12098. },
  12099. /**
  12100. * Handle an event
  12101. * @private
  12102. * @param {IEvent} event - The event to handle
  12103. */
  12104. handleEvent: function(e) {
  12105. var me = this;
  12106. var opts = me.options;
  12107. var type = e.type === 'mouseup' ? 'click' : e.type;
  12108. var hoveredItem;
  12109. if (type === 'mousemove') {
  12110. if (!opts.onHover && !opts.onLeave) {
  12111. return;
  12112. }
  12113. } else if (type === 'click') {
  12114. if (!opts.onClick) {
  12115. return;
  12116. }
  12117. } else {
  12118. return;
  12119. }
  12120. // Chart event already has relative position in it
  12121. hoveredItem = me._getLegendItemAt(e.x, e.y);
  12122. if (type === 'click') {
  12123. if (hoveredItem && opts.onClick) {
  12124. // use e.native for backwards compatibility
  12125. opts.onClick.call(me, e.native, hoveredItem);
  12126. }
  12127. } else {
  12128. if (opts.onLeave && hoveredItem !== me._hoveredItem) {
  12129. if (me._hoveredItem) {
  12130. opts.onLeave.call(me, e.native, me._hoveredItem);
  12131. }
  12132. me._hoveredItem = hoveredItem;
  12133. }
  12134. if (opts.onHover && hoveredItem) {
  12135. // use e.native for backwards compatibility
  12136. opts.onHover.call(me, e.native, hoveredItem);
  12137. }
  12138. }
  12139. }
  12140. });
  12141. function createNewLegendAndAttach(chart, legendOpts) {
  12142. var legend = new Legend({
  12143. ctx: chart.ctx,
  12144. options: legendOpts,
  12145. chart: chart
  12146. });
  12147. core_layouts.configure(chart, legend, legendOpts);
  12148. core_layouts.addBox(chart, legend);
  12149. chart.legend = legend;
  12150. }
  12151. var plugin_legend = {
  12152. id: 'legend',
  12153. /**
  12154. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  12155. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  12156. * the plugin, which one will be re-exposed in the chart.js file.
  12157. * https://github.com/chartjs/Chart.js/pull/2640
  12158. * @private
  12159. */
  12160. _element: Legend,
  12161. beforeInit: function(chart) {
  12162. var legendOpts = chart.options.legend;
  12163. if (legendOpts) {
  12164. createNewLegendAndAttach(chart, legendOpts);
  12165. }
  12166. },
  12167. beforeUpdate: function(chart) {
  12168. var legendOpts = chart.options.legend;
  12169. var legend = chart.legend;
  12170. if (legendOpts) {
  12171. helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
  12172. if (legend) {
  12173. core_layouts.configure(chart, legend, legendOpts);
  12174. legend.options = legendOpts;
  12175. } else {
  12176. createNewLegendAndAttach(chart, legendOpts);
  12177. }
  12178. } else if (legend) {
  12179. core_layouts.removeBox(chart, legend);
  12180. delete chart.legend;
  12181. }
  12182. },
  12183. afterEvent: function(chart, e) {
  12184. var legend = chart.legend;
  12185. if (legend) {
  12186. legend.handleEvent(e);
  12187. }
  12188. }
  12189. };
  12190. var noop$2 = helpers$1.noop;
  12191. core_defaults._set('global', {
  12192. title: {
  12193. display: false,
  12194. fontStyle: 'bold',
  12195. fullWidth: true,
  12196. padding: 10,
  12197. position: 'top',
  12198. text: '',
  12199. weight: 2000 // by default greater than legend (1000) to be above
  12200. }
  12201. });
  12202. /**
  12203. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  12204. */
  12205. var Title = core_element.extend({
  12206. initialize: function(config) {
  12207. var me = this;
  12208. helpers$1.extend(me, config);
  12209. // Contains hit boxes for each dataset (in dataset order)
  12210. me.legendHitBoxes = [];
  12211. },
  12212. // These methods are ordered by lifecycle. Utilities then follow.
  12213. beforeUpdate: noop$2,
  12214. update: function(maxWidth, maxHeight, margins) {
  12215. var me = this;
  12216. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  12217. me.beforeUpdate();
  12218. // Absorb the master measurements
  12219. me.maxWidth = maxWidth;
  12220. me.maxHeight = maxHeight;
  12221. me.margins = margins;
  12222. // Dimensions
  12223. me.beforeSetDimensions();
  12224. me.setDimensions();
  12225. me.afterSetDimensions();
  12226. // Labels
  12227. me.beforeBuildLabels();
  12228. me.buildLabels();
  12229. me.afterBuildLabels();
  12230. // Fit
  12231. me.beforeFit();
  12232. me.fit();
  12233. me.afterFit();
  12234. //
  12235. me.afterUpdate();
  12236. return me.minSize;
  12237. },
  12238. afterUpdate: noop$2,
  12239. //
  12240. beforeSetDimensions: noop$2,
  12241. setDimensions: function() {
  12242. var me = this;
  12243. // Set the unconstrained dimension before label rotation
  12244. if (me.isHorizontal()) {
  12245. // Reset position before calculating rotation
  12246. me.width = me.maxWidth;
  12247. me.left = 0;
  12248. me.right = me.width;
  12249. } else {
  12250. me.height = me.maxHeight;
  12251. // Reset position before calculating rotation
  12252. me.top = 0;
  12253. me.bottom = me.height;
  12254. }
  12255. // Reset padding
  12256. me.paddingLeft = 0;
  12257. me.paddingTop = 0;
  12258. me.paddingRight = 0;
  12259. me.paddingBottom = 0;
  12260. // Reset minSize
  12261. me.minSize = {
  12262. width: 0,
  12263. height: 0
  12264. };
  12265. },
  12266. afterSetDimensions: noop$2,
  12267. //
  12268. beforeBuildLabels: noop$2,
  12269. buildLabels: noop$2,
  12270. afterBuildLabels: noop$2,
  12271. //
  12272. beforeFit: noop$2,
  12273. fit: function() {
  12274. var me = this;
  12275. var opts = me.options;
  12276. var display = opts.display;
  12277. var minSize = me.minSize;
  12278. var lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
  12279. var fontOpts = helpers$1.options._parseFont(opts);
  12280. var textSize = display ? (lineCount * fontOpts.lineHeight) + (opts.padding * 2) : 0;
  12281. if (me.isHorizontal()) {
  12282. minSize.width = me.maxWidth; // fill all the width
  12283. minSize.height = textSize;
  12284. } else {
  12285. minSize.width = textSize;
  12286. minSize.height = me.maxHeight; // fill all the height
  12287. }
  12288. me.width = minSize.width;
  12289. me.height = minSize.height;
  12290. },
  12291. afterFit: noop$2,
  12292. // Shared Methods
  12293. isHorizontal: function() {
  12294. var pos = this.options.position;
  12295. return pos === 'top' || pos === 'bottom';
  12296. },
  12297. // Actually draw the title block on the canvas
  12298. draw: function() {
  12299. var me = this;
  12300. var ctx = me.ctx;
  12301. var opts = me.options;
  12302. if (opts.display) {
  12303. var fontOpts = helpers$1.options._parseFont(opts);
  12304. var lineHeight = fontOpts.lineHeight;
  12305. var offset = lineHeight / 2 + opts.padding;
  12306. var rotation = 0;
  12307. var top = me.top;
  12308. var left = me.left;
  12309. var bottom = me.bottom;
  12310. var right = me.right;
  12311. var maxWidth, titleX, titleY;
  12312. ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
  12313. ctx.font = fontOpts.string;
  12314. // Horizontal
  12315. if (me.isHorizontal()) {
  12316. titleX = left + ((right - left) / 2); // midpoint of the width
  12317. titleY = top + offset;
  12318. maxWidth = right - left;
  12319. } else {
  12320. titleX = opts.position === 'left' ? left + offset : right - offset;
  12321. titleY = top + ((bottom - top) / 2);
  12322. maxWidth = bottom - top;
  12323. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  12324. }
  12325. ctx.save();
  12326. ctx.translate(titleX, titleY);
  12327. ctx.rotate(rotation);
  12328. ctx.textAlign = 'center';
  12329. ctx.textBaseline = 'middle';
  12330. var text = opts.text;
  12331. if (helpers$1.isArray(text)) {
  12332. var y = 0;
  12333. for (var i = 0; i < text.length; ++i) {
  12334. ctx.fillText(text[i], 0, y, maxWidth);
  12335. y += lineHeight;
  12336. }
  12337. } else {
  12338. ctx.fillText(text, 0, 0, maxWidth);
  12339. }
  12340. ctx.restore();
  12341. }
  12342. }
  12343. });
  12344. function createNewTitleBlockAndAttach(chart, titleOpts) {
  12345. var title = new Title({
  12346. ctx: chart.ctx,
  12347. options: titleOpts,
  12348. chart: chart
  12349. });
  12350. core_layouts.configure(chart, title, titleOpts);
  12351. core_layouts.addBox(chart, title);
  12352. chart.titleBlock = title;
  12353. }
  12354. var plugin_title = {
  12355. id: 'title',
  12356. /**
  12357. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  12358. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  12359. * the plugin, which one will be re-exposed in the chart.js file.
  12360. * https://github.com/chartjs/Chart.js/pull/2640
  12361. * @private
  12362. */
  12363. _element: Title,
  12364. beforeInit: function(chart) {
  12365. var titleOpts = chart.options.title;
  12366. if (titleOpts) {
  12367. createNewTitleBlockAndAttach(chart, titleOpts);
  12368. }
  12369. },
  12370. beforeUpdate: function(chart) {
  12371. var titleOpts = chart.options.title;
  12372. var titleBlock = chart.titleBlock;
  12373. if (titleOpts) {
  12374. helpers$1.mergeIf(titleOpts, core_defaults.global.title);
  12375. if (titleBlock) {
  12376. core_layouts.configure(chart, titleBlock, titleOpts);
  12377. titleBlock.options = titleOpts;
  12378. } else {
  12379. createNewTitleBlockAndAttach(chart, titleOpts);
  12380. }
  12381. } else if (titleBlock) {
  12382. core_layouts.removeBox(chart, titleBlock);
  12383. delete chart.titleBlock;
  12384. }
  12385. }
  12386. };
  12387. var plugins = {};
  12388. var filler = plugin_filler;
  12389. var legend = plugin_legend;
  12390. var title = plugin_title;
  12391. plugins.filler = filler;
  12392. plugins.legend = legend;
  12393. plugins.title = title;
  12394. /**
  12395. * @namespace Chart
  12396. */
  12397. core_controller.helpers = helpers$1;
  12398. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  12399. core_helpers(core_controller);
  12400. core_controller._adapters = core_adapters;
  12401. core_controller.Animation = core_animation;
  12402. core_controller.animationService = core_animations;
  12403. core_controller.controllers = controllers;
  12404. core_controller.DatasetController = core_datasetController;
  12405. core_controller.defaults = core_defaults;
  12406. core_controller.Element = core_element;
  12407. core_controller.elements = elements;
  12408. core_controller.Interaction = core_interaction;
  12409. core_controller.layouts = core_layouts;
  12410. core_controller.platform = platform;
  12411. core_controller.plugins = core_plugins;
  12412. core_controller.Scale = core_scale;
  12413. core_controller.scaleService = core_scaleService;
  12414. core_controller.Ticks = core_ticks;
  12415. core_controller.Tooltip = core_tooltip;
  12416. // Register built-in scales
  12417. core_controller.helpers.each(scales, function(scale, type) {
  12418. core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
  12419. });
  12420. // Load to register built-in adapters (as side effects)
  12421. // Loading built-in plugins
  12422. for (var k in plugins) {
  12423. if (plugins.hasOwnProperty(k)) {
  12424. core_controller.plugins.register(plugins[k]);
  12425. }
  12426. }
  12427. core_controller.platform.initialize();
  12428. var src = core_controller;
  12429. if (typeof window !== 'undefined') {
  12430. window.Chart = core_controller;
  12431. }
  12432. // DEPRECATIONS
  12433. /**
  12434. * Provided for backward compatibility, not available anymore
  12435. * @namespace Chart.Chart
  12436. * @deprecated since version 2.8.0
  12437. * @todo remove at version 3
  12438. * @private
  12439. */
  12440. core_controller.Chart = core_controller;
  12441. /**
  12442. * Provided for backward compatibility, not available anymore
  12443. * @namespace Chart.Legend
  12444. * @deprecated since version 2.1.5
  12445. * @todo remove at version 3
  12446. * @private
  12447. */
  12448. core_controller.Legend = plugins.legend._element;
  12449. /**
  12450. * Provided for backward compatibility, not available anymore
  12451. * @namespace Chart.Title
  12452. * @deprecated since version 2.1.5
  12453. * @todo remove at version 3
  12454. * @private
  12455. */
  12456. core_controller.Title = plugins.title._element;
  12457. /**
  12458. * Provided for backward compatibility, use Chart.plugins instead
  12459. * @namespace Chart.pluginService
  12460. * @deprecated since version 2.1.5
  12461. * @todo remove at version 3
  12462. * @private
  12463. */
  12464. core_controller.pluginService = core_controller.plugins;
  12465. /**
  12466. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  12467. * effect, instead simply create/register plugins via plain JavaScript objects.
  12468. * @interface Chart.PluginBase
  12469. * @deprecated since version 2.5.0
  12470. * @todo remove at version 3
  12471. * @private
  12472. */
  12473. core_controller.PluginBase = core_controller.Element.extend({});
  12474. /**
  12475. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  12476. * @namespace Chart.canvasHelpers
  12477. * @deprecated since version 2.6.0
  12478. * @todo remove at version 3
  12479. * @private
  12480. */
  12481. core_controller.canvasHelpers = core_controller.helpers.canvas;
  12482. /**
  12483. * Provided for backward compatibility, use Chart.layouts instead.
  12484. * @namespace Chart.layoutService
  12485. * @deprecated since version 2.7.3
  12486. * @todo remove at version 3
  12487. * @private
  12488. */
  12489. core_controller.layoutService = core_controller.layouts;
  12490. /**
  12491. * Provided for backward compatibility, not available anymore.
  12492. * @namespace Chart.LinearScaleBase
  12493. * @deprecated since version 2.8
  12494. * @todo remove at version 3
  12495. * @private
  12496. */
  12497. core_controller.LinearScaleBase = scale_linearbase;
  12498. /**
  12499. * Provided for backward compatibility, instead we should create a new Chart
  12500. * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
  12501. * @deprecated since version 2.8.0
  12502. * @todo remove at version 3
  12503. */
  12504. core_controller.helpers.each(
  12505. [
  12506. 'Bar',
  12507. 'Bubble',
  12508. 'Doughnut',
  12509. 'Line',
  12510. 'PolarArea',
  12511. 'Radar',
  12512. 'Scatter'
  12513. ],
  12514. function(klass) {
  12515. core_controller[klass] = function(ctx, cfg) {
  12516. return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
  12517. type: klass.charAt(0).toLowerCase() + klass.slice(1)
  12518. }));
  12519. };
  12520. }
  12521. );
  12522. return src;
  12523. })));