chartjs.bundle.js 566 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755
  1. /*!
  2. * Chart.js v2.9.3
  3. * https://www.chartjs.org
  4. * (c) 2019 Chart.js Contributors
  5. * Released under the MIT License
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  9. typeof define === 'function' && define.amd ? define(factory) :
  10. (global = global || self, global.Chart = factory());
  11. }(this, (function () { 'use strict';
  12. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  13. function commonjsRequire () {
  14. throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
  15. }
  16. function createCommonjsModule(fn, module) {
  17. return module = { exports: {} }, fn(module, module.exports), module.exports;
  18. }
  19. function getCjsExportFromNamespace (n) {
  20. return n && n['default'] || n;
  21. }
  22. var colorName = {
  23. "aliceblue": [240, 248, 255],
  24. "antiquewhite": [250, 235, 215],
  25. "aqua": [0, 255, 255],
  26. "aquamarine": [127, 255, 212],
  27. "azure": [240, 255, 255],
  28. "beige": [245, 245, 220],
  29. "bisque": [255, 228, 196],
  30. "black": [0, 0, 0],
  31. "blanchedalmond": [255, 235, 205],
  32. "blue": [0, 0, 255],
  33. "blueviolet": [138, 43, 226],
  34. "brown": [165, 42, 42],
  35. "burlywood": [222, 184, 135],
  36. "cadetblue": [95, 158, 160],
  37. "chartreuse": [127, 255, 0],
  38. "chocolate": [210, 105, 30],
  39. "coral": [255, 127, 80],
  40. "cornflowerblue": [100, 149, 237],
  41. "cornsilk": [255, 248, 220],
  42. "crimson": [220, 20, 60],
  43. "cyan": [0, 255, 255],
  44. "darkblue": [0, 0, 139],
  45. "darkcyan": [0, 139, 139],
  46. "darkgoldenrod": [184, 134, 11],
  47. "darkgray": [169, 169, 169],
  48. "darkgreen": [0, 100, 0],
  49. "darkgrey": [169, 169, 169],
  50. "darkkhaki": [189, 183, 107],
  51. "darkmagenta": [139, 0, 139],
  52. "darkolivegreen": [85, 107, 47],
  53. "darkorange": [255, 140, 0],
  54. "darkorchid": [153, 50, 204],
  55. "darkred": [139, 0, 0],
  56. "darksalmon": [233, 150, 122],
  57. "darkseagreen": [143, 188, 143],
  58. "darkslateblue": [72, 61, 139],
  59. "darkslategray": [47, 79, 79],
  60. "darkslategrey": [47, 79, 79],
  61. "darkturquoise": [0, 206, 209],
  62. "darkviolet": [148, 0, 211],
  63. "deeppink": [255, 20, 147],
  64. "deepskyblue": [0, 191, 255],
  65. "dimgray": [105, 105, 105],
  66. "dimgrey": [105, 105, 105],
  67. "dodgerblue": [30, 144, 255],
  68. "firebrick": [178, 34, 34],
  69. "floralwhite": [255, 250, 240],
  70. "forestgreen": [34, 139, 34],
  71. "fuchsia": [255, 0, 255],
  72. "gainsboro": [220, 220, 220],
  73. "ghostwhite": [248, 248, 255],
  74. "gold": [255, 215, 0],
  75. "goldenrod": [218, 165, 32],
  76. "gray": [128, 128, 128],
  77. "green": [0, 128, 0],
  78. "greenyellow": [173, 255, 47],
  79. "grey": [128, 128, 128],
  80. "honeydew": [240, 255, 240],
  81. "hotpink": [255, 105, 180],
  82. "indianred": [205, 92, 92],
  83. "indigo": [75, 0, 130],
  84. "ivory": [255, 255, 240],
  85. "khaki": [240, 230, 140],
  86. "lavender": [230, 230, 250],
  87. "lavenderblush": [255, 240, 245],
  88. "lawngreen": [124, 252, 0],
  89. "lemonchiffon": [255, 250, 205],
  90. "lightblue": [173, 216, 230],
  91. "lightcoral": [240, 128, 128],
  92. "lightcyan": [224, 255, 255],
  93. "lightgoldenrodyellow": [250, 250, 210],
  94. "lightgray": [211, 211, 211],
  95. "lightgreen": [144, 238, 144],
  96. "lightgrey": [211, 211, 211],
  97. "lightpink": [255, 182, 193],
  98. "lightsalmon": [255, 160, 122],
  99. "lightseagreen": [32, 178, 170],
  100. "lightskyblue": [135, 206, 250],
  101. "lightslategray": [119, 136, 153],
  102. "lightslategrey": [119, 136, 153],
  103. "lightsteelblue": [176, 196, 222],
  104. "lightyellow": [255, 255, 224],
  105. "lime": [0, 255, 0],
  106. "limegreen": [50, 205, 50],
  107. "linen": [250, 240, 230],
  108. "magenta": [255, 0, 255],
  109. "maroon": [128, 0, 0],
  110. "mediumaquamarine": [102, 205, 170],
  111. "mediumblue": [0, 0, 205],
  112. "mediumorchid": [186, 85, 211],
  113. "mediumpurple": [147, 112, 219],
  114. "mediumseagreen": [60, 179, 113],
  115. "mediumslateblue": [123, 104, 238],
  116. "mediumspringgreen": [0, 250, 154],
  117. "mediumturquoise": [72, 209, 204],
  118. "mediumvioletred": [199, 21, 133],
  119. "midnightblue": [25, 25, 112],
  120. "mintcream": [245, 255, 250],
  121. "mistyrose": [255, 228, 225],
  122. "moccasin": [255, 228, 181],
  123. "navajowhite": [255, 222, 173],
  124. "navy": [0, 0, 128],
  125. "oldlace": [253, 245, 230],
  126. "olive": [128, 128, 0],
  127. "olivedrab": [107, 142, 35],
  128. "orange": [255, 165, 0],
  129. "orangered": [255, 69, 0],
  130. "orchid": [218, 112, 214],
  131. "palegoldenrod": [238, 232, 170],
  132. "palegreen": [152, 251, 152],
  133. "paleturquoise": [175, 238, 238],
  134. "palevioletred": [219, 112, 147],
  135. "papayawhip": [255, 239, 213],
  136. "peachpuff": [255, 218, 185],
  137. "peru": [205, 133, 63],
  138. "pink": [255, 192, 203],
  139. "plum": [221, 160, 221],
  140. "powderblue": [176, 224, 230],
  141. "purple": [128, 0, 128],
  142. "rebeccapurple": [102, 51, 153],
  143. "red": [255, 0, 0],
  144. "rosybrown": [188, 143, 143],
  145. "royalblue": [65, 105, 225],
  146. "saddlebrown": [139, 69, 19],
  147. "salmon": [250, 128, 114],
  148. "sandybrown": [244, 164, 96],
  149. "seagreen": [46, 139, 87],
  150. "seashell": [255, 245, 238],
  151. "sienna": [160, 82, 45],
  152. "silver": [192, 192, 192],
  153. "skyblue": [135, 206, 235],
  154. "slateblue": [106, 90, 205],
  155. "slategray": [112, 128, 144],
  156. "slategrey": [112, 128, 144],
  157. "snow": [255, 250, 250],
  158. "springgreen": [0, 255, 127],
  159. "steelblue": [70, 130, 180],
  160. "tan": [210, 180, 140],
  161. "teal": [0, 128, 128],
  162. "thistle": [216, 191, 216],
  163. "tomato": [255, 99, 71],
  164. "turquoise": [64, 224, 208],
  165. "violet": [238, 130, 238],
  166. "wheat": [245, 222, 179],
  167. "white": [255, 255, 255],
  168. "whitesmoke": [245, 245, 245],
  169. "yellow": [255, 255, 0],
  170. "yellowgreen": [154, 205, 50]
  171. };
  172. var conversions = createCommonjsModule(function (module) {
  173. /* MIT license */
  174. // NOTE: conversions should only return primitive values (i.e. arrays, or
  175. // values that give correct `typeof` results).
  176. // do not use box values types (i.e. Number(), String(), etc.)
  177. var reverseKeywords = {};
  178. for (var key in colorName) {
  179. if (colorName.hasOwnProperty(key)) {
  180. reverseKeywords[colorName[key]] = key;
  181. }
  182. }
  183. var convert = module.exports = {
  184. rgb: {channels: 3, labels: 'rgb'},
  185. hsl: {channels: 3, labels: 'hsl'},
  186. hsv: {channels: 3, labels: 'hsv'},
  187. hwb: {channels: 3, labels: 'hwb'},
  188. cmyk: {channels: 4, labels: 'cmyk'},
  189. xyz: {channels: 3, labels: 'xyz'},
  190. lab: {channels: 3, labels: 'lab'},
  191. lch: {channels: 3, labels: 'lch'},
  192. hex: {channels: 1, labels: ['hex']},
  193. keyword: {channels: 1, labels: ['keyword']},
  194. ansi16: {channels: 1, labels: ['ansi16']},
  195. ansi256: {channels: 1, labels: ['ansi256']},
  196. hcg: {channels: 3, labels: ['h', 'c', 'g']},
  197. apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
  198. gray: {channels: 1, labels: ['gray']}
  199. };
  200. // hide .channels and .labels properties
  201. for (var model in convert) {
  202. if (convert.hasOwnProperty(model)) {
  203. if (!('channels' in convert[model])) {
  204. throw new Error('missing channels property: ' + model);
  205. }
  206. if (!('labels' in convert[model])) {
  207. throw new Error('missing channel labels property: ' + model);
  208. }
  209. if (convert[model].labels.length !== convert[model].channels) {
  210. throw new Error('channel and label counts mismatch: ' + model);
  211. }
  212. var channels = convert[model].channels;
  213. var labels = convert[model].labels;
  214. delete convert[model].channels;
  215. delete convert[model].labels;
  216. Object.defineProperty(convert[model], 'channels', {value: channels});
  217. Object.defineProperty(convert[model], 'labels', {value: labels});
  218. }
  219. }
  220. convert.rgb.hsl = function (rgb) {
  221. var r = rgb[0] / 255;
  222. var g = rgb[1] / 255;
  223. var b = rgb[2] / 255;
  224. var min = Math.min(r, g, b);
  225. var max = Math.max(r, g, b);
  226. var delta = max - min;
  227. var h;
  228. var s;
  229. var l;
  230. if (max === min) {
  231. h = 0;
  232. } else if (r === max) {
  233. h = (g - b) / delta;
  234. } else if (g === max) {
  235. h = 2 + (b - r) / delta;
  236. } else if (b === max) {
  237. h = 4 + (r - g) / delta;
  238. }
  239. h = Math.min(h * 60, 360);
  240. if (h < 0) {
  241. h += 360;
  242. }
  243. l = (min + max) / 2;
  244. if (max === min) {
  245. s = 0;
  246. } else if (l <= 0.5) {
  247. s = delta / (max + min);
  248. } else {
  249. s = delta / (2 - max - min);
  250. }
  251. return [h, s * 100, l * 100];
  252. };
  253. convert.rgb.hsv = function (rgb) {
  254. var rdif;
  255. var gdif;
  256. var bdif;
  257. var h;
  258. var s;
  259. var r = rgb[0] / 255;
  260. var g = rgb[1] / 255;
  261. var b = rgb[2] / 255;
  262. var v = Math.max(r, g, b);
  263. var diff = v - Math.min(r, g, b);
  264. var diffc = function (c) {
  265. return (v - c) / 6 / diff + 1 / 2;
  266. };
  267. if (diff === 0) {
  268. h = s = 0;
  269. } else {
  270. s = diff / v;
  271. rdif = diffc(r);
  272. gdif = diffc(g);
  273. bdif = diffc(b);
  274. if (r === v) {
  275. h = bdif - gdif;
  276. } else if (g === v) {
  277. h = (1 / 3) + rdif - bdif;
  278. } else if (b === v) {
  279. h = (2 / 3) + gdif - rdif;
  280. }
  281. if (h < 0) {
  282. h += 1;
  283. } else if (h > 1) {
  284. h -= 1;
  285. }
  286. }
  287. return [
  288. h * 360,
  289. s * 100,
  290. v * 100
  291. ];
  292. };
  293. convert.rgb.hwb = function (rgb) {
  294. var r = rgb[0];
  295. var g = rgb[1];
  296. var b = rgb[2];
  297. var h = convert.rgb.hsl(rgb)[0];
  298. var w = 1 / 255 * Math.min(r, Math.min(g, b));
  299. b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
  300. return [h, w * 100, b * 100];
  301. };
  302. convert.rgb.cmyk = function (rgb) {
  303. var r = rgb[0] / 255;
  304. var g = rgb[1] / 255;
  305. var b = rgb[2] / 255;
  306. var c;
  307. var m;
  308. var y;
  309. var k;
  310. k = Math.min(1 - r, 1 - g, 1 - b);
  311. c = (1 - r - k) / (1 - k) || 0;
  312. m = (1 - g - k) / (1 - k) || 0;
  313. y = (1 - b - k) / (1 - k) || 0;
  314. return [c * 100, m * 100, y * 100, k * 100];
  315. };
  316. /**
  317. * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
  318. * */
  319. function comparativeDistance(x, y) {
  320. return (
  321. Math.pow(x[0] - y[0], 2) +
  322. Math.pow(x[1] - y[1], 2) +
  323. Math.pow(x[2] - y[2], 2)
  324. );
  325. }
  326. convert.rgb.keyword = function (rgb) {
  327. var reversed = reverseKeywords[rgb];
  328. if (reversed) {
  329. return reversed;
  330. }
  331. var currentClosestDistance = Infinity;
  332. var currentClosestKeyword;
  333. for (var keyword in colorName) {
  334. if (colorName.hasOwnProperty(keyword)) {
  335. var value = colorName[keyword];
  336. // Compute comparative distance
  337. var distance = comparativeDistance(rgb, value);
  338. // Check if its less, if so set as closest
  339. if (distance < currentClosestDistance) {
  340. currentClosestDistance = distance;
  341. currentClosestKeyword = keyword;
  342. }
  343. }
  344. }
  345. return currentClosestKeyword;
  346. };
  347. convert.keyword.rgb = function (keyword) {
  348. return colorName[keyword];
  349. };
  350. convert.rgb.xyz = function (rgb) {
  351. var r = rgb[0] / 255;
  352. var g = rgb[1] / 255;
  353. var b = rgb[2] / 255;
  354. // assume sRGB
  355. r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
  356. g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
  357. b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
  358. var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
  359. var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
  360. var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
  361. return [x * 100, y * 100, z * 100];
  362. };
  363. convert.rgb.lab = function (rgb) {
  364. var xyz = convert.rgb.xyz(rgb);
  365. var x = xyz[0];
  366. var y = xyz[1];
  367. var z = xyz[2];
  368. var l;
  369. var a;
  370. var b;
  371. x /= 95.047;
  372. y /= 100;
  373. z /= 108.883;
  374. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  375. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  376. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  377. l = (116 * y) - 16;
  378. a = 500 * (x - y);
  379. b = 200 * (y - z);
  380. return [l, a, b];
  381. };
  382. convert.hsl.rgb = function (hsl) {
  383. var h = hsl[0] / 360;
  384. var s = hsl[1] / 100;
  385. var l = hsl[2] / 100;
  386. var t1;
  387. var t2;
  388. var t3;
  389. var rgb;
  390. var val;
  391. if (s === 0) {
  392. val = l * 255;
  393. return [val, val, val];
  394. }
  395. if (l < 0.5) {
  396. t2 = l * (1 + s);
  397. } else {
  398. t2 = l + s - l * s;
  399. }
  400. t1 = 2 * l - t2;
  401. rgb = [0, 0, 0];
  402. for (var i = 0; i < 3; i++) {
  403. t3 = h + 1 / 3 * -(i - 1);
  404. if (t3 < 0) {
  405. t3++;
  406. }
  407. if (t3 > 1) {
  408. t3--;
  409. }
  410. if (6 * t3 < 1) {
  411. val = t1 + (t2 - t1) * 6 * t3;
  412. } else if (2 * t3 < 1) {
  413. val = t2;
  414. } else if (3 * t3 < 2) {
  415. val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
  416. } else {
  417. val = t1;
  418. }
  419. rgb[i] = val * 255;
  420. }
  421. return rgb;
  422. };
  423. convert.hsl.hsv = function (hsl) {
  424. var h = hsl[0];
  425. var s = hsl[1] / 100;
  426. var l = hsl[2] / 100;
  427. var smin = s;
  428. var lmin = Math.max(l, 0.01);
  429. var sv;
  430. var v;
  431. l *= 2;
  432. s *= (l <= 1) ? l : 2 - l;
  433. smin *= lmin <= 1 ? lmin : 2 - lmin;
  434. v = (l + s) / 2;
  435. sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
  436. return [h, sv * 100, v * 100];
  437. };
  438. convert.hsv.rgb = function (hsv) {
  439. var h = hsv[0] / 60;
  440. var s = hsv[1] / 100;
  441. var v = hsv[2] / 100;
  442. var hi = Math.floor(h) % 6;
  443. var f = h - Math.floor(h);
  444. var p = 255 * v * (1 - s);
  445. var q = 255 * v * (1 - (s * f));
  446. var t = 255 * v * (1 - (s * (1 - f)));
  447. v *= 255;
  448. switch (hi) {
  449. case 0:
  450. return [v, t, p];
  451. case 1:
  452. return [q, v, p];
  453. case 2:
  454. return [p, v, t];
  455. case 3:
  456. return [p, q, v];
  457. case 4:
  458. return [t, p, v];
  459. case 5:
  460. return [v, p, q];
  461. }
  462. };
  463. convert.hsv.hsl = function (hsv) {
  464. var h = hsv[0];
  465. var s = hsv[1] / 100;
  466. var v = hsv[2] / 100;
  467. var vmin = Math.max(v, 0.01);
  468. var lmin;
  469. var sl;
  470. var l;
  471. l = (2 - s) * v;
  472. lmin = (2 - s) * vmin;
  473. sl = s * vmin;
  474. sl /= (lmin <= 1) ? lmin : 2 - lmin;
  475. sl = sl || 0;
  476. l /= 2;
  477. return [h, sl * 100, l * 100];
  478. };
  479. // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
  480. convert.hwb.rgb = function (hwb) {
  481. var h = hwb[0] / 360;
  482. var wh = hwb[1] / 100;
  483. var bl = hwb[2] / 100;
  484. var ratio = wh + bl;
  485. var i;
  486. var v;
  487. var f;
  488. var n;
  489. // wh + bl cant be > 1
  490. if (ratio > 1) {
  491. wh /= ratio;
  492. bl /= ratio;
  493. }
  494. i = Math.floor(6 * h);
  495. v = 1 - bl;
  496. f = 6 * h - i;
  497. if ((i & 0x01) !== 0) {
  498. f = 1 - f;
  499. }
  500. n = wh + f * (v - wh); // linear interpolation
  501. var r;
  502. var g;
  503. var b;
  504. switch (i) {
  505. default:
  506. case 6:
  507. case 0: r = v; g = n; b = wh; break;
  508. case 1: r = n; g = v; b = wh; break;
  509. case 2: r = wh; g = v; b = n; break;
  510. case 3: r = wh; g = n; b = v; break;
  511. case 4: r = n; g = wh; b = v; break;
  512. case 5: r = v; g = wh; b = n; break;
  513. }
  514. return [r * 255, g * 255, b * 255];
  515. };
  516. convert.cmyk.rgb = function (cmyk) {
  517. var c = cmyk[0] / 100;
  518. var m = cmyk[1] / 100;
  519. var y = cmyk[2] / 100;
  520. var k = cmyk[3] / 100;
  521. var r;
  522. var g;
  523. var b;
  524. r = 1 - Math.min(1, c * (1 - k) + k);
  525. g = 1 - Math.min(1, m * (1 - k) + k);
  526. b = 1 - Math.min(1, y * (1 - k) + k);
  527. return [r * 255, g * 255, b * 255];
  528. };
  529. convert.xyz.rgb = function (xyz) {
  530. var x = xyz[0] / 100;
  531. var y = xyz[1] / 100;
  532. var z = xyz[2] / 100;
  533. var r;
  534. var g;
  535. var b;
  536. r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
  537. g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
  538. b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
  539. // assume sRGB
  540. r = r > 0.0031308
  541. ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
  542. : r * 12.92;
  543. g = g > 0.0031308
  544. ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
  545. : g * 12.92;
  546. b = b > 0.0031308
  547. ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
  548. : b * 12.92;
  549. r = Math.min(Math.max(0, r), 1);
  550. g = Math.min(Math.max(0, g), 1);
  551. b = Math.min(Math.max(0, b), 1);
  552. return [r * 255, g * 255, b * 255];
  553. };
  554. convert.xyz.lab = function (xyz) {
  555. var x = xyz[0];
  556. var y = xyz[1];
  557. var z = xyz[2];
  558. var l;
  559. var a;
  560. var b;
  561. x /= 95.047;
  562. y /= 100;
  563. z /= 108.883;
  564. x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
  565. y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
  566. z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
  567. l = (116 * y) - 16;
  568. a = 500 * (x - y);
  569. b = 200 * (y - z);
  570. return [l, a, b];
  571. };
  572. convert.lab.xyz = function (lab) {
  573. var l = lab[0];
  574. var a = lab[1];
  575. var b = lab[2];
  576. var x;
  577. var y;
  578. var z;
  579. y = (l + 16) / 116;
  580. x = a / 500 + y;
  581. z = y - b / 200;
  582. var y2 = Math.pow(y, 3);
  583. var x2 = Math.pow(x, 3);
  584. var z2 = Math.pow(z, 3);
  585. y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
  586. x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
  587. z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
  588. x *= 95.047;
  589. y *= 100;
  590. z *= 108.883;
  591. return [x, y, z];
  592. };
  593. convert.lab.lch = function (lab) {
  594. var l = lab[0];
  595. var a = lab[1];
  596. var b = lab[2];
  597. var hr;
  598. var h;
  599. var c;
  600. hr = Math.atan2(b, a);
  601. h = hr * 360 / 2 / Math.PI;
  602. if (h < 0) {
  603. h += 360;
  604. }
  605. c = Math.sqrt(a * a + b * b);
  606. return [l, c, h];
  607. };
  608. convert.lch.lab = function (lch) {
  609. var l = lch[0];
  610. var c = lch[1];
  611. var h = lch[2];
  612. var a;
  613. var b;
  614. var hr;
  615. hr = h / 360 * 2 * Math.PI;
  616. a = c * Math.cos(hr);
  617. b = c * Math.sin(hr);
  618. return [l, a, b];
  619. };
  620. convert.rgb.ansi16 = function (args) {
  621. var r = args[0];
  622. var g = args[1];
  623. var b = args[2];
  624. var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
  625. value = Math.round(value / 50);
  626. if (value === 0) {
  627. return 30;
  628. }
  629. var ansi = 30
  630. + ((Math.round(b / 255) << 2)
  631. | (Math.round(g / 255) << 1)
  632. | Math.round(r / 255));
  633. if (value === 2) {
  634. ansi += 60;
  635. }
  636. return ansi;
  637. };
  638. convert.hsv.ansi16 = function (args) {
  639. // optimization here; we already know the value and don't need to get
  640. // it converted for us.
  641. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
  642. };
  643. convert.rgb.ansi256 = function (args) {
  644. var r = args[0];
  645. var g = args[1];
  646. var b = args[2];
  647. // we use the extended greyscale palette here, with the exception of
  648. // black and white. normal palette only has 4 greyscale shades.
  649. if (r === g && g === b) {
  650. if (r < 8) {
  651. return 16;
  652. }
  653. if (r > 248) {
  654. return 231;
  655. }
  656. return Math.round(((r - 8) / 247) * 24) + 232;
  657. }
  658. var ansi = 16
  659. + (36 * Math.round(r / 255 * 5))
  660. + (6 * Math.round(g / 255 * 5))
  661. + Math.round(b / 255 * 5);
  662. return ansi;
  663. };
  664. convert.ansi16.rgb = function (args) {
  665. var color = args % 10;
  666. // handle greyscale
  667. if (color === 0 || color === 7) {
  668. if (args > 50) {
  669. color += 3.5;
  670. }
  671. color = color / 10.5 * 255;
  672. return [color, color, color];
  673. }
  674. var mult = (~~(args > 50) + 1) * 0.5;
  675. var r = ((color & 1) * mult) * 255;
  676. var g = (((color >> 1) & 1) * mult) * 255;
  677. var b = (((color >> 2) & 1) * mult) * 255;
  678. return [r, g, b];
  679. };
  680. convert.ansi256.rgb = function (args) {
  681. // handle greyscale
  682. if (args >= 232) {
  683. var c = (args - 232) * 10 + 8;
  684. return [c, c, c];
  685. }
  686. args -= 16;
  687. var rem;
  688. var r = Math.floor(args / 36) / 5 * 255;
  689. var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
  690. var b = (rem % 6) / 5 * 255;
  691. return [r, g, b];
  692. };
  693. convert.rgb.hex = function (args) {
  694. var integer = ((Math.round(args[0]) & 0xFF) << 16)
  695. + ((Math.round(args[1]) & 0xFF) << 8)
  696. + (Math.round(args[2]) & 0xFF);
  697. var string = integer.toString(16).toUpperCase();
  698. return '000000'.substring(string.length) + string;
  699. };
  700. convert.hex.rgb = function (args) {
  701. var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
  702. if (!match) {
  703. return [0, 0, 0];
  704. }
  705. var colorString = match[0];
  706. if (match[0].length === 3) {
  707. colorString = colorString.split('').map(function (char) {
  708. return char + char;
  709. }).join('');
  710. }
  711. var integer = parseInt(colorString, 16);
  712. var r = (integer >> 16) & 0xFF;
  713. var g = (integer >> 8) & 0xFF;
  714. var b = integer & 0xFF;
  715. return [r, g, b];
  716. };
  717. convert.rgb.hcg = function (rgb) {
  718. var r = rgb[0] / 255;
  719. var g = rgb[1] / 255;
  720. var b = rgb[2] / 255;
  721. var max = Math.max(Math.max(r, g), b);
  722. var min = Math.min(Math.min(r, g), b);
  723. var chroma = (max - min);
  724. var grayscale;
  725. var hue;
  726. if (chroma < 1) {
  727. grayscale = min / (1 - chroma);
  728. } else {
  729. grayscale = 0;
  730. }
  731. if (chroma <= 0) {
  732. hue = 0;
  733. } else
  734. if (max === r) {
  735. hue = ((g - b) / chroma) % 6;
  736. } else
  737. if (max === g) {
  738. hue = 2 + (b - r) / chroma;
  739. } else {
  740. hue = 4 + (r - g) / chroma + 4;
  741. }
  742. hue /= 6;
  743. hue %= 1;
  744. return [hue * 360, chroma * 100, grayscale * 100];
  745. };
  746. convert.hsl.hcg = function (hsl) {
  747. var s = hsl[1] / 100;
  748. var l = hsl[2] / 100;
  749. var c = 1;
  750. var f = 0;
  751. if (l < 0.5) {
  752. c = 2.0 * s * l;
  753. } else {
  754. c = 2.0 * s * (1.0 - l);
  755. }
  756. if (c < 1.0) {
  757. f = (l - 0.5 * c) / (1.0 - c);
  758. }
  759. return [hsl[0], c * 100, f * 100];
  760. };
  761. convert.hsv.hcg = function (hsv) {
  762. var s = hsv[1] / 100;
  763. var v = hsv[2] / 100;
  764. var c = s * v;
  765. var f = 0;
  766. if (c < 1.0) {
  767. f = (v - c) / (1 - c);
  768. }
  769. return [hsv[0], c * 100, f * 100];
  770. };
  771. convert.hcg.rgb = function (hcg) {
  772. var h = hcg[0] / 360;
  773. var c = hcg[1] / 100;
  774. var g = hcg[2] / 100;
  775. if (c === 0.0) {
  776. return [g * 255, g * 255, g * 255];
  777. }
  778. var pure = [0, 0, 0];
  779. var hi = (h % 1) * 6;
  780. var v = hi % 1;
  781. var w = 1 - v;
  782. var mg = 0;
  783. switch (Math.floor(hi)) {
  784. case 0:
  785. pure[0] = 1; pure[1] = v; pure[2] = 0; break;
  786. case 1:
  787. pure[0] = w; pure[1] = 1; pure[2] = 0; break;
  788. case 2:
  789. pure[0] = 0; pure[1] = 1; pure[2] = v; break;
  790. case 3:
  791. pure[0] = 0; pure[1] = w; pure[2] = 1; break;
  792. case 4:
  793. pure[0] = v; pure[1] = 0; pure[2] = 1; break;
  794. default:
  795. pure[0] = 1; pure[1] = 0; pure[2] = w;
  796. }
  797. mg = (1.0 - c) * g;
  798. return [
  799. (c * pure[0] + mg) * 255,
  800. (c * pure[1] + mg) * 255,
  801. (c * pure[2] + mg) * 255
  802. ];
  803. };
  804. convert.hcg.hsv = function (hcg) {
  805. var c = hcg[1] / 100;
  806. var g = hcg[2] / 100;
  807. var v = c + g * (1.0 - c);
  808. var f = 0;
  809. if (v > 0.0) {
  810. f = c / v;
  811. }
  812. return [hcg[0], f * 100, v * 100];
  813. };
  814. convert.hcg.hsl = function (hcg) {
  815. var c = hcg[1] / 100;
  816. var g = hcg[2] / 100;
  817. var l = g * (1.0 - c) + 0.5 * c;
  818. var s = 0;
  819. if (l > 0.0 && l < 0.5) {
  820. s = c / (2 * l);
  821. } else
  822. if (l >= 0.5 && l < 1.0) {
  823. s = c / (2 * (1 - l));
  824. }
  825. return [hcg[0], s * 100, l * 100];
  826. };
  827. convert.hcg.hwb = function (hcg) {
  828. var c = hcg[1] / 100;
  829. var g = hcg[2] / 100;
  830. var v = c + g * (1.0 - c);
  831. return [hcg[0], (v - c) * 100, (1 - v) * 100];
  832. };
  833. convert.hwb.hcg = function (hwb) {
  834. var w = hwb[1] / 100;
  835. var b = hwb[2] / 100;
  836. var v = 1 - b;
  837. var c = v - w;
  838. var g = 0;
  839. if (c < 1) {
  840. g = (v - c) / (1 - c);
  841. }
  842. return [hwb[0], c * 100, g * 100];
  843. };
  844. convert.apple.rgb = function (apple) {
  845. return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
  846. };
  847. convert.rgb.apple = function (rgb) {
  848. return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
  849. };
  850. convert.gray.rgb = function (args) {
  851. return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
  852. };
  853. convert.gray.hsl = convert.gray.hsv = function (args) {
  854. return [0, 0, args[0]];
  855. };
  856. convert.gray.hwb = function (gray) {
  857. return [0, 100, gray[0]];
  858. };
  859. convert.gray.cmyk = function (gray) {
  860. return [0, 0, 0, gray[0]];
  861. };
  862. convert.gray.lab = function (gray) {
  863. return [gray[0], 0, 0];
  864. };
  865. convert.gray.hex = function (gray) {
  866. var val = Math.round(gray[0] / 100 * 255) & 0xFF;
  867. var integer = (val << 16) + (val << 8) + val;
  868. var string = integer.toString(16).toUpperCase();
  869. return '000000'.substring(string.length) + string;
  870. };
  871. convert.rgb.gray = function (rgb) {
  872. var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
  873. return [val / 255 * 100];
  874. };
  875. });
  876. var conversions_1 = conversions.rgb;
  877. var conversions_2 = conversions.hsl;
  878. var conversions_3 = conversions.hsv;
  879. var conversions_4 = conversions.hwb;
  880. var conversions_5 = conversions.cmyk;
  881. var conversions_6 = conversions.xyz;
  882. var conversions_7 = conversions.lab;
  883. var conversions_8 = conversions.lch;
  884. var conversions_9 = conversions.hex;
  885. var conversions_10 = conversions.keyword;
  886. var conversions_11 = conversions.ansi16;
  887. var conversions_12 = conversions.ansi256;
  888. var conversions_13 = conversions.hcg;
  889. var conversions_14 = conversions.apple;
  890. var conversions_15 = conversions.gray;
  891. /*
  892. this function routes a model to all other models.
  893. all functions that are routed have a property `.conversion` attached
  894. to the returned synthetic function. This property is an array
  895. of strings, each with the steps in between the 'from' and 'to'
  896. color models (inclusive).
  897. conversions that are not possible simply are not included.
  898. */
  899. function buildGraph() {
  900. var graph = {};
  901. // https://jsperf.com/object-keys-vs-for-in-with-closure/3
  902. var models = Object.keys(conversions);
  903. for (var len = models.length, i = 0; i < len; i++) {
  904. graph[models[i]] = {
  905. // http://jsperf.com/1-vs-infinity
  906. // micro-opt, but this is simple.
  907. distance: -1,
  908. parent: null
  909. };
  910. }
  911. return graph;
  912. }
  913. // https://en.wikipedia.org/wiki/Breadth-first_search
  914. function deriveBFS(fromModel) {
  915. var graph = buildGraph();
  916. var queue = [fromModel]; // unshift -> queue -> pop
  917. graph[fromModel].distance = 0;
  918. while (queue.length) {
  919. var current = queue.pop();
  920. var adjacents = Object.keys(conversions[current]);
  921. for (var len = adjacents.length, i = 0; i < len; i++) {
  922. var adjacent = adjacents[i];
  923. var node = graph[adjacent];
  924. if (node.distance === -1) {
  925. node.distance = graph[current].distance + 1;
  926. node.parent = current;
  927. queue.unshift(adjacent);
  928. }
  929. }
  930. }
  931. return graph;
  932. }
  933. function link(from, to) {
  934. return function (args) {
  935. return to(from(args));
  936. };
  937. }
  938. function wrapConversion(toModel, graph) {
  939. var path = [graph[toModel].parent, toModel];
  940. var fn = conversions[graph[toModel].parent][toModel];
  941. var cur = graph[toModel].parent;
  942. while (graph[cur].parent) {
  943. path.unshift(graph[cur].parent);
  944. fn = link(conversions[graph[cur].parent][cur], fn);
  945. cur = graph[cur].parent;
  946. }
  947. fn.conversion = path;
  948. return fn;
  949. }
  950. var route = function (fromModel) {
  951. var graph = deriveBFS(fromModel);
  952. var conversion = {};
  953. var models = Object.keys(graph);
  954. for (var len = models.length, i = 0; i < len; i++) {
  955. var toModel = models[i];
  956. var node = graph[toModel];
  957. if (node.parent === null) {
  958. // no possible conversion, or this node is the source model.
  959. continue;
  960. }
  961. conversion[toModel] = wrapConversion(toModel, graph);
  962. }
  963. return conversion;
  964. };
  965. var convert = {};
  966. var models = Object.keys(conversions);
  967. function wrapRaw(fn) {
  968. var wrappedFn = function (args) {
  969. if (args === undefined || args === null) {
  970. return args;
  971. }
  972. if (arguments.length > 1) {
  973. args = Array.prototype.slice.call(arguments);
  974. }
  975. return fn(args);
  976. };
  977. // preserve .conversion property if there is one
  978. if ('conversion' in fn) {
  979. wrappedFn.conversion = fn.conversion;
  980. }
  981. return wrappedFn;
  982. }
  983. function wrapRounded(fn) {
  984. var wrappedFn = function (args) {
  985. if (args === undefined || args === null) {
  986. return args;
  987. }
  988. if (arguments.length > 1) {
  989. args = Array.prototype.slice.call(arguments);
  990. }
  991. var result = fn(args);
  992. // we're assuming the result is an array here.
  993. // see notice in conversions.js; don't use box types
  994. // in conversion functions.
  995. if (typeof result === 'object') {
  996. for (var len = result.length, i = 0; i < len; i++) {
  997. result[i] = Math.round(result[i]);
  998. }
  999. }
  1000. return result;
  1001. };
  1002. // preserve .conversion property if there is one
  1003. if ('conversion' in fn) {
  1004. wrappedFn.conversion = fn.conversion;
  1005. }
  1006. return wrappedFn;
  1007. }
  1008. models.forEach(function (fromModel) {
  1009. convert[fromModel] = {};
  1010. Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
  1011. Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
  1012. var routes = route(fromModel);
  1013. var routeModels = Object.keys(routes);
  1014. routeModels.forEach(function (toModel) {
  1015. var fn = routes[toModel];
  1016. convert[fromModel][toModel] = wrapRounded(fn);
  1017. convert[fromModel][toModel].raw = wrapRaw(fn);
  1018. });
  1019. });
  1020. var colorConvert = convert;
  1021. var colorName$1 = {
  1022. "aliceblue": [240, 248, 255],
  1023. "antiquewhite": [250, 235, 215],
  1024. "aqua": [0, 255, 255],
  1025. "aquamarine": [127, 255, 212],
  1026. "azure": [240, 255, 255],
  1027. "beige": [245, 245, 220],
  1028. "bisque": [255, 228, 196],
  1029. "black": [0, 0, 0],
  1030. "blanchedalmond": [255, 235, 205],
  1031. "blue": [0, 0, 255],
  1032. "blueviolet": [138, 43, 226],
  1033. "brown": [165, 42, 42],
  1034. "burlywood": [222, 184, 135],
  1035. "cadetblue": [95, 158, 160],
  1036. "chartreuse": [127, 255, 0],
  1037. "chocolate": [210, 105, 30],
  1038. "coral": [255, 127, 80],
  1039. "cornflowerblue": [100, 149, 237],
  1040. "cornsilk": [255, 248, 220],
  1041. "crimson": [220, 20, 60],
  1042. "cyan": [0, 255, 255],
  1043. "darkblue": [0, 0, 139],
  1044. "darkcyan": [0, 139, 139],
  1045. "darkgoldenrod": [184, 134, 11],
  1046. "darkgray": [169, 169, 169],
  1047. "darkgreen": [0, 100, 0],
  1048. "darkgrey": [169, 169, 169],
  1049. "darkkhaki": [189, 183, 107],
  1050. "darkmagenta": [139, 0, 139],
  1051. "darkolivegreen": [85, 107, 47],
  1052. "darkorange": [255, 140, 0],
  1053. "darkorchid": [153, 50, 204],
  1054. "darkred": [139, 0, 0],
  1055. "darksalmon": [233, 150, 122],
  1056. "darkseagreen": [143, 188, 143],
  1057. "darkslateblue": [72, 61, 139],
  1058. "darkslategray": [47, 79, 79],
  1059. "darkslategrey": [47, 79, 79],
  1060. "darkturquoise": [0, 206, 209],
  1061. "darkviolet": [148, 0, 211],
  1062. "deeppink": [255, 20, 147],
  1063. "deepskyblue": [0, 191, 255],
  1064. "dimgray": [105, 105, 105],
  1065. "dimgrey": [105, 105, 105],
  1066. "dodgerblue": [30, 144, 255],
  1067. "firebrick": [178, 34, 34],
  1068. "floralwhite": [255, 250, 240],
  1069. "forestgreen": [34, 139, 34],
  1070. "fuchsia": [255, 0, 255],
  1071. "gainsboro": [220, 220, 220],
  1072. "ghostwhite": [248, 248, 255],
  1073. "gold": [255, 215, 0],
  1074. "goldenrod": [218, 165, 32],
  1075. "gray": [128, 128, 128],
  1076. "green": [0, 128, 0],
  1077. "greenyellow": [173, 255, 47],
  1078. "grey": [128, 128, 128],
  1079. "honeydew": [240, 255, 240],
  1080. "hotpink": [255, 105, 180],
  1081. "indianred": [205, 92, 92],
  1082. "indigo": [75, 0, 130],
  1083. "ivory": [255, 255, 240],
  1084. "khaki": [240, 230, 140],
  1085. "lavender": [230, 230, 250],
  1086. "lavenderblush": [255, 240, 245],
  1087. "lawngreen": [124, 252, 0],
  1088. "lemonchiffon": [255, 250, 205],
  1089. "lightblue": [173, 216, 230],
  1090. "lightcoral": [240, 128, 128],
  1091. "lightcyan": [224, 255, 255],
  1092. "lightgoldenrodyellow": [250, 250, 210],
  1093. "lightgray": [211, 211, 211],
  1094. "lightgreen": [144, 238, 144],
  1095. "lightgrey": [211, 211, 211],
  1096. "lightpink": [255, 182, 193],
  1097. "lightsalmon": [255, 160, 122],
  1098. "lightseagreen": [32, 178, 170],
  1099. "lightskyblue": [135, 206, 250],
  1100. "lightslategray": [119, 136, 153],
  1101. "lightslategrey": [119, 136, 153],
  1102. "lightsteelblue": [176, 196, 222],
  1103. "lightyellow": [255, 255, 224],
  1104. "lime": [0, 255, 0],
  1105. "limegreen": [50, 205, 50],
  1106. "linen": [250, 240, 230],
  1107. "magenta": [255, 0, 255],
  1108. "maroon": [128, 0, 0],
  1109. "mediumaquamarine": [102, 205, 170],
  1110. "mediumblue": [0, 0, 205],
  1111. "mediumorchid": [186, 85, 211],
  1112. "mediumpurple": [147, 112, 219],
  1113. "mediumseagreen": [60, 179, 113],
  1114. "mediumslateblue": [123, 104, 238],
  1115. "mediumspringgreen": [0, 250, 154],
  1116. "mediumturquoise": [72, 209, 204],
  1117. "mediumvioletred": [199, 21, 133],
  1118. "midnightblue": [25, 25, 112],
  1119. "mintcream": [245, 255, 250],
  1120. "mistyrose": [255, 228, 225],
  1121. "moccasin": [255, 228, 181],
  1122. "navajowhite": [255, 222, 173],
  1123. "navy": [0, 0, 128],
  1124. "oldlace": [253, 245, 230],
  1125. "olive": [128, 128, 0],
  1126. "olivedrab": [107, 142, 35],
  1127. "orange": [255, 165, 0],
  1128. "orangered": [255, 69, 0],
  1129. "orchid": [218, 112, 214],
  1130. "palegoldenrod": [238, 232, 170],
  1131. "palegreen": [152, 251, 152],
  1132. "paleturquoise": [175, 238, 238],
  1133. "palevioletred": [219, 112, 147],
  1134. "papayawhip": [255, 239, 213],
  1135. "peachpuff": [255, 218, 185],
  1136. "peru": [205, 133, 63],
  1137. "pink": [255, 192, 203],
  1138. "plum": [221, 160, 221],
  1139. "powderblue": [176, 224, 230],
  1140. "purple": [128, 0, 128],
  1141. "rebeccapurple": [102, 51, 153],
  1142. "red": [255, 0, 0],
  1143. "rosybrown": [188, 143, 143],
  1144. "royalblue": [65, 105, 225],
  1145. "saddlebrown": [139, 69, 19],
  1146. "salmon": [250, 128, 114],
  1147. "sandybrown": [244, 164, 96],
  1148. "seagreen": [46, 139, 87],
  1149. "seashell": [255, 245, 238],
  1150. "sienna": [160, 82, 45],
  1151. "silver": [192, 192, 192],
  1152. "skyblue": [135, 206, 235],
  1153. "slateblue": [106, 90, 205],
  1154. "slategray": [112, 128, 144],
  1155. "slategrey": [112, 128, 144],
  1156. "snow": [255, 250, 250],
  1157. "springgreen": [0, 255, 127],
  1158. "steelblue": [70, 130, 180],
  1159. "tan": [210, 180, 140],
  1160. "teal": [0, 128, 128],
  1161. "thistle": [216, 191, 216],
  1162. "tomato": [255, 99, 71],
  1163. "turquoise": [64, 224, 208],
  1164. "violet": [238, 130, 238],
  1165. "wheat": [245, 222, 179],
  1166. "white": [255, 255, 255],
  1167. "whitesmoke": [245, 245, 245],
  1168. "yellow": [255, 255, 0],
  1169. "yellowgreen": [154, 205, 50]
  1170. };
  1171. /* MIT license */
  1172. var colorString = {
  1173. getRgba: getRgba,
  1174. getHsla: getHsla,
  1175. getRgb: getRgb,
  1176. getHsl: getHsl,
  1177. getHwb: getHwb,
  1178. getAlpha: getAlpha,
  1179. hexString: hexString,
  1180. rgbString: rgbString,
  1181. rgbaString: rgbaString,
  1182. percentString: percentString,
  1183. percentaString: percentaString,
  1184. hslString: hslString,
  1185. hslaString: hslaString,
  1186. hwbString: hwbString,
  1187. keyword: keyword
  1188. };
  1189. function getRgba(string) {
  1190. if (!string) {
  1191. return;
  1192. }
  1193. var abbr = /^#([a-fA-F0-9]{3,4})$/i,
  1194. hex = /^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i,
  1195. rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1196. per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i,
  1197. keyword = /(\w+)/;
  1198. var rgb = [0, 0, 0],
  1199. a = 1,
  1200. match = string.match(abbr),
  1201. hexAlpha = "";
  1202. if (match) {
  1203. match = match[1];
  1204. hexAlpha = match[3];
  1205. for (var i = 0; i < rgb.length; i++) {
  1206. rgb[i] = parseInt(match[i] + match[i], 16);
  1207. }
  1208. if (hexAlpha) {
  1209. a = Math.round((parseInt(hexAlpha + hexAlpha, 16) / 255) * 100) / 100;
  1210. }
  1211. }
  1212. else if (match = string.match(hex)) {
  1213. hexAlpha = match[2];
  1214. match = match[1];
  1215. for (var i = 0; i < rgb.length; i++) {
  1216. rgb[i] = parseInt(match.slice(i * 2, i * 2 + 2), 16);
  1217. }
  1218. if (hexAlpha) {
  1219. a = Math.round((parseInt(hexAlpha, 16) / 255) * 100) / 100;
  1220. }
  1221. }
  1222. else if (match = string.match(rgba)) {
  1223. for (var i = 0; i < rgb.length; i++) {
  1224. rgb[i] = parseInt(match[i + 1]);
  1225. }
  1226. a = parseFloat(match[4]);
  1227. }
  1228. else if (match = string.match(per)) {
  1229. for (var i = 0; i < rgb.length; i++) {
  1230. rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
  1231. }
  1232. a = parseFloat(match[4]);
  1233. }
  1234. else if (match = string.match(keyword)) {
  1235. if (match[1] == "transparent") {
  1236. return [0, 0, 0, 0];
  1237. }
  1238. rgb = colorName$1[match[1]];
  1239. if (!rgb) {
  1240. return;
  1241. }
  1242. }
  1243. for (var i = 0; i < rgb.length; i++) {
  1244. rgb[i] = scale(rgb[i], 0, 255);
  1245. }
  1246. if (!a && a != 0) {
  1247. a = 1;
  1248. }
  1249. else {
  1250. a = scale(a, 0, 1);
  1251. }
  1252. rgb[3] = a;
  1253. return rgb;
  1254. }
  1255. function getHsla(string) {
  1256. if (!string) {
  1257. return;
  1258. }
  1259. var hsl = /^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1260. var match = string.match(hsl);
  1261. if (match) {
  1262. var alpha = parseFloat(match[4]);
  1263. var h = scale(parseInt(match[1]), 0, 360),
  1264. s = scale(parseFloat(match[2]), 0, 100),
  1265. l = scale(parseFloat(match[3]), 0, 100),
  1266. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1267. return [h, s, l, a];
  1268. }
  1269. }
  1270. function getHwb(string) {
  1271. if (!string) {
  1272. return;
  1273. }
  1274. var hwb = /^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/;
  1275. var match = string.match(hwb);
  1276. if (match) {
  1277. var alpha = parseFloat(match[4]);
  1278. var h = scale(parseInt(match[1]), 0, 360),
  1279. w = scale(parseFloat(match[2]), 0, 100),
  1280. b = scale(parseFloat(match[3]), 0, 100),
  1281. a = scale(isNaN(alpha) ? 1 : alpha, 0, 1);
  1282. return [h, w, b, a];
  1283. }
  1284. }
  1285. function getRgb(string) {
  1286. var rgba = getRgba(string);
  1287. return rgba && rgba.slice(0, 3);
  1288. }
  1289. function getHsl(string) {
  1290. var hsla = getHsla(string);
  1291. return hsla && hsla.slice(0, 3);
  1292. }
  1293. function getAlpha(string) {
  1294. var vals = getRgba(string);
  1295. if (vals) {
  1296. return vals[3];
  1297. }
  1298. else if (vals = getHsla(string)) {
  1299. return vals[3];
  1300. }
  1301. else if (vals = getHwb(string)) {
  1302. return vals[3];
  1303. }
  1304. }
  1305. // generators
  1306. function hexString(rgba, a) {
  1307. var a = (a !== undefined && rgba.length === 3) ? a : rgba[3];
  1308. return "#" + hexDouble(rgba[0])
  1309. + hexDouble(rgba[1])
  1310. + hexDouble(rgba[2])
  1311. + (
  1312. (a >= 0 && a < 1)
  1313. ? hexDouble(Math.round(a * 255))
  1314. : ""
  1315. );
  1316. }
  1317. function rgbString(rgba, alpha) {
  1318. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1319. return rgbaString(rgba, alpha);
  1320. }
  1321. return "rgb(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ")";
  1322. }
  1323. function rgbaString(rgba, alpha) {
  1324. if (alpha === undefined) {
  1325. alpha = (rgba[3] !== undefined ? rgba[3] : 1);
  1326. }
  1327. return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2]
  1328. + ", " + alpha + ")";
  1329. }
  1330. function percentString(rgba, alpha) {
  1331. if (alpha < 1 || (rgba[3] && rgba[3] < 1)) {
  1332. return percentaString(rgba, alpha);
  1333. }
  1334. var r = Math.round(rgba[0]/255 * 100),
  1335. g = Math.round(rgba[1]/255 * 100),
  1336. b = Math.round(rgba[2]/255 * 100);
  1337. return "rgb(" + r + "%, " + g + "%, " + b + "%)";
  1338. }
  1339. function percentaString(rgba, alpha) {
  1340. var r = Math.round(rgba[0]/255 * 100),
  1341. g = Math.round(rgba[1]/255 * 100),
  1342. b = Math.round(rgba[2]/255 * 100);
  1343. return "rgba(" + r + "%, " + g + "%, " + b + "%, " + (alpha || rgba[3] || 1) + ")";
  1344. }
  1345. function hslString(hsla, alpha) {
  1346. if (alpha < 1 || (hsla[3] && hsla[3] < 1)) {
  1347. return hslaString(hsla, alpha);
  1348. }
  1349. return "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)";
  1350. }
  1351. function hslaString(hsla, alpha) {
  1352. if (alpha === undefined) {
  1353. alpha = (hsla[3] !== undefined ? hsla[3] : 1);
  1354. }
  1355. return "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, "
  1356. + alpha + ")";
  1357. }
  1358. // hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
  1359. // (hwb have alpha optional & 1 is default value)
  1360. function hwbString(hwb, alpha) {
  1361. if (alpha === undefined) {
  1362. alpha = (hwb[3] !== undefined ? hwb[3] : 1);
  1363. }
  1364. return "hwb(" + hwb[0] + ", " + hwb[1] + "%, " + hwb[2] + "%"
  1365. + (alpha !== undefined && alpha !== 1 ? ", " + alpha : "") + ")";
  1366. }
  1367. function keyword(rgb) {
  1368. return reverseNames[rgb.slice(0, 3)];
  1369. }
  1370. // helpers
  1371. function scale(num, min, max) {
  1372. return Math.min(Math.max(min, num), max);
  1373. }
  1374. function hexDouble(num) {
  1375. var str = num.toString(16).toUpperCase();
  1376. return (str.length < 2) ? "0" + str : str;
  1377. }
  1378. //create a list of reverse color names
  1379. var reverseNames = {};
  1380. for (var name in colorName$1) {
  1381. reverseNames[colorName$1[name]] = name;
  1382. }
  1383. /* MIT license */
  1384. var Color = function (obj) {
  1385. if (obj instanceof Color) {
  1386. return obj;
  1387. }
  1388. if (!(this instanceof Color)) {
  1389. return new Color(obj);
  1390. }
  1391. this.valid = false;
  1392. this.values = {
  1393. rgb: [0, 0, 0],
  1394. hsl: [0, 0, 0],
  1395. hsv: [0, 0, 0],
  1396. hwb: [0, 0, 0],
  1397. cmyk: [0, 0, 0, 0],
  1398. alpha: 1
  1399. };
  1400. // parse Color() argument
  1401. var vals;
  1402. if (typeof obj === 'string') {
  1403. vals = colorString.getRgba(obj);
  1404. if (vals) {
  1405. this.setValues('rgb', vals);
  1406. } else if (vals = colorString.getHsla(obj)) {
  1407. this.setValues('hsl', vals);
  1408. } else if (vals = colorString.getHwb(obj)) {
  1409. this.setValues('hwb', vals);
  1410. }
  1411. } else if (typeof obj === 'object') {
  1412. vals = obj;
  1413. if (vals.r !== undefined || vals.red !== undefined) {
  1414. this.setValues('rgb', vals);
  1415. } else if (vals.l !== undefined || vals.lightness !== undefined) {
  1416. this.setValues('hsl', vals);
  1417. } else if (vals.v !== undefined || vals.value !== undefined) {
  1418. this.setValues('hsv', vals);
  1419. } else if (vals.w !== undefined || vals.whiteness !== undefined) {
  1420. this.setValues('hwb', vals);
  1421. } else if (vals.c !== undefined || vals.cyan !== undefined) {
  1422. this.setValues('cmyk', vals);
  1423. }
  1424. }
  1425. };
  1426. Color.prototype = {
  1427. isValid: function () {
  1428. return this.valid;
  1429. },
  1430. rgb: function () {
  1431. return this.setSpace('rgb', arguments);
  1432. },
  1433. hsl: function () {
  1434. return this.setSpace('hsl', arguments);
  1435. },
  1436. hsv: function () {
  1437. return this.setSpace('hsv', arguments);
  1438. },
  1439. hwb: function () {
  1440. return this.setSpace('hwb', arguments);
  1441. },
  1442. cmyk: function () {
  1443. return this.setSpace('cmyk', arguments);
  1444. },
  1445. rgbArray: function () {
  1446. return this.values.rgb;
  1447. },
  1448. hslArray: function () {
  1449. return this.values.hsl;
  1450. },
  1451. hsvArray: function () {
  1452. return this.values.hsv;
  1453. },
  1454. hwbArray: function () {
  1455. var values = this.values;
  1456. if (values.alpha !== 1) {
  1457. return values.hwb.concat([values.alpha]);
  1458. }
  1459. return values.hwb;
  1460. },
  1461. cmykArray: function () {
  1462. return this.values.cmyk;
  1463. },
  1464. rgbaArray: function () {
  1465. var values = this.values;
  1466. return values.rgb.concat([values.alpha]);
  1467. },
  1468. hslaArray: function () {
  1469. var values = this.values;
  1470. return values.hsl.concat([values.alpha]);
  1471. },
  1472. alpha: function (val) {
  1473. if (val === undefined) {
  1474. return this.values.alpha;
  1475. }
  1476. this.setValues('alpha', val);
  1477. return this;
  1478. },
  1479. red: function (val) {
  1480. return this.setChannel('rgb', 0, val);
  1481. },
  1482. green: function (val) {
  1483. return this.setChannel('rgb', 1, val);
  1484. },
  1485. blue: function (val) {
  1486. return this.setChannel('rgb', 2, val);
  1487. },
  1488. hue: function (val) {
  1489. if (val) {
  1490. val %= 360;
  1491. val = val < 0 ? 360 + val : val;
  1492. }
  1493. return this.setChannel('hsl', 0, val);
  1494. },
  1495. saturation: function (val) {
  1496. return this.setChannel('hsl', 1, val);
  1497. },
  1498. lightness: function (val) {
  1499. return this.setChannel('hsl', 2, val);
  1500. },
  1501. saturationv: function (val) {
  1502. return this.setChannel('hsv', 1, val);
  1503. },
  1504. whiteness: function (val) {
  1505. return this.setChannel('hwb', 1, val);
  1506. },
  1507. blackness: function (val) {
  1508. return this.setChannel('hwb', 2, val);
  1509. },
  1510. value: function (val) {
  1511. return this.setChannel('hsv', 2, val);
  1512. },
  1513. cyan: function (val) {
  1514. return this.setChannel('cmyk', 0, val);
  1515. },
  1516. magenta: function (val) {
  1517. return this.setChannel('cmyk', 1, val);
  1518. },
  1519. yellow: function (val) {
  1520. return this.setChannel('cmyk', 2, val);
  1521. },
  1522. black: function (val) {
  1523. return this.setChannel('cmyk', 3, val);
  1524. },
  1525. hexString: function () {
  1526. return colorString.hexString(this.values.rgb);
  1527. },
  1528. rgbString: function () {
  1529. return colorString.rgbString(this.values.rgb, this.values.alpha);
  1530. },
  1531. rgbaString: function () {
  1532. return colorString.rgbaString(this.values.rgb, this.values.alpha);
  1533. },
  1534. percentString: function () {
  1535. return colorString.percentString(this.values.rgb, this.values.alpha);
  1536. },
  1537. hslString: function () {
  1538. return colorString.hslString(this.values.hsl, this.values.alpha);
  1539. },
  1540. hslaString: function () {
  1541. return colorString.hslaString(this.values.hsl, this.values.alpha);
  1542. },
  1543. hwbString: function () {
  1544. return colorString.hwbString(this.values.hwb, this.values.alpha);
  1545. },
  1546. keyword: function () {
  1547. return colorString.keyword(this.values.rgb, this.values.alpha);
  1548. },
  1549. rgbNumber: function () {
  1550. var rgb = this.values.rgb;
  1551. return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2];
  1552. },
  1553. luminosity: function () {
  1554. // http://www.w3.org/TR/WCAG20/#relativeluminancedef
  1555. var rgb = this.values.rgb;
  1556. var lum = [];
  1557. for (var i = 0; i < rgb.length; i++) {
  1558. var chan = rgb[i] / 255;
  1559. lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
  1560. }
  1561. return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
  1562. },
  1563. contrast: function (color2) {
  1564. // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
  1565. var lum1 = this.luminosity();
  1566. var lum2 = color2.luminosity();
  1567. if (lum1 > lum2) {
  1568. return (lum1 + 0.05) / (lum2 + 0.05);
  1569. }
  1570. return (lum2 + 0.05) / (lum1 + 0.05);
  1571. },
  1572. level: function (color2) {
  1573. var contrastRatio = this.contrast(color2);
  1574. if (contrastRatio >= 7.1) {
  1575. return 'AAA';
  1576. }
  1577. return (contrastRatio >= 4.5) ? 'AA' : '';
  1578. },
  1579. dark: function () {
  1580. // YIQ equation from http://24ways.org/2010/calculating-color-contrast
  1581. var rgb = this.values.rgb;
  1582. var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  1583. return yiq < 128;
  1584. },
  1585. light: function () {
  1586. return !this.dark();
  1587. },
  1588. negate: function () {
  1589. var rgb = [];
  1590. for (var i = 0; i < 3; i++) {
  1591. rgb[i] = 255 - this.values.rgb[i];
  1592. }
  1593. this.setValues('rgb', rgb);
  1594. return this;
  1595. },
  1596. lighten: function (ratio) {
  1597. var hsl = this.values.hsl;
  1598. hsl[2] += hsl[2] * ratio;
  1599. this.setValues('hsl', hsl);
  1600. return this;
  1601. },
  1602. darken: function (ratio) {
  1603. var hsl = this.values.hsl;
  1604. hsl[2] -= hsl[2] * ratio;
  1605. this.setValues('hsl', hsl);
  1606. return this;
  1607. },
  1608. saturate: function (ratio) {
  1609. var hsl = this.values.hsl;
  1610. hsl[1] += hsl[1] * ratio;
  1611. this.setValues('hsl', hsl);
  1612. return this;
  1613. },
  1614. desaturate: function (ratio) {
  1615. var hsl = this.values.hsl;
  1616. hsl[1] -= hsl[1] * ratio;
  1617. this.setValues('hsl', hsl);
  1618. return this;
  1619. },
  1620. whiten: function (ratio) {
  1621. var hwb = this.values.hwb;
  1622. hwb[1] += hwb[1] * ratio;
  1623. this.setValues('hwb', hwb);
  1624. return this;
  1625. },
  1626. blacken: function (ratio) {
  1627. var hwb = this.values.hwb;
  1628. hwb[2] += hwb[2] * ratio;
  1629. this.setValues('hwb', hwb);
  1630. return this;
  1631. },
  1632. greyscale: function () {
  1633. var rgb = this.values.rgb;
  1634. // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
  1635. var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
  1636. this.setValues('rgb', [val, val, val]);
  1637. return this;
  1638. },
  1639. clearer: function (ratio) {
  1640. var alpha = this.values.alpha;
  1641. this.setValues('alpha', alpha - (alpha * ratio));
  1642. return this;
  1643. },
  1644. opaquer: function (ratio) {
  1645. var alpha = this.values.alpha;
  1646. this.setValues('alpha', alpha + (alpha * ratio));
  1647. return this;
  1648. },
  1649. rotate: function (degrees) {
  1650. var hsl = this.values.hsl;
  1651. var hue = (hsl[0] + degrees) % 360;
  1652. hsl[0] = hue < 0 ? 360 + hue : hue;
  1653. this.setValues('hsl', hsl);
  1654. return this;
  1655. },
  1656. /**
  1657. * Ported from sass implementation in C
  1658. * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
  1659. */
  1660. mix: function (mixinColor, weight) {
  1661. var color1 = this;
  1662. var color2 = mixinColor;
  1663. var p = weight === undefined ? 0.5 : weight;
  1664. var w = 2 * p - 1;
  1665. var a = color1.alpha() - color2.alpha();
  1666. var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
  1667. var w2 = 1 - w1;
  1668. return this
  1669. .rgb(
  1670. w1 * color1.red() + w2 * color2.red(),
  1671. w1 * color1.green() + w2 * color2.green(),
  1672. w1 * color1.blue() + w2 * color2.blue()
  1673. )
  1674. .alpha(color1.alpha() * p + color2.alpha() * (1 - p));
  1675. },
  1676. toJSON: function () {
  1677. return this.rgb();
  1678. },
  1679. clone: function () {
  1680. // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify,
  1681. // making the final build way to big to embed in Chart.js. So let's do it manually,
  1682. // assuming that values to clone are 1 dimension arrays containing only numbers,
  1683. // except 'alpha' which is a number.
  1684. var result = new Color();
  1685. var source = this.values;
  1686. var target = result.values;
  1687. var value, type;
  1688. for (var prop in source) {
  1689. if (source.hasOwnProperty(prop)) {
  1690. value = source[prop];
  1691. type = ({}).toString.call(value);
  1692. if (type === '[object Array]') {
  1693. target[prop] = value.slice(0);
  1694. } else if (type === '[object Number]') {
  1695. target[prop] = value;
  1696. } else {
  1697. console.error('unexpected color value:', value);
  1698. }
  1699. }
  1700. }
  1701. return result;
  1702. }
  1703. };
  1704. Color.prototype.spaces = {
  1705. rgb: ['red', 'green', 'blue'],
  1706. hsl: ['hue', 'saturation', 'lightness'],
  1707. hsv: ['hue', 'saturation', 'value'],
  1708. hwb: ['hue', 'whiteness', 'blackness'],
  1709. cmyk: ['cyan', 'magenta', 'yellow', 'black']
  1710. };
  1711. Color.prototype.maxes = {
  1712. rgb: [255, 255, 255],
  1713. hsl: [360, 100, 100],
  1714. hsv: [360, 100, 100],
  1715. hwb: [360, 100, 100],
  1716. cmyk: [100, 100, 100, 100]
  1717. };
  1718. Color.prototype.getValues = function (space) {
  1719. var values = this.values;
  1720. var vals = {};
  1721. for (var i = 0; i < space.length; i++) {
  1722. vals[space.charAt(i)] = values[space][i];
  1723. }
  1724. if (values.alpha !== 1) {
  1725. vals.a = values.alpha;
  1726. }
  1727. // {r: 255, g: 255, b: 255, a: 0.4}
  1728. return vals;
  1729. };
  1730. Color.prototype.setValues = function (space, vals) {
  1731. var values = this.values;
  1732. var spaces = this.spaces;
  1733. var maxes = this.maxes;
  1734. var alpha = 1;
  1735. var i;
  1736. this.valid = true;
  1737. if (space === 'alpha') {
  1738. alpha = vals;
  1739. } else if (vals.length) {
  1740. // [10, 10, 10]
  1741. values[space] = vals.slice(0, space.length);
  1742. alpha = vals[space.length];
  1743. } else if (vals[space.charAt(0)] !== undefined) {
  1744. // {r: 10, g: 10, b: 10}
  1745. for (i = 0; i < space.length; i++) {
  1746. values[space][i] = vals[space.charAt(i)];
  1747. }
  1748. alpha = vals.a;
  1749. } else if (vals[spaces[space][0]] !== undefined) {
  1750. // {red: 10, green: 10, blue: 10}
  1751. var chans = spaces[space];
  1752. for (i = 0; i < space.length; i++) {
  1753. values[space][i] = vals[chans[i]];
  1754. }
  1755. alpha = vals.alpha;
  1756. }
  1757. values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha)));
  1758. if (space === 'alpha') {
  1759. return false;
  1760. }
  1761. var capped;
  1762. // cap values of the space prior converting all values
  1763. for (i = 0; i < space.length; i++) {
  1764. capped = Math.max(0, Math.min(maxes[space][i], values[space][i]));
  1765. values[space][i] = Math.round(capped);
  1766. }
  1767. // convert to all the other color spaces
  1768. for (var sname in spaces) {
  1769. if (sname !== space) {
  1770. values[sname] = colorConvert[space][sname](values[space]);
  1771. }
  1772. }
  1773. return true;
  1774. };
  1775. Color.prototype.setSpace = function (space, args) {
  1776. var vals = args[0];
  1777. if (vals === undefined) {
  1778. // color.rgb()
  1779. return this.getValues(space);
  1780. }
  1781. // color.rgb(10, 10, 10)
  1782. if (typeof vals === 'number') {
  1783. vals = Array.prototype.slice.call(args);
  1784. }
  1785. this.setValues(space, vals);
  1786. return this;
  1787. };
  1788. Color.prototype.setChannel = function (space, index, val) {
  1789. var svalues = this.values[space];
  1790. if (val === undefined) {
  1791. // color.red()
  1792. return svalues[index];
  1793. } else if (val === svalues[index]) {
  1794. // color.red(color.red())
  1795. return this;
  1796. }
  1797. // color.red(100)
  1798. svalues[index] = val;
  1799. this.setValues(space, svalues);
  1800. return this;
  1801. };
  1802. if (typeof window !== 'undefined') {
  1803. window.Color = Color;
  1804. }
  1805. var chartjsColor = Color;
  1806. /**
  1807. * @namespace Chart.helpers
  1808. */
  1809. var helpers = {
  1810. /**
  1811. * An empty function that can be used, for example, for optional callback.
  1812. */
  1813. noop: function() {},
  1814. /**
  1815. * Returns a unique id, sequentially generated from a global variable.
  1816. * @returns {number}
  1817. * @function
  1818. */
  1819. uid: (function() {
  1820. var id = 0;
  1821. return function() {
  1822. return id++;
  1823. };
  1824. }()),
  1825. /**
  1826. * Returns true if `value` is neither null nor undefined, else returns false.
  1827. * @param {*} value - The value to test.
  1828. * @returns {boolean}
  1829. * @since 2.7.0
  1830. */
  1831. isNullOrUndef: function(value) {
  1832. return value === null || typeof value === 'undefined';
  1833. },
  1834. /**
  1835. * Returns true if `value` is an array (including typed arrays), else returns false.
  1836. * @param {*} value - The value to test.
  1837. * @returns {boolean}
  1838. * @function
  1839. */
  1840. isArray: function(value) {
  1841. if (Array.isArray && Array.isArray(value)) {
  1842. return true;
  1843. }
  1844. var type = Object.prototype.toString.call(value);
  1845. if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') {
  1846. return true;
  1847. }
  1848. return false;
  1849. },
  1850. /**
  1851. * Returns true if `value` is an object (excluding null), else returns false.
  1852. * @param {*} value - The value to test.
  1853. * @returns {boolean}
  1854. * @since 2.7.0
  1855. */
  1856. isObject: function(value) {
  1857. return value !== null && Object.prototype.toString.call(value) === '[object Object]';
  1858. },
  1859. /**
  1860. * Returns true if `value` is a finite number, else returns false
  1861. * @param {*} value - The value to test.
  1862. * @returns {boolean}
  1863. */
  1864. isFinite: function(value) {
  1865. return (typeof value === 'number' || value instanceof Number) && isFinite(value);
  1866. },
  1867. /**
  1868. * Returns `value` if defined, else returns `defaultValue`.
  1869. * @param {*} value - The value to return if defined.
  1870. * @param {*} defaultValue - The value to return if `value` is undefined.
  1871. * @returns {*}
  1872. */
  1873. valueOrDefault: function(value, defaultValue) {
  1874. return typeof value === 'undefined' ? defaultValue : value;
  1875. },
  1876. /**
  1877. * Returns value at the given `index` in array if defined, else returns `defaultValue`.
  1878. * @param {Array} value - The array to lookup for value at `index`.
  1879. * @param {number} index - The index in `value` to lookup for value.
  1880. * @param {*} defaultValue - The value to return if `value[index]` is undefined.
  1881. * @returns {*}
  1882. */
  1883. valueAtIndexOrDefault: function(value, index, defaultValue) {
  1884. return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue);
  1885. },
  1886. /**
  1887. * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the
  1888. * value returned by `fn`. If `fn` is not a function, this method returns undefined.
  1889. * @param {function} fn - The function to call.
  1890. * @param {Array|undefined|null} args - The arguments with which `fn` should be called.
  1891. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1892. * @returns {*}
  1893. */
  1894. callback: function(fn, args, thisArg) {
  1895. if (fn && typeof fn.call === 'function') {
  1896. return fn.apply(thisArg, args);
  1897. }
  1898. },
  1899. /**
  1900. * Note(SB) for performance sake, this method should only be used when loopable type
  1901. * is unknown or in none intensive code (not called often and small loopable). Else
  1902. * it's preferable to use a regular for() loop and save extra function calls.
  1903. * @param {object|Array} loopable - The object or array to be iterated.
  1904. * @param {function} fn - The function to call for each item.
  1905. * @param {object} [thisArg] - The value of `this` provided for the call to `fn`.
  1906. * @param {boolean} [reverse] - If true, iterates backward on the loopable.
  1907. */
  1908. each: function(loopable, fn, thisArg, reverse) {
  1909. var i, len, keys;
  1910. if (helpers.isArray(loopable)) {
  1911. len = loopable.length;
  1912. if (reverse) {
  1913. for (i = len - 1; i >= 0; i--) {
  1914. fn.call(thisArg, loopable[i], i);
  1915. }
  1916. } else {
  1917. for (i = 0; i < len; i++) {
  1918. fn.call(thisArg, loopable[i], i);
  1919. }
  1920. }
  1921. } else if (helpers.isObject(loopable)) {
  1922. keys = Object.keys(loopable);
  1923. len = keys.length;
  1924. for (i = 0; i < len; i++) {
  1925. fn.call(thisArg, loopable[keys[i]], keys[i]);
  1926. }
  1927. }
  1928. },
  1929. /**
  1930. * Returns true if the `a0` and `a1` arrays have the same content, else returns false.
  1931. * @see https://stackoverflow.com/a/14853974
  1932. * @param {Array} a0 - The array to compare
  1933. * @param {Array} a1 - The array to compare
  1934. * @returns {boolean}
  1935. */
  1936. arrayEquals: function(a0, a1) {
  1937. var i, ilen, v0, v1;
  1938. if (!a0 || !a1 || a0.length !== a1.length) {
  1939. return false;
  1940. }
  1941. for (i = 0, ilen = a0.length; i < ilen; ++i) {
  1942. v0 = a0[i];
  1943. v1 = a1[i];
  1944. if (v0 instanceof Array && v1 instanceof Array) {
  1945. if (!helpers.arrayEquals(v0, v1)) {
  1946. return false;
  1947. }
  1948. } else if (v0 !== v1) {
  1949. // NOTE: two different object instances will never be equal: {x:20} != {x:20}
  1950. return false;
  1951. }
  1952. }
  1953. return true;
  1954. },
  1955. /**
  1956. * Returns a deep copy of `source` without keeping references on objects and arrays.
  1957. * @param {*} source - The value to clone.
  1958. * @returns {*}
  1959. */
  1960. clone: function(source) {
  1961. if (helpers.isArray(source)) {
  1962. return source.map(helpers.clone);
  1963. }
  1964. if (helpers.isObject(source)) {
  1965. var target = {};
  1966. var keys = Object.keys(source);
  1967. var klen = keys.length;
  1968. var k = 0;
  1969. for (; k < klen; ++k) {
  1970. target[keys[k]] = helpers.clone(source[keys[k]]);
  1971. }
  1972. return target;
  1973. }
  1974. return source;
  1975. },
  1976. /**
  1977. * The default merger when Chart.helpers.merge is called without merger option.
  1978. * Note(SB): also used by mergeConfig and mergeScaleConfig as fallback.
  1979. * @private
  1980. */
  1981. _merger: function(key, target, source, options) {
  1982. var tval = target[key];
  1983. var sval = source[key];
  1984. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1985. helpers.merge(tval, sval, options);
  1986. } else {
  1987. target[key] = helpers.clone(sval);
  1988. }
  1989. },
  1990. /**
  1991. * Merges source[key] in target[key] only if target[key] is undefined.
  1992. * @private
  1993. */
  1994. _mergerIf: function(key, target, source) {
  1995. var tval = target[key];
  1996. var sval = source[key];
  1997. if (helpers.isObject(tval) && helpers.isObject(sval)) {
  1998. helpers.mergeIf(tval, sval);
  1999. } else if (!target.hasOwnProperty(key)) {
  2000. target[key] = helpers.clone(sval);
  2001. }
  2002. },
  2003. /**
  2004. * Recursively deep copies `source` properties into `target` with the given `options`.
  2005. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2006. * @param {object} target - The target object in which all sources are merged into.
  2007. * @param {object|object[]} source - Object(s) to merge into `target`.
  2008. * @param {object} [options] - Merging options:
  2009. * @param {function} [options.merger] - The merge method (key, target, source, options)
  2010. * @returns {object} The `target` object.
  2011. */
  2012. merge: function(target, source, options) {
  2013. var sources = helpers.isArray(source) ? source : [source];
  2014. var ilen = sources.length;
  2015. var merge, i, keys, klen, k;
  2016. if (!helpers.isObject(target)) {
  2017. return target;
  2018. }
  2019. options = options || {};
  2020. merge = options.merger || helpers._merger;
  2021. for (i = 0; i < ilen; ++i) {
  2022. source = sources[i];
  2023. if (!helpers.isObject(source)) {
  2024. continue;
  2025. }
  2026. keys = Object.keys(source);
  2027. for (k = 0, klen = keys.length; k < klen; ++k) {
  2028. merge(keys[k], target, source, options);
  2029. }
  2030. }
  2031. return target;
  2032. },
  2033. /**
  2034. * Recursively deep copies `source` properties into `target` *only* if not defined in target.
  2035. * IMPORTANT: `target` is not cloned and will be updated with `source` properties.
  2036. * @param {object} target - The target object in which all sources are merged into.
  2037. * @param {object|object[]} source - Object(s) to merge into `target`.
  2038. * @returns {object} The `target` object.
  2039. */
  2040. mergeIf: function(target, source) {
  2041. return helpers.merge(target, source, {merger: helpers._mergerIf});
  2042. },
  2043. /**
  2044. * Applies the contents of two or more objects together into the first object.
  2045. * @param {object} target - The target object in which all objects are merged into.
  2046. * @param {object} arg1 - Object containing additional properties to merge in target.
  2047. * @param {object} argN - Additional objects containing properties to merge in target.
  2048. * @returns {object} The `target` object.
  2049. */
  2050. extend: Object.assign || function(target) {
  2051. return helpers.merge(target, [].slice.call(arguments, 1), {
  2052. merger: function(key, dst, src) {
  2053. dst[key] = src[key];
  2054. }
  2055. });
  2056. },
  2057. /**
  2058. * Basic javascript inheritance based on the model created in Backbone.js
  2059. */
  2060. inherits: function(extensions) {
  2061. var me = this;
  2062. var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() {
  2063. return me.apply(this, arguments);
  2064. };
  2065. var Surrogate = function() {
  2066. this.constructor = ChartElement;
  2067. };
  2068. Surrogate.prototype = me.prototype;
  2069. ChartElement.prototype = new Surrogate();
  2070. ChartElement.extend = helpers.inherits;
  2071. if (extensions) {
  2072. helpers.extend(ChartElement.prototype, extensions);
  2073. }
  2074. ChartElement.__super__ = me.prototype;
  2075. return ChartElement;
  2076. },
  2077. _deprecated: function(scope, value, previous, current) {
  2078. if (value !== undefined) {
  2079. console.warn(scope + ': "' + previous +
  2080. '" is deprecated. Please use "' + current + '" instead');
  2081. }
  2082. }
  2083. };
  2084. var helpers_core = helpers;
  2085. // DEPRECATIONS
  2086. /**
  2087. * Provided for backward compatibility, use Chart.helpers.callback instead.
  2088. * @function Chart.helpers.callCallback
  2089. * @deprecated since version 2.6.0
  2090. * @todo remove at version 3
  2091. * @private
  2092. */
  2093. helpers.callCallback = helpers.callback;
  2094. /**
  2095. * Provided for backward compatibility, use Array.prototype.indexOf instead.
  2096. * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+
  2097. * @function Chart.helpers.indexOf
  2098. * @deprecated since version 2.7.0
  2099. * @todo remove at version 3
  2100. * @private
  2101. */
  2102. helpers.indexOf = function(array, item, fromIndex) {
  2103. return Array.prototype.indexOf.call(array, item, fromIndex);
  2104. };
  2105. /**
  2106. * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead.
  2107. * @function Chart.helpers.getValueOrDefault
  2108. * @deprecated since version 2.7.0
  2109. * @todo remove at version 3
  2110. * @private
  2111. */
  2112. helpers.getValueOrDefault = helpers.valueOrDefault;
  2113. /**
  2114. * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead.
  2115. * @function Chart.helpers.getValueAtIndexOrDefault
  2116. * @deprecated since version 2.7.0
  2117. * @todo remove at version 3
  2118. * @private
  2119. */
  2120. helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault;
  2121. /**
  2122. * Easing functions adapted from Robert Penner's easing equations.
  2123. * @namespace Chart.helpers.easingEffects
  2124. * @see http://www.robertpenner.com/easing/
  2125. */
  2126. var effects = {
  2127. linear: function(t) {
  2128. return t;
  2129. },
  2130. easeInQuad: function(t) {
  2131. return t * t;
  2132. },
  2133. easeOutQuad: function(t) {
  2134. return -t * (t - 2);
  2135. },
  2136. easeInOutQuad: function(t) {
  2137. if ((t /= 0.5) < 1) {
  2138. return 0.5 * t * t;
  2139. }
  2140. return -0.5 * ((--t) * (t - 2) - 1);
  2141. },
  2142. easeInCubic: function(t) {
  2143. return t * t * t;
  2144. },
  2145. easeOutCubic: function(t) {
  2146. return (t = t - 1) * t * t + 1;
  2147. },
  2148. easeInOutCubic: function(t) {
  2149. if ((t /= 0.5) < 1) {
  2150. return 0.5 * t * t * t;
  2151. }
  2152. return 0.5 * ((t -= 2) * t * t + 2);
  2153. },
  2154. easeInQuart: function(t) {
  2155. return t * t * t * t;
  2156. },
  2157. easeOutQuart: function(t) {
  2158. return -((t = t - 1) * t * t * t - 1);
  2159. },
  2160. easeInOutQuart: function(t) {
  2161. if ((t /= 0.5) < 1) {
  2162. return 0.5 * t * t * t * t;
  2163. }
  2164. return -0.5 * ((t -= 2) * t * t * t - 2);
  2165. },
  2166. easeInQuint: function(t) {
  2167. return t * t * t * t * t;
  2168. },
  2169. easeOutQuint: function(t) {
  2170. return (t = t - 1) * t * t * t * t + 1;
  2171. },
  2172. easeInOutQuint: function(t) {
  2173. if ((t /= 0.5) < 1) {
  2174. return 0.5 * t * t * t * t * t;
  2175. }
  2176. return 0.5 * ((t -= 2) * t * t * t * t + 2);
  2177. },
  2178. easeInSine: function(t) {
  2179. return -Math.cos(t * (Math.PI / 2)) + 1;
  2180. },
  2181. easeOutSine: function(t) {
  2182. return Math.sin(t * (Math.PI / 2));
  2183. },
  2184. easeInOutSine: function(t) {
  2185. return -0.5 * (Math.cos(Math.PI * t) - 1);
  2186. },
  2187. easeInExpo: function(t) {
  2188. return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1));
  2189. },
  2190. easeOutExpo: function(t) {
  2191. return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1;
  2192. },
  2193. easeInOutExpo: function(t) {
  2194. if (t === 0) {
  2195. return 0;
  2196. }
  2197. if (t === 1) {
  2198. return 1;
  2199. }
  2200. if ((t /= 0.5) < 1) {
  2201. return 0.5 * Math.pow(2, 10 * (t - 1));
  2202. }
  2203. return 0.5 * (-Math.pow(2, -10 * --t) + 2);
  2204. },
  2205. easeInCirc: function(t) {
  2206. if (t >= 1) {
  2207. return t;
  2208. }
  2209. return -(Math.sqrt(1 - t * t) - 1);
  2210. },
  2211. easeOutCirc: function(t) {
  2212. return Math.sqrt(1 - (t = t - 1) * t);
  2213. },
  2214. easeInOutCirc: function(t) {
  2215. if ((t /= 0.5) < 1) {
  2216. return -0.5 * (Math.sqrt(1 - t * t) - 1);
  2217. }
  2218. return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
  2219. },
  2220. easeInElastic: function(t) {
  2221. var s = 1.70158;
  2222. var p = 0;
  2223. var a = 1;
  2224. if (t === 0) {
  2225. return 0;
  2226. }
  2227. if (t === 1) {
  2228. return 1;
  2229. }
  2230. if (!p) {
  2231. p = 0.3;
  2232. }
  2233. if (a < 1) {
  2234. a = 1;
  2235. s = p / 4;
  2236. } else {
  2237. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2238. }
  2239. return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2240. },
  2241. easeOutElastic: function(t) {
  2242. var s = 1.70158;
  2243. var p = 0;
  2244. var a = 1;
  2245. if (t === 0) {
  2246. return 0;
  2247. }
  2248. if (t === 1) {
  2249. return 1;
  2250. }
  2251. if (!p) {
  2252. p = 0.3;
  2253. }
  2254. if (a < 1) {
  2255. a = 1;
  2256. s = p / 4;
  2257. } else {
  2258. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2259. }
  2260. return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
  2261. },
  2262. easeInOutElastic: function(t) {
  2263. var s = 1.70158;
  2264. var p = 0;
  2265. var a = 1;
  2266. if (t === 0) {
  2267. return 0;
  2268. }
  2269. if ((t /= 0.5) === 2) {
  2270. return 1;
  2271. }
  2272. if (!p) {
  2273. p = 0.45;
  2274. }
  2275. if (a < 1) {
  2276. a = 1;
  2277. s = p / 4;
  2278. } else {
  2279. s = p / (2 * Math.PI) * Math.asin(1 / a);
  2280. }
  2281. if (t < 1) {
  2282. return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p));
  2283. }
  2284. return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2285. },
  2286. easeInBack: function(t) {
  2287. var s = 1.70158;
  2288. return t * t * ((s + 1) * t - s);
  2289. },
  2290. easeOutBack: function(t) {
  2291. var s = 1.70158;
  2292. return (t = t - 1) * t * ((s + 1) * t + s) + 1;
  2293. },
  2294. easeInOutBack: function(t) {
  2295. var s = 1.70158;
  2296. if ((t /= 0.5) < 1) {
  2297. return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s));
  2298. }
  2299. return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
  2300. },
  2301. easeInBounce: function(t) {
  2302. return 1 - effects.easeOutBounce(1 - t);
  2303. },
  2304. easeOutBounce: function(t) {
  2305. if (t < (1 / 2.75)) {
  2306. return 7.5625 * t * t;
  2307. }
  2308. if (t < (2 / 2.75)) {
  2309. return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
  2310. }
  2311. if (t < (2.5 / 2.75)) {
  2312. return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
  2313. }
  2314. return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
  2315. },
  2316. easeInOutBounce: function(t) {
  2317. if (t < 0.5) {
  2318. return effects.easeInBounce(t * 2) * 0.5;
  2319. }
  2320. return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
  2321. }
  2322. };
  2323. var helpers_easing = {
  2324. effects: effects
  2325. };
  2326. // DEPRECATIONS
  2327. /**
  2328. * Provided for backward compatibility, use Chart.helpers.easing.effects instead.
  2329. * @function Chart.helpers.easingEffects
  2330. * @deprecated since version 2.7.0
  2331. * @todo remove at version 3
  2332. * @private
  2333. */
  2334. helpers_core.easingEffects = effects;
  2335. var PI = Math.PI;
  2336. var RAD_PER_DEG = PI / 180;
  2337. var DOUBLE_PI = PI * 2;
  2338. var HALF_PI = PI / 2;
  2339. var QUARTER_PI = PI / 4;
  2340. var TWO_THIRDS_PI = PI * 2 / 3;
  2341. /**
  2342. * @namespace Chart.helpers.canvas
  2343. */
  2344. var exports$1 = {
  2345. /**
  2346. * Clears the entire canvas associated to the given `chart`.
  2347. * @param {Chart} chart - The chart for which to clear the canvas.
  2348. */
  2349. clear: function(chart) {
  2350. chart.ctx.clearRect(0, 0, chart.width, chart.height);
  2351. },
  2352. /**
  2353. * Creates a "path" for a rectangle with rounded corners at position (x, y) with a
  2354. * given size (width, height) and the same `radius` for all corners.
  2355. * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context.
  2356. * @param {number} x - The x axis of the coordinate for the rectangle starting point.
  2357. * @param {number} y - The y axis of the coordinate for the rectangle starting point.
  2358. * @param {number} width - The rectangle's width.
  2359. * @param {number} height - The rectangle's height.
  2360. * @param {number} radius - The rounded amount (in pixels) for the four corners.
  2361. * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object?
  2362. */
  2363. roundedRect: function(ctx, x, y, width, height, radius) {
  2364. if (radius) {
  2365. var r = Math.min(radius, height / 2, width / 2);
  2366. var left = x + r;
  2367. var top = y + r;
  2368. var right = x + width - r;
  2369. var bottom = y + height - r;
  2370. ctx.moveTo(x, top);
  2371. if (left < right && top < bottom) {
  2372. ctx.arc(left, top, r, -PI, -HALF_PI);
  2373. ctx.arc(right, top, r, -HALF_PI, 0);
  2374. ctx.arc(right, bottom, r, 0, HALF_PI);
  2375. ctx.arc(left, bottom, r, HALF_PI, PI);
  2376. } else if (left < right) {
  2377. ctx.moveTo(left, y);
  2378. ctx.arc(right, top, r, -HALF_PI, HALF_PI);
  2379. ctx.arc(left, top, r, HALF_PI, PI + HALF_PI);
  2380. } else if (top < bottom) {
  2381. ctx.arc(left, top, r, -PI, 0);
  2382. ctx.arc(left, bottom, r, 0, PI);
  2383. } else {
  2384. ctx.arc(left, top, r, -PI, PI);
  2385. }
  2386. ctx.closePath();
  2387. ctx.moveTo(x, y);
  2388. } else {
  2389. ctx.rect(x, y, width, height);
  2390. }
  2391. },
  2392. drawPoint: function(ctx, style, radius, x, y, rotation) {
  2393. var type, xOffset, yOffset, size, cornerRadius;
  2394. var rad = (rotation || 0) * RAD_PER_DEG;
  2395. if (style && typeof style === 'object') {
  2396. type = style.toString();
  2397. if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') {
  2398. ctx.save();
  2399. ctx.translate(x, y);
  2400. ctx.rotate(rad);
  2401. ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
  2402. ctx.restore();
  2403. return;
  2404. }
  2405. }
  2406. if (isNaN(radius) || radius <= 0) {
  2407. return;
  2408. }
  2409. ctx.beginPath();
  2410. switch (style) {
  2411. // Default includes circle
  2412. default:
  2413. ctx.arc(x, y, radius, 0, DOUBLE_PI);
  2414. ctx.closePath();
  2415. break;
  2416. case 'triangle':
  2417. ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2418. rad += TWO_THIRDS_PI;
  2419. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2420. rad += TWO_THIRDS_PI;
  2421. ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
  2422. ctx.closePath();
  2423. break;
  2424. case 'rectRounded':
  2425. // NOTE: the rounded rect implementation changed to use `arc` instead of
  2426. // `quadraticCurveTo` since it generates better results when rect is
  2427. // almost a circle. 0.516 (instead of 0.5) produces results with visually
  2428. // closer proportion to the previous impl and it is inscribed in the
  2429. // circle with `radius`. For more details, see the following PRs:
  2430. // https://github.com/chartjs/Chart.js/issues/5597
  2431. // https://github.com/chartjs/Chart.js/issues/5858
  2432. cornerRadius = radius * 0.516;
  2433. size = radius - cornerRadius;
  2434. xOffset = Math.cos(rad + QUARTER_PI) * size;
  2435. yOffset = Math.sin(rad + QUARTER_PI) * size;
  2436. ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
  2437. ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
  2438. ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
  2439. ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
  2440. ctx.closePath();
  2441. break;
  2442. case 'rect':
  2443. if (!rotation) {
  2444. size = Math.SQRT1_2 * radius;
  2445. ctx.rect(x - size, y - size, 2 * size, 2 * size);
  2446. break;
  2447. }
  2448. rad += QUARTER_PI;
  2449. /* falls through */
  2450. case 'rectRot':
  2451. xOffset = Math.cos(rad) * radius;
  2452. yOffset = Math.sin(rad) * radius;
  2453. ctx.moveTo(x - xOffset, y - yOffset);
  2454. ctx.lineTo(x + yOffset, y - xOffset);
  2455. ctx.lineTo(x + xOffset, y + yOffset);
  2456. ctx.lineTo(x - yOffset, y + xOffset);
  2457. ctx.closePath();
  2458. break;
  2459. case 'crossRot':
  2460. rad += QUARTER_PI;
  2461. /* falls through */
  2462. case 'cross':
  2463. xOffset = Math.cos(rad) * radius;
  2464. yOffset = Math.sin(rad) * radius;
  2465. ctx.moveTo(x - xOffset, y - yOffset);
  2466. ctx.lineTo(x + xOffset, y + yOffset);
  2467. ctx.moveTo(x + yOffset, y - xOffset);
  2468. ctx.lineTo(x - yOffset, y + xOffset);
  2469. break;
  2470. case 'star':
  2471. xOffset = Math.cos(rad) * radius;
  2472. yOffset = Math.sin(rad) * radius;
  2473. ctx.moveTo(x - xOffset, y - yOffset);
  2474. ctx.lineTo(x + xOffset, y + yOffset);
  2475. ctx.moveTo(x + yOffset, y - xOffset);
  2476. ctx.lineTo(x - yOffset, y + xOffset);
  2477. rad += QUARTER_PI;
  2478. xOffset = Math.cos(rad) * radius;
  2479. yOffset = Math.sin(rad) * radius;
  2480. ctx.moveTo(x - xOffset, y - yOffset);
  2481. ctx.lineTo(x + xOffset, y + yOffset);
  2482. ctx.moveTo(x + yOffset, y - xOffset);
  2483. ctx.lineTo(x - yOffset, y + xOffset);
  2484. break;
  2485. case 'line':
  2486. xOffset = Math.cos(rad) * radius;
  2487. yOffset = Math.sin(rad) * radius;
  2488. ctx.moveTo(x - xOffset, y - yOffset);
  2489. ctx.lineTo(x + xOffset, y + yOffset);
  2490. break;
  2491. case 'dash':
  2492. ctx.moveTo(x, y);
  2493. ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
  2494. break;
  2495. }
  2496. ctx.fill();
  2497. ctx.stroke();
  2498. },
  2499. /**
  2500. * Returns true if the point is inside the rectangle
  2501. * @param {object} point - The point to test
  2502. * @param {object} area - The rectangle
  2503. * @returns {boolean}
  2504. * @private
  2505. */
  2506. _isPointInArea: function(point, area) {
  2507. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  2508. return point.x > area.left - epsilon && point.x < area.right + epsilon &&
  2509. point.y > area.top - epsilon && point.y < area.bottom + epsilon;
  2510. },
  2511. clipArea: function(ctx, area) {
  2512. ctx.save();
  2513. ctx.beginPath();
  2514. ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top);
  2515. ctx.clip();
  2516. },
  2517. unclipArea: function(ctx) {
  2518. ctx.restore();
  2519. },
  2520. lineTo: function(ctx, previous, target, flip) {
  2521. var stepped = target.steppedLine;
  2522. if (stepped) {
  2523. if (stepped === 'middle') {
  2524. var midpoint = (previous.x + target.x) / 2.0;
  2525. ctx.lineTo(midpoint, flip ? target.y : previous.y);
  2526. ctx.lineTo(midpoint, flip ? previous.y : target.y);
  2527. } else if ((stepped === 'after' && !flip) || (stepped !== 'after' && flip)) {
  2528. ctx.lineTo(previous.x, target.y);
  2529. } else {
  2530. ctx.lineTo(target.x, previous.y);
  2531. }
  2532. ctx.lineTo(target.x, target.y);
  2533. return;
  2534. }
  2535. if (!target.tension) {
  2536. ctx.lineTo(target.x, target.y);
  2537. return;
  2538. }
  2539. ctx.bezierCurveTo(
  2540. flip ? previous.controlPointPreviousX : previous.controlPointNextX,
  2541. flip ? previous.controlPointPreviousY : previous.controlPointNextY,
  2542. flip ? target.controlPointNextX : target.controlPointPreviousX,
  2543. flip ? target.controlPointNextY : target.controlPointPreviousY,
  2544. target.x,
  2545. target.y);
  2546. }
  2547. };
  2548. var helpers_canvas = exports$1;
  2549. // DEPRECATIONS
  2550. /**
  2551. * Provided for backward compatibility, use Chart.helpers.canvas.clear instead.
  2552. * @namespace Chart.helpers.clear
  2553. * @deprecated since version 2.7.0
  2554. * @todo remove at version 3
  2555. * @private
  2556. */
  2557. helpers_core.clear = exports$1.clear;
  2558. /**
  2559. * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead.
  2560. * @namespace Chart.helpers.drawRoundedRectangle
  2561. * @deprecated since version 2.7.0
  2562. * @todo remove at version 3
  2563. * @private
  2564. */
  2565. helpers_core.drawRoundedRectangle = function(ctx) {
  2566. ctx.beginPath();
  2567. exports$1.roundedRect.apply(exports$1, arguments);
  2568. };
  2569. var defaults = {
  2570. /**
  2571. * @private
  2572. */
  2573. _set: function(scope, values) {
  2574. return helpers_core.merge(this[scope] || (this[scope] = {}), values);
  2575. }
  2576. };
  2577. // TODO(v3): remove 'global' from namespace. all default are global and
  2578. // there's inconsistency around which options are under 'global'
  2579. defaults._set('global', {
  2580. defaultColor: 'rgba(0,0,0,0.1)',
  2581. defaultFontColor: '#666',
  2582. defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
  2583. defaultFontSize: 12,
  2584. defaultFontStyle: 'normal',
  2585. defaultLineHeight: 1.2,
  2586. showLines: true
  2587. });
  2588. var core_defaults = defaults;
  2589. var valueOrDefault = helpers_core.valueOrDefault;
  2590. /**
  2591. * Converts the given font object into a CSS font string.
  2592. * @param {object} font - A font object.
  2593. * @return {string} The CSS font string. See https://developer.mozilla.org/en-US/docs/Web/CSS/font
  2594. * @private
  2595. */
  2596. function toFontString(font) {
  2597. if (!font || helpers_core.isNullOrUndef(font.size) || helpers_core.isNullOrUndef(font.family)) {
  2598. return null;
  2599. }
  2600. return (font.style ? font.style + ' ' : '')
  2601. + (font.weight ? font.weight + ' ' : '')
  2602. + font.size + 'px '
  2603. + font.family;
  2604. }
  2605. /**
  2606. * @alias Chart.helpers.options
  2607. * @namespace
  2608. */
  2609. var helpers_options = {
  2610. /**
  2611. * Converts the given line height `value` in pixels for a specific font `size`.
  2612. * @param {number|string} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em').
  2613. * @param {number} size - The font size (in pixels) used to resolve relative `value`.
  2614. * @returns {number} The effective line height in pixels (size * 1.2 if value is invalid).
  2615. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
  2616. * @since 2.7.0
  2617. */
  2618. toLineHeight: function(value, size) {
  2619. var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);
  2620. if (!matches || matches[1] === 'normal') {
  2621. return size * 1.2;
  2622. }
  2623. value = +matches[2];
  2624. switch (matches[3]) {
  2625. case 'px':
  2626. return value;
  2627. case '%':
  2628. value /= 100;
  2629. break;
  2630. }
  2631. return size * value;
  2632. },
  2633. /**
  2634. * Converts the given value into a padding object with pre-computed width/height.
  2635. * @param {number|object} value - If a number, set the value to all TRBL component,
  2636. * else, if and object, use defined properties and sets undefined ones to 0.
  2637. * @returns {object} The padding values (top, right, bottom, left, width, height)
  2638. * @since 2.7.0
  2639. */
  2640. toPadding: function(value) {
  2641. var t, r, b, l;
  2642. if (helpers_core.isObject(value)) {
  2643. t = +value.top || 0;
  2644. r = +value.right || 0;
  2645. b = +value.bottom || 0;
  2646. l = +value.left || 0;
  2647. } else {
  2648. t = r = b = l = +value || 0;
  2649. }
  2650. return {
  2651. top: t,
  2652. right: r,
  2653. bottom: b,
  2654. left: l,
  2655. height: t + b,
  2656. width: l + r
  2657. };
  2658. },
  2659. /**
  2660. * Parses font options and returns the font object.
  2661. * @param {object} options - A object that contains font options to be parsed.
  2662. * @return {object} The font object.
  2663. * @todo Support font.* options and renamed to toFont().
  2664. * @private
  2665. */
  2666. _parseFont: function(options) {
  2667. var globalDefaults = core_defaults.global;
  2668. var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize);
  2669. var font = {
  2670. family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily),
  2671. lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size),
  2672. size: size,
  2673. style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle),
  2674. weight: null,
  2675. string: ''
  2676. };
  2677. font.string = toFontString(font);
  2678. return font;
  2679. },
  2680. /**
  2681. * Evaluates the given `inputs` sequentially and returns the first defined value.
  2682. * @param {Array} inputs - An array of values, falling back to the last value.
  2683. * @param {object} [context] - If defined and the current value is a function, the value
  2684. * is called with `context` as first argument and the result becomes the new input.
  2685. * @param {number} [index] - If defined and the current value is an array, the value
  2686. * at `index` become the new input.
  2687. * @param {object} [info] - object to return information about resolution in
  2688. * @param {boolean} [info.cacheable] - Will be set to `false` if option is not cacheable.
  2689. * @since 2.7.0
  2690. */
  2691. resolve: function(inputs, context, index, info) {
  2692. var cacheable = true;
  2693. var i, ilen, value;
  2694. for (i = 0, ilen = inputs.length; i < ilen; ++i) {
  2695. value = inputs[i];
  2696. if (value === undefined) {
  2697. continue;
  2698. }
  2699. if (context !== undefined && typeof value === 'function') {
  2700. value = value(context);
  2701. cacheable = false;
  2702. }
  2703. if (index !== undefined && helpers_core.isArray(value)) {
  2704. value = value[index];
  2705. cacheable = false;
  2706. }
  2707. if (value !== undefined) {
  2708. if (info && !cacheable) {
  2709. info.cacheable = false;
  2710. }
  2711. return value;
  2712. }
  2713. }
  2714. }
  2715. };
  2716. /**
  2717. * @alias Chart.helpers.math
  2718. * @namespace
  2719. */
  2720. var exports$2 = {
  2721. /**
  2722. * Returns an array of factors sorted from 1 to sqrt(value)
  2723. * @private
  2724. */
  2725. _factorize: function(value) {
  2726. var result = [];
  2727. var sqrt = Math.sqrt(value);
  2728. var i;
  2729. for (i = 1; i < sqrt; i++) {
  2730. if (value % i === 0) {
  2731. result.push(i);
  2732. result.push(value / i);
  2733. }
  2734. }
  2735. if (sqrt === (sqrt | 0)) { // if value is a square number
  2736. result.push(sqrt);
  2737. }
  2738. result.sort(function(a, b) {
  2739. return a - b;
  2740. }).pop();
  2741. return result;
  2742. },
  2743. log10: Math.log10 || function(x) {
  2744. var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
  2745. // Check for whole powers of 10,
  2746. // which due to floating point rounding error should be corrected.
  2747. var powerOf10 = Math.round(exponent);
  2748. var isPowerOf10 = x === Math.pow(10, powerOf10);
  2749. return isPowerOf10 ? powerOf10 : exponent;
  2750. }
  2751. };
  2752. var helpers_math = exports$2;
  2753. // DEPRECATIONS
  2754. /**
  2755. * Provided for backward compatibility, use Chart.helpers.math.log10 instead.
  2756. * @namespace Chart.helpers.log10
  2757. * @deprecated since version 2.9.0
  2758. * @todo remove at version 3
  2759. * @private
  2760. */
  2761. helpers_core.log10 = exports$2.log10;
  2762. var getRtlAdapter = function(rectX, width) {
  2763. return {
  2764. x: function(x) {
  2765. return rectX + rectX + width - x;
  2766. },
  2767. setWidth: function(w) {
  2768. width = w;
  2769. },
  2770. textAlign: function(align) {
  2771. if (align === 'center') {
  2772. return align;
  2773. }
  2774. return align === 'right' ? 'left' : 'right';
  2775. },
  2776. xPlus: function(x, value) {
  2777. return x - value;
  2778. },
  2779. leftForLtr: function(x, itemWidth) {
  2780. return x - itemWidth;
  2781. },
  2782. };
  2783. };
  2784. var getLtrAdapter = function() {
  2785. return {
  2786. x: function(x) {
  2787. return x;
  2788. },
  2789. setWidth: function(w) { // eslint-disable-line no-unused-vars
  2790. },
  2791. textAlign: function(align) {
  2792. return align;
  2793. },
  2794. xPlus: function(x, value) {
  2795. return x + value;
  2796. },
  2797. leftForLtr: function(x, _itemWidth) { // eslint-disable-line no-unused-vars
  2798. return x;
  2799. },
  2800. };
  2801. };
  2802. var getAdapter = function(rtl, rectX, width) {
  2803. return rtl ? getRtlAdapter(rectX, width) : getLtrAdapter();
  2804. };
  2805. var overrideTextDirection = function(ctx, direction) {
  2806. var style, original;
  2807. if (direction === 'ltr' || direction === 'rtl') {
  2808. style = ctx.canvas.style;
  2809. original = [
  2810. style.getPropertyValue('direction'),
  2811. style.getPropertyPriority('direction'),
  2812. ];
  2813. style.setProperty('direction', direction, 'important');
  2814. ctx.prevTextDirection = original;
  2815. }
  2816. };
  2817. var restoreTextDirection = function(ctx) {
  2818. var original = ctx.prevTextDirection;
  2819. if (original !== undefined) {
  2820. delete ctx.prevTextDirection;
  2821. ctx.canvas.style.setProperty('direction', original[0], original[1]);
  2822. }
  2823. };
  2824. var helpers_rtl = {
  2825. getRtlAdapter: getAdapter,
  2826. overrideTextDirection: overrideTextDirection,
  2827. restoreTextDirection: restoreTextDirection,
  2828. };
  2829. var helpers$1 = helpers_core;
  2830. var easing = helpers_easing;
  2831. var canvas = helpers_canvas;
  2832. var options = helpers_options;
  2833. var math = helpers_math;
  2834. var rtl = helpers_rtl;
  2835. helpers$1.easing = easing;
  2836. helpers$1.canvas = canvas;
  2837. helpers$1.options = options;
  2838. helpers$1.math = math;
  2839. helpers$1.rtl = rtl;
  2840. function interpolate(start, view, model, ease) {
  2841. var keys = Object.keys(model);
  2842. var i, ilen, key, actual, origin, target, type, c0, c1;
  2843. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  2844. key = keys[i];
  2845. target = model[key];
  2846. // if a value is added to the model after pivot() has been called, the view
  2847. // doesn't contain it, so let's initialize the view to the target value.
  2848. if (!view.hasOwnProperty(key)) {
  2849. view[key] = target;
  2850. }
  2851. actual = view[key];
  2852. if (actual === target || key[0] === '_') {
  2853. continue;
  2854. }
  2855. if (!start.hasOwnProperty(key)) {
  2856. start[key] = actual;
  2857. }
  2858. origin = start[key];
  2859. type = typeof target;
  2860. if (type === typeof origin) {
  2861. if (type === 'string') {
  2862. c0 = chartjsColor(origin);
  2863. if (c0.valid) {
  2864. c1 = chartjsColor(target);
  2865. if (c1.valid) {
  2866. view[key] = c1.mix(c0, ease).rgbString();
  2867. continue;
  2868. }
  2869. }
  2870. } else if (helpers$1.isFinite(origin) && helpers$1.isFinite(target)) {
  2871. view[key] = origin + (target - origin) * ease;
  2872. continue;
  2873. }
  2874. }
  2875. view[key] = target;
  2876. }
  2877. }
  2878. var Element = function(configuration) {
  2879. helpers$1.extend(this, configuration);
  2880. this.initialize.apply(this, arguments);
  2881. };
  2882. helpers$1.extend(Element.prototype, {
  2883. _type: undefined,
  2884. initialize: function() {
  2885. this.hidden = false;
  2886. },
  2887. pivot: function() {
  2888. var me = this;
  2889. if (!me._view) {
  2890. me._view = helpers$1.extend({}, me._model);
  2891. }
  2892. me._start = {};
  2893. return me;
  2894. },
  2895. transition: function(ease) {
  2896. var me = this;
  2897. var model = me._model;
  2898. var start = me._start;
  2899. var view = me._view;
  2900. // No animation -> No Transition
  2901. if (!model || ease === 1) {
  2902. me._view = helpers$1.extend({}, model);
  2903. me._start = null;
  2904. return me;
  2905. }
  2906. if (!view) {
  2907. view = me._view = {};
  2908. }
  2909. if (!start) {
  2910. start = me._start = {};
  2911. }
  2912. interpolate(start, view, model, ease);
  2913. return me;
  2914. },
  2915. tooltipPosition: function() {
  2916. return {
  2917. x: this._model.x,
  2918. y: this._model.y
  2919. };
  2920. },
  2921. hasValue: function() {
  2922. return helpers$1.isNumber(this._model.x) && helpers$1.isNumber(this._model.y);
  2923. }
  2924. });
  2925. Element.extend = helpers$1.inherits;
  2926. var core_element = Element;
  2927. var exports$3 = core_element.extend({
  2928. chart: null, // the animation associated chart instance
  2929. currentStep: 0, // the current animation step
  2930. numSteps: 60, // default number of steps
  2931. easing: '', // the easing to use for this animation
  2932. render: null, // render function used by the animation service
  2933. onAnimationProgress: null, // user specified callback to fire on each step of the animation
  2934. onAnimationComplete: null, // user specified callback to fire when the animation finishes
  2935. });
  2936. var core_animation = exports$3;
  2937. // DEPRECATIONS
  2938. /**
  2939. * Provided for backward compatibility, use Chart.Animation instead
  2940. * @prop Chart.Animation#animationObject
  2941. * @deprecated since version 2.6.0
  2942. * @todo remove at version 3
  2943. */
  2944. Object.defineProperty(exports$3.prototype, 'animationObject', {
  2945. get: function() {
  2946. return this;
  2947. }
  2948. });
  2949. /**
  2950. * Provided for backward compatibility, use Chart.Animation#chart instead
  2951. * @prop Chart.Animation#chartInstance
  2952. * @deprecated since version 2.6.0
  2953. * @todo remove at version 3
  2954. */
  2955. Object.defineProperty(exports$3.prototype, 'chartInstance', {
  2956. get: function() {
  2957. return this.chart;
  2958. },
  2959. set: function(value) {
  2960. this.chart = value;
  2961. }
  2962. });
  2963. core_defaults._set('global', {
  2964. animation: {
  2965. duration: 1000,
  2966. easing: 'easeOutQuart',
  2967. onProgress: helpers$1.noop,
  2968. onComplete: helpers$1.noop
  2969. }
  2970. });
  2971. var core_animations = {
  2972. animations: [],
  2973. request: null,
  2974. /**
  2975. * @param {Chart} chart - The chart to animate.
  2976. * @param {Chart.Animation} animation - The animation that we will animate.
  2977. * @param {number} duration - The animation duration in ms.
  2978. * @param {boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions
  2979. */
  2980. addAnimation: function(chart, animation, duration, lazy) {
  2981. var animations = this.animations;
  2982. var i, ilen;
  2983. animation.chart = chart;
  2984. animation.startTime = Date.now();
  2985. animation.duration = duration;
  2986. if (!lazy) {
  2987. chart.animating = true;
  2988. }
  2989. for (i = 0, ilen = animations.length; i < ilen; ++i) {
  2990. if (animations[i].chart === chart) {
  2991. animations[i] = animation;
  2992. return;
  2993. }
  2994. }
  2995. animations.push(animation);
  2996. // If there are no animations queued, manually kickstart a digest, for lack of a better word
  2997. if (animations.length === 1) {
  2998. this.requestAnimationFrame();
  2999. }
  3000. },
  3001. cancelAnimation: function(chart) {
  3002. var index = helpers$1.findIndex(this.animations, function(animation) {
  3003. return animation.chart === chart;
  3004. });
  3005. if (index !== -1) {
  3006. this.animations.splice(index, 1);
  3007. chart.animating = false;
  3008. }
  3009. },
  3010. requestAnimationFrame: function() {
  3011. var me = this;
  3012. if (me.request === null) {
  3013. // Skip animation frame requests until the active one is executed.
  3014. // This can happen when processing mouse events, e.g. 'mousemove'
  3015. // and 'mouseout' events will trigger multiple renders.
  3016. me.request = helpers$1.requestAnimFrame.call(window, function() {
  3017. me.request = null;
  3018. me.startDigest();
  3019. });
  3020. }
  3021. },
  3022. /**
  3023. * @private
  3024. */
  3025. startDigest: function() {
  3026. var me = this;
  3027. me.advance();
  3028. // Do we have more stuff to animate?
  3029. if (me.animations.length > 0) {
  3030. me.requestAnimationFrame();
  3031. }
  3032. },
  3033. /**
  3034. * @private
  3035. */
  3036. advance: function() {
  3037. var animations = this.animations;
  3038. var animation, chart, numSteps, nextStep;
  3039. var i = 0;
  3040. // 1 animation per chart, so we are looping charts here
  3041. while (i < animations.length) {
  3042. animation = animations[i];
  3043. chart = animation.chart;
  3044. numSteps = animation.numSteps;
  3045. // Make sure that currentStep starts at 1
  3046. // https://github.com/chartjs/Chart.js/issues/6104
  3047. nextStep = Math.floor((Date.now() - animation.startTime) / animation.duration * numSteps) + 1;
  3048. animation.currentStep = Math.min(nextStep, numSteps);
  3049. helpers$1.callback(animation.render, [chart, animation], chart);
  3050. helpers$1.callback(animation.onAnimationProgress, [animation], chart);
  3051. if (animation.currentStep >= numSteps) {
  3052. helpers$1.callback(animation.onAnimationComplete, [animation], chart);
  3053. chart.animating = false;
  3054. animations.splice(i, 1);
  3055. } else {
  3056. ++i;
  3057. }
  3058. }
  3059. }
  3060. };
  3061. var resolve = helpers$1.options.resolve;
  3062. var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift'];
  3063. /**
  3064. * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice',
  3065. * 'unshift') and notify the listener AFTER the array has been altered. Listeners are
  3066. * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments.
  3067. */
  3068. function listenArrayEvents(array, listener) {
  3069. if (array._chartjs) {
  3070. array._chartjs.listeners.push(listener);
  3071. return;
  3072. }
  3073. Object.defineProperty(array, '_chartjs', {
  3074. configurable: true,
  3075. enumerable: false,
  3076. value: {
  3077. listeners: [listener]
  3078. }
  3079. });
  3080. arrayEvents.forEach(function(key) {
  3081. var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1);
  3082. var base = array[key];
  3083. Object.defineProperty(array, key, {
  3084. configurable: true,
  3085. enumerable: false,
  3086. value: function() {
  3087. var args = Array.prototype.slice.call(arguments);
  3088. var res = base.apply(this, args);
  3089. helpers$1.each(array._chartjs.listeners, function(object) {
  3090. if (typeof object[method] === 'function') {
  3091. object[method].apply(object, args);
  3092. }
  3093. });
  3094. return res;
  3095. }
  3096. });
  3097. });
  3098. }
  3099. /**
  3100. * Removes the given array event listener and cleanup extra attached properties (such as
  3101. * the _chartjs stub and overridden methods) if array doesn't have any more listeners.
  3102. */
  3103. function unlistenArrayEvents(array, listener) {
  3104. var stub = array._chartjs;
  3105. if (!stub) {
  3106. return;
  3107. }
  3108. var listeners = stub.listeners;
  3109. var index = listeners.indexOf(listener);
  3110. if (index !== -1) {
  3111. listeners.splice(index, 1);
  3112. }
  3113. if (listeners.length > 0) {
  3114. return;
  3115. }
  3116. arrayEvents.forEach(function(key) {
  3117. delete array[key];
  3118. });
  3119. delete array._chartjs;
  3120. }
  3121. // Base class for all dataset controllers (line, bar, etc)
  3122. var DatasetController = function(chart, datasetIndex) {
  3123. this.initialize(chart, datasetIndex);
  3124. };
  3125. helpers$1.extend(DatasetController.prototype, {
  3126. /**
  3127. * Element type used to generate a meta dataset (e.g. Chart.element.Line).
  3128. * @type {Chart.core.element}
  3129. */
  3130. datasetElementType: null,
  3131. /**
  3132. * Element type used to generate a meta data (e.g. Chart.element.Point).
  3133. * @type {Chart.core.element}
  3134. */
  3135. dataElementType: null,
  3136. /**
  3137. * Dataset element option keys to be resolved in _resolveDatasetElementOptions.
  3138. * A derived controller may override this to resolve controller-specific options.
  3139. * The keys defined here are for backward compatibility for legend styles.
  3140. * @private
  3141. */
  3142. _datasetElementOptions: [
  3143. 'backgroundColor',
  3144. 'borderCapStyle',
  3145. 'borderColor',
  3146. 'borderDash',
  3147. 'borderDashOffset',
  3148. 'borderJoinStyle',
  3149. 'borderWidth'
  3150. ],
  3151. /**
  3152. * Data element option keys to be resolved in _resolveDataElementOptions.
  3153. * A derived controller may override this to resolve controller-specific options.
  3154. * The keys defined here are for backward compatibility for legend styles.
  3155. * @private
  3156. */
  3157. _dataElementOptions: [
  3158. 'backgroundColor',
  3159. 'borderColor',
  3160. 'borderWidth',
  3161. 'pointStyle'
  3162. ],
  3163. initialize: function(chart, datasetIndex) {
  3164. var me = this;
  3165. me.chart = chart;
  3166. me.index = datasetIndex;
  3167. me.linkScales();
  3168. me.addElements();
  3169. me._type = me.getMeta().type;
  3170. },
  3171. updateIndex: function(datasetIndex) {
  3172. this.index = datasetIndex;
  3173. },
  3174. linkScales: function() {
  3175. var me = this;
  3176. var meta = me.getMeta();
  3177. var chart = me.chart;
  3178. var scales = chart.scales;
  3179. var dataset = me.getDataset();
  3180. var scalesOpts = chart.options.scales;
  3181. if (meta.xAxisID === null || !(meta.xAxisID in scales) || dataset.xAxisID) {
  3182. meta.xAxisID = dataset.xAxisID || scalesOpts.xAxes[0].id;
  3183. }
  3184. if (meta.yAxisID === null || !(meta.yAxisID in scales) || dataset.yAxisID) {
  3185. meta.yAxisID = dataset.yAxisID || scalesOpts.yAxes[0].id;
  3186. }
  3187. },
  3188. getDataset: function() {
  3189. return this.chart.data.datasets[this.index];
  3190. },
  3191. getMeta: function() {
  3192. return this.chart.getDatasetMeta(this.index);
  3193. },
  3194. getScaleForId: function(scaleID) {
  3195. return this.chart.scales[scaleID];
  3196. },
  3197. /**
  3198. * @private
  3199. */
  3200. _getValueScaleId: function() {
  3201. return this.getMeta().yAxisID;
  3202. },
  3203. /**
  3204. * @private
  3205. */
  3206. _getIndexScaleId: function() {
  3207. return this.getMeta().xAxisID;
  3208. },
  3209. /**
  3210. * @private
  3211. */
  3212. _getValueScale: function() {
  3213. return this.getScaleForId(this._getValueScaleId());
  3214. },
  3215. /**
  3216. * @private
  3217. */
  3218. _getIndexScale: function() {
  3219. return this.getScaleForId(this._getIndexScaleId());
  3220. },
  3221. reset: function() {
  3222. this._update(true);
  3223. },
  3224. /**
  3225. * @private
  3226. */
  3227. destroy: function() {
  3228. if (this._data) {
  3229. unlistenArrayEvents(this._data, this);
  3230. }
  3231. },
  3232. createMetaDataset: function() {
  3233. var me = this;
  3234. var type = me.datasetElementType;
  3235. return type && new type({
  3236. _chart: me.chart,
  3237. _datasetIndex: me.index
  3238. });
  3239. },
  3240. createMetaData: function(index) {
  3241. var me = this;
  3242. var type = me.dataElementType;
  3243. return type && new type({
  3244. _chart: me.chart,
  3245. _datasetIndex: me.index,
  3246. _index: index
  3247. });
  3248. },
  3249. addElements: function() {
  3250. var me = this;
  3251. var meta = me.getMeta();
  3252. var data = me.getDataset().data || [];
  3253. var metaData = meta.data;
  3254. var i, ilen;
  3255. for (i = 0, ilen = data.length; i < ilen; ++i) {
  3256. metaData[i] = metaData[i] || me.createMetaData(i);
  3257. }
  3258. meta.dataset = meta.dataset || me.createMetaDataset();
  3259. },
  3260. addElementAndReset: function(index) {
  3261. var element = this.createMetaData(index);
  3262. this.getMeta().data.splice(index, 0, element);
  3263. this.updateElement(element, index, true);
  3264. },
  3265. buildOrUpdateElements: function() {
  3266. var me = this;
  3267. var dataset = me.getDataset();
  3268. var data = dataset.data || (dataset.data = []);
  3269. // In order to correctly handle data addition/deletion animation (an thus simulate
  3270. // real-time charts), we need to monitor these data modifications and synchronize
  3271. // the internal meta data accordingly.
  3272. if (me._data !== data) {
  3273. if (me._data) {
  3274. // This case happens when the user replaced the data array instance.
  3275. unlistenArrayEvents(me._data, me);
  3276. }
  3277. if (data && Object.isExtensible(data)) {
  3278. listenArrayEvents(data, me);
  3279. }
  3280. me._data = data;
  3281. }
  3282. // Re-sync meta data in case the user replaced the data array or if we missed
  3283. // any updates and so make sure that we handle number of datapoints changing.
  3284. me.resyncElements();
  3285. },
  3286. /**
  3287. * Returns the merged user-supplied and default dataset-level options
  3288. * @private
  3289. */
  3290. _configure: function() {
  3291. var me = this;
  3292. me._config = helpers$1.merge({}, [
  3293. me.chart.options.datasets[me._type],
  3294. me.getDataset(),
  3295. ], {
  3296. merger: function(key, target, source) {
  3297. if (key !== '_meta' && key !== 'data') {
  3298. helpers$1._merger(key, target, source);
  3299. }
  3300. }
  3301. });
  3302. },
  3303. _update: function(reset) {
  3304. var me = this;
  3305. me._configure();
  3306. me._cachedDataOpts = null;
  3307. me.update(reset);
  3308. },
  3309. update: helpers$1.noop,
  3310. transition: function(easingValue) {
  3311. var meta = this.getMeta();
  3312. var elements = meta.data || [];
  3313. var ilen = elements.length;
  3314. var i = 0;
  3315. for (; i < ilen; ++i) {
  3316. elements[i].transition(easingValue);
  3317. }
  3318. if (meta.dataset) {
  3319. meta.dataset.transition(easingValue);
  3320. }
  3321. },
  3322. draw: function() {
  3323. var meta = this.getMeta();
  3324. var elements = meta.data || [];
  3325. var ilen = elements.length;
  3326. var i = 0;
  3327. if (meta.dataset) {
  3328. meta.dataset.draw();
  3329. }
  3330. for (; i < ilen; ++i) {
  3331. elements[i].draw();
  3332. }
  3333. },
  3334. /**
  3335. * Returns a set of predefined style properties that should be used to represent the dataset
  3336. * or the data if the index is specified
  3337. * @param {number} index - data index
  3338. * @return {IStyleInterface} style object
  3339. */
  3340. getStyle: function(index) {
  3341. var me = this;
  3342. var meta = me.getMeta();
  3343. var dataset = meta.dataset;
  3344. var style;
  3345. me._configure();
  3346. if (dataset && index === undefined) {
  3347. style = me._resolveDatasetElementOptions(dataset || {});
  3348. } else {
  3349. index = index || 0;
  3350. style = me._resolveDataElementOptions(meta.data[index] || {}, index);
  3351. }
  3352. if (style.fill === false || style.fill === null) {
  3353. style.backgroundColor = style.borderColor;
  3354. }
  3355. return style;
  3356. },
  3357. /**
  3358. * @private
  3359. */
  3360. _resolveDatasetElementOptions: function(element, hover) {
  3361. var me = this;
  3362. var chart = me.chart;
  3363. var datasetOpts = me._config;
  3364. var custom = element.custom || {};
  3365. var options = chart.options.elements[me.datasetElementType.prototype._type] || {};
  3366. var elementOptions = me._datasetElementOptions;
  3367. var values = {};
  3368. var i, ilen, key, readKey;
  3369. // Scriptable options
  3370. var context = {
  3371. chart: chart,
  3372. dataset: me.getDataset(),
  3373. datasetIndex: me.index,
  3374. hover: hover
  3375. };
  3376. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3377. key = elementOptions[i];
  3378. readKey = hover ? 'hover' + key.charAt(0).toUpperCase() + key.slice(1) : key;
  3379. values[key] = resolve([
  3380. custom[readKey],
  3381. datasetOpts[readKey],
  3382. options[readKey]
  3383. ], context);
  3384. }
  3385. return values;
  3386. },
  3387. /**
  3388. * @private
  3389. */
  3390. _resolveDataElementOptions: function(element, index) {
  3391. var me = this;
  3392. var custom = element && element.custom;
  3393. var cached = me._cachedDataOpts;
  3394. if (cached && !custom) {
  3395. return cached;
  3396. }
  3397. var chart = me.chart;
  3398. var datasetOpts = me._config;
  3399. var options = chart.options.elements[me.dataElementType.prototype._type] || {};
  3400. var elementOptions = me._dataElementOptions;
  3401. var values = {};
  3402. // Scriptable options
  3403. var context = {
  3404. chart: chart,
  3405. dataIndex: index,
  3406. dataset: me.getDataset(),
  3407. datasetIndex: me.index
  3408. };
  3409. // `resolve` sets cacheable to `false` if any option is indexed or scripted
  3410. var info = {cacheable: !custom};
  3411. var keys, i, ilen, key;
  3412. custom = custom || {};
  3413. if (helpers$1.isArray(elementOptions)) {
  3414. for (i = 0, ilen = elementOptions.length; i < ilen; ++i) {
  3415. key = elementOptions[i];
  3416. values[key] = resolve([
  3417. custom[key],
  3418. datasetOpts[key],
  3419. options[key]
  3420. ], context, index, info);
  3421. }
  3422. } else {
  3423. keys = Object.keys(elementOptions);
  3424. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3425. key = keys[i];
  3426. values[key] = resolve([
  3427. custom[key],
  3428. datasetOpts[elementOptions[key]],
  3429. datasetOpts[key],
  3430. options[key]
  3431. ], context, index, info);
  3432. }
  3433. }
  3434. if (info.cacheable) {
  3435. me._cachedDataOpts = Object.freeze(values);
  3436. }
  3437. return values;
  3438. },
  3439. removeHoverStyle: function(element) {
  3440. helpers$1.merge(element._model, element.$previousStyle || {});
  3441. delete element.$previousStyle;
  3442. },
  3443. setHoverStyle: function(element) {
  3444. var dataset = this.chart.data.datasets[element._datasetIndex];
  3445. var index = element._index;
  3446. var custom = element.custom || {};
  3447. var model = element._model;
  3448. var getHoverColor = helpers$1.getHoverColor;
  3449. element.$previousStyle = {
  3450. backgroundColor: model.backgroundColor,
  3451. borderColor: model.borderColor,
  3452. borderWidth: model.borderWidth
  3453. };
  3454. model.backgroundColor = resolve([custom.hoverBackgroundColor, dataset.hoverBackgroundColor, getHoverColor(model.backgroundColor)], undefined, index);
  3455. model.borderColor = resolve([custom.hoverBorderColor, dataset.hoverBorderColor, getHoverColor(model.borderColor)], undefined, index);
  3456. model.borderWidth = resolve([custom.hoverBorderWidth, dataset.hoverBorderWidth, model.borderWidth], undefined, index);
  3457. },
  3458. /**
  3459. * @private
  3460. */
  3461. _removeDatasetHoverStyle: function() {
  3462. var element = this.getMeta().dataset;
  3463. if (element) {
  3464. this.removeHoverStyle(element);
  3465. }
  3466. },
  3467. /**
  3468. * @private
  3469. */
  3470. _setDatasetHoverStyle: function() {
  3471. var element = this.getMeta().dataset;
  3472. var prev = {};
  3473. var i, ilen, key, keys, hoverOptions, model;
  3474. if (!element) {
  3475. return;
  3476. }
  3477. model = element._model;
  3478. hoverOptions = this._resolveDatasetElementOptions(element, true);
  3479. keys = Object.keys(hoverOptions);
  3480. for (i = 0, ilen = keys.length; i < ilen; ++i) {
  3481. key = keys[i];
  3482. prev[key] = model[key];
  3483. model[key] = hoverOptions[key];
  3484. }
  3485. element.$previousStyle = prev;
  3486. },
  3487. /**
  3488. * @private
  3489. */
  3490. resyncElements: function() {
  3491. var me = this;
  3492. var meta = me.getMeta();
  3493. var data = me.getDataset().data;
  3494. var numMeta = meta.data.length;
  3495. var numData = data.length;
  3496. if (numData < numMeta) {
  3497. meta.data.splice(numData, numMeta - numData);
  3498. } else if (numData > numMeta) {
  3499. me.insertElements(numMeta, numData - numMeta);
  3500. }
  3501. },
  3502. /**
  3503. * @private
  3504. */
  3505. insertElements: function(start, count) {
  3506. for (var i = 0; i < count; ++i) {
  3507. this.addElementAndReset(start + i);
  3508. }
  3509. },
  3510. /**
  3511. * @private
  3512. */
  3513. onDataPush: function() {
  3514. var count = arguments.length;
  3515. this.insertElements(this.getDataset().data.length - count, count);
  3516. },
  3517. /**
  3518. * @private
  3519. */
  3520. onDataPop: function() {
  3521. this.getMeta().data.pop();
  3522. },
  3523. /**
  3524. * @private
  3525. */
  3526. onDataShift: function() {
  3527. this.getMeta().data.shift();
  3528. },
  3529. /**
  3530. * @private
  3531. */
  3532. onDataSplice: function(start, count) {
  3533. this.getMeta().data.splice(start, count);
  3534. this.insertElements(start, arguments.length - 2);
  3535. },
  3536. /**
  3537. * @private
  3538. */
  3539. onDataUnshift: function() {
  3540. this.insertElements(0, arguments.length);
  3541. }
  3542. });
  3543. DatasetController.extend = helpers$1.inherits;
  3544. var core_datasetController = DatasetController;
  3545. var TAU = Math.PI * 2;
  3546. core_defaults._set('global', {
  3547. elements: {
  3548. arc: {
  3549. backgroundColor: core_defaults.global.defaultColor,
  3550. borderColor: '#fff',
  3551. borderWidth: 2,
  3552. borderAlign: 'center'
  3553. }
  3554. }
  3555. });
  3556. function clipArc(ctx, arc) {
  3557. var startAngle = arc.startAngle;
  3558. var endAngle = arc.endAngle;
  3559. var pixelMargin = arc.pixelMargin;
  3560. var angleMargin = pixelMargin / arc.outerRadius;
  3561. var x = arc.x;
  3562. var y = arc.y;
  3563. // Draw an inner border by cliping the arc and drawing a double-width border
  3564. // Enlarge the clipping arc by 0.33 pixels to eliminate glitches between borders
  3565. ctx.beginPath();
  3566. ctx.arc(x, y, arc.outerRadius, startAngle - angleMargin, endAngle + angleMargin);
  3567. if (arc.innerRadius > pixelMargin) {
  3568. angleMargin = pixelMargin / arc.innerRadius;
  3569. ctx.arc(x, y, arc.innerRadius - pixelMargin, endAngle + angleMargin, startAngle - angleMargin, true);
  3570. } else {
  3571. ctx.arc(x, y, pixelMargin, endAngle + Math.PI / 2, startAngle - Math.PI / 2);
  3572. }
  3573. ctx.closePath();
  3574. ctx.clip();
  3575. }
  3576. function drawFullCircleBorders(ctx, vm, arc, inner) {
  3577. var endAngle = arc.endAngle;
  3578. var i;
  3579. if (inner) {
  3580. arc.endAngle = arc.startAngle + TAU;
  3581. clipArc(ctx, arc);
  3582. arc.endAngle = endAngle;
  3583. if (arc.endAngle === arc.startAngle && arc.fullCircles) {
  3584. arc.endAngle += TAU;
  3585. arc.fullCircles--;
  3586. }
  3587. }
  3588. ctx.beginPath();
  3589. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.startAngle + TAU, arc.startAngle, true);
  3590. for (i = 0; i < arc.fullCircles; ++i) {
  3591. ctx.stroke();
  3592. }
  3593. ctx.beginPath();
  3594. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.startAngle + TAU);
  3595. for (i = 0; i < arc.fullCircles; ++i) {
  3596. ctx.stroke();
  3597. }
  3598. }
  3599. function drawBorder(ctx, vm, arc) {
  3600. var inner = vm.borderAlign === 'inner';
  3601. if (inner) {
  3602. ctx.lineWidth = vm.borderWidth * 2;
  3603. ctx.lineJoin = 'round';
  3604. } else {
  3605. ctx.lineWidth = vm.borderWidth;
  3606. ctx.lineJoin = 'bevel';
  3607. }
  3608. if (arc.fullCircles) {
  3609. drawFullCircleBorders(ctx, vm, arc, inner);
  3610. }
  3611. if (inner) {
  3612. clipArc(ctx, arc);
  3613. }
  3614. ctx.beginPath();
  3615. ctx.arc(arc.x, arc.y, vm.outerRadius, arc.startAngle, arc.endAngle);
  3616. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3617. ctx.closePath();
  3618. ctx.stroke();
  3619. }
  3620. var element_arc = core_element.extend({
  3621. _type: 'arc',
  3622. inLabelRange: function(mouseX) {
  3623. var vm = this._view;
  3624. if (vm) {
  3625. return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2));
  3626. }
  3627. return false;
  3628. },
  3629. inRange: function(chartX, chartY) {
  3630. var vm = this._view;
  3631. if (vm) {
  3632. var pointRelativePosition = helpers$1.getAngleFromPoint(vm, {x: chartX, y: chartY});
  3633. var angle = pointRelativePosition.angle;
  3634. var distance = pointRelativePosition.distance;
  3635. // Sanitise angle range
  3636. var startAngle = vm.startAngle;
  3637. var endAngle = vm.endAngle;
  3638. while (endAngle < startAngle) {
  3639. endAngle += TAU;
  3640. }
  3641. while (angle > endAngle) {
  3642. angle -= TAU;
  3643. }
  3644. while (angle < startAngle) {
  3645. angle += TAU;
  3646. }
  3647. // Check if within the range of the open/close angle
  3648. var betweenAngles = (angle >= startAngle && angle <= endAngle);
  3649. var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius);
  3650. return (betweenAngles && withinRadius);
  3651. }
  3652. return false;
  3653. },
  3654. getCenterPoint: function() {
  3655. var vm = this._view;
  3656. var halfAngle = (vm.startAngle + vm.endAngle) / 2;
  3657. var halfRadius = (vm.innerRadius + vm.outerRadius) / 2;
  3658. return {
  3659. x: vm.x + Math.cos(halfAngle) * halfRadius,
  3660. y: vm.y + Math.sin(halfAngle) * halfRadius
  3661. };
  3662. },
  3663. getArea: function() {
  3664. var vm = this._view;
  3665. return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2));
  3666. },
  3667. tooltipPosition: function() {
  3668. var vm = this._view;
  3669. var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2);
  3670. var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius;
  3671. return {
  3672. x: vm.x + (Math.cos(centreAngle) * rangeFromCentre),
  3673. y: vm.y + (Math.sin(centreAngle) * rangeFromCentre)
  3674. };
  3675. },
  3676. draw: function() {
  3677. var ctx = this._chart.ctx;
  3678. var vm = this._view;
  3679. var pixelMargin = (vm.borderAlign === 'inner') ? 0.33 : 0;
  3680. var arc = {
  3681. x: vm.x,
  3682. y: vm.y,
  3683. innerRadius: vm.innerRadius,
  3684. outerRadius: Math.max(vm.outerRadius - pixelMargin, 0),
  3685. pixelMargin: pixelMargin,
  3686. startAngle: vm.startAngle,
  3687. endAngle: vm.endAngle,
  3688. fullCircles: Math.floor(vm.circumference / TAU)
  3689. };
  3690. var i;
  3691. ctx.save();
  3692. ctx.fillStyle = vm.backgroundColor;
  3693. ctx.strokeStyle = vm.borderColor;
  3694. if (arc.fullCircles) {
  3695. arc.endAngle = arc.startAngle + TAU;
  3696. ctx.beginPath();
  3697. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3698. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3699. ctx.closePath();
  3700. for (i = 0; i < arc.fullCircles; ++i) {
  3701. ctx.fill();
  3702. }
  3703. arc.endAngle = arc.startAngle + vm.circumference % TAU;
  3704. }
  3705. ctx.beginPath();
  3706. ctx.arc(arc.x, arc.y, arc.outerRadius, arc.startAngle, arc.endAngle);
  3707. ctx.arc(arc.x, arc.y, arc.innerRadius, arc.endAngle, arc.startAngle, true);
  3708. ctx.closePath();
  3709. ctx.fill();
  3710. if (vm.borderWidth) {
  3711. drawBorder(ctx, vm, arc);
  3712. }
  3713. ctx.restore();
  3714. }
  3715. });
  3716. var valueOrDefault$1 = helpers$1.valueOrDefault;
  3717. var defaultColor = core_defaults.global.defaultColor;
  3718. core_defaults._set('global', {
  3719. elements: {
  3720. line: {
  3721. tension: 0.4,
  3722. backgroundColor: defaultColor,
  3723. borderWidth: 3,
  3724. borderColor: defaultColor,
  3725. borderCapStyle: 'butt',
  3726. borderDash: [],
  3727. borderDashOffset: 0.0,
  3728. borderJoinStyle: 'miter',
  3729. capBezierPoints: true,
  3730. fill: true, // do we fill in the area between the line and its base axis
  3731. }
  3732. }
  3733. });
  3734. var element_line = core_element.extend({
  3735. _type: 'line',
  3736. draw: function() {
  3737. var me = this;
  3738. var vm = me._view;
  3739. var ctx = me._chart.ctx;
  3740. var spanGaps = vm.spanGaps;
  3741. var points = me._children.slice(); // clone array
  3742. var globalDefaults = core_defaults.global;
  3743. var globalOptionLineElements = globalDefaults.elements.line;
  3744. var lastDrawnIndex = -1;
  3745. var closePath = me._loop;
  3746. var index, previous, currentVM;
  3747. if (!points.length) {
  3748. return;
  3749. }
  3750. if (me._loop) {
  3751. for (index = 0; index < points.length; ++index) {
  3752. previous = helpers$1.previousItem(points, index);
  3753. // If the line has an open path, shift the point array
  3754. if (!points[index]._view.skip && previous._view.skip) {
  3755. points = points.slice(index).concat(points.slice(0, index));
  3756. closePath = spanGaps;
  3757. break;
  3758. }
  3759. }
  3760. // If the line has a close path, add the first point again
  3761. if (closePath) {
  3762. points.push(points[0]);
  3763. }
  3764. }
  3765. ctx.save();
  3766. // Stroke Line Options
  3767. ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
  3768. // IE 9 and 10 do not support line dash
  3769. if (ctx.setLineDash) {
  3770. ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
  3771. }
  3772. ctx.lineDashOffset = valueOrDefault$1(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
  3773. ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
  3774. ctx.lineWidth = valueOrDefault$1(vm.borderWidth, globalOptionLineElements.borderWidth);
  3775. ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
  3776. // Stroke Line
  3777. ctx.beginPath();
  3778. // First point moves to it's starting position no matter what
  3779. currentVM = points[0]._view;
  3780. if (!currentVM.skip) {
  3781. ctx.moveTo(currentVM.x, currentVM.y);
  3782. lastDrawnIndex = 0;
  3783. }
  3784. for (index = 1; index < points.length; ++index) {
  3785. currentVM = points[index]._view;
  3786. previous = lastDrawnIndex === -1 ? helpers$1.previousItem(points, index) : points[lastDrawnIndex];
  3787. if (!currentVM.skip) {
  3788. if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
  3789. // There was a gap and this is the first point after the gap
  3790. ctx.moveTo(currentVM.x, currentVM.y);
  3791. } else {
  3792. // Line to next point
  3793. helpers$1.canvas.lineTo(ctx, previous._view, currentVM);
  3794. }
  3795. lastDrawnIndex = index;
  3796. }
  3797. }
  3798. if (closePath) {
  3799. ctx.closePath();
  3800. }
  3801. ctx.stroke();
  3802. ctx.restore();
  3803. }
  3804. });
  3805. var valueOrDefault$2 = helpers$1.valueOrDefault;
  3806. var defaultColor$1 = core_defaults.global.defaultColor;
  3807. core_defaults._set('global', {
  3808. elements: {
  3809. point: {
  3810. radius: 3,
  3811. pointStyle: 'circle',
  3812. backgroundColor: defaultColor$1,
  3813. borderColor: defaultColor$1,
  3814. borderWidth: 1,
  3815. // Hover
  3816. hitRadius: 1,
  3817. hoverRadius: 4,
  3818. hoverBorderWidth: 1
  3819. }
  3820. }
  3821. });
  3822. function xRange(mouseX) {
  3823. var vm = this._view;
  3824. return vm ? (Math.abs(mouseX - vm.x) < vm.radius + vm.hitRadius) : false;
  3825. }
  3826. function yRange(mouseY) {
  3827. var vm = this._view;
  3828. return vm ? (Math.abs(mouseY - vm.y) < vm.radius + vm.hitRadius) : false;
  3829. }
  3830. var element_point = core_element.extend({
  3831. _type: 'point',
  3832. inRange: function(mouseX, mouseY) {
  3833. var vm = this._view;
  3834. return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
  3835. },
  3836. inLabelRange: xRange,
  3837. inXRange: xRange,
  3838. inYRange: yRange,
  3839. getCenterPoint: function() {
  3840. var vm = this._view;
  3841. return {
  3842. x: vm.x,
  3843. y: vm.y
  3844. };
  3845. },
  3846. getArea: function() {
  3847. return Math.PI * Math.pow(this._view.radius, 2);
  3848. },
  3849. tooltipPosition: function() {
  3850. var vm = this._view;
  3851. return {
  3852. x: vm.x,
  3853. y: vm.y,
  3854. padding: vm.radius + vm.borderWidth
  3855. };
  3856. },
  3857. draw: function(chartArea) {
  3858. var vm = this._view;
  3859. var ctx = this._chart.ctx;
  3860. var pointStyle = vm.pointStyle;
  3861. var rotation = vm.rotation;
  3862. var radius = vm.radius;
  3863. var x = vm.x;
  3864. var y = vm.y;
  3865. var globalDefaults = core_defaults.global;
  3866. var defaultColor = globalDefaults.defaultColor; // eslint-disable-line no-shadow
  3867. if (vm.skip) {
  3868. return;
  3869. }
  3870. // Clipping for Points.
  3871. if (chartArea === undefined || helpers$1.canvas._isPointInArea(vm, chartArea)) {
  3872. ctx.strokeStyle = vm.borderColor || defaultColor;
  3873. ctx.lineWidth = valueOrDefault$2(vm.borderWidth, globalDefaults.elements.point.borderWidth);
  3874. ctx.fillStyle = vm.backgroundColor || defaultColor;
  3875. helpers$1.canvas.drawPoint(ctx, pointStyle, radius, x, y, rotation);
  3876. }
  3877. }
  3878. });
  3879. var defaultColor$2 = core_defaults.global.defaultColor;
  3880. core_defaults._set('global', {
  3881. elements: {
  3882. rectangle: {
  3883. backgroundColor: defaultColor$2,
  3884. borderColor: defaultColor$2,
  3885. borderSkipped: 'bottom',
  3886. borderWidth: 0
  3887. }
  3888. }
  3889. });
  3890. function isVertical(vm) {
  3891. return vm && vm.width !== undefined;
  3892. }
  3893. /**
  3894. * Helper function to get the bounds of the bar regardless of the orientation
  3895. * @param bar {Chart.Element.Rectangle} the bar
  3896. * @return {Bounds} bounds of the bar
  3897. * @private
  3898. */
  3899. function getBarBounds(vm) {
  3900. var x1, x2, y1, y2, half;
  3901. if (isVertical(vm)) {
  3902. half = vm.width / 2;
  3903. x1 = vm.x - half;
  3904. x2 = vm.x + half;
  3905. y1 = Math.min(vm.y, vm.base);
  3906. y2 = Math.max(vm.y, vm.base);
  3907. } else {
  3908. half = vm.height / 2;
  3909. x1 = Math.min(vm.x, vm.base);
  3910. x2 = Math.max(vm.x, vm.base);
  3911. y1 = vm.y - half;
  3912. y2 = vm.y + half;
  3913. }
  3914. return {
  3915. left: x1,
  3916. top: y1,
  3917. right: x2,
  3918. bottom: y2
  3919. };
  3920. }
  3921. function swap(orig, v1, v2) {
  3922. return orig === v1 ? v2 : orig === v2 ? v1 : orig;
  3923. }
  3924. function parseBorderSkipped(vm) {
  3925. var edge = vm.borderSkipped;
  3926. var res = {};
  3927. if (!edge) {
  3928. return res;
  3929. }
  3930. if (vm.horizontal) {
  3931. if (vm.base > vm.x) {
  3932. edge = swap(edge, 'left', 'right');
  3933. }
  3934. } else if (vm.base < vm.y) {
  3935. edge = swap(edge, 'bottom', 'top');
  3936. }
  3937. res[edge] = true;
  3938. return res;
  3939. }
  3940. function parseBorderWidth(vm, maxW, maxH) {
  3941. var value = vm.borderWidth;
  3942. var skip = parseBorderSkipped(vm);
  3943. var t, r, b, l;
  3944. if (helpers$1.isObject(value)) {
  3945. t = +value.top || 0;
  3946. r = +value.right || 0;
  3947. b = +value.bottom || 0;
  3948. l = +value.left || 0;
  3949. } else {
  3950. t = r = b = l = +value || 0;
  3951. }
  3952. return {
  3953. t: skip.top || (t < 0) ? 0 : t > maxH ? maxH : t,
  3954. r: skip.right || (r < 0) ? 0 : r > maxW ? maxW : r,
  3955. b: skip.bottom || (b < 0) ? 0 : b > maxH ? maxH : b,
  3956. l: skip.left || (l < 0) ? 0 : l > maxW ? maxW : l
  3957. };
  3958. }
  3959. function boundingRects(vm) {
  3960. var bounds = getBarBounds(vm);
  3961. var width = bounds.right - bounds.left;
  3962. var height = bounds.bottom - bounds.top;
  3963. var border = parseBorderWidth(vm, width / 2, height / 2);
  3964. return {
  3965. outer: {
  3966. x: bounds.left,
  3967. y: bounds.top,
  3968. w: width,
  3969. h: height
  3970. },
  3971. inner: {
  3972. x: bounds.left + border.l,
  3973. y: bounds.top + border.t,
  3974. w: width - border.l - border.r,
  3975. h: height - border.t - border.b
  3976. }
  3977. };
  3978. }
  3979. function inRange(vm, x, y) {
  3980. var skipX = x === null;
  3981. var skipY = y === null;
  3982. var bounds = !vm || (skipX && skipY) ? false : getBarBounds(vm);
  3983. return bounds
  3984. && (skipX || x >= bounds.left && x <= bounds.right)
  3985. && (skipY || y >= bounds.top && y <= bounds.bottom);
  3986. }
  3987. var element_rectangle = core_element.extend({
  3988. _type: 'rectangle',
  3989. draw: function() {
  3990. var ctx = this._chart.ctx;
  3991. var vm = this._view;
  3992. var rects = boundingRects(vm);
  3993. var outer = rects.outer;
  3994. var inner = rects.inner;
  3995. ctx.fillStyle = vm.backgroundColor;
  3996. ctx.fillRect(outer.x, outer.y, outer.w, outer.h);
  3997. if (outer.w === inner.w && outer.h === inner.h) {
  3998. return;
  3999. }
  4000. ctx.save();
  4001. ctx.beginPath();
  4002. ctx.rect(outer.x, outer.y, outer.w, outer.h);
  4003. ctx.clip();
  4004. ctx.fillStyle = vm.borderColor;
  4005. ctx.rect(inner.x, inner.y, inner.w, inner.h);
  4006. ctx.fill('evenodd');
  4007. ctx.restore();
  4008. },
  4009. height: function() {
  4010. var vm = this._view;
  4011. return vm.base - vm.y;
  4012. },
  4013. inRange: function(mouseX, mouseY) {
  4014. return inRange(this._view, mouseX, mouseY);
  4015. },
  4016. inLabelRange: function(mouseX, mouseY) {
  4017. var vm = this._view;
  4018. return isVertical(vm)
  4019. ? inRange(vm, mouseX, null)
  4020. : inRange(vm, null, mouseY);
  4021. },
  4022. inXRange: function(mouseX) {
  4023. return inRange(this._view, mouseX, null);
  4024. },
  4025. inYRange: function(mouseY) {
  4026. return inRange(this._view, null, mouseY);
  4027. },
  4028. getCenterPoint: function() {
  4029. var vm = this._view;
  4030. var x, y;
  4031. if (isVertical(vm)) {
  4032. x = vm.x;
  4033. y = (vm.y + vm.base) / 2;
  4034. } else {
  4035. x = (vm.x + vm.base) / 2;
  4036. y = vm.y;
  4037. }
  4038. return {x: x, y: y};
  4039. },
  4040. getArea: function() {
  4041. var vm = this._view;
  4042. return isVertical(vm)
  4043. ? vm.width * Math.abs(vm.y - vm.base)
  4044. : vm.height * Math.abs(vm.x - vm.base);
  4045. },
  4046. tooltipPosition: function() {
  4047. var vm = this._view;
  4048. return {
  4049. x: vm.x,
  4050. y: vm.y
  4051. };
  4052. }
  4053. });
  4054. var elements = {};
  4055. var Arc = element_arc;
  4056. var Line = element_line;
  4057. var Point = element_point;
  4058. var Rectangle = element_rectangle;
  4059. elements.Arc = Arc;
  4060. elements.Line = Line;
  4061. elements.Point = Point;
  4062. elements.Rectangle = Rectangle;
  4063. var deprecated = helpers$1._deprecated;
  4064. var valueOrDefault$3 = helpers$1.valueOrDefault;
  4065. core_defaults._set('bar', {
  4066. hover: {
  4067. mode: 'label'
  4068. },
  4069. scales: {
  4070. xAxes: [{
  4071. type: 'category',
  4072. offset: true,
  4073. gridLines: {
  4074. offsetGridLines: true
  4075. }
  4076. }],
  4077. yAxes: [{
  4078. type: 'linear'
  4079. }]
  4080. }
  4081. });
  4082. core_defaults._set('global', {
  4083. datasets: {
  4084. bar: {
  4085. categoryPercentage: 0.8,
  4086. barPercentage: 0.9
  4087. }
  4088. }
  4089. });
  4090. /**
  4091. * Computes the "optimal" sample size to maintain bars equally sized while preventing overlap.
  4092. * @private
  4093. */
  4094. function computeMinSampleSize(scale, pixels) {
  4095. var min = scale._length;
  4096. var prev, curr, i, ilen;
  4097. for (i = 1, ilen = pixels.length; i < ilen; ++i) {
  4098. min = Math.min(min, Math.abs(pixels[i] - pixels[i - 1]));
  4099. }
  4100. for (i = 0, ilen = scale.getTicks().length; i < ilen; ++i) {
  4101. curr = scale.getPixelForTick(i);
  4102. min = i > 0 ? Math.min(min, Math.abs(curr - prev)) : min;
  4103. prev = curr;
  4104. }
  4105. return min;
  4106. }
  4107. /**
  4108. * Computes an "ideal" category based on the absolute bar thickness or, if undefined or null,
  4109. * uses the smallest interval (see computeMinSampleSize) that prevents bar overlapping. This
  4110. * mode currently always generates bars equally sized (until we introduce scriptable options?).
  4111. * @private
  4112. */
  4113. function computeFitCategoryTraits(index, ruler, options) {
  4114. var thickness = options.barThickness;
  4115. var count = ruler.stackCount;
  4116. var curr = ruler.pixels[index];
  4117. var min = helpers$1.isNullOrUndef(thickness)
  4118. ? computeMinSampleSize(ruler.scale, ruler.pixels)
  4119. : -1;
  4120. var size, ratio;
  4121. if (helpers$1.isNullOrUndef(thickness)) {
  4122. size = min * options.categoryPercentage;
  4123. ratio = options.barPercentage;
  4124. } else {
  4125. // When bar thickness is enforced, category and bar percentages are ignored.
  4126. // Note(SB): we could add support for relative bar thickness (e.g. barThickness: '50%')
  4127. // and deprecate barPercentage since this value is ignored when thickness is absolute.
  4128. size = thickness * count;
  4129. ratio = 1;
  4130. }
  4131. return {
  4132. chunk: size / count,
  4133. ratio: ratio,
  4134. start: curr - (size / 2)
  4135. };
  4136. }
  4137. /**
  4138. * Computes an "optimal" category that globally arranges bars side by side (no gap when
  4139. * percentage options are 1), based on the previous and following categories. This mode
  4140. * generates bars with different widths when data are not evenly spaced.
  4141. * @private
  4142. */
  4143. function computeFlexCategoryTraits(index, ruler, options) {
  4144. var pixels = ruler.pixels;
  4145. var curr = pixels[index];
  4146. var prev = index > 0 ? pixels[index - 1] : null;
  4147. var next = index < pixels.length - 1 ? pixels[index + 1] : null;
  4148. var percent = options.categoryPercentage;
  4149. var start, size;
  4150. if (prev === null) {
  4151. // first data: its size is double based on the next point or,
  4152. // if it's also the last data, we use the scale size.
  4153. prev = curr - (next === null ? ruler.end - ruler.start : next - curr);
  4154. }
  4155. if (next === null) {
  4156. // last data: its size is also double based on the previous point.
  4157. next = curr + curr - prev;
  4158. }
  4159. start = curr - (curr - Math.min(prev, next)) / 2 * percent;
  4160. size = Math.abs(next - prev) / 2 * percent;
  4161. return {
  4162. chunk: size / ruler.stackCount,
  4163. ratio: options.barPercentage,
  4164. start: start
  4165. };
  4166. }
  4167. var controller_bar = core_datasetController.extend({
  4168. dataElementType: elements.Rectangle,
  4169. /**
  4170. * @private
  4171. */
  4172. _dataElementOptions: [
  4173. 'backgroundColor',
  4174. 'borderColor',
  4175. 'borderSkipped',
  4176. 'borderWidth',
  4177. 'barPercentage',
  4178. 'barThickness',
  4179. 'categoryPercentage',
  4180. 'maxBarThickness',
  4181. 'minBarLength'
  4182. ],
  4183. initialize: function() {
  4184. var me = this;
  4185. var meta, scaleOpts;
  4186. core_datasetController.prototype.initialize.apply(me, arguments);
  4187. meta = me.getMeta();
  4188. meta.stack = me.getDataset().stack;
  4189. meta.bar = true;
  4190. scaleOpts = me._getIndexScale().options;
  4191. deprecated('bar chart', scaleOpts.barPercentage, 'scales.[x/y]Axes.barPercentage', 'dataset.barPercentage');
  4192. deprecated('bar chart', scaleOpts.barThickness, 'scales.[x/y]Axes.barThickness', 'dataset.barThickness');
  4193. deprecated('bar chart', scaleOpts.categoryPercentage, 'scales.[x/y]Axes.categoryPercentage', 'dataset.categoryPercentage');
  4194. deprecated('bar chart', me._getValueScale().options.minBarLength, 'scales.[x/y]Axes.minBarLength', 'dataset.minBarLength');
  4195. deprecated('bar chart', scaleOpts.maxBarThickness, 'scales.[x/y]Axes.maxBarThickness', 'dataset.maxBarThickness');
  4196. },
  4197. update: function(reset) {
  4198. var me = this;
  4199. var rects = me.getMeta().data;
  4200. var i, ilen;
  4201. me._ruler = me.getRuler();
  4202. for (i = 0, ilen = rects.length; i < ilen; ++i) {
  4203. me.updateElement(rects[i], i, reset);
  4204. }
  4205. },
  4206. updateElement: function(rectangle, index, reset) {
  4207. var me = this;
  4208. var meta = me.getMeta();
  4209. var dataset = me.getDataset();
  4210. var options = me._resolveDataElementOptions(rectangle, index);
  4211. rectangle._xScale = me.getScaleForId(meta.xAxisID);
  4212. rectangle._yScale = me.getScaleForId(meta.yAxisID);
  4213. rectangle._datasetIndex = me.index;
  4214. rectangle._index = index;
  4215. rectangle._model = {
  4216. backgroundColor: options.backgroundColor,
  4217. borderColor: options.borderColor,
  4218. borderSkipped: options.borderSkipped,
  4219. borderWidth: options.borderWidth,
  4220. datasetLabel: dataset.label,
  4221. label: me.chart.data.labels[index]
  4222. };
  4223. if (helpers$1.isArray(dataset.data[index])) {
  4224. rectangle._model.borderSkipped = null;
  4225. }
  4226. me._updateElementGeometry(rectangle, index, reset, options);
  4227. rectangle.pivot();
  4228. },
  4229. /**
  4230. * @private
  4231. */
  4232. _updateElementGeometry: function(rectangle, index, reset, options) {
  4233. var me = this;
  4234. var model = rectangle._model;
  4235. var vscale = me._getValueScale();
  4236. var base = vscale.getBasePixel();
  4237. var horizontal = vscale.isHorizontal();
  4238. var ruler = me._ruler || me.getRuler();
  4239. var vpixels = me.calculateBarValuePixels(me.index, index, options);
  4240. var ipixels = me.calculateBarIndexPixels(me.index, index, ruler, options);
  4241. model.horizontal = horizontal;
  4242. model.base = reset ? base : vpixels.base;
  4243. model.x = horizontal ? reset ? base : vpixels.head : ipixels.center;
  4244. model.y = horizontal ? ipixels.center : reset ? base : vpixels.head;
  4245. model.height = horizontal ? ipixels.size : undefined;
  4246. model.width = horizontal ? undefined : ipixels.size;
  4247. },
  4248. /**
  4249. * Returns the stacks based on groups and bar visibility.
  4250. * @param {number} [last] - The dataset index
  4251. * @returns {string[]} The list of stack IDs
  4252. * @private
  4253. */
  4254. _getStacks: function(last) {
  4255. var me = this;
  4256. var scale = me._getIndexScale();
  4257. var metasets = scale._getMatchingVisibleMetas(me._type);
  4258. var stacked = scale.options.stacked;
  4259. var ilen = metasets.length;
  4260. var stacks = [];
  4261. var i, meta;
  4262. for (i = 0; i < ilen; ++i) {
  4263. meta = metasets[i];
  4264. // stacked | meta.stack
  4265. // | found | not found | undefined
  4266. // false | x | x | x
  4267. // true | | x |
  4268. // undefined | | x | x
  4269. if (stacked === false || stacks.indexOf(meta.stack) === -1 ||
  4270. (stacked === undefined && meta.stack === undefined)) {
  4271. stacks.push(meta.stack);
  4272. }
  4273. if (meta.index === last) {
  4274. break;
  4275. }
  4276. }
  4277. return stacks;
  4278. },
  4279. /**
  4280. * Returns the effective number of stacks based on groups and bar visibility.
  4281. * @private
  4282. */
  4283. getStackCount: function() {
  4284. return this._getStacks().length;
  4285. },
  4286. /**
  4287. * Returns the stack index for the given dataset based on groups and bar visibility.
  4288. * @param {number} [datasetIndex] - The dataset index
  4289. * @param {string} [name] - The stack name to find
  4290. * @returns {number} The stack index
  4291. * @private
  4292. */
  4293. getStackIndex: function(datasetIndex, name) {
  4294. var stacks = this._getStacks(datasetIndex);
  4295. var index = (name !== undefined)
  4296. ? stacks.indexOf(name)
  4297. : -1; // indexOf returns -1 if element is not present
  4298. return (index === -1)
  4299. ? stacks.length - 1
  4300. : index;
  4301. },
  4302. /**
  4303. * @private
  4304. */
  4305. getRuler: function() {
  4306. var me = this;
  4307. var scale = me._getIndexScale();
  4308. var pixels = [];
  4309. var i, ilen;
  4310. for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) {
  4311. pixels.push(scale.getPixelForValue(null, i, me.index));
  4312. }
  4313. return {
  4314. pixels: pixels,
  4315. start: scale._startPixel,
  4316. end: scale._endPixel,
  4317. stackCount: me.getStackCount(),
  4318. scale: scale
  4319. };
  4320. },
  4321. /**
  4322. * Note: pixel values are not clamped to the scale area.
  4323. * @private
  4324. */
  4325. calculateBarValuePixels: function(datasetIndex, index, options) {
  4326. var me = this;
  4327. var chart = me.chart;
  4328. var scale = me._getValueScale();
  4329. var isHorizontal = scale.isHorizontal();
  4330. var datasets = chart.data.datasets;
  4331. var metasets = scale._getMatchingVisibleMetas(me._type);
  4332. var value = scale._parseValue(datasets[datasetIndex].data[index]);
  4333. var minBarLength = options.minBarLength;
  4334. var stacked = scale.options.stacked;
  4335. var stack = me.getMeta().stack;
  4336. var start = value.start === undefined ? 0 : value.max >= 0 && value.min >= 0 ? value.min : value.max;
  4337. var length = value.start === undefined ? value.end : value.max >= 0 && value.min >= 0 ? value.max - value.min : value.min - value.max;
  4338. var ilen = metasets.length;
  4339. var i, imeta, ivalue, base, head, size, stackLength;
  4340. if (stacked || (stacked === undefined && stack !== undefined)) {
  4341. for (i = 0; i < ilen; ++i) {
  4342. imeta = metasets[i];
  4343. if (imeta.index === datasetIndex) {
  4344. break;
  4345. }
  4346. if (imeta.stack === stack) {
  4347. stackLength = scale._parseValue(datasets[imeta.index].data[index]);
  4348. ivalue = stackLength.start === undefined ? stackLength.end : stackLength.min >= 0 && stackLength.max >= 0 ? stackLength.max : stackLength.min;
  4349. if ((value.min < 0 && ivalue < 0) || (value.max >= 0 && ivalue > 0)) {
  4350. start += ivalue;
  4351. }
  4352. }
  4353. }
  4354. }
  4355. base = scale.getPixelForValue(start);
  4356. head = scale.getPixelForValue(start + length);
  4357. size = head - base;
  4358. if (minBarLength !== undefined && Math.abs(size) < minBarLength) {
  4359. size = minBarLength;
  4360. if (length >= 0 && !isHorizontal || length < 0 && isHorizontal) {
  4361. head = base - minBarLength;
  4362. } else {
  4363. head = base + minBarLength;
  4364. }
  4365. }
  4366. return {
  4367. size: size,
  4368. base: base,
  4369. head: head,
  4370. center: head + size / 2
  4371. };
  4372. },
  4373. /**
  4374. * @private
  4375. */
  4376. calculateBarIndexPixels: function(datasetIndex, index, ruler, options) {
  4377. var me = this;
  4378. var range = options.barThickness === 'flex'
  4379. ? computeFlexCategoryTraits(index, ruler, options)
  4380. : computeFitCategoryTraits(index, ruler, options);
  4381. var stackIndex = me.getStackIndex(datasetIndex, me.getMeta().stack);
  4382. var center = range.start + (range.chunk * stackIndex) + (range.chunk / 2);
  4383. var size = Math.min(
  4384. valueOrDefault$3(options.maxBarThickness, Infinity),
  4385. range.chunk * range.ratio);
  4386. return {
  4387. base: center - size / 2,
  4388. head: center + size / 2,
  4389. center: center,
  4390. size: size
  4391. };
  4392. },
  4393. draw: function() {
  4394. var me = this;
  4395. var chart = me.chart;
  4396. var scale = me._getValueScale();
  4397. var rects = me.getMeta().data;
  4398. var dataset = me.getDataset();
  4399. var ilen = rects.length;
  4400. var i = 0;
  4401. helpers$1.canvas.clipArea(chart.ctx, chart.chartArea);
  4402. for (; i < ilen; ++i) {
  4403. var val = scale._parseValue(dataset.data[i]);
  4404. if (!isNaN(val.min) && !isNaN(val.max)) {
  4405. rects[i].draw();
  4406. }
  4407. }
  4408. helpers$1.canvas.unclipArea(chart.ctx);
  4409. },
  4410. /**
  4411. * @private
  4412. */
  4413. _resolveDataElementOptions: function() {
  4414. var me = this;
  4415. var values = helpers$1.extend({}, core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments));
  4416. var indexOpts = me._getIndexScale().options;
  4417. var valueOpts = me._getValueScale().options;
  4418. values.barPercentage = valueOrDefault$3(indexOpts.barPercentage, values.barPercentage);
  4419. values.barThickness = valueOrDefault$3(indexOpts.barThickness, values.barThickness);
  4420. values.categoryPercentage = valueOrDefault$3(indexOpts.categoryPercentage, values.categoryPercentage);
  4421. values.maxBarThickness = valueOrDefault$3(indexOpts.maxBarThickness, values.maxBarThickness);
  4422. values.minBarLength = valueOrDefault$3(valueOpts.minBarLength, values.minBarLength);
  4423. return values;
  4424. }
  4425. });
  4426. var valueOrDefault$4 = helpers$1.valueOrDefault;
  4427. var resolve$1 = helpers$1.options.resolve;
  4428. core_defaults._set('bubble', {
  4429. hover: {
  4430. mode: 'single'
  4431. },
  4432. scales: {
  4433. xAxes: [{
  4434. type: 'linear', // bubble should probably use a linear scale by default
  4435. position: 'bottom',
  4436. id: 'x-axis-0' // need an ID so datasets can reference the scale
  4437. }],
  4438. yAxes: [{
  4439. type: 'linear',
  4440. position: 'left',
  4441. id: 'y-axis-0'
  4442. }]
  4443. },
  4444. tooltips: {
  4445. callbacks: {
  4446. title: function() {
  4447. // Title doesn't make sense for scatter since we format the data as a point
  4448. return '';
  4449. },
  4450. label: function(item, data) {
  4451. var datasetLabel = data.datasets[item.datasetIndex].label || '';
  4452. var dataPoint = data.datasets[item.datasetIndex].data[item.index];
  4453. return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')';
  4454. }
  4455. }
  4456. }
  4457. });
  4458. var controller_bubble = core_datasetController.extend({
  4459. /**
  4460. * @protected
  4461. */
  4462. dataElementType: elements.Point,
  4463. /**
  4464. * @private
  4465. */
  4466. _dataElementOptions: [
  4467. 'backgroundColor',
  4468. 'borderColor',
  4469. 'borderWidth',
  4470. 'hoverBackgroundColor',
  4471. 'hoverBorderColor',
  4472. 'hoverBorderWidth',
  4473. 'hoverRadius',
  4474. 'hitRadius',
  4475. 'pointStyle',
  4476. 'rotation'
  4477. ],
  4478. /**
  4479. * @protected
  4480. */
  4481. update: function(reset) {
  4482. var me = this;
  4483. var meta = me.getMeta();
  4484. var points = meta.data;
  4485. // Update Points
  4486. helpers$1.each(points, function(point, index) {
  4487. me.updateElement(point, index, reset);
  4488. });
  4489. },
  4490. /**
  4491. * @protected
  4492. */
  4493. updateElement: function(point, index, reset) {
  4494. var me = this;
  4495. var meta = me.getMeta();
  4496. var custom = point.custom || {};
  4497. var xScale = me.getScaleForId(meta.xAxisID);
  4498. var yScale = me.getScaleForId(meta.yAxisID);
  4499. var options = me._resolveDataElementOptions(point, index);
  4500. var data = me.getDataset().data[index];
  4501. var dsIndex = me.index;
  4502. var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex);
  4503. var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex);
  4504. point._xScale = xScale;
  4505. point._yScale = yScale;
  4506. point._options = options;
  4507. point._datasetIndex = dsIndex;
  4508. point._index = index;
  4509. point._model = {
  4510. backgroundColor: options.backgroundColor,
  4511. borderColor: options.borderColor,
  4512. borderWidth: options.borderWidth,
  4513. hitRadius: options.hitRadius,
  4514. pointStyle: options.pointStyle,
  4515. rotation: options.rotation,
  4516. radius: reset ? 0 : options.radius,
  4517. skip: custom.skip || isNaN(x) || isNaN(y),
  4518. x: x,
  4519. y: y,
  4520. };
  4521. point.pivot();
  4522. },
  4523. /**
  4524. * @protected
  4525. */
  4526. setHoverStyle: function(point) {
  4527. var model = point._model;
  4528. var options = point._options;
  4529. var getHoverColor = helpers$1.getHoverColor;
  4530. point.$previousStyle = {
  4531. backgroundColor: model.backgroundColor,
  4532. borderColor: model.borderColor,
  4533. borderWidth: model.borderWidth,
  4534. radius: model.radius
  4535. };
  4536. model.backgroundColor = valueOrDefault$4(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4537. model.borderColor = valueOrDefault$4(options.hoverBorderColor, getHoverColor(options.borderColor));
  4538. model.borderWidth = valueOrDefault$4(options.hoverBorderWidth, options.borderWidth);
  4539. model.radius = options.radius + options.hoverRadius;
  4540. },
  4541. /**
  4542. * @private
  4543. */
  4544. _resolveDataElementOptions: function(point, index) {
  4545. var me = this;
  4546. var chart = me.chart;
  4547. var dataset = me.getDataset();
  4548. var custom = point.custom || {};
  4549. var data = dataset.data[index] || {};
  4550. var values = core_datasetController.prototype._resolveDataElementOptions.apply(me, arguments);
  4551. // Scriptable options
  4552. var context = {
  4553. chart: chart,
  4554. dataIndex: index,
  4555. dataset: dataset,
  4556. datasetIndex: me.index
  4557. };
  4558. // In case values were cached (and thus frozen), we need to clone the values
  4559. if (me._cachedDataOpts === values) {
  4560. values = helpers$1.extend({}, values);
  4561. }
  4562. // Custom radius resolution
  4563. values.radius = resolve$1([
  4564. custom.radius,
  4565. data.r,
  4566. me._config.radius,
  4567. chart.options.elements.point.radius
  4568. ], context, index);
  4569. return values;
  4570. }
  4571. });
  4572. var valueOrDefault$5 = helpers$1.valueOrDefault;
  4573. var PI$1 = Math.PI;
  4574. var DOUBLE_PI$1 = PI$1 * 2;
  4575. var HALF_PI$1 = PI$1 / 2;
  4576. core_defaults._set('doughnut', {
  4577. animation: {
  4578. // Boolean - Whether we animate the rotation of the Doughnut
  4579. animateRotate: true,
  4580. // Boolean - Whether we animate scaling the Doughnut from the centre
  4581. animateScale: false
  4582. },
  4583. hover: {
  4584. mode: 'single'
  4585. },
  4586. legendCallback: function(chart) {
  4587. var list = document.createElement('ul');
  4588. var data = chart.data;
  4589. var datasets = data.datasets;
  4590. var labels = data.labels;
  4591. var i, ilen, listItem, listItemSpan;
  4592. list.setAttribute('class', chart.id + '-legend');
  4593. if (datasets.length) {
  4594. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  4595. listItem = list.appendChild(document.createElement('li'));
  4596. listItemSpan = listItem.appendChild(document.createElement('span'));
  4597. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  4598. if (labels[i]) {
  4599. listItem.appendChild(document.createTextNode(labels[i]));
  4600. }
  4601. }
  4602. }
  4603. return list.outerHTML;
  4604. },
  4605. legend: {
  4606. labels: {
  4607. generateLabels: function(chart) {
  4608. var data = chart.data;
  4609. if (data.labels.length && data.datasets.length) {
  4610. return data.labels.map(function(label, i) {
  4611. var meta = chart.getDatasetMeta(0);
  4612. var style = meta.controller.getStyle(i);
  4613. return {
  4614. text: label,
  4615. fillStyle: style.backgroundColor,
  4616. strokeStyle: style.borderColor,
  4617. lineWidth: style.borderWidth,
  4618. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  4619. // Extra data used for toggling the correct item
  4620. index: i
  4621. };
  4622. });
  4623. }
  4624. return [];
  4625. }
  4626. },
  4627. onClick: function(e, legendItem) {
  4628. var index = legendItem.index;
  4629. var chart = this.chart;
  4630. var i, ilen, meta;
  4631. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  4632. meta = chart.getDatasetMeta(i);
  4633. // toggle visibility of index if exists
  4634. if (meta.data[index]) {
  4635. meta.data[index].hidden = !meta.data[index].hidden;
  4636. }
  4637. }
  4638. chart.update();
  4639. }
  4640. },
  4641. // The percentage of the chart that we cut out of the middle.
  4642. cutoutPercentage: 50,
  4643. // The rotation of the chart, where the first data arc begins.
  4644. rotation: -HALF_PI$1,
  4645. // The total circumference of the chart.
  4646. circumference: DOUBLE_PI$1,
  4647. // Need to override these to give a nice default
  4648. tooltips: {
  4649. callbacks: {
  4650. title: function() {
  4651. return '';
  4652. },
  4653. label: function(tooltipItem, data) {
  4654. var dataLabel = data.labels[tooltipItem.index];
  4655. var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
  4656. if (helpers$1.isArray(dataLabel)) {
  4657. // show value on first line of multiline label
  4658. // need to clone because we are changing the value
  4659. dataLabel = dataLabel.slice();
  4660. dataLabel[0] += value;
  4661. } else {
  4662. dataLabel += value;
  4663. }
  4664. return dataLabel;
  4665. }
  4666. }
  4667. }
  4668. });
  4669. var controller_doughnut = core_datasetController.extend({
  4670. dataElementType: elements.Arc,
  4671. linkScales: helpers$1.noop,
  4672. /**
  4673. * @private
  4674. */
  4675. _dataElementOptions: [
  4676. 'backgroundColor',
  4677. 'borderColor',
  4678. 'borderWidth',
  4679. 'borderAlign',
  4680. 'hoverBackgroundColor',
  4681. 'hoverBorderColor',
  4682. 'hoverBorderWidth',
  4683. ],
  4684. // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly
  4685. getRingIndex: function(datasetIndex) {
  4686. var ringIndex = 0;
  4687. for (var j = 0; j < datasetIndex; ++j) {
  4688. if (this.chart.isDatasetVisible(j)) {
  4689. ++ringIndex;
  4690. }
  4691. }
  4692. return ringIndex;
  4693. },
  4694. update: function(reset) {
  4695. var me = this;
  4696. var chart = me.chart;
  4697. var chartArea = chart.chartArea;
  4698. var opts = chart.options;
  4699. var ratioX = 1;
  4700. var ratioY = 1;
  4701. var offsetX = 0;
  4702. var offsetY = 0;
  4703. var meta = me.getMeta();
  4704. var arcs = meta.data;
  4705. var cutout = opts.cutoutPercentage / 100 || 0;
  4706. var circumference = opts.circumference;
  4707. var chartWeight = me._getRingWeight(me.index);
  4708. var maxWidth, maxHeight, i, ilen;
  4709. // If the chart's circumference isn't a full circle, calculate size as a ratio of the width/height of the arc
  4710. if (circumference < DOUBLE_PI$1) {
  4711. var startAngle = opts.rotation % DOUBLE_PI$1;
  4712. startAngle += startAngle >= PI$1 ? -DOUBLE_PI$1 : startAngle < -PI$1 ? DOUBLE_PI$1 : 0;
  4713. var endAngle = startAngle + circumference;
  4714. var startX = Math.cos(startAngle);
  4715. var startY = Math.sin(startAngle);
  4716. var endX = Math.cos(endAngle);
  4717. var endY = Math.sin(endAngle);
  4718. var contains0 = (startAngle <= 0 && endAngle >= 0) || endAngle >= DOUBLE_PI$1;
  4719. var contains90 = (startAngle <= HALF_PI$1 && endAngle >= HALF_PI$1) || endAngle >= DOUBLE_PI$1 + HALF_PI$1;
  4720. var contains180 = startAngle === -PI$1 || endAngle >= PI$1;
  4721. var contains270 = (startAngle <= -HALF_PI$1 && endAngle >= -HALF_PI$1) || endAngle >= PI$1 + HALF_PI$1;
  4722. var minX = contains180 ? -1 : Math.min(startX, startX * cutout, endX, endX * cutout);
  4723. var minY = contains270 ? -1 : Math.min(startY, startY * cutout, endY, endY * cutout);
  4724. var maxX = contains0 ? 1 : Math.max(startX, startX * cutout, endX, endX * cutout);
  4725. var maxY = contains90 ? 1 : Math.max(startY, startY * cutout, endY, endY * cutout);
  4726. ratioX = (maxX - minX) / 2;
  4727. ratioY = (maxY - minY) / 2;
  4728. offsetX = -(maxX + minX) / 2;
  4729. offsetY = -(maxY + minY) / 2;
  4730. }
  4731. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4732. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  4733. }
  4734. chart.borderWidth = me.getMaxBorderWidth();
  4735. maxWidth = (chartArea.right - chartArea.left - chart.borderWidth) / ratioX;
  4736. maxHeight = (chartArea.bottom - chartArea.top - chart.borderWidth) / ratioY;
  4737. chart.outerRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0);
  4738. chart.innerRadius = Math.max(chart.outerRadius * cutout, 0);
  4739. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / (me._getVisibleDatasetWeightTotal() || 1);
  4740. chart.offsetX = offsetX * chart.outerRadius;
  4741. chart.offsetY = offsetY * chart.outerRadius;
  4742. meta.total = me.calculateTotal();
  4743. me.outerRadius = chart.outerRadius - chart.radiusLength * me._getRingWeightOffset(me.index);
  4744. me.innerRadius = Math.max(me.outerRadius - chart.radiusLength * chartWeight, 0);
  4745. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4746. me.updateElement(arcs[i], i, reset);
  4747. }
  4748. },
  4749. updateElement: function(arc, index, reset) {
  4750. var me = this;
  4751. var chart = me.chart;
  4752. var chartArea = chart.chartArea;
  4753. var opts = chart.options;
  4754. var animationOpts = opts.animation;
  4755. var centerX = (chartArea.left + chartArea.right) / 2;
  4756. var centerY = (chartArea.top + chartArea.bottom) / 2;
  4757. var startAngle = opts.rotation; // non reset case handled later
  4758. var endAngle = opts.rotation; // non reset case handled later
  4759. var dataset = me.getDataset();
  4760. var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / DOUBLE_PI$1);
  4761. var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius;
  4762. var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius;
  4763. var options = arc._options || {};
  4764. helpers$1.extend(arc, {
  4765. // Utility
  4766. _datasetIndex: me.index,
  4767. _index: index,
  4768. // Desired view properties
  4769. _model: {
  4770. backgroundColor: options.backgroundColor,
  4771. borderColor: options.borderColor,
  4772. borderWidth: options.borderWidth,
  4773. borderAlign: options.borderAlign,
  4774. x: centerX + chart.offsetX,
  4775. y: centerY + chart.offsetY,
  4776. startAngle: startAngle,
  4777. endAngle: endAngle,
  4778. circumference: circumference,
  4779. outerRadius: outerRadius,
  4780. innerRadius: innerRadius,
  4781. label: helpers$1.valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index])
  4782. }
  4783. });
  4784. var model = arc._model;
  4785. // Set correct angles if not resetting
  4786. if (!reset || !animationOpts.animateRotate) {
  4787. if (index === 0) {
  4788. model.startAngle = opts.rotation;
  4789. } else {
  4790. model.startAngle = me.getMeta().data[index - 1]._model.endAngle;
  4791. }
  4792. model.endAngle = model.startAngle + model.circumference;
  4793. }
  4794. arc.pivot();
  4795. },
  4796. calculateTotal: function() {
  4797. var dataset = this.getDataset();
  4798. var meta = this.getMeta();
  4799. var total = 0;
  4800. var value;
  4801. helpers$1.each(meta.data, function(element, index) {
  4802. value = dataset.data[index];
  4803. if (!isNaN(value) && !element.hidden) {
  4804. total += Math.abs(value);
  4805. }
  4806. });
  4807. /* if (total === 0) {
  4808. total = NaN;
  4809. }*/
  4810. return total;
  4811. },
  4812. calculateCircumference: function(value) {
  4813. var total = this.getMeta().total;
  4814. if (total > 0 && !isNaN(value)) {
  4815. return DOUBLE_PI$1 * (Math.abs(value) / total);
  4816. }
  4817. return 0;
  4818. },
  4819. // gets the max border or hover width to properly scale pie charts
  4820. getMaxBorderWidth: function(arcs) {
  4821. var me = this;
  4822. var max = 0;
  4823. var chart = me.chart;
  4824. var i, ilen, meta, arc, controller, options, borderWidth, hoverWidth;
  4825. if (!arcs) {
  4826. // Find the outmost visible dataset
  4827. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  4828. if (chart.isDatasetVisible(i)) {
  4829. meta = chart.getDatasetMeta(i);
  4830. arcs = meta.data;
  4831. if (i !== me.index) {
  4832. controller = meta.controller;
  4833. }
  4834. break;
  4835. }
  4836. }
  4837. }
  4838. if (!arcs) {
  4839. return 0;
  4840. }
  4841. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  4842. arc = arcs[i];
  4843. if (controller) {
  4844. controller._configure();
  4845. options = controller._resolveDataElementOptions(arc, i);
  4846. } else {
  4847. options = arc._options;
  4848. }
  4849. if (options.borderAlign !== 'inner') {
  4850. borderWidth = options.borderWidth;
  4851. hoverWidth = options.hoverBorderWidth;
  4852. max = borderWidth > max ? borderWidth : max;
  4853. max = hoverWidth > max ? hoverWidth : max;
  4854. }
  4855. }
  4856. return max;
  4857. },
  4858. /**
  4859. * @protected
  4860. */
  4861. setHoverStyle: function(arc) {
  4862. var model = arc._model;
  4863. var options = arc._options;
  4864. var getHoverColor = helpers$1.getHoverColor;
  4865. arc.$previousStyle = {
  4866. backgroundColor: model.backgroundColor,
  4867. borderColor: model.borderColor,
  4868. borderWidth: model.borderWidth,
  4869. };
  4870. model.backgroundColor = valueOrDefault$5(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  4871. model.borderColor = valueOrDefault$5(options.hoverBorderColor, getHoverColor(options.borderColor));
  4872. model.borderWidth = valueOrDefault$5(options.hoverBorderWidth, options.borderWidth);
  4873. },
  4874. /**
  4875. * Get radius length offset of the dataset in relation to the visible datasets weights. This allows determining the inner and outer radius correctly
  4876. * @private
  4877. */
  4878. _getRingWeightOffset: function(datasetIndex) {
  4879. var ringWeightOffset = 0;
  4880. for (var i = 0; i < datasetIndex; ++i) {
  4881. if (this.chart.isDatasetVisible(i)) {
  4882. ringWeightOffset += this._getRingWeight(i);
  4883. }
  4884. }
  4885. return ringWeightOffset;
  4886. },
  4887. /**
  4888. * @private
  4889. */
  4890. _getRingWeight: function(dataSetIndex) {
  4891. return Math.max(valueOrDefault$5(this.chart.data.datasets[dataSetIndex].weight, 1), 0);
  4892. },
  4893. /**
  4894. * Returns the sum of all visibile data set weights. This value can be 0.
  4895. * @private
  4896. */
  4897. _getVisibleDatasetWeightTotal: function() {
  4898. return this._getRingWeightOffset(this.chart.data.datasets.length);
  4899. }
  4900. });
  4901. core_defaults._set('horizontalBar', {
  4902. hover: {
  4903. mode: 'index',
  4904. axis: 'y'
  4905. },
  4906. scales: {
  4907. xAxes: [{
  4908. type: 'linear',
  4909. position: 'bottom'
  4910. }],
  4911. yAxes: [{
  4912. type: 'category',
  4913. position: 'left',
  4914. offset: true,
  4915. gridLines: {
  4916. offsetGridLines: true
  4917. }
  4918. }]
  4919. },
  4920. elements: {
  4921. rectangle: {
  4922. borderSkipped: 'left'
  4923. }
  4924. },
  4925. tooltips: {
  4926. mode: 'index',
  4927. axis: 'y'
  4928. }
  4929. });
  4930. core_defaults._set('global', {
  4931. datasets: {
  4932. horizontalBar: {
  4933. categoryPercentage: 0.8,
  4934. barPercentage: 0.9
  4935. }
  4936. }
  4937. });
  4938. var controller_horizontalBar = controller_bar.extend({
  4939. /**
  4940. * @private
  4941. */
  4942. _getValueScaleId: function() {
  4943. return this.getMeta().xAxisID;
  4944. },
  4945. /**
  4946. * @private
  4947. */
  4948. _getIndexScaleId: function() {
  4949. return this.getMeta().yAxisID;
  4950. }
  4951. });
  4952. var valueOrDefault$6 = helpers$1.valueOrDefault;
  4953. var resolve$2 = helpers$1.options.resolve;
  4954. var isPointInArea = helpers$1.canvas._isPointInArea;
  4955. core_defaults._set('line', {
  4956. showLines: true,
  4957. spanGaps: false,
  4958. hover: {
  4959. mode: 'label'
  4960. },
  4961. scales: {
  4962. xAxes: [{
  4963. type: 'category',
  4964. id: 'x-axis-0'
  4965. }],
  4966. yAxes: [{
  4967. type: 'linear',
  4968. id: 'y-axis-0'
  4969. }]
  4970. }
  4971. });
  4972. function scaleClip(scale, halfBorderWidth) {
  4973. var tickOpts = scale && scale.options.ticks || {};
  4974. var reverse = tickOpts.reverse;
  4975. var min = tickOpts.min === undefined ? halfBorderWidth : 0;
  4976. var max = tickOpts.max === undefined ? halfBorderWidth : 0;
  4977. return {
  4978. start: reverse ? max : min,
  4979. end: reverse ? min : max
  4980. };
  4981. }
  4982. function defaultClip(xScale, yScale, borderWidth) {
  4983. var halfBorderWidth = borderWidth / 2;
  4984. var x = scaleClip(xScale, halfBorderWidth);
  4985. var y = scaleClip(yScale, halfBorderWidth);
  4986. return {
  4987. top: y.end,
  4988. right: x.end,
  4989. bottom: y.start,
  4990. left: x.start
  4991. };
  4992. }
  4993. function toClip(value) {
  4994. var t, r, b, l;
  4995. if (helpers$1.isObject(value)) {
  4996. t = value.top;
  4997. r = value.right;
  4998. b = value.bottom;
  4999. l = value.left;
  5000. } else {
  5001. t = r = b = l = value;
  5002. }
  5003. return {
  5004. top: t,
  5005. right: r,
  5006. bottom: b,
  5007. left: l
  5008. };
  5009. }
  5010. var controller_line = core_datasetController.extend({
  5011. datasetElementType: elements.Line,
  5012. dataElementType: elements.Point,
  5013. /**
  5014. * @private
  5015. */
  5016. _datasetElementOptions: [
  5017. 'backgroundColor',
  5018. 'borderCapStyle',
  5019. 'borderColor',
  5020. 'borderDash',
  5021. 'borderDashOffset',
  5022. 'borderJoinStyle',
  5023. 'borderWidth',
  5024. 'cubicInterpolationMode',
  5025. 'fill'
  5026. ],
  5027. /**
  5028. * @private
  5029. */
  5030. _dataElementOptions: {
  5031. backgroundColor: 'pointBackgroundColor',
  5032. borderColor: 'pointBorderColor',
  5033. borderWidth: 'pointBorderWidth',
  5034. hitRadius: 'pointHitRadius',
  5035. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5036. hoverBorderColor: 'pointHoverBorderColor',
  5037. hoverBorderWidth: 'pointHoverBorderWidth',
  5038. hoverRadius: 'pointHoverRadius',
  5039. pointStyle: 'pointStyle',
  5040. radius: 'pointRadius',
  5041. rotation: 'pointRotation'
  5042. },
  5043. update: function(reset) {
  5044. var me = this;
  5045. var meta = me.getMeta();
  5046. var line = meta.dataset;
  5047. var points = meta.data || [];
  5048. var options = me.chart.options;
  5049. var config = me._config;
  5050. var showLine = me._showLine = valueOrDefault$6(config.showLine, options.showLines);
  5051. var i, ilen;
  5052. me._xScale = me.getScaleForId(meta.xAxisID);
  5053. me._yScale = me.getScaleForId(meta.yAxisID);
  5054. // Update Line
  5055. if (showLine) {
  5056. // Compatibility: If the properties are defined with only the old name, use those values
  5057. if (config.tension !== undefined && config.lineTension === undefined) {
  5058. config.lineTension = config.tension;
  5059. }
  5060. // Utility
  5061. line._scale = me._yScale;
  5062. line._datasetIndex = me.index;
  5063. // Data
  5064. line._children = points;
  5065. // Model
  5066. line._model = me._resolveDatasetElementOptions(line);
  5067. line.pivot();
  5068. }
  5069. // Update Points
  5070. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5071. me.updateElement(points[i], i, reset);
  5072. }
  5073. if (showLine && line._model.tension !== 0) {
  5074. me.updateBezierControlPoints();
  5075. }
  5076. // Now pivot the point for animation
  5077. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5078. points[i].pivot();
  5079. }
  5080. },
  5081. updateElement: function(point, index, reset) {
  5082. var me = this;
  5083. var meta = me.getMeta();
  5084. var custom = point.custom || {};
  5085. var dataset = me.getDataset();
  5086. var datasetIndex = me.index;
  5087. var value = dataset.data[index];
  5088. var xScale = me._xScale;
  5089. var yScale = me._yScale;
  5090. var lineModel = meta.dataset._model;
  5091. var x, y;
  5092. var options = me._resolveDataElementOptions(point, index);
  5093. x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex);
  5094. y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex);
  5095. // Utility
  5096. point._xScale = xScale;
  5097. point._yScale = yScale;
  5098. point._options = options;
  5099. point._datasetIndex = datasetIndex;
  5100. point._index = index;
  5101. // Desired view properties
  5102. point._model = {
  5103. x: x,
  5104. y: y,
  5105. skip: custom.skip || isNaN(x) || isNaN(y),
  5106. // Appearance
  5107. radius: options.radius,
  5108. pointStyle: options.pointStyle,
  5109. rotation: options.rotation,
  5110. backgroundColor: options.backgroundColor,
  5111. borderColor: options.borderColor,
  5112. borderWidth: options.borderWidth,
  5113. tension: valueOrDefault$6(custom.tension, lineModel ? lineModel.tension : 0),
  5114. steppedLine: lineModel ? lineModel.steppedLine : false,
  5115. // Tooltip
  5116. hitRadius: options.hitRadius
  5117. };
  5118. },
  5119. /**
  5120. * @private
  5121. */
  5122. _resolveDatasetElementOptions: function(element) {
  5123. var me = this;
  5124. var config = me._config;
  5125. var custom = element.custom || {};
  5126. var options = me.chart.options;
  5127. var lineOptions = options.elements.line;
  5128. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5129. // The default behavior of lines is to break at null values, according
  5130. // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158
  5131. // This option gives lines the ability to span gaps
  5132. values.spanGaps = valueOrDefault$6(config.spanGaps, options.spanGaps);
  5133. values.tension = valueOrDefault$6(config.lineTension, lineOptions.tension);
  5134. values.steppedLine = resolve$2([custom.steppedLine, config.steppedLine, lineOptions.stepped]);
  5135. values.clip = toClip(valueOrDefault$6(config.clip, defaultClip(me._xScale, me._yScale, values.borderWidth)));
  5136. return values;
  5137. },
  5138. calculatePointY: function(value, index, datasetIndex) {
  5139. var me = this;
  5140. var chart = me.chart;
  5141. var yScale = me._yScale;
  5142. var sumPos = 0;
  5143. var sumNeg = 0;
  5144. var i, ds, dsMeta, stackedRightValue, rightValue, metasets, ilen;
  5145. if (yScale.options.stacked) {
  5146. rightValue = +yScale.getRightValue(value);
  5147. metasets = chart._getSortedVisibleDatasetMetas();
  5148. ilen = metasets.length;
  5149. for (i = 0; i < ilen; ++i) {
  5150. dsMeta = metasets[i];
  5151. if (dsMeta.index === datasetIndex) {
  5152. break;
  5153. }
  5154. ds = chart.data.datasets[dsMeta.index];
  5155. if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id) {
  5156. stackedRightValue = +yScale.getRightValue(ds.data[index]);
  5157. if (stackedRightValue < 0) {
  5158. sumNeg += stackedRightValue || 0;
  5159. } else {
  5160. sumPos += stackedRightValue || 0;
  5161. }
  5162. }
  5163. }
  5164. if (rightValue < 0) {
  5165. return yScale.getPixelForValue(sumNeg + rightValue);
  5166. }
  5167. return yScale.getPixelForValue(sumPos + rightValue);
  5168. }
  5169. return yScale.getPixelForValue(value);
  5170. },
  5171. updateBezierControlPoints: function() {
  5172. var me = this;
  5173. var chart = me.chart;
  5174. var meta = me.getMeta();
  5175. var lineModel = meta.dataset._model;
  5176. var area = chart.chartArea;
  5177. var points = meta.data || [];
  5178. var i, ilen, model, controlPoints;
  5179. // Only consider points that are drawn in case the spanGaps option is used
  5180. if (lineModel.spanGaps) {
  5181. points = points.filter(function(pt) {
  5182. return !pt._model.skip;
  5183. });
  5184. }
  5185. function capControlPoint(pt, min, max) {
  5186. return Math.max(Math.min(pt, max), min);
  5187. }
  5188. if (lineModel.cubicInterpolationMode === 'monotone') {
  5189. helpers$1.splineCurveMonotone(points);
  5190. } else {
  5191. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5192. model = points[i]._model;
  5193. controlPoints = helpers$1.splineCurve(
  5194. helpers$1.previousItem(points, i)._model,
  5195. model,
  5196. helpers$1.nextItem(points, i)._model,
  5197. lineModel.tension
  5198. );
  5199. model.controlPointPreviousX = controlPoints.previous.x;
  5200. model.controlPointPreviousY = controlPoints.previous.y;
  5201. model.controlPointNextX = controlPoints.next.x;
  5202. model.controlPointNextY = controlPoints.next.y;
  5203. }
  5204. }
  5205. if (chart.options.elements.line.capBezierPoints) {
  5206. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5207. model = points[i]._model;
  5208. if (isPointInArea(model, area)) {
  5209. if (i > 0 && isPointInArea(points[i - 1]._model, area)) {
  5210. model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right);
  5211. model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom);
  5212. }
  5213. if (i < points.length - 1 && isPointInArea(points[i + 1]._model, area)) {
  5214. model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right);
  5215. model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom);
  5216. }
  5217. }
  5218. }
  5219. }
  5220. },
  5221. draw: function() {
  5222. var me = this;
  5223. var chart = me.chart;
  5224. var meta = me.getMeta();
  5225. var points = meta.data || [];
  5226. var area = chart.chartArea;
  5227. var canvas = chart.canvas;
  5228. var i = 0;
  5229. var ilen = points.length;
  5230. var clip;
  5231. if (me._showLine) {
  5232. clip = meta.dataset._model.clip;
  5233. helpers$1.canvas.clipArea(chart.ctx, {
  5234. left: clip.left === false ? 0 : area.left - clip.left,
  5235. right: clip.right === false ? canvas.width : area.right + clip.right,
  5236. top: clip.top === false ? 0 : area.top - clip.top,
  5237. bottom: clip.bottom === false ? canvas.height : area.bottom + clip.bottom
  5238. });
  5239. meta.dataset.draw();
  5240. helpers$1.canvas.unclipArea(chart.ctx);
  5241. }
  5242. // Draw the points
  5243. for (; i < ilen; ++i) {
  5244. points[i].draw(area);
  5245. }
  5246. },
  5247. /**
  5248. * @protected
  5249. */
  5250. setHoverStyle: function(point) {
  5251. var model = point._model;
  5252. var options = point._options;
  5253. var getHoverColor = helpers$1.getHoverColor;
  5254. point.$previousStyle = {
  5255. backgroundColor: model.backgroundColor,
  5256. borderColor: model.borderColor,
  5257. borderWidth: model.borderWidth,
  5258. radius: model.radius
  5259. };
  5260. model.backgroundColor = valueOrDefault$6(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5261. model.borderColor = valueOrDefault$6(options.hoverBorderColor, getHoverColor(options.borderColor));
  5262. model.borderWidth = valueOrDefault$6(options.hoverBorderWidth, options.borderWidth);
  5263. model.radius = valueOrDefault$6(options.hoverRadius, options.radius);
  5264. },
  5265. });
  5266. var resolve$3 = helpers$1.options.resolve;
  5267. core_defaults._set('polarArea', {
  5268. scale: {
  5269. type: 'radialLinear',
  5270. angleLines: {
  5271. display: false
  5272. },
  5273. gridLines: {
  5274. circular: true
  5275. },
  5276. pointLabels: {
  5277. display: false
  5278. },
  5279. ticks: {
  5280. beginAtZero: true
  5281. }
  5282. },
  5283. // Boolean - Whether to animate the rotation of the chart
  5284. animation: {
  5285. animateRotate: true,
  5286. animateScale: true
  5287. },
  5288. startAngle: -0.5 * Math.PI,
  5289. legendCallback: function(chart) {
  5290. var list = document.createElement('ul');
  5291. var data = chart.data;
  5292. var datasets = data.datasets;
  5293. var labels = data.labels;
  5294. var i, ilen, listItem, listItemSpan;
  5295. list.setAttribute('class', chart.id + '-legend');
  5296. if (datasets.length) {
  5297. for (i = 0, ilen = datasets[0].data.length; i < ilen; ++i) {
  5298. listItem = list.appendChild(document.createElement('li'));
  5299. listItemSpan = listItem.appendChild(document.createElement('span'));
  5300. listItemSpan.style.backgroundColor = datasets[0].backgroundColor[i];
  5301. if (labels[i]) {
  5302. listItem.appendChild(document.createTextNode(labels[i]));
  5303. }
  5304. }
  5305. }
  5306. return list.outerHTML;
  5307. },
  5308. legend: {
  5309. labels: {
  5310. generateLabels: function(chart) {
  5311. var data = chart.data;
  5312. if (data.labels.length && data.datasets.length) {
  5313. return data.labels.map(function(label, i) {
  5314. var meta = chart.getDatasetMeta(0);
  5315. var style = meta.controller.getStyle(i);
  5316. return {
  5317. text: label,
  5318. fillStyle: style.backgroundColor,
  5319. strokeStyle: style.borderColor,
  5320. lineWidth: style.borderWidth,
  5321. hidden: isNaN(data.datasets[0].data[i]) || meta.data[i].hidden,
  5322. // Extra data used for toggling the correct item
  5323. index: i
  5324. };
  5325. });
  5326. }
  5327. return [];
  5328. }
  5329. },
  5330. onClick: function(e, legendItem) {
  5331. var index = legendItem.index;
  5332. var chart = this.chart;
  5333. var i, ilen, meta;
  5334. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  5335. meta = chart.getDatasetMeta(i);
  5336. meta.data[index].hidden = !meta.data[index].hidden;
  5337. }
  5338. chart.update();
  5339. }
  5340. },
  5341. // Need to override these to give a nice default
  5342. tooltips: {
  5343. callbacks: {
  5344. title: function() {
  5345. return '';
  5346. },
  5347. label: function(item, data) {
  5348. return data.labels[item.index] + ': ' + item.yLabel;
  5349. }
  5350. }
  5351. }
  5352. });
  5353. var controller_polarArea = core_datasetController.extend({
  5354. dataElementType: elements.Arc,
  5355. linkScales: helpers$1.noop,
  5356. /**
  5357. * @private
  5358. */
  5359. _dataElementOptions: [
  5360. 'backgroundColor',
  5361. 'borderColor',
  5362. 'borderWidth',
  5363. 'borderAlign',
  5364. 'hoverBackgroundColor',
  5365. 'hoverBorderColor',
  5366. 'hoverBorderWidth',
  5367. ],
  5368. /**
  5369. * @private
  5370. */
  5371. _getIndexScaleId: function() {
  5372. return this.chart.scale.id;
  5373. },
  5374. /**
  5375. * @private
  5376. */
  5377. _getValueScaleId: function() {
  5378. return this.chart.scale.id;
  5379. },
  5380. update: function(reset) {
  5381. var me = this;
  5382. var dataset = me.getDataset();
  5383. var meta = me.getMeta();
  5384. var start = me.chart.options.startAngle || 0;
  5385. var starts = me._starts = [];
  5386. var angles = me._angles = [];
  5387. var arcs = meta.data;
  5388. var i, ilen, angle;
  5389. me._updateRadius();
  5390. meta.count = me.countVisibleElements();
  5391. for (i = 0, ilen = dataset.data.length; i < ilen; i++) {
  5392. starts[i] = start;
  5393. angle = me._computeAngle(i);
  5394. angles[i] = angle;
  5395. start += angle;
  5396. }
  5397. for (i = 0, ilen = arcs.length; i < ilen; ++i) {
  5398. arcs[i]._options = me._resolveDataElementOptions(arcs[i], i);
  5399. me.updateElement(arcs[i], i, reset);
  5400. }
  5401. },
  5402. /**
  5403. * @private
  5404. */
  5405. _updateRadius: function() {
  5406. var me = this;
  5407. var chart = me.chart;
  5408. var chartArea = chart.chartArea;
  5409. var opts = chart.options;
  5410. var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top);
  5411. chart.outerRadius = Math.max(minSize / 2, 0);
  5412. chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0);
  5413. chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount();
  5414. me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index);
  5415. me.innerRadius = me.outerRadius - chart.radiusLength;
  5416. },
  5417. updateElement: function(arc, index, reset) {
  5418. var me = this;
  5419. var chart = me.chart;
  5420. var dataset = me.getDataset();
  5421. var opts = chart.options;
  5422. var animationOpts = opts.animation;
  5423. var scale = chart.scale;
  5424. var labels = chart.data.labels;
  5425. var centerX = scale.xCenter;
  5426. var centerY = scale.yCenter;
  5427. // var negHalfPI = -0.5 * Math.PI;
  5428. var datasetStartAngle = opts.startAngle;
  5429. var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5430. var startAngle = me._starts[index];
  5431. var endAngle = startAngle + (arc.hidden ? 0 : me._angles[index]);
  5432. var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]);
  5433. var options = arc._options || {};
  5434. helpers$1.extend(arc, {
  5435. // Utility
  5436. _datasetIndex: me.index,
  5437. _index: index,
  5438. _scale: scale,
  5439. // Desired view properties
  5440. _model: {
  5441. backgroundColor: options.backgroundColor,
  5442. borderColor: options.borderColor,
  5443. borderWidth: options.borderWidth,
  5444. borderAlign: options.borderAlign,
  5445. x: centerX,
  5446. y: centerY,
  5447. innerRadius: 0,
  5448. outerRadius: reset ? resetRadius : distance,
  5449. startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle,
  5450. endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle,
  5451. label: helpers$1.valueAtIndexOrDefault(labels, index, labels[index])
  5452. }
  5453. });
  5454. arc.pivot();
  5455. },
  5456. countVisibleElements: function() {
  5457. var dataset = this.getDataset();
  5458. var meta = this.getMeta();
  5459. var count = 0;
  5460. helpers$1.each(meta.data, function(element, index) {
  5461. if (!isNaN(dataset.data[index]) && !element.hidden) {
  5462. count++;
  5463. }
  5464. });
  5465. return count;
  5466. },
  5467. /**
  5468. * @protected
  5469. */
  5470. setHoverStyle: function(arc) {
  5471. var model = arc._model;
  5472. var options = arc._options;
  5473. var getHoverColor = helpers$1.getHoverColor;
  5474. var valueOrDefault = helpers$1.valueOrDefault;
  5475. arc.$previousStyle = {
  5476. backgroundColor: model.backgroundColor,
  5477. borderColor: model.borderColor,
  5478. borderWidth: model.borderWidth,
  5479. };
  5480. model.backgroundColor = valueOrDefault(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5481. model.borderColor = valueOrDefault(options.hoverBorderColor, getHoverColor(options.borderColor));
  5482. model.borderWidth = valueOrDefault(options.hoverBorderWidth, options.borderWidth);
  5483. },
  5484. /**
  5485. * @private
  5486. */
  5487. _computeAngle: function(index) {
  5488. var me = this;
  5489. var count = this.getMeta().count;
  5490. var dataset = me.getDataset();
  5491. var meta = me.getMeta();
  5492. if (isNaN(dataset.data[index]) || meta.data[index].hidden) {
  5493. return 0;
  5494. }
  5495. // Scriptable options
  5496. var context = {
  5497. chart: me.chart,
  5498. dataIndex: index,
  5499. dataset: dataset,
  5500. datasetIndex: me.index
  5501. };
  5502. return resolve$3([
  5503. me.chart.options.elements.arc.angle,
  5504. (2 * Math.PI) / count
  5505. ], context, index);
  5506. }
  5507. });
  5508. core_defaults._set('pie', helpers$1.clone(core_defaults.doughnut));
  5509. core_defaults._set('pie', {
  5510. cutoutPercentage: 0
  5511. });
  5512. // Pie charts are Doughnut chart with different defaults
  5513. var controller_pie = controller_doughnut;
  5514. var valueOrDefault$7 = helpers$1.valueOrDefault;
  5515. core_defaults._set('radar', {
  5516. spanGaps: false,
  5517. scale: {
  5518. type: 'radialLinear'
  5519. },
  5520. elements: {
  5521. line: {
  5522. fill: 'start',
  5523. tension: 0 // no bezier in radar
  5524. }
  5525. }
  5526. });
  5527. var controller_radar = core_datasetController.extend({
  5528. datasetElementType: elements.Line,
  5529. dataElementType: elements.Point,
  5530. linkScales: helpers$1.noop,
  5531. /**
  5532. * @private
  5533. */
  5534. _datasetElementOptions: [
  5535. 'backgroundColor',
  5536. 'borderWidth',
  5537. 'borderColor',
  5538. 'borderCapStyle',
  5539. 'borderDash',
  5540. 'borderDashOffset',
  5541. 'borderJoinStyle',
  5542. 'fill'
  5543. ],
  5544. /**
  5545. * @private
  5546. */
  5547. _dataElementOptions: {
  5548. backgroundColor: 'pointBackgroundColor',
  5549. borderColor: 'pointBorderColor',
  5550. borderWidth: 'pointBorderWidth',
  5551. hitRadius: 'pointHitRadius',
  5552. hoverBackgroundColor: 'pointHoverBackgroundColor',
  5553. hoverBorderColor: 'pointHoverBorderColor',
  5554. hoverBorderWidth: 'pointHoverBorderWidth',
  5555. hoverRadius: 'pointHoverRadius',
  5556. pointStyle: 'pointStyle',
  5557. radius: 'pointRadius',
  5558. rotation: 'pointRotation'
  5559. },
  5560. /**
  5561. * @private
  5562. */
  5563. _getIndexScaleId: function() {
  5564. return this.chart.scale.id;
  5565. },
  5566. /**
  5567. * @private
  5568. */
  5569. _getValueScaleId: function() {
  5570. return this.chart.scale.id;
  5571. },
  5572. update: function(reset) {
  5573. var me = this;
  5574. var meta = me.getMeta();
  5575. var line = meta.dataset;
  5576. var points = meta.data || [];
  5577. var scale = me.chart.scale;
  5578. var config = me._config;
  5579. var i, ilen;
  5580. // Compatibility: If the properties are defined with only the old name, use those values
  5581. if (config.tension !== undefined && config.lineTension === undefined) {
  5582. config.lineTension = config.tension;
  5583. }
  5584. // Utility
  5585. line._scale = scale;
  5586. line._datasetIndex = me.index;
  5587. // Data
  5588. line._children = points;
  5589. line._loop = true;
  5590. // Model
  5591. line._model = me._resolveDatasetElementOptions(line);
  5592. line.pivot();
  5593. // Update Points
  5594. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5595. me.updateElement(points[i], i, reset);
  5596. }
  5597. // Update bezier control points
  5598. me.updateBezierControlPoints();
  5599. // Now pivot the point for animation
  5600. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5601. points[i].pivot();
  5602. }
  5603. },
  5604. updateElement: function(point, index, reset) {
  5605. var me = this;
  5606. var custom = point.custom || {};
  5607. var dataset = me.getDataset();
  5608. var scale = me.chart.scale;
  5609. var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]);
  5610. var options = me._resolveDataElementOptions(point, index);
  5611. var lineModel = me.getMeta().dataset._model;
  5612. var x = reset ? scale.xCenter : pointPosition.x;
  5613. var y = reset ? scale.yCenter : pointPosition.y;
  5614. // Utility
  5615. point._scale = scale;
  5616. point._options = options;
  5617. point._datasetIndex = me.index;
  5618. point._index = index;
  5619. // Desired view properties
  5620. point._model = {
  5621. x: x, // value not used in dataset scale, but we want a consistent API between scales
  5622. y: y,
  5623. skip: custom.skip || isNaN(x) || isNaN(y),
  5624. // Appearance
  5625. radius: options.radius,
  5626. pointStyle: options.pointStyle,
  5627. rotation: options.rotation,
  5628. backgroundColor: options.backgroundColor,
  5629. borderColor: options.borderColor,
  5630. borderWidth: options.borderWidth,
  5631. tension: valueOrDefault$7(custom.tension, lineModel ? lineModel.tension : 0),
  5632. // Tooltip
  5633. hitRadius: options.hitRadius
  5634. };
  5635. },
  5636. /**
  5637. * @private
  5638. */
  5639. _resolveDatasetElementOptions: function() {
  5640. var me = this;
  5641. var config = me._config;
  5642. var options = me.chart.options;
  5643. var values = core_datasetController.prototype._resolveDatasetElementOptions.apply(me, arguments);
  5644. values.spanGaps = valueOrDefault$7(config.spanGaps, options.spanGaps);
  5645. values.tension = valueOrDefault$7(config.lineTension, options.elements.line.tension);
  5646. return values;
  5647. },
  5648. updateBezierControlPoints: function() {
  5649. var me = this;
  5650. var meta = me.getMeta();
  5651. var area = me.chart.chartArea;
  5652. var points = meta.data || [];
  5653. var i, ilen, model, controlPoints;
  5654. // Only consider points that are drawn in case the spanGaps option is used
  5655. if (meta.dataset._model.spanGaps) {
  5656. points = points.filter(function(pt) {
  5657. return !pt._model.skip;
  5658. });
  5659. }
  5660. function capControlPoint(pt, min, max) {
  5661. return Math.max(Math.min(pt, max), min);
  5662. }
  5663. for (i = 0, ilen = points.length; i < ilen; ++i) {
  5664. model = points[i]._model;
  5665. controlPoints = helpers$1.splineCurve(
  5666. helpers$1.previousItem(points, i, true)._model,
  5667. model,
  5668. helpers$1.nextItem(points, i, true)._model,
  5669. model.tension
  5670. );
  5671. // Prevent the bezier going outside of the bounds of the graph
  5672. model.controlPointPreviousX = capControlPoint(controlPoints.previous.x, area.left, area.right);
  5673. model.controlPointPreviousY = capControlPoint(controlPoints.previous.y, area.top, area.bottom);
  5674. model.controlPointNextX = capControlPoint(controlPoints.next.x, area.left, area.right);
  5675. model.controlPointNextY = capControlPoint(controlPoints.next.y, area.top, area.bottom);
  5676. }
  5677. },
  5678. setHoverStyle: function(point) {
  5679. var model = point._model;
  5680. var options = point._options;
  5681. var getHoverColor = helpers$1.getHoverColor;
  5682. point.$previousStyle = {
  5683. backgroundColor: model.backgroundColor,
  5684. borderColor: model.borderColor,
  5685. borderWidth: model.borderWidth,
  5686. radius: model.radius
  5687. };
  5688. model.backgroundColor = valueOrDefault$7(options.hoverBackgroundColor, getHoverColor(options.backgroundColor));
  5689. model.borderColor = valueOrDefault$7(options.hoverBorderColor, getHoverColor(options.borderColor));
  5690. model.borderWidth = valueOrDefault$7(options.hoverBorderWidth, options.borderWidth);
  5691. model.radius = valueOrDefault$7(options.hoverRadius, options.radius);
  5692. }
  5693. });
  5694. core_defaults._set('scatter', {
  5695. hover: {
  5696. mode: 'single'
  5697. },
  5698. scales: {
  5699. xAxes: [{
  5700. id: 'x-axis-1', // need an ID so datasets can reference the scale
  5701. type: 'linear', // scatter should not use a category axis
  5702. position: 'bottom'
  5703. }],
  5704. yAxes: [{
  5705. id: 'y-axis-1',
  5706. type: 'linear',
  5707. position: 'left'
  5708. }]
  5709. },
  5710. tooltips: {
  5711. callbacks: {
  5712. title: function() {
  5713. return ''; // doesn't make sense for scatter since data are formatted as a point
  5714. },
  5715. label: function(item) {
  5716. return '(' + item.xLabel + ', ' + item.yLabel + ')';
  5717. }
  5718. }
  5719. }
  5720. });
  5721. core_defaults._set('global', {
  5722. datasets: {
  5723. scatter: {
  5724. showLine: false
  5725. }
  5726. }
  5727. });
  5728. // Scatter charts use line controllers
  5729. var controller_scatter = controller_line;
  5730. // NOTE export a map in which the key represents the controller type, not
  5731. // the class, and so must be CamelCase in order to be correctly retrieved
  5732. // by the controller in core.controller.js (`controllers[meta.type]`).
  5733. var controllers = {
  5734. bar: controller_bar,
  5735. bubble: controller_bubble,
  5736. doughnut: controller_doughnut,
  5737. horizontalBar: controller_horizontalBar,
  5738. line: controller_line,
  5739. polarArea: controller_polarArea,
  5740. pie: controller_pie,
  5741. radar: controller_radar,
  5742. scatter: controller_scatter
  5743. };
  5744. /**
  5745. * Helper function to get relative position for an event
  5746. * @param {Event|IEvent} event - The event to get the position for
  5747. * @param {Chart} chart - The chart
  5748. * @returns {object} the event position
  5749. */
  5750. function getRelativePosition(e, chart) {
  5751. if (e.native) {
  5752. return {
  5753. x: e.x,
  5754. y: e.y
  5755. };
  5756. }
  5757. return helpers$1.getRelativePosition(e, chart);
  5758. }
  5759. /**
  5760. * Helper function to traverse all of the visible elements in the chart
  5761. * @param {Chart} chart - the chart
  5762. * @param {function} handler - the callback to execute for each visible item
  5763. */
  5764. function parseVisibleItems(chart, handler) {
  5765. var metasets = chart._getSortedVisibleDatasetMetas();
  5766. var metadata, i, j, ilen, jlen, element;
  5767. for (i = 0, ilen = metasets.length; i < ilen; ++i) {
  5768. metadata = metasets[i].data;
  5769. for (j = 0, jlen = metadata.length; j < jlen; ++j) {
  5770. element = metadata[j];
  5771. if (!element._view.skip) {
  5772. handler(element);
  5773. }
  5774. }
  5775. }
  5776. }
  5777. /**
  5778. * Helper function to get the items that intersect the event position
  5779. * @param {ChartElement[]} items - elements to filter
  5780. * @param {object} position - the point to be nearest to
  5781. * @return {ChartElement[]} the nearest items
  5782. */
  5783. function getIntersectItems(chart, position) {
  5784. var elements = [];
  5785. parseVisibleItems(chart, function(element) {
  5786. if (element.inRange(position.x, position.y)) {
  5787. elements.push(element);
  5788. }
  5789. });
  5790. return elements;
  5791. }
  5792. /**
  5793. * Helper function to get the items nearest to the event position considering all visible items in teh chart
  5794. * @param {Chart} chart - the chart to look at elements from
  5795. * @param {object} position - the point to be nearest to
  5796. * @param {boolean} intersect - if true, only consider items that intersect the position
  5797. * @param {function} distanceMetric - function to provide the distance between points
  5798. * @return {ChartElement[]} the nearest items
  5799. */
  5800. function getNearestItems(chart, position, intersect, distanceMetric) {
  5801. var minDistance = Number.POSITIVE_INFINITY;
  5802. var nearestItems = [];
  5803. parseVisibleItems(chart, function(element) {
  5804. if (intersect && !element.inRange(position.x, position.y)) {
  5805. return;
  5806. }
  5807. var center = element.getCenterPoint();
  5808. var distance = distanceMetric(position, center);
  5809. if (distance < minDistance) {
  5810. nearestItems = [element];
  5811. minDistance = distance;
  5812. } else if (distance === minDistance) {
  5813. // Can have multiple items at the same distance in which case we sort by size
  5814. nearestItems.push(element);
  5815. }
  5816. });
  5817. return nearestItems;
  5818. }
  5819. /**
  5820. * Get a distance metric function for two points based on the
  5821. * axis mode setting
  5822. * @param {string} axis - the axis mode. x|y|xy
  5823. */
  5824. function getDistanceMetricForAxis(axis) {
  5825. var useX = axis.indexOf('x') !== -1;
  5826. var useY = axis.indexOf('y') !== -1;
  5827. return function(pt1, pt2) {
  5828. var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0;
  5829. var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0;
  5830. return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  5831. };
  5832. }
  5833. function indexMode(chart, e, options) {
  5834. var position = getRelativePosition(e, chart);
  5835. // Default axis for index mode is 'x' to match old behaviour
  5836. options.axis = options.axis || 'x';
  5837. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5838. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5839. var elements = [];
  5840. if (!items.length) {
  5841. return [];
  5842. }
  5843. chart._getSortedVisibleDatasetMetas().forEach(function(meta) {
  5844. var element = meta.data[items[0]._index];
  5845. // don't count items that are skipped (null data)
  5846. if (element && !element._view.skip) {
  5847. elements.push(element);
  5848. }
  5849. });
  5850. return elements;
  5851. }
  5852. /**
  5853. * @interface IInteractionOptions
  5854. */
  5855. /**
  5856. * If true, only consider items that intersect the point
  5857. * @name IInterfaceOptions#boolean
  5858. * @type Boolean
  5859. */
  5860. /**
  5861. * Contains interaction related functions
  5862. * @namespace Chart.Interaction
  5863. */
  5864. var core_interaction = {
  5865. // Helper function for different modes
  5866. modes: {
  5867. single: function(chart, e) {
  5868. var position = getRelativePosition(e, chart);
  5869. var elements = [];
  5870. parseVisibleItems(chart, function(element) {
  5871. if (element.inRange(position.x, position.y)) {
  5872. elements.push(element);
  5873. return elements;
  5874. }
  5875. });
  5876. return elements.slice(0, 1);
  5877. },
  5878. /**
  5879. * @function Chart.Interaction.modes.label
  5880. * @deprecated since version 2.4.0
  5881. * @todo remove at version 3
  5882. * @private
  5883. */
  5884. label: indexMode,
  5885. /**
  5886. * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something
  5887. * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item
  5888. * @function Chart.Interaction.modes.index
  5889. * @since v2.4.0
  5890. * @param {Chart} chart - the chart we are returning items from
  5891. * @param {Event} e - the event we are find things at
  5892. * @param {IInteractionOptions} options - options to use during interaction
  5893. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5894. */
  5895. index: indexMode,
  5896. /**
  5897. * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something
  5898. * If the options.intersect is false, we find the nearest item and return the items in that dataset
  5899. * @function Chart.Interaction.modes.dataset
  5900. * @param {Chart} chart - the chart we are returning items from
  5901. * @param {Event} e - the event we are find things at
  5902. * @param {IInteractionOptions} options - options to use during interaction
  5903. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5904. */
  5905. dataset: function(chart, e, options) {
  5906. var position = getRelativePosition(e, chart);
  5907. options.axis = options.axis || 'xy';
  5908. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5909. var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric);
  5910. if (items.length > 0) {
  5911. items = chart.getDatasetMeta(items[0]._datasetIndex).data;
  5912. }
  5913. return items;
  5914. },
  5915. /**
  5916. * @function Chart.Interaction.modes.x-axis
  5917. * @deprecated since version 2.4.0. Use index mode and intersect == true
  5918. * @todo remove at version 3
  5919. * @private
  5920. */
  5921. 'x-axis': function(chart, e) {
  5922. return indexMode(chart, e, {intersect: false});
  5923. },
  5924. /**
  5925. * Point mode returns all elements that hit test based on the event position
  5926. * of the event
  5927. * @function Chart.Interaction.modes.intersect
  5928. * @param {Chart} chart - the chart we are returning items from
  5929. * @param {Event} e - the event we are find things at
  5930. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5931. */
  5932. point: function(chart, e) {
  5933. var position = getRelativePosition(e, chart);
  5934. return getIntersectItems(chart, position);
  5935. },
  5936. /**
  5937. * nearest mode returns the element closest to the point
  5938. * @function Chart.Interaction.modes.intersect
  5939. * @param {Chart} chart - the chart we are returning items from
  5940. * @param {Event} e - the event we are find things at
  5941. * @param {IInteractionOptions} options - options to use
  5942. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5943. */
  5944. nearest: function(chart, e, options) {
  5945. var position = getRelativePosition(e, chart);
  5946. options.axis = options.axis || 'xy';
  5947. var distanceMetric = getDistanceMetricForAxis(options.axis);
  5948. return getNearestItems(chart, position, options.intersect, distanceMetric);
  5949. },
  5950. /**
  5951. * x mode returns the elements that hit-test at the current x coordinate
  5952. * @function Chart.Interaction.modes.x
  5953. * @param {Chart} chart - the chart we are returning items from
  5954. * @param {Event} e - the event we are find things at
  5955. * @param {IInteractionOptions} options - options to use
  5956. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5957. */
  5958. x: function(chart, e, options) {
  5959. var position = getRelativePosition(e, chart);
  5960. var items = [];
  5961. var intersectsItem = false;
  5962. parseVisibleItems(chart, function(element) {
  5963. if (element.inXRange(position.x)) {
  5964. items.push(element);
  5965. }
  5966. if (element.inRange(position.x, position.y)) {
  5967. intersectsItem = true;
  5968. }
  5969. });
  5970. // If we want to trigger on an intersect and we don't have any items
  5971. // that intersect the position, return nothing
  5972. if (options.intersect && !intersectsItem) {
  5973. items = [];
  5974. }
  5975. return items;
  5976. },
  5977. /**
  5978. * y mode returns the elements that hit-test at the current y coordinate
  5979. * @function Chart.Interaction.modes.y
  5980. * @param {Chart} chart - the chart we are returning items from
  5981. * @param {Event} e - the event we are find things at
  5982. * @param {IInteractionOptions} options - options to use
  5983. * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned
  5984. */
  5985. y: function(chart, e, options) {
  5986. var position = getRelativePosition(e, chart);
  5987. var items = [];
  5988. var intersectsItem = false;
  5989. parseVisibleItems(chart, function(element) {
  5990. if (element.inYRange(position.y)) {
  5991. items.push(element);
  5992. }
  5993. if (element.inRange(position.x, position.y)) {
  5994. intersectsItem = true;
  5995. }
  5996. });
  5997. // If we want to trigger on an intersect and we don't have any items
  5998. // that intersect the position, return nothing
  5999. if (options.intersect && !intersectsItem) {
  6000. items = [];
  6001. }
  6002. return items;
  6003. }
  6004. }
  6005. };
  6006. var extend = helpers$1.extend;
  6007. function filterByPosition(array, position) {
  6008. return helpers$1.where(array, function(v) {
  6009. return v.pos === position;
  6010. });
  6011. }
  6012. function sortByWeight(array, reverse) {
  6013. return array.sort(function(a, b) {
  6014. var v0 = reverse ? b : a;
  6015. var v1 = reverse ? a : b;
  6016. return v0.weight === v1.weight ?
  6017. v0.index - v1.index :
  6018. v0.weight - v1.weight;
  6019. });
  6020. }
  6021. function wrapBoxes(boxes) {
  6022. var layoutBoxes = [];
  6023. var i, ilen, box;
  6024. for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) {
  6025. box = boxes[i];
  6026. layoutBoxes.push({
  6027. index: i,
  6028. box: box,
  6029. pos: box.position,
  6030. horizontal: box.isHorizontal(),
  6031. weight: box.weight
  6032. });
  6033. }
  6034. return layoutBoxes;
  6035. }
  6036. function setLayoutDims(layouts, params) {
  6037. var i, ilen, layout;
  6038. for (i = 0, ilen = layouts.length; i < ilen; ++i) {
  6039. layout = layouts[i];
  6040. // store width used instead of chartArea.w in fitBoxes
  6041. layout.width = layout.horizontal
  6042. ? layout.box.fullWidth && params.availableWidth
  6043. : params.vBoxMaxWidth;
  6044. // store height used instead of chartArea.h in fitBoxes
  6045. layout.height = layout.horizontal && params.hBoxMaxHeight;
  6046. }
  6047. }
  6048. function buildLayoutBoxes(boxes) {
  6049. var layoutBoxes = wrapBoxes(boxes);
  6050. var left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true);
  6051. var right = sortByWeight(filterByPosition(layoutBoxes, 'right'));
  6052. var top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true);
  6053. var bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom'));
  6054. return {
  6055. leftAndTop: left.concat(top),
  6056. rightAndBottom: right.concat(bottom),
  6057. chartArea: filterByPosition(layoutBoxes, 'chartArea'),
  6058. vertical: left.concat(right),
  6059. horizontal: top.concat(bottom)
  6060. };
  6061. }
  6062. function getCombinedMax(maxPadding, chartArea, a, b) {
  6063. return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]);
  6064. }
  6065. function updateDims(chartArea, params, layout) {
  6066. var box = layout.box;
  6067. var maxPadding = chartArea.maxPadding;
  6068. var newWidth, newHeight;
  6069. if (layout.size) {
  6070. // this layout was already counted for, lets first reduce old size
  6071. chartArea[layout.pos] -= layout.size;
  6072. }
  6073. layout.size = layout.horizontal ? box.height : box.width;
  6074. chartArea[layout.pos] += layout.size;
  6075. if (box.getPadding) {
  6076. var boxPadding = box.getPadding();
  6077. maxPadding.top = Math.max(maxPadding.top, boxPadding.top);
  6078. maxPadding.left = Math.max(maxPadding.left, boxPadding.left);
  6079. maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom);
  6080. maxPadding.right = Math.max(maxPadding.right, boxPadding.right);
  6081. }
  6082. newWidth = params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right');
  6083. newHeight = params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom');
  6084. if (newWidth !== chartArea.w || newHeight !== chartArea.h) {
  6085. chartArea.w = newWidth;
  6086. chartArea.h = newHeight;
  6087. // return true if chart area changed in layout's direction
  6088. return layout.horizontal ? newWidth !== chartArea.w : newHeight !== chartArea.h;
  6089. }
  6090. }
  6091. function handleMaxPadding(chartArea) {
  6092. var maxPadding = chartArea.maxPadding;
  6093. function updatePos(pos) {
  6094. var change = Math.max(maxPadding[pos] - chartArea[pos], 0);
  6095. chartArea[pos] += change;
  6096. return change;
  6097. }
  6098. chartArea.y += updatePos('top');
  6099. chartArea.x += updatePos('left');
  6100. updatePos('right');
  6101. updatePos('bottom');
  6102. }
  6103. function getMargins(horizontal, chartArea) {
  6104. var maxPadding = chartArea.maxPadding;
  6105. function marginForPositions(positions) {
  6106. var margin = {left: 0, top: 0, right: 0, bottom: 0};
  6107. positions.forEach(function(pos) {
  6108. margin[pos] = Math.max(chartArea[pos], maxPadding[pos]);
  6109. });
  6110. return margin;
  6111. }
  6112. return horizontal
  6113. ? marginForPositions(['left', 'right'])
  6114. : marginForPositions(['top', 'bottom']);
  6115. }
  6116. function fitBoxes(boxes, chartArea, params) {
  6117. var refitBoxes = [];
  6118. var i, ilen, layout, box, refit, changed;
  6119. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6120. layout = boxes[i];
  6121. box = layout.box;
  6122. box.update(
  6123. layout.width || chartArea.w,
  6124. layout.height || chartArea.h,
  6125. getMargins(layout.horizontal, chartArea)
  6126. );
  6127. if (updateDims(chartArea, params, layout)) {
  6128. changed = true;
  6129. if (refitBoxes.length) {
  6130. // Dimensions changed and there were non full width boxes before this
  6131. // -> we have to refit those
  6132. refit = true;
  6133. }
  6134. }
  6135. if (!box.fullWidth) { // fullWidth boxes don't need to be re-fitted in any case
  6136. refitBoxes.push(layout);
  6137. }
  6138. }
  6139. return refit ? fitBoxes(refitBoxes, chartArea, params) || changed : changed;
  6140. }
  6141. function placeBoxes(boxes, chartArea, params) {
  6142. var userPadding = params.padding;
  6143. var x = chartArea.x;
  6144. var y = chartArea.y;
  6145. var i, ilen, layout, box;
  6146. for (i = 0, ilen = boxes.length; i < ilen; ++i) {
  6147. layout = boxes[i];
  6148. box = layout.box;
  6149. if (layout.horizontal) {
  6150. box.left = box.fullWidth ? userPadding.left : chartArea.left;
  6151. box.right = box.fullWidth ? params.outerWidth - userPadding.right : chartArea.left + chartArea.w;
  6152. box.top = y;
  6153. box.bottom = y + box.height;
  6154. box.width = box.right - box.left;
  6155. y = box.bottom;
  6156. } else {
  6157. box.left = x;
  6158. box.right = x + box.width;
  6159. box.top = chartArea.top;
  6160. box.bottom = chartArea.top + chartArea.h;
  6161. box.height = box.bottom - box.top;
  6162. x = box.right;
  6163. }
  6164. }
  6165. chartArea.x = x;
  6166. chartArea.y = y;
  6167. }
  6168. core_defaults._set('global', {
  6169. layout: {
  6170. padding: {
  6171. top: 0,
  6172. right: 0,
  6173. bottom: 0,
  6174. left: 0
  6175. }
  6176. }
  6177. });
  6178. /**
  6179. * @interface ILayoutItem
  6180. * @prop {string} position - The position of the item in the chart layout. Possible values are
  6181. * 'left', 'top', 'right', 'bottom', and 'chartArea'
  6182. * @prop {number} weight - The weight used to sort the item. Higher weights are further away from the chart area
  6183. * @prop {boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down
  6184. * @prop {function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom)
  6185. * @prop {function} update - Takes two parameters: width and height. Returns size of item
  6186. * @prop {function} getPadding - Returns an object with padding on the edges
  6187. * @prop {number} width - Width of item. Must be valid after update()
  6188. * @prop {number} height - Height of item. Must be valid after update()
  6189. * @prop {number} left - Left edge of the item. Set by layout system and cannot be used in update
  6190. * @prop {number} top - Top edge of the item. Set by layout system and cannot be used in update
  6191. * @prop {number} right - Right edge of the item. Set by layout system and cannot be used in update
  6192. * @prop {number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update
  6193. */
  6194. // The layout service is very self explanatory. It's responsible for the layout within a chart.
  6195. // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need
  6196. // It is this service's responsibility of carrying out that layout.
  6197. var core_layouts = {
  6198. defaults: {},
  6199. /**
  6200. * Register a box to a chart.
  6201. * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title.
  6202. * @param {Chart} chart - the chart to use
  6203. * @param {ILayoutItem} item - the item to add to be layed out
  6204. */
  6205. addBox: function(chart, item) {
  6206. if (!chart.boxes) {
  6207. chart.boxes = [];
  6208. }
  6209. // initialize item with default values
  6210. item.fullWidth = item.fullWidth || false;
  6211. item.position = item.position || 'top';
  6212. item.weight = item.weight || 0;
  6213. item._layers = item._layers || function() {
  6214. return [{
  6215. z: 0,
  6216. draw: function() {
  6217. item.draw.apply(item, arguments);
  6218. }
  6219. }];
  6220. };
  6221. chart.boxes.push(item);
  6222. },
  6223. /**
  6224. * Remove a layoutItem from a chart
  6225. * @param {Chart} chart - the chart to remove the box from
  6226. * @param {ILayoutItem} layoutItem - the item to remove from the layout
  6227. */
  6228. removeBox: function(chart, layoutItem) {
  6229. var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1;
  6230. if (index !== -1) {
  6231. chart.boxes.splice(index, 1);
  6232. }
  6233. },
  6234. /**
  6235. * Sets (or updates) options on the given `item`.
  6236. * @param {Chart} chart - the chart in which the item lives (or will be added to)
  6237. * @param {ILayoutItem} item - the item to configure with the given options
  6238. * @param {object} options - the new item options.
  6239. */
  6240. configure: function(chart, item, options) {
  6241. var props = ['fullWidth', 'position', 'weight'];
  6242. var ilen = props.length;
  6243. var i = 0;
  6244. var prop;
  6245. for (; i < ilen; ++i) {
  6246. prop = props[i];
  6247. if (options.hasOwnProperty(prop)) {
  6248. item[prop] = options[prop];
  6249. }
  6250. }
  6251. },
  6252. /**
  6253. * Fits boxes of the given chart into the given size by having each box measure itself
  6254. * then running a fitting algorithm
  6255. * @param {Chart} chart - the chart
  6256. * @param {number} width - the width to fit into
  6257. * @param {number} height - the height to fit into
  6258. */
  6259. update: function(chart, width, height) {
  6260. if (!chart) {
  6261. return;
  6262. }
  6263. var layoutOptions = chart.options.layout || {};
  6264. var padding = helpers$1.options.toPadding(layoutOptions.padding);
  6265. var availableWidth = width - padding.width;
  6266. var availableHeight = height - padding.height;
  6267. var boxes = buildLayoutBoxes(chart.boxes);
  6268. var verticalBoxes = boxes.vertical;
  6269. var horizontalBoxes = boxes.horizontal;
  6270. // Essentially we now have any number of boxes on each of the 4 sides.
  6271. // Our canvas looks like the following.
  6272. // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and
  6273. // B1 is the bottom axis
  6274. // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays
  6275. // These locations are single-box locations only, when trying to register a chartArea location that is already taken,
  6276. // an error will be thrown.
  6277. //
  6278. // |----------------------------------------------------|
  6279. // | T1 (Full Width) |
  6280. // |----------------------------------------------------|
  6281. // | | | T2 | |
  6282. // | |----|-------------------------------------|----|
  6283. // | | | C1 | | C2 | |
  6284. // | | |----| |----| |
  6285. // | | | | |
  6286. // | L1 | L2 | ChartArea (C0) | R1 |
  6287. // | | | | |
  6288. // | | |----| |----| |
  6289. // | | | C3 | | C4 | |
  6290. // | |----|-------------------------------------|----|
  6291. // | | | B1 | |
  6292. // |----------------------------------------------------|
  6293. // | B2 (Full Width) |
  6294. // |----------------------------------------------------|
  6295. //
  6296. var params = Object.freeze({
  6297. outerWidth: width,
  6298. outerHeight: height,
  6299. padding: padding,
  6300. availableWidth: availableWidth,
  6301. vBoxMaxWidth: availableWidth / 2 / verticalBoxes.length,
  6302. hBoxMaxHeight: availableHeight / 2
  6303. });
  6304. var chartArea = extend({
  6305. maxPadding: extend({}, padding),
  6306. w: availableWidth,
  6307. h: availableHeight,
  6308. x: padding.left,
  6309. y: padding.top
  6310. }, padding);
  6311. setLayoutDims(verticalBoxes.concat(horizontalBoxes), params);
  6312. // First fit vertical boxes
  6313. fitBoxes(verticalBoxes, chartArea, params);
  6314. // Then fit horizontal boxes
  6315. if (fitBoxes(horizontalBoxes, chartArea, params)) {
  6316. // if the area changed, re-fit vertical boxes
  6317. fitBoxes(verticalBoxes, chartArea, params);
  6318. }
  6319. handleMaxPadding(chartArea);
  6320. // Finally place the boxes to correct coordinates
  6321. placeBoxes(boxes.leftAndTop, chartArea, params);
  6322. // Move to opposite side of chart
  6323. chartArea.x += chartArea.w;
  6324. chartArea.y += chartArea.h;
  6325. placeBoxes(boxes.rightAndBottom, chartArea, params);
  6326. chart.chartArea = {
  6327. left: chartArea.left,
  6328. top: chartArea.top,
  6329. right: chartArea.left + chartArea.w,
  6330. bottom: chartArea.top + chartArea.h
  6331. };
  6332. // Finally update boxes in chartArea (radial scale for example)
  6333. helpers$1.each(boxes.chartArea, function(layout) {
  6334. var box = layout.box;
  6335. extend(box, chart.chartArea);
  6336. box.update(chartArea.w, chartArea.h);
  6337. });
  6338. }
  6339. };
  6340. /**
  6341. * Platform fallback implementation (minimal).
  6342. * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939
  6343. */
  6344. var platform_basic = {
  6345. acquireContext: function(item) {
  6346. if (item && item.canvas) {
  6347. // Support for any object associated to a canvas (including a context2d)
  6348. item = item.canvas;
  6349. }
  6350. return item && item.getContext('2d') || null;
  6351. }
  6352. };
  6353. 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";
  6354. var platform_dom$1 = /*#__PURE__*/Object.freeze({
  6355. __proto__: null,
  6356. 'default': platform_dom
  6357. });
  6358. var stylesheet = getCjsExportFromNamespace(platform_dom$1);
  6359. var EXPANDO_KEY = '$chartjs';
  6360. var CSS_PREFIX = 'chartjs-';
  6361. var CSS_SIZE_MONITOR = CSS_PREFIX + 'size-monitor';
  6362. var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor';
  6363. var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation';
  6364. var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart'];
  6365. /**
  6366. * DOM event types -> Chart.js event types.
  6367. * Note: only events with different types are mapped.
  6368. * @see https://developer.mozilla.org/en-US/docs/Web/Events
  6369. */
  6370. var EVENT_TYPES = {
  6371. touchstart: 'mousedown',
  6372. touchmove: 'mousemove',
  6373. touchend: 'mouseup',
  6374. pointerenter: 'mouseenter',
  6375. pointerdown: 'mousedown',
  6376. pointermove: 'mousemove',
  6377. pointerup: 'mouseup',
  6378. pointerleave: 'mouseout',
  6379. pointerout: 'mouseout'
  6380. };
  6381. /**
  6382. * The "used" size is the final value of a dimension property after all calculations have
  6383. * been performed. This method uses the computed style of `element` but returns undefined
  6384. * if the computed style is not expressed in pixels. That can happen in some cases where
  6385. * `element` has a size relative to its parent and this last one is not yet displayed,
  6386. * for example because of `display: none` on a parent node.
  6387. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value
  6388. * @returns {number} Size in pixels or undefined if unknown.
  6389. */
  6390. function readUsedSize(element, property) {
  6391. var value = helpers$1.getStyle(element, property);
  6392. var matches = value && value.match(/^(\d+)(\.\d+)?px$/);
  6393. return matches ? Number(matches[1]) : undefined;
  6394. }
  6395. /**
  6396. * Initializes the canvas style and render size without modifying the canvas display size,
  6397. * since responsiveness is handled by the controller.resize() method. The config is used
  6398. * to determine the aspect ratio to apply in case no explicit height has been specified.
  6399. */
  6400. function initCanvas(canvas, config) {
  6401. var style = canvas.style;
  6402. // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it
  6403. // returns null or '' if no explicit value has been set to the canvas attribute.
  6404. var renderHeight = canvas.getAttribute('height');
  6405. var renderWidth = canvas.getAttribute('width');
  6406. // Chart.js modifies some canvas values that we want to restore on destroy
  6407. canvas[EXPANDO_KEY] = {
  6408. initial: {
  6409. height: renderHeight,
  6410. width: renderWidth,
  6411. style: {
  6412. display: style.display,
  6413. height: style.height,
  6414. width: style.width
  6415. }
  6416. }
  6417. };
  6418. // Force canvas to display as block to avoid extra space caused by inline
  6419. // elements, which would interfere with the responsive resize process.
  6420. // https://github.com/chartjs/Chart.js/issues/2538
  6421. style.display = style.display || 'block';
  6422. if (renderWidth === null || renderWidth === '') {
  6423. var displayWidth = readUsedSize(canvas, 'width');
  6424. if (displayWidth !== undefined) {
  6425. canvas.width = displayWidth;
  6426. }
  6427. }
  6428. if (renderHeight === null || renderHeight === '') {
  6429. if (canvas.style.height === '') {
  6430. // If no explicit render height and style height, let's apply the aspect ratio,
  6431. // which one can be specified by the user but also by charts as default option
  6432. // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2.
  6433. canvas.height = canvas.width / (config.options.aspectRatio || 2);
  6434. } else {
  6435. var displayHeight = readUsedSize(canvas, 'height');
  6436. if (displayWidth !== undefined) {
  6437. canvas.height = displayHeight;
  6438. }
  6439. }
  6440. }
  6441. return canvas;
  6442. }
  6443. /**
  6444. * Detects support for options object argument in addEventListener.
  6445. * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support
  6446. * @private
  6447. */
  6448. var supportsEventListenerOptions = (function() {
  6449. var supports = false;
  6450. try {
  6451. var options = Object.defineProperty({}, 'passive', {
  6452. // eslint-disable-next-line getter-return
  6453. get: function() {
  6454. supports = true;
  6455. }
  6456. });
  6457. window.addEventListener('e', null, options);
  6458. } catch (e) {
  6459. // continue regardless of error
  6460. }
  6461. return supports;
  6462. }());
  6463. // Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events.
  6464. // https://github.com/chartjs/Chart.js/issues/4287
  6465. var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false;
  6466. function addListener(node, type, listener) {
  6467. node.addEventListener(type, listener, eventListenerOptions);
  6468. }
  6469. function removeListener(node, type, listener) {
  6470. node.removeEventListener(type, listener, eventListenerOptions);
  6471. }
  6472. function createEvent(type, chart, x, y, nativeEvent) {
  6473. return {
  6474. type: type,
  6475. chart: chart,
  6476. native: nativeEvent || null,
  6477. x: x !== undefined ? x : null,
  6478. y: y !== undefined ? y : null,
  6479. };
  6480. }
  6481. function fromNativeEvent(event, chart) {
  6482. var type = EVENT_TYPES[event.type] || event.type;
  6483. var pos = helpers$1.getRelativePosition(event, chart);
  6484. return createEvent(type, chart, pos.x, pos.y, event);
  6485. }
  6486. function throttled(fn, thisArg) {
  6487. var ticking = false;
  6488. var args = [];
  6489. return function() {
  6490. args = Array.prototype.slice.call(arguments);
  6491. thisArg = thisArg || this;
  6492. if (!ticking) {
  6493. ticking = true;
  6494. helpers$1.requestAnimFrame.call(window, function() {
  6495. ticking = false;
  6496. fn.apply(thisArg, args);
  6497. });
  6498. }
  6499. };
  6500. }
  6501. function createDiv(cls) {
  6502. var el = document.createElement('div');
  6503. el.className = cls || '';
  6504. return el;
  6505. }
  6506. // Implementation based on https://github.com/marcj/css-element-queries
  6507. function createResizer(handler) {
  6508. var maxSize = 1000000;
  6509. // NOTE(SB) Don't use innerHTML because it could be considered unsafe.
  6510. // https://github.com/chartjs/Chart.js/issues/5902
  6511. var resizer = createDiv(CSS_SIZE_MONITOR);
  6512. var expand = createDiv(CSS_SIZE_MONITOR + '-expand');
  6513. var shrink = createDiv(CSS_SIZE_MONITOR + '-shrink');
  6514. expand.appendChild(createDiv());
  6515. shrink.appendChild(createDiv());
  6516. resizer.appendChild(expand);
  6517. resizer.appendChild(shrink);
  6518. resizer._reset = function() {
  6519. expand.scrollLeft = maxSize;
  6520. expand.scrollTop = maxSize;
  6521. shrink.scrollLeft = maxSize;
  6522. shrink.scrollTop = maxSize;
  6523. };
  6524. var onScroll = function() {
  6525. resizer._reset();
  6526. handler();
  6527. };
  6528. addListener(expand, 'scroll', onScroll.bind(expand, 'expand'));
  6529. addListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink'));
  6530. return resizer;
  6531. }
  6532. // https://davidwalsh.name/detect-node-insertion
  6533. function watchForRender(node, handler) {
  6534. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6535. var proxy = expando.renderProxy = function(e) {
  6536. if (e.animationName === CSS_RENDER_ANIMATION) {
  6537. handler();
  6538. }
  6539. };
  6540. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  6541. addListener(node, type, proxy);
  6542. });
  6543. // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class
  6544. // is removed then added back immediately (same animation frame?). Accessing the
  6545. // `offsetParent` property will force a reflow and re-evaluate the CSS animation.
  6546. // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics
  6547. // https://github.com/chartjs/Chart.js/issues/4737
  6548. expando.reflow = !!node.offsetParent;
  6549. node.classList.add(CSS_RENDER_MONITOR);
  6550. }
  6551. function unwatchForRender(node) {
  6552. var expando = node[EXPANDO_KEY] || {};
  6553. var proxy = expando.renderProxy;
  6554. if (proxy) {
  6555. helpers$1.each(ANIMATION_START_EVENTS, function(type) {
  6556. removeListener(node, type, proxy);
  6557. });
  6558. delete expando.renderProxy;
  6559. }
  6560. node.classList.remove(CSS_RENDER_MONITOR);
  6561. }
  6562. function addResizeListener(node, listener, chart) {
  6563. var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {});
  6564. // Let's keep track of this added resizer and thus avoid DOM query when removing it.
  6565. var resizer = expando.resizer = createResizer(throttled(function() {
  6566. if (expando.resizer) {
  6567. var container = chart.options.maintainAspectRatio && node.parentNode;
  6568. var w = container ? container.clientWidth : 0;
  6569. listener(createEvent('resize', chart));
  6570. if (container && container.clientWidth < w && chart.canvas) {
  6571. // If the container size shrank during chart resize, let's assume
  6572. // scrollbar appeared. So we resize again with the scrollbar visible -
  6573. // effectively making chart smaller and the scrollbar hidden again.
  6574. // Because we are inside `throttled`, and currently `ticking`, scroll
  6575. // events are ignored during this whole 2 resize process.
  6576. // If we assumed wrong and something else happened, we are resizing
  6577. // twice in a frame (potential performance issue)
  6578. listener(createEvent('resize', chart));
  6579. }
  6580. }
  6581. }));
  6582. // The resizer needs to be attached to the node parent, so we first need to be
  6583. // sure that `node` is attached to the DOM before injecting the resizer element.
  6584. watchForRender(node, function() {
  6585. if (expando.resizer) {
  6586. var container = node.parentNode;
  6587. if (container && container !== resizer.parentNode) {
  6588. container.insertBefore(resizer, container.firstChild);
  6589. }
  6590. // The container size might have changed, let's reset the resizer state.
  6591. resizer._reset();
  6592. }
  6593. });
  6594. }
  6595. function removeResizeListener(node) {
  6596. var expando = node[EXPANDO_KEY] || {};
  6597. var resizer = expando.resizer;
  6598. delete expando.resizer;
  6599. unwatchForRender(node);
  6600. if (resizer && resizer.parentNode) {
  6601. resizer.parentNode.removeChild(resizer);
  6602. }
  6603. }
  6604. /**
  6605. * Injects CSS styles inline if the styles are not already present.
  6606. * @param {HTMLDocument|ShadowRoot} rootNode - the node to contain the <style>.
  6607. * @param {string} css - the CSS to be injected.
  6608. */
  6609. function injectCSS(rootNode, css) {
  6610. // https://stackoverflow.com/q/3922139
  6611. var expando = rootNode[EXPANDO_KEY] || (rootNode[EXPANDO_KEY] = {});
  6612. if (!expando.containsStyles) {
  6613. expando.containsStyles = true;
  6614. css = '/* Chart.js */\n' + css;
  6615. var style = document.createElement('style');
  6616. style.setAttribute('type', 'text/css');
  6617. style.appendChild(document.createTextNode(css));
  6618. rootNode.appendChild(style);
  6619. }
  6620. }
  6621. var platform_dom$2 = {
  6622. /**
  6623. * When `true`, prevents the automatic injection of the stylesheet required to
  6624. * correctly detect when the chart is added to the DOM and then resized. This
  6625. * switch has been added to allow external stylesheet (`dist/Chart(.min)?.js`)
  6626. * to be manually imported to make this library compatible with any CSP.
  6627. * See https://github.com/chartjs/Chart.js/issues/5208
  6628. */
  6629. disableCSSInjection: false,
  6630. /**
  6631. * This property holds whether this platform is enabled for the current environment.
  6632. * Currently used by platform.js to select the proper implementation.
  6633. * @private
  6634. */
  6635. _enabled: typeof window !== 'undefined' && typeof document !== 'undefined',
  6636. /**
  6637. * Initializes resources that depend on platform options.
  6638. * @param {HTMLCanvasElement} canvas - The Canvas element.
  6639. * @private
  6640. */
  6641. _ensureLoaded: function(canvas) {
  6642. if (!this.disableCSSInjection) {
  6643. // If the canvas is in a shadow DOM, then the styles must also be inserted
  6644. // into the same shadow DOM.
  6645. // https://github.com/chartjs/Chart.js/issues/5763
  6646. var root = canvas.getRootNode ? canvas.getRootNode() : document;
  6647. var targetNode = root.host ? root : document.head;
  6648. injectCSS(targetNode, stylesheet);
  6649. }
  6650. },
  6651. acquireContext: function(item, config) {
  6652. if (typeof item === 'string') {
  6653. item = document.getElementById(item);
  6654. } else if (item.length) {
  6655. // Support for array based queries (such as jQuery)
  6656. item = item[0];
  6657. }
  6658. if (item && item.canvas) {
  6659. // Support for any object associated to a canvas (including a context2d)
  6660. item = item.canvas;
  6661. }
  6662. // To prevent canvas fingerprinting, some add-ons undefine the getContext
  6663. // method, for example: https://github.com/kkapsner/CanvasBlocker
  6664. // https://github.com/chartjs/Chart.js/issues/2807
  6665. var context = item && item.getContext && item.getContext('2d');
  6666. // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is
  6667. // inside an iframe or when running in a protected environment. We could guess the
  6668. // types from their toString() value but let's keep things flexible and assume it's
  6669. // a sufficient condition if the item has a context2D which has item as `canvas`.
  6670. // https://github.com/chartjs/Chart.js/issues/3887
  6671. // https://github.com/chartjs/Chart.js/issues/4102
  6672. // https://github.com/chartjs/Chart.js/issues/4152
  6673. if (context && context.canvas === item) {
  6674. // Load platform resources on first chart creation, to make it possible to
  6675. // import the library before setting platform options.
  6676. this._ensureLoaded(item);
  6677. initCanvas(item, config);
  6678. return context;
  6679. }
  6680. return null;
  6681. },
  6682. releaseContext: function(context) {
  6683. var canvas = context.canvas;
  6684. if (!canvas[EXPANDO_KEY]) {
  6685. return;
  6686. }
  6687. var initial = canvas[EXPANDO_KEY].initial;
  6688. ['height', 'width'].forEach(function(prop) {
  6689. var value = initial[prop];
  6690. if (helpers$1.isNullOrUndef(value)) {
  6691. canvas.removeAttribute(prop);
  6692. } else {
  6693. canvas.setAttribute(prop, value);
  6694. }
  6695. });
  6696. helpers$1.each(initial.style || {}, function(value, key) {
  6697. canvas.style[key] = value;
  6698. });
  6699. // The canvas render size might have been changed (and thus the state stack discarded),
  6700. // we can't use save() and restore() to restore the initial state. So make sure that at
  6701. // least the canvas context is reset to the default state by setting the canvas width.
  6702. // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
  6703. // eslint-disable-next-line no-self-assign
  6704. canvas.width = canvas.width;
  6705. delete canvas[EXPANDO_KEY];
  6706. },
  6707. addEventListener: function(chart, type, listener) {
  6708. var canvas = chart.canvas;
  6709. if (type === 'resize') {
  6710. // Note: the resize event is not supported on all browsers.
  6711. addResizeListener(canvas, listener, chart);
  6712. return;
  6713. }
  6714. var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {});
  6715. var proxies = expando.proxies || (expando.proxies = {});
  6716. var proxy = proxies[chart.id + '_' + type] = function(event) {
  6717. listener(fromNativeEvent(event, chart));
  6718. };
  6719. addListener(canvas, type, proxy);
  6720. },
  6721. removeEventListener: function(chart, type, listener) {
  6722. var canvas = chart.canvas;
  6723. if (type === 'resize') {
  6724. // Note: the resize event is not supported on all browsers.
  6725. removeResizeListener(canvas);
  6726. return;
  6727. }
  6728. var expando = listener[EXPANDO_KEY] || {};
  6729. var proxies = expando.proxies || {};
  6730. var proxy = proxies[chart.id + '_' + type];
  6731. if (!proxy) {
  6732. return;
  6733. }
  6734. removeListener(canvas, type, proxy);
  6735. }
  6736. };
  6737. // DEPRECATIONS
  6738. /**
  6739. * Provided for backward compatibility, use EventTarget.addEventListener instead.
  6740. * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6741. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  6742. * @function Chart.helpers.addEvent
  6743. * @deprecated since version 2.7.0
  6744. * @todo remove at version 3
  6745. * @private
  6746. */
  6747. helpers$1.addEvent = addListener;
  6748. /**
  6749. * Provided for backward compatibility, use EventTarget.removeEventListener instead.
  6750. * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+
  6751. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
  6752. * @function Chart.helpers.removeEvent
  6753. * @deprecated since version 2.7.0
  6754. * @todo remove at version 3
  6755. * @private
  6756. */
  6757. helpers$1.removeEvent = removeListener;
  6758. // @TODO Make possible to select another platform at build time.
  6759. var implementation = platform_dom$2._enabled ? platform_dom$2 : platform_basic;
  6760. /**
  6761. * @namespace Chart.platform
  6762. * @see https://chartjs.gitbooks.io/proposals/content/Platform.html
  6763. * @since 2.4.0
  6764. */
  6765. var platform = helpers$1.extend({
  6766. /**
  6767. * @since 2.7.0
  6768. */
  6769. initialize: function() {},
  6770. /**
  6771. * Called at chart construction time, returns a context2d instance implementing
  6772. * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}.
  6773. * @param {*} item - The native item from which to acquire context (platform specific)
  6774. * @param {object} options - The chart options
  6775. * @returns {CanvasRenderingContext2D} context2d instance
  6776. */
  6777. acquireContext: function() {},
  6778. /**
  6779. * Called at chart destruction time, releases any resources associated to the context
  6780. * previously returned by the acquireContext() method.
  6781. * @param {CanvasRenderingContext2D} context - The context2d instance
  6782. * @returns {boolean} true if the method succeeded, else false
  6783. */
  6784. releaseContext: function() {},
  6785. /**
  6786. * Registers the specified listener on the given chart.
  6787. * @param {Chart} chart - Chart from which to listen for event
  6788. * @param {string} type - The ({@link IEvent}) type to listen for
  6789. * @param {function} listener - Receives a notification (an object that implements
  6790. * the {@link IEvent} interface) when an event of the specified type occurs.
  6791. */
  6792. addEventListener: function() {},
  6793. /**
  6794. * Removes the specified listener previously registered with addEventListener.
  6795. * @param {Chart} chart - Chart from which to remove the listener
  6796. * @param {string} type - The ({@link IEvent}) type to remove
  6797. * @param {function} listener - The listener function to remove from the event target.
  6798. */
  6799. removeEventListener: function() {}
  6800. }, implementation);
  6801. core_defaults._set('global', {
  6802. plugins: {}
  6803. });
  6804. /**
  6805. * The plugin service singleton
  6806. * @namespace Chart.plugins
  6807. * @since 2.1.0
  6808. */
  6809. var core_plugins = {
  6810. /**
  6811. * Globally registered plugins.
  6812. * @private
  6813. */
  6814. _plugins: [],
  6815. /**
  6816. * This identifier is used to invalidate the descriptors cache attached to each chart
  6817. * when a global plugin is registered or unregistered. In this case, the cache ID is
  6818. * incremented and descriptors are regenerated during following API calls.
  6819. * @private
  6820. */
  6821. _cacheId: 0,
  6822. /**
  6823. * Registers the given plugin(s) if not already registered.
  6824. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6825. */
  6826. register: function(plugins) {
  6827. var p = this._plugins;
  6828. ([]).concat(plugins).forEach(function(plugin) {
  6829. if (p.indexOf(plugin) === -1) {
  6830. p.push(plugin);
  6831. }
  6832. });
  6833. this._cacheId++;
  6834. },
  6835. /**
  6836. * Unregisters the given plugin(s) only if registered.
  6837. * @param {IPlugin[]|IPlugin} plugins plugin instance(s).
  6838. */
  6839. unregister: function(plugins) {
  6840. var p = this._plugins;
  6841. ([]).concat(plugins).forEach(function(plugin) {
  6842. var idx = p.indexOf(plugin);
  6843. if (idx !== -1) {
  6844. p.splice(idx, 1);
  6845. }
  6846. });
  6847. this._cacheId++;
  6848. },
  6849. /**
  6850. * Remove all registered plugins.
  6851. * @since 2.1.5
  6852. */
  6853. clear: function() {
  6854. this._plugins = [];
  6855. this._cacheId++;
  6856. },
  6857. /**
  6858. * Returns the number of registered plugins?
  6859. * @returns {number}
  6860. * @since 2.1.5
  6861. */
  6862. count: function() {
  6863. return this._plugins.length;
  6864. },
  6865. /**
  6866. * Returns all registered plugin instances.
  6867. * @returns {IPlugin[]} array of plugin objects.
  6868. * @since 2.1.5
  6869. */
  6870. getAll: function() {
  6871. return this._plugins;
  6872. },
  6873. /**
  6874. * Calls enabled plugins for `chart` on the specified hook and with the given args.
  6875. * This method immediately returns as soon as a plugin explicitly returns false. The
  6876. * returned value can be used, for instance, to interrupt the current action.
  6877. * @param {Chart} chart - The chart instance for which plugins should be called.
  6878. * @param {string} hook - The name of the plugin method to call (e.g. 'beforeUpdate').
  6879. * @param {Array} [args] - Extra arguments to apply to the hook call.
  6880. * @returns {boolean} false if any of the plugins return false, else returns true.
  6881. */
  6882. notify: function(chart, hook, args) {
  6883. var descriptors = this.descriptors(chart);
  6884. var ilen = descriptors.length;
  6885. var i, descriptor, plugin, params, method;
  6886. for (i = 0; i < ilen; ++i) {
  6887. descriptor = descriptors[i];
  6888. plugin = descriptor.plugin;
  6889. method = plugin[hook];
  6890. if (typeof method === 'function') {
  6891. params = [chart].concat(args || []);
  6892. params.push(descriptor.options);
  6893. if (method.apply(plugin, params) === false) {
  6894. return false;
  6895. }
  6896. }
  6897. }
  6898. return true;
  6899. },
  6900. /**
  6901. * Returns descriptors of enabled plugins for the given chart.
  6902. * @returns {object[]} [{ plugin, options }]
  6903. * @private
  6904. */
  6905. descriptors: function(chart) {
  6906. var cache = chart.$plugins || (chart.$plugins = {});
  6907. if (cache.id === this._cacheId) {
  6908. return cache.descriptors;
  6909. }
  6910. var plugins = [];
  6911. var descriptors = [];
  6912. var config = (chart && chart.config) || {};
  6913. var options = (config.options && config.options.plugins) || {};
  6914. this._plugins.concat(config.plugins || []).forEach(function(plugin) {
  6915. var idx = plugins.indexOf(plugin);
  6916. if (idx !== -1) {
  6917. return;
  6918. }
  6919. var id = plugin.id;
  6920. var opts = options[id];
  6921. if (opts === false) {
  6922. return;
  6923. }
  6924. if (opts === true) {
  6925. opts = helpers$1.clone(core_defaults.global.plugins[id]);
  6926. }
  6927. plugins.push(plugin);
  6928. descriptors.push({
  6929. plugin: plugin,
  6930. options: opts || {}
  6931. });
  6932. });
  6933. cache.descriptors = descriptors;
  6934. cache.id = this._cacheId;
  6935. return descriptors;
  6936. },
  6937. /**
  6938. * Invalidates cache for the given chart: descriptors hold a reference on plugin option,
  6939. * but in some cases, this reference can be changed by the user when updating options.
  6940. * https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  6941. * @private
  6942. */
  6943. _invalidate: function(chart) {
  6944. delete chart.$plugins;
  6945. }
  6946. };
  6947. var core_scaleService = {
  6948. // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then
  6949. // use the new chart options to grab the correct scale
  6950. constructors: {},
  6951. // Use a registration function so that we can move to an ES6 map when we no longer need to support
  6952. // old browsers
  6953. // Scale config defaults
  6954. defaults: {},
  6955. registerScaleType: function(type, scaleConstructor, scaleDefaults) {
  6956. this.constructors[type] = scaleConstructor;
  6957. this.defaults[type] = helpers$1.clone(scaleDefaults);
  6958. },
  6959. getScaleConstructor: function(type) {
  6960. return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined;
  6961. },
  6962. getScaleDefaults: function(type) {
  6963. // Return the scale defaults merged with the global settings so that we always use the latest ones
  6964. return this.defaults.hasOwnProperty(type) ? helpers$1.merge({}, [core_defaults.scale, this.defaults[type]]) : {};
  6965. },
  6966. updateScaleDefaults: function(type, additions) {
  6967. var me = this;
  6968. if (me.defaults.hasOwnProperty(type)) {
  6969. me.defaults[type] = helpers$1.extend(me.defaults[type], additions);
  6970. }
  6971. },
  6972. addScalesToLayout: function(chart) {
  6973. // Adds each scale to the chart.boxes array to be sized accordingly
  6974. helpers$1.each(chart.scales, function(scale) {
  6975. // Set ILayoutItem parameters for backwards compatibility
  6976. scale.fullWidth = scale.options.fullWidth;
  6977. scale.position = scale.options.position;
  6978. scale.weight = scale.options.weight;
  6979. core_layouts.addBox(chart, scale);
  6980. });
  6981. }
  6982. };
  6983. var valueOrDefault$8 = helpers$1.valueOrDefault;
  6984. var getRtlHelper = helpers$1.rtl.getRtlAdapter;
  6985. core_defaults._set('global', {
  6986. tooltips: {
  6987. enabled: true,
  6988. custom: null,
  6989. mode: 'nearest',
  6990. position: 'average',
  6991. intersect: true,
  6992. backgroundColor: 'rgba(0,0,0,0.8)',
  6993. titleFontStyle: 'bold',
  6994. titleSpacing: 2,
  6995. titleMarginBottom: 6,
  6996. titleFontColor: '#fff',
  6997. titleAlign: 'left',
  6998. bodySpacing: 2,
  6999. bodyFontColor: '#fff',
  7000. bodyAlign: 'left',
  7001. footerFontStyle: 'bold',
  7002. footerSpacing: 2,
  7003. footerMarginTop: 6,
  7004. footerFontColor: '#fff',
  7005. footerAlign: 'left',
  7006. yPadding: 6,
  7007. xPadding: 6,
  7008. caretPadding: 2,
  7009. caretSize: 5,
  7010. cornerRadius: 6,
  7011. multiKeyBackground: '#fff',
  7012. displayColors: true,
  7013. borderColor: 'rgba(0,0,0,0)',
  7014. borderWidth: 0,
  7015. callbacks: {
  7016. // Args are: (tooltipItems, data)
  7017. beforeTitle: helpers$1.noop,
  7018. title: function(tooltipItems, data) {
  7019. var title = '';
  7020. var labels = data.labels;
  7021. var labelCount = labels ? labels.length : 0;
  7022. if (tooltipItems.length > 0) {
  7023. var item = tooltipItems[0];
  7024. if (item.label) {
  7025. title = item.label;
  7026. } else if (item.xLabel) {
  7027. title = item.xLabel;
  7028. } else if (labelCount > 0 && item.index < labelCount) {
  7029. title = labels[item.index];
  7030. }
  7031. }
  7032. return title;
  7033. },
  7034. afterTitle: helpers$1.noop,
  7035. // Args are: (tooltipItems, data)
  7036. beforeBody: helpers$1.noop,
  7037. // Args are: (tooltipItem, data)
  7038. beforeLabel: helpers$1.noop,
  7039. label: function(tooltipItem, data) {
  7040. var label = data.datasets[tooltipItem.datasetIndex].label || '';
  7041. if (label) {
  7042. label += ': ';
  7043. }
  7044. if (!helpers$1.isNullOrUndef(tooltipItem.value)) {
  7045. label += tooltipItem.value;
  7046. } else {
  7047. label += tooltipItem.yLabel;
  7048. }
  7049. return label;
  7050. },
  7051. labelColor: function(tooltipItem, chart) {
  7052. var meta = chart.getDatasetMeta(tooltipItem.datasetIndex);
  7053. var activeElement = meta.data[tooltipItem.index];
  7054. var view = activeElement._view;
  7055. return {
  7056. borderColor: view.borderColor,
  7057. backgroundColor: view.backgroundColor
  7058. };
  7059. },
  7060. labelTextColor: function() {
  7061. return this._options.bodyFontColor;
  7062. },
  7063. afterLabel: helpers$1.noop,
  7064. // Args are: (tooltipItems, data)
  7065. afterBody: helpers$1.noop,
  7066. // Args are: (tooltipItems, data)
  7067. beforeFooter: helpers$1.noop,
  7068. footer: helpers$1.noop,
  7069. afterFooter: helpers$1.noop
  7070. }
  7071. }
  7072. });
  7073. var positioners = {
  7074. /**
  7075. * Average mode places the tooltip at the average position of the elements shown
  7076. * @function Chart.Tooltip.positioners.average
  7077. * @param elements {ChartElement[]} the elements being displayed in the tooltip
  7078. * @returns {object} tooltip position
  7079. */
  7080. average: function(elements) {
  7081. if (!elements.length) {
  7082. return false;
  7083. }
  7084. var i, len;
  7085. var x = 0;
  7086. var y = 0;
  7087. var count = 0;
  7088. for (i = 0, len = elements.length; i < len; ++i) {
  7089. var el = elements[i];
  7090. if (el && el.hasValue()) {
  7091. var pos = el.tooltipPosition();
  7092. x += pos.x;
  7093. y += pos.y;
  7094. ++count;
  7095. }
  7096. }
  7097. return {
  7098. x: x / count,
  7099. y: y / count
  7100. };
  7101. },
  7102. /**
  7103. * Gets the tooltip position nearest of the item nearest to the event position
  7104. * @function Chart.Tooltip.positioners.nearest
  7105. * @param elements {Chart.Element[]} the tooltip elements
  7106. * @param eventPosition {object} the position of the event in canvas coordinates
  7107. * @returns {object} the tooltip position
  7108. */
  7109. nearest: function(elements, eventPosition) {
  7110. var x = eventPosition.x;
  7111. var y = eventPosition.y;
  7112. var minDistance = Number.POSITIVE_INFINITY;
  7113. var i, len, nearestElement;
  7114. for (i = 0, len = elements.length; i < len; ++i) {
  7115. var el = elements[i];
  7116. if (el && el.hasValue()) {
  7117. var center = el.getCenterPoint();
  7118. var d = helpers$1.distanceBetweenPoints(eventPosition, center);
  7119. if (d < minDistance) {
  7120. minDistance = d;
  7121. nearestElement = el;
  7122. }
  7123. }
  7124. }
  7125. if (nearestElement) {
  7126. var tp = nearestElement.tooltipPosition();
  7127. x = tp.x;
  7128. y = tp.y;
  7129. }
  7130. return {
  7131. x: x,
  7132. y: y
  7133. };
  7134. }
  7135. };
  7136. // Helper to push or concat based on if the 2nd parameter is an array or not
  7137. function pushOrConcat(base, toPush) {
  7138. if (toPush) {
  7139. if (helpers$1.isArray(toPush)) {
  7140. // base = base.concat(toPush);
  7141. Array.prototype.push.apply(base, toPush);
  7142. } else {
  7143. base.push(toPush);
  7144. }
  7145. }
  7146. return base;
  7147. }
  7148. /**
  7149. * Returns array of strings split by newline
  7150. * @param {string} value - The value to split by newline.
  7151. * @returns {string[]} value if newline present - Returned from String split() method
  7152. * @function
  7153. */
  7154. function splitNewlines(str) {
  7155. if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) {
  7156. return str.split('\n');
  7157. }
  7158. return str;
  7159. }
  7160. /**
  7161. * Private helper to create a tooltip item model
  7162. * @param element - the chart element (point, arc, bar) to create the tooltip item for
  7163. * @return new tooltip item
  7164. */
  7165. function createTooltipItem(element) {
  7166. var xScale = element._xScale;
  7167. var yScale = element._yScale || element._scale; // handle radar || polarArea charts
  7168. var index = element._index;
  7169. var datasetIndex = element._datasetIndex;
  7170. var controller = element._chart.getDatasetMeta(datasetIndex).controller;
  7171. var indexScale = controller._getIndexScale();
  7172. var valueScale = controller._getValueScale();
  7173. return {
  7174. xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '',
  7175. yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '',
  7176. label: indexScale ? '' + indexScale.getLabelForIndex(index, datasetIndex) : '',
  7177. value: valueScale ? '' + valueScale.getLabelForIndex(index, datasetIndex) : '',
  7178. index: index,
  7179. datasetIndex: datasetIndex,
  7180. x: element._model.x,
  7181. y: element._model.y
  7182. };
  7183. }
  7184. /**
  7185. * Helper to get the reset model for the tooltip
  7186. * @param tooltipOpts {object} the tooltip options
  7187. */
  7188. function getBaseModel(tooltipOpts) {
  7189. var globalDefaults = core_defaults.global;
  7190. return {
  7191. // Positioning
  7192. xPadding: tooltipOpts.xPadding,
  7193. yPadding: tooltipOpts.yPadding,
  7194. xAlign: tooltipOpts.xAlign,
  7195. yAlign: tooltipOpts.yAlign,
  7196. // Drawing direction and text direction
  7197. rtl: tooltipOpts.rtl,
  7198. textDirection: tooltipOpts.textDirection,
  7199. // Body
  7200. bodyFontColor: tooltipOpts.bodyFontColor,
  7201. _bodyFontFamily: valueOrDefault$8(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily),
  7202. _bodyFontStyle: valueOrDefault$8(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle),
  7203. _bodyAlign: tooltipOpts.bodyAlign,
  7204. bodyFontSize: valueOrDefault$8(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize),
  7205. bodySpacing: tooltipOpts.bodySpacing,
  7206. // Title
  7207. titleFontColor: tooltipOpts.titleFontColor,
  7208. _titleFontFamily: valueOrDefault$8(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily),
  7209. _titleFontStyle: valueOrDefault$8(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle),
  7210. titleFontSize: valueOrDefault$8(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize),
  7211. _titleAlign: tooltipOpts.titleAlign,
  7212. titleSpacing: tooltipOpts.titleSpacing,
  7213. titleMarginBottom: tooltipOpts.titleMarginBottom,
  7214. // Footer
  7215. footerFontColor: tooltipOpts.footerFontColor,
  7216. _footerFontFamily: valueOrDefault$8(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily),
  7217. _footerFontStyle: valueOrDefault$8(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle),
  7218. footerFontSize: valueOrDefault$8(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize),
  7219. _footerAlign: tooltipOpts.footerAlign,
  7220. footerSpacing: tooltipOpts.footerSpacing,
  7221. footerMarginTop: tooltipOpts.footerMarginTop,
  7222. // Appearance
  7223. caretSize: tooltipOpts.caretSize,
  7224. cornerRadius: tooltipOpts.cornerRadius,
  7225. backgroundColor: tooltipOpts.backgroundColor,
  7226. opacity: 0,
  7227. legendColorBackground: tooltipOpts.multiKeyBackground,
  7228. displayColors: tooltipOpts.displayColors,
  7229. borderColor: tooltipOpts.borderColor,
  7230. borderWidth: tooltipOpts.borderWidth
  7231. };
  7232. }
  7233. /**
  7234. * Get the size of the tooltip
  7235. */
  7236. function getTooltipSize(tooltip, model) {
  7237. var ctx = tooltip._chart.ctx;
  7238. var height = model.yPadding * 2; // Tooltip Padding
  7239. var width = 0;
  7240. // Count of all lines in the body
  7241. var body = model.body;
  7242. var combinedBodyLength = body.reduce(function(count, bodyItem) {
  7243. return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length;
  7244. }, 0);
  7245. combinedBodyLength += model.beforeBody.length + model.afterBody.length;
  7246. var titleLineCount = model.title.length;
  7247. var footerLineCount = model.footer.length;
  7248. var titleFontSize = model.titleFontSize;
  7249. var bodyFontSize = model.bodyFontSize;
  7250. var footerFontSize = model.footerFontSize;
  7251. height += titleLineCount * titleFontSize; // Title Lines
  7252. height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing
  7253. height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin
  7254. height += combinedBodyLength * bodyFontSize; // Body Lines
  7255. height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing
  7256. height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin
  7257. height += footerLineCount * (footerFontSize); // Footer Lines
  7258. height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing
  7259. // Title width
  7260. var widthPadding = 0;
  7261. var maxLineWidth = function(line) {
  7262. width = Math.max(width, ctx.measureText(line).width + widthPadding);
  7263. };
  7264. ctx.font = helpers$1.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily);
  7265. helpers$1.each(model.title, maxLineWidth);
  7266. // Body width
  7267. ctx.font = helpers$1.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily);
  7268. helpers$1.each(model.beforeBody.concat(model.afterBody), maxLineWidth);
  7269. // Body lines may include some extra width due to the color box
  7270. widthPadding = model.displayColors ? (bodyFontSize + 2) : 0;
  7271. helpers$1.each(body, function(bodyItem) {
  7272. helpers$1.each(bodyItem.before, maxLineWidth);
  7273. helpers$1.each(bodyItem.lines, maxLineWidth);
  7274. helpers$1.each(bodyItem.after, maxLineWidth);
  7275. });
  7276. // Reset back to 0
  7277. widthPadding = 0;
  7278. // Footer width
  7279. ctx.font = helpers$1.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily);
  7280. helpers$1.each(model.footer, maxLineWidth);
  7281. // Add padding
  7282. width += 2 * model.xPadding;
  7283. return {
  7284. width: width,
  7285. height: height
  7286. };
  7287. }
  7288. /**
  7289. * Helper to get the alignment of a tooltip given the size
  7290. */
  7291. function determineAlignment(tooltip, size) {
  7292. var model = tooltip._model;
  7293. var chart = tooltip._chart;
  7294. var chartArea = tooltip._chart.chartArea;
  7295. var xAlign = 'center';
  7296. var yAlign = 'center';
  7297. if (model.y < size.height) {
  7298. yAlign = 'top';
  7299. } else if (model.y > (chart.height - size.height)) {
  7300. yAlign = 'bottom';
  7301. }
  7302. var lf, rf; // functions to determine left, right alignment
  7303. var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart
  7304. var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges
  7305. var midX = (chartArea.left + chartArea.right) / 2;
  7306. var midY = (chartArea.top + chartArea.bottom) / 2;
  7307. if (yAlign === 'center') {
  7308. lf = function(x) {
  7309. return x <= midX;
  7310. };
  7311. rf = function(x) {
  7312. return x > midX;
  7313. };
  7314. } else {
  7315. lf = function(x) {
  7316. return x <= (size.width / 2);
  7317. };
  7318. rf = function(x) {
  7319. return x >= (chart.width - (size.width / 2));
  7320. };
  7321. }
  7322. olf = function(x) {
  7323. return x + size.width + model.caretSize + model.caretPadding > chart.width;
  7324. };
  7325. orf = function(x) {
  7326. return x - size.width - model.caretSize - model.caretPadding < 0;
  7327. };
  7328. yf = function(y) {
  7329. return y <= midY ? 'top' : 'bottom';
  7330. };
  7331. if (lf(model.x)) {
  7332. xAlign = 'left';
  7333. // Is tooltip too wide and goes over the right side of the chart.?
  7334. if (olf(model.x)) {
  7335. xAlign = 'center';
  7336. yAlign = yf(model.y);
  7337. }
  7338. } else if (rf(model.x)) {
  7339. xAlign = 'right';
  7340. // Is tooltip too wide and goes outside left edge of canvas?
  7341. if (orf(model.x)) {
  7342. xAlign = 'center';
  7343. yAlign = yf(model.y);
  7344. }
  7345. }
  7346. var opts = tooltip._options;
  7347. return {
  7348. xAlign: opts.xAlign ? opts.xAlign : xAlign,
  7349. yAlign: opts.yAlign ? opts.yAlign : yAlign
  7350. };
  7351. }
  7352. /**
  7353. * Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment
  7354. */
  7355. function getBackgroundPoint(vm, size, alignment, chart) {
  7356. // Background Position
  7357. var x = vm.x;
  7358. var y = vm.y;
  7359. var caretSize = vm.caretSize;
  7360. var caretPadding = vm.caretPadding;
  7361. var cornerRadius = vm.cornerRadius;
  7362. var xAlign = alignment.xAlign;
  7363. var yAlign = alignment.yAlign;
  7364. var paddingAndSize = caretSize + caretPadding;
  7365. var radiusAndPadding = cornerRadius + caretPadding;
  7366. if (xAlign === 'right') {
  7367. x -= size.width;
  7368. } else if (xAlign === 'center') {
  7369. x -= (size.width / 2);
  7370. if (x + size.width > chart.width) {
  7371. x = chart.width - size.width;
  7372. }
  7373. if (x < 0) {
  7374. x = 0;
  7375. }
  7376. }
  7377. if (yAlign === 'top') {
  7378. y += paddingAndSize;
  7379. } else if (yAlign === 'bottom') {
  7380. y -= size.height + paddingAndSize;
  7381. } else {
  7382. y -= (size.height / 2);
  7383. }
  7384. if (yAlign === 'center') {
  7385. if (xAlign === 'left') {
  7386. x += paddingAndSize;
  7387. } else if (xAlign === 'right') {
  7388. x -= paddingAndSize;
  7389. }
  7390. } else if (xAlign === 'left') {
  7391. x -= radiusAndPadding;
  7392. } else if (xAlign === 'right') {
  7393. x += radiusAndPadding;
  7394. }
  7395. return {
  7396. x: x,
  7397. y: y
  7398. };
  7399. }
  7400. function getAlignedX(vm, align) {
  7401. return align === 'center'
  7402. ? vm.x + vm.width / 2
  7403. : align === 'right'
  7404. ? vm.x + vm.width - vm.xPadding
  7405. : vm.x + vm.xPadding;
  7406. }
  7407. /**
  7408. * Helper to build before and after body lines
  7409. */
  7410. function getBeforeAfterBodyLines(callback) {
  7411. return pushOrConcat([], splitNewlines(callback));
  7412. }
  7413. var exports$4 = core_element.extend({
  7414. initialize: function() {
  7415. this._model = getBaseModel(this._options);
  7416. this._lastActive = [];
  7417. },
  7418. // Get the title
  7419. // Args are: (tooltipItem, data)
  7420. getTitle: function() {
  7421. var me = this;
  7422. var opts = me._options;
  7423. var callbacks = opts.callbacks;
  7424. var beforeTitle = callbacks.beforeTitle.apply(me, arguments);
  7425. var title = callbacks.title.apply(me, arguments);
  7426. var afterTitle = callbacks.afterTitle.apply(me, arguments);
  7427. var lines = [];
  7428. lines = pushOrConcat(lines, splitNewlines(beforeTitle));
  7429. lines = pushOrConcat(lines, splitNewlines(title));
  7430. lines = pushOrConcat(lines, splitNewlines(afterTitle));
  7431. return lines;
  7432. },
  7433. // Args are: (tooltipItem, data)
  7434. getBeforeBody: function() {
  7435. return getBeforeAfterBodyLines(this._options.callbacks.beforeBody.apply(this, arguments));
  7436. },
  7437. // Args are: (tooltipItem, data)
  7438. getBody: function(tooltipItems, data) {
  7439. var me = this;
  7440. var callbacks = me._options.callbacks;
  7441. var bodyItems = [];
  7442. helpers$1.each(tooltipItems, function(tooltipItem) {
  7443. var bodyItem = {
  7444. before: [],
  7445. lines: [],
  7446. after: []
  7447. };
  7448. pushOrConcat(bodyItem.before, splitNewlines(callbacks.beforeLabel.call(me, tooltipItem, data)));
  7449. pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data));
  7450. pushOrConcat(bodyItem.after, splitNewlines(callbacks.afterLabel.call(me, tooltipItem, data)));
  7451. bodyItems.push(bodyItem);
  7452. });
  7453. return bodyItems;
  7454. },
  7455. // Args are: (tooltipItem, data)
  7456. getAfterBody: function() {
  7457. return getBeforeAfterBodyLines(this._options.callbacks.afterBody.apply(this, arguments));
  7458. },
  7459. // Get the footer and beforeFooter and afterFooter lines
  7460. // Args are: (tooltipItem, data)
  7461. getFooter: function() {
  7462. var me = this;
  7463. var callbacks = me._options.callbacks;
  7464. var beforeFooter = callbacks.beforeFooter.apply(me, arguments);
  7465. var footer = callbacks.footer.apply(me, arguments);
  7466. var afterFooter = callbacks.afterFooter.apply(me, arguments);
  7467. var lines = [];
  7468. lines = pushOrConcat(lines, splitNewlines(beforeFooter));
  7469. lines = pushOrConcat(lines, splitNewlines(footer));
  7470. lines = pushOrConcat(lines, splitNewlines(afterFooter));
  7471. return lines;
  7472. },
  7473. update: function(changed) {
  7474. var me = this;
  7475. var opts = me._options;
  7476. // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition
  7477. // 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
  7478. // which breaks any animations.
  7479. var existingModel = me._model;
  7480. var model = me._model = getBaseModel(opts);
  7481. var active = me._active;
  7482. var data = me._data;
  7483. // In the case where active.length === 0 we need to keep these at existing values for good animations
  7484. var alignment = {
  7485. xAlign: existingModel.xAlign,
  7486. yAlign: existingModel.yAlign
  7487. };
  7488. var backgroundPoint = {
  7489. x: existingModel.x,
  7490. y: existingModel.y
  7491. };
  7492. var tooltipSize = {
  7493. width: existingModel.width,
  7494. height: existingModel.height
  7495. };
  7496. var tooltipPosition = {
  7497. x: existingModel.caretX,
  7498. y: existingModel.caretY
  7499. };
  7500. var i, len;
  7501. if (active.length) {
  7502. model.opacity = 1;
  7503. var labelColors = [];
  7504. var labelTextColors = [];
  7505. tooltipPosition = positioners[opts.position].call(me, active, me._eventPosition);
  7506. var tooltipItems = [];
  7507. for (i = 0, len = active.length; i < len; ++i) {
  7508. tooltipItems.push(createTooltipItem(active[i]));
  7509. }
  7510. // If the user provided a filter function, use it to modify the tooltip items
  7511. if (opts.filter) {
  7512. tooltipItems = tooltipItems.filter(function(a) {
  7513. return opts.filter(a, data);
  7514. });
  7515. }
  7516. // If the user provided a sorting function, use it to modify the tooltip items
  7517. if (opts.itemSort) {
  7518. tooltipItems = tooltipItems.sort(function(a, b) {
  7519. return opts.itemSort(a, b, data);
  7520. });
  7521. }
  7522. // Determine colors for boxes
  7523. helpers$1.each(tooltipItems, function(tooltipItem) {
  7524. labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart));
  7525. labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart));
  7526. });
  7527. // Build the Text Lines
  7528. model.title = me.getTitle(tooltipItems, data);
  7529. model.beforeBody = me.getBeforeBody(tooltipItems, data);
  7530. model.body = me.getBody(tooltipItems, data);
  7531. model.afterBody = me.getAfterBody(tooltipItems, data);
  7532. model.footer = me.getFooter(tooltipItems, data);
  7533. // Initial positioning and colors
  7534. model.x = tooltipPosition.x;
  7535. model.y = tooltipPosition.y;
  7536. model.caretPadding = opts.caretPadding;
  7537. model.labelColors = labelColors;
  7538. model.labelTextColors = labelTextColors;
  7539. // data points
  7540. model.dataPoints = tooltipItems;
  7541. // We need to determine alignment of the tooltip
  7542. tooltipSize = getTooltipSize(this, model);
  7543. alignment = determineAlignment(this, tooltipSize);
  7544. // Final Size and Position
  7545. backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment, me._chart);
  7546. } else {
  7547. model.opacity = 0;
  7548. }
  7549. model.xAlign = alignment.xAlign;
  7550. model.yAlign = alignment.yAlign;
  7551. model.x = backgroundPoint.x;
  7552. model.y = backgroundPoint.y;
  7553. model.width = tooltipSize.width;
  7554. model.height = tooltipSize.height;
  7555. // Point where the caret on the tooltip points to
  7556. model.caretX = tooltipPosition.x;
  7557. model.caretY = tooltipPosition.y;
  7558. me._model = model;
  7559. if (changed && opts.custom) {
  7560. opts.custom.call(me, model);
  7561. }
  7562. return me;
  7563. },
  7564. drawCaret: function(tooltipPoint, size) {
  7565. var ctx = this._chart.ctx;
  7566. var vm = this._view;
  7567. var caretPosition = this.getCaretPosition(tooltipPoint, size, vm);
  7568. ctx.lineTo(caretPosition.x1, caretPosition.y1);
  7569. ctx.lineTo(caretPosition.x2, caretPosition.y2);
  7570. ctx.lineTo(caretPosition.x3, caretPosition.y3);
  7571. },
  7572. getCaretPosition: function(tooltipPoint, size, vm) {
  7573. var x1, x2, x3, y1, y2, y3;
  7574. var caretSize = vm.caretSize;
  7575. var cornerRadius = vm.cornerRadius;
  7576. var xAlign = vm.xAlign;
  7577. var yAlign = vm.yAlign;
  7578. var ptX = tooltipPoint.x;
  7579. var ptY = tooltipPoint.y;
  7580. var width = size.width;
  7581. var height = size.height;
  7582. if (yAlign === 'center') {
  7583. y2 = ptY + (height / 2);
  7584. if (xAlign === 'left') {
  7585. x1 = ptX;
  7586. x2 = x1 - caretSize;
  7587. x3 = x1;
  7588. y1 = y2 + caretSize;
  7589. y3 = y2 - caretSize;
  7590. } else {
  7591. x1 = ptX + width;
  7592. x2 = x1 + caretSize;
  7593. x3 = x1;
  7594. y1 = y2 - caretSize;
  7595. y3 = y2 + caretSize;
  7596. }
  7597. } else {
  7598. if (xAlign === 'left') {
  7599. x2 = ptX + cornerRadius + (caretSize);
  7600. x1 = x2 - caretSize;
  7601. x3 = x2 + caretSize;
  7602. } else if (xAlign === 'right') {
  7603. x2 = ptX + width - cornerRadius - caretSize;
  7604. x1 = x2 - caretSize;
  7605. x3 = x2 + caretSize;
  7606. } else {
  7607. x2 = vm.caretX;
  7608. x1 = x2 - caretSize;
  7609. x3 = x2 + caretSize;
  7610. }
  7611. if (yAlign === 'top') {
  7612. y1 = ptY;
  7613. y2 = y1 - caretSize;
  7614. y3 = y1;
  7615. } else {
  7616. y1 = ptY + height;
  7617. y2 = y1 + caretSize;
  7618. y3 = y1;
  7619. // invert drawing order
  7620. var tmp = x3;
  7621. x3 = x1;
  7622. x1 = tmp;
  7623. }
  7624. }
  7625. return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3};
  7626. },
  7627. drawTitle: function(pt, vm, ctx) {
  7628. var title = vm.title;
  7629. var length = title.length;
  7630. var titleFontSize, titleSpacing, i;
  7631. if (length) {
  7632. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7633. pt.x = getAlignedX(vm, vm._titleAlign);
  7634. ctx.textAlign = rtlHelper.textAlign(vm._titleAlign);
  7635. ctx.textBaseline = 'middle';
  7636. titleFontSize = vm.titleFontSize;
  7637. titleSpacing = vm.titleSpacing;
  7638. ctx.fillStyle = vm.titleFontColor;
  7639. ctx.font = helpers$1.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily);
  7640. for (i = 0; i < length; ++i) {
  7641. ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFontSize / 2);
  7642. pt.y += titleFontSize + titleSpacing; // Line Height and spacing
  7643. if (i + 1 === length) {
  7644. pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing
  7645. }
  7646. }
  7647. }
  7648. },
  7649. drawBody: function(pt, vm, ctx) {
  7650. var bodyFontSize = vm.bodyFontSize;
  7651. var bodySpacing = vm.bodySpacing;
  7652. var bodyAlign = vm._bodyAlign;
  7653. var body = vm.body;
  7654. var drawColorBoxes = vm.displayColors;
  7655. var xLinePadding = 0;
  7656. var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0;
  7657. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7658. var fillLineOfText = function(line) {
  7659. ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyFontSize / 2);
  7660. pt.y += bodyFontSize + bodySpacing;
  7661. };
  7662. var bodyItem, textColor, labelColors, lines, i, j, ilen, jlen;
  7663. var bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign);
  7664. ctx.textAlign = bodyAlign;
  7665. ctx.textBaseline = 'middle';
  7666. ctx.font = helpers$1.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily);
  7667. pt.x = getAlignedX(vm, bodyAlignForCalculation);
  7668. // Before body lines
  7669. ctx.fillStyle = vm.bodyFontColor;
  7670. helpers$1.each(vm.beforeBody, fillLineOfText);
  7671. xLinePadding = drawColorBoxes && bodyAlignForCalculation !== 'right'
  7672. ? bodyAlign === 'center' ? (bodyFontSize / 2 + 1) : (bodyFontSize + 2)
  7673. : 0;
  7674. // Draw body lines now
  7675. for (i = 0, ilen = body.length; i < ilen; ++i) {
  7676. bodyItem = body[i];
  7677. textColor = vm.labelTextColors[i];
  7678. labelColors = vm.labelColors[i];
  7679. ctx.fillStyle = textColor;
  7680. helpers$1.each(bodyItem.before, fillLineOfText);
  7681. lines = bodyItem.lines;
  7682. for (j = 0, jlen = lines.length; j < jlen; ++j) {
  7683. // Draw Legend-like boxes if needed
  7684. if (drawColorBoxes) {
  7685. var rtlColorX = rtlHelper.x(colorX);
  7686. // Fill a white rect so that colours merge nicely if the opacity is < 1
  7687. ctx.fillStyle = vm.legendColorBackground;
  7688. ctx.fillRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7689. // Border
  7690. ctx.lineWidth = 1;
  7691. ctx.strokeStyle = labelColors.borderColor;
  7692. ctx.strokeRect(rtlHelper.leftForLtr(rtlColorX, bodyFontSize), pt.y, bodyFontSize, bodyFontSize);
  7693. // Inner square
  7694. ctx.fillStyle = labelColors.backgroundColor;
  7695. ctx.fillRect(rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), bodyFontSize - 2), pt.y + 1, bodyFontSize - 2, bodyFontSize - 2);
  7696. ctx.fillStyle = textColor;
  7697. }
  7698. fillLineOfText(lines[j]);
  7699. }
  7700. helpers$1.each(bodyItem.after, fillLineOfText);
  7701. }
  7702. // Reset back to 0 for after body
  7703. xLinePadding = 0;
  7704. // After body lines
  7705. helpers$1.each(vm.afterBody, fillLineOfText);
  7706. pt.y -= bodySpacing; // Remove last body spacing
  7707. },
  7708. drawFooter: function(pt, vm, ctx) {
  7709. var footer = vm.footer;
  7710. var length = footer.length;
  7711. var footerFontSize, i;
  7712. if (length) {
  7713. var rtlHelper = getRtlHelper(vm.rtl, vm.x, vm.width);
  7714. pt.x = getAlignedX(vm, vm._footerAlign);
  7715. pt.y += vm.footerMarginTop;
  7716. ctx.textAlign = rtlHelper.textAlign(vm._footerAlign);
  7717. ctx.textBaseline = 'middle';
  7718. footerFontSize = vm.footerFontSize;
  7719. ctx.fillStyle = vm.footerFontColor;
  7720. ctx.font = helpers$1.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily);
  7721. for (i = 0; i < length; ++i) {
  7722. ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFontSize / 2);
  7723. pt.y += footerFontSize + vm.footerSpacing;
  7724. }
  7725. }
  7726. },
  7727. drawBackground: function(pt, vm, ctx, tooltipSize) {
  7728. ctx.fillStyle = vm.backgroundColor;
  7729. ctx.strokeStyle = vm.borderColor;
  7730. ctx.lineWidth = vm.borderWidth;
  7731. var xAlign = vm.xAlign;
  7732. var yAlign = vm.yAlign;
  7733. var x = pt.x;
  7734. var y = pt.y;
  7735. var width = tooltipSize.width;
  7736. var height = tooltipSize.height;
  7737. var radius = vm.cornerRadius;
  7738. ctx.beginPath();
  7739. ctx.moveTo(x + radius, y);
  7740. if (yAlign === 'top') {
  7741. this.drawCaret(pt, tooltipSize);
  7742. }
  7743. ctx.lineTo(x + width - radius, y);
  7744. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  7745. if (yAlign === 'center' && xAlign === 'right') {
  7746. this.drawCaret(pt, tooltipSize);
  7747. }
  7748. ctx.lineTo(x + width, y + height - radius);
  7749. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  7750. if (yAlign === 'bottom') {
  7751. this.drawCaret(pt, tooltipSize);
  7752. }
  7753. ctx.lineTo(x + radius, y + height);
  7754. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  7755. if (yAlign === 'center' && xAlign === 'left') {
  7756. this.drawCaret(pt, tooltipSize);
  7757. }
  7758. ctx.lineTo(x, y + radius);
  7759. ctx.quadraticCurveTo(x, y, x + radius, y);
  7760. ctx.closePath();
  7761. ctx.fill();
  7762. if (vm.borderWidth > 0) {
  7763. ctx.stroke();
  7764. }
  7765. },
  7766. draw: function() {
  7767. var ctx = this._chart.ctx;
  7768. var vm = this._view;
  7769. if (vm.opacity === 0) {
  7770. return;
  7771. }
  7772. var tooltipSize = {
  7773. width: vm.width,
  7774. height: vm.height
  7775. };
  7776. var pt = {
  7777. x: vm.x,
  7778. y: vm.y
  7779. };
  7780. // IE11/Edge does not like very small opacities, so snap to 0
  7781. var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity;
  7782. // Truthy/falsey value for empty tooltip
  7783. var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length;
  7784. if (this._options.enabled && hasTooltipContent) {
  7785. ctx.save();
  7786. ctx.globalAlpha = opacity;
  7787. // Draw Background
  7788. this.drawBackground(pt, vm, ctx, tooltipSize);
  7789. // Draw Title, Body, and Footer
  7790. pt.y += vm.yPadding;
  7791. helpers$1.rtl.overrideTextDirection(ctx, vm.textDirection);
  7792. // Titles
  7793. this.drawTitle(pt, vm, ctx);
  7794. // Body
  7795. this.drawBody(pt, vm, ctx);
  7796. // Footer
  7797. this.drawFooter(pt, vm, ctx);
  7798. helpers$1.rtl.restoreTextDirection(ctx, vm.textDirection);
  7799. ctx.restore();
  7800. }
  7801. },
  7802. /**
  7803. * Handle an event
  7804. * @private
  7805. * @param {IEvent} event - The event to handle
  7806. * @returns {boolean} true if the tooltip changed
  7807. */
  7808. handleEvent: function(e) {
  7809. var me = this;
  7810. var options = me._options;
  7811. var changed = false;
  7812. me._lastActive = me._lastActive || [];
  7813. // Find Active Elements for tooltips
  7814. if (e.type === 'mouseout') {
  7815. me._active = [];
  7816. } else {
  7817. me._active = me._chart.getElementsAtEventForMode(e, options.mode, options);
  7818. if (options.reverse) {
  7819. me._active.reverse();
  7820. }
  7821. }
  7822. // Remember Last Actives
  7823. changed = !helpers$1.arrayEquals(me._active, me._lastActive);
  7824. // Only handle target event on tooltip change
  7825. if (changed) {
  7826. me._lastActive = me._active;
  7827. if (options.enabled || options.custom) {
  7828. me._eventPosition = {
  7829. x: e.x,
  7830. y: e.y
  7831. };
  7832. me.update(true);
  7833. me.pivot();
  7834. }
  7835. }
  7836. return changed;
  7837. }
  7838. });
  7839. /**
  7840. * @namespace Chart.Tooltip.positioners
  7841. */
  7842. var positioners_1 = positioners;
  7843. var core_tooltip = exports$4;
  7844. core_tooltip.positioners = positioners_1;
  7845. var valueOrDefault$9 = helpers$1.valueOrDefault;
  7846. core_defaults._set('global', {
  7847. elements: {},
  7848. events: [
  7849. 'mousemove',
  7850. 'mouseout',
  7851. 'click',
  7852. 'touchstart',
  7853. 'touchmove'
  7854. ],
  7855. hover: {
  7856. onHover: null,
  7857. mode: 'nearest',
  7858. intersect: true,
  7859. animationDuration: 400
  7860. },
  7861. onClick: null,
  7862. maintainAspectRatio: true,
  7863. responsive: true,
  7864. responsiveAnimationDuration: 0
  7865. });
  7866. /**
  7867. * Recursively merge the given config objects representing the `scales` option
  7868. * by incorporating scale defaults in `xAxes` and `yAxes` array items, then
  7869. * returns a deep copy of the result, thus doesn't alter inputs.
  7870. */
  7871. function mergeScaleConfig(/* config objects ... */) {
  7872. return helpers$1.merge({}, [].slice.call(arguments), {
  7873. merger: function(key, target, source, options) {
  7874. if (key === 'xAxes' || key === 'yAxes') {
  7875. var slen = source[key].length;
  7876. var i, type, scale;
  7877. if (!target[key]) {
  7878. target[key] = [];
  7879. }
  7880. for (i = 0; i < slen; ++i) {
  7881. scale = source[key][i];
  7882. type = valueOrDefault$9(scale.type, key === 'xAxes' ? 'category' : 'linear');
  7883. if (i >= target[key].length) {
  7884. target[key].push({});
  7885. }
  7886. if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) {
  7887. // new/untyped scale or type changed: let's apply the new defaults
  7888. // then merge source scale to correctly overwrite the defaults.
  7889. helpers$1.merge(target[key][i], [core_scaleService.getScaleDefaults(type), scale]);
  7890. } else {
  7891. // scales type are the same
  7892. helpers$1.merge(target[key][i], scale);
  7893. }
  7894. }
  7895. } else {
  7896. helpers$1._merger(key, target, source, options);
  7897. }
  7898. }
  7899. });
  7900. }
  7901. /**
  7902. * Recursively merge the given config objects as the root options by handling
  7903. * default scale options for the `scales` and `scale` properties, then returns
  7904. * a deep copy of the result, thus doesn't alter inputs.
  7905. */
  7906. function mergeConfig(/* config objects ... */) {
  7907. return helpers$1.merge({}, [].slice.call(arguments), {
  7908. merger: function(key, target, source, options) {
  7909. var tval = target[key] || {};
  7910. var sval = source[key];
  7911. if (key === 'scales') {
  7912. // scale config merging is complex. Add our own function here for that
  7913. target[key] = mergeScaleConfig(tval, sval);
  7914. } else if (key === 'scale') {
  7915. // used in polar area & radar charts since there is only one scale
  7916. target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]);
  7917. } else {
  7918. helpers$1._merger(key, target, source, options);
  7919. }
  7920. }
  7921. });
  7922. }
  7923. function initConfig(config) {
  7924. config = config || {};
  7925. // Do NOT use mergeConfig for the data object because this method merges arrays
  7926. // and so would change references to labels and datasets, preventing data updates.
  7927. var data = config.data = config.data || {};
  7928. data.datasets = data.datasets || [];
  7929. data.labels = data.labels || [];
  7930. config.options = mergeConfig(
  7931. core_defaults.global,
  7932. core_defaults[config.type],
  7933. config.options || {});
  7934. return config;
  7935. }
  7936. function updateConfig(chart) {
  7937. var newOptions = chart.options;
  7938. helpers$1.each(chart.scales, function(scale) {
  7939. core_layouts.removeBox(chart, scale);
  7940. });
  7941. newOptions = mergeConfig(
  7942. core_defaults.global,
  7943. core_defaults[chart.config.type],
  7944. newOptions);
  7945. chart.options = chart.config.options = newOptions;
  7946. chart.ensureScalesHaveIDs();
  7947. chart.buildOrUpdateScales();
  7948. // Tooltip
  7949. chart.tooltip._options = newOptions.tooltips;
  7950. chart.tooltip.initialize();
  7951. }
  7952. function nextAvailableScaleId(axesOpts, prefix, index) {
  7953. var id;
  7954. var hasId = function(obj) {
  7955. return obj.id === id;
  7956. };
  7957. do {
  7958. id = prefix + index++;
  7959. } while (helpers$1.findIndex(axesOpts, hasId) >= 0);
  7960. return id;
  7961. }
  7962. function positionIsHorizontal(position) {
  7963. return position === 'top' || position === 'bottom';
  7964. }
  7965. function compare2Level(l1, l2) {
  7966. return function(a, b) {
  7967. return a[l1] === b[l1]
  7968. ? a[l2] - b[l2]
  7969. : a[l1] - b[l1];
  7970. };
  7971. }
  7972. var Chart = function(item, config) {
  7973. this.construct(item, config);
  7974. return this;
  7975. };
  7976. helpers$1.extend(Chart.prototype, /** @lends Chart */ {
  7977. /**
  7978. * @private
  7979. */
  7980. construct: function(item, config) {
  7981. var me = this;
  7982. config = initConfig(config);
  7983. var context = platform.acquireContext(item, config);
  7984. var canvas = context && context.canvas;
  7985. var height = canvas && canvas.height;
  7986. var width = canvas && canvas.width;
  7987. me.id = helpers$1.uid();
  7988. me.ctx = context;
  7989. me.canvas = canvas;
  7990. me.config = config;
  7991. me.width = width;
  7992. me.height = height;
  7993. me.aspectRatio = height ? width / height : null;
  7994. me.options = config.options;
  7995. me._bufferedRender = false;
  7996. me._layers = [];
  7997. /**
  7998. * Provided for backward compatibility, Chart and Chart.Controller have been merged,
  7999. * the "instance" still need to be defined since it might be called from plugins.
  8000. * @prop Chart#chart
  8001. * @deprecated since version 2.6.0
  8002. * @todo remove at version 3
  8003. * @private
  8004. */
  8005. me.chart = me;
  8006. me.controller = me; // chart.chart.controller #inception
  8007. // Add the chart instance to the global namespace
  8008. Chart.instances[me.id] = me;
  8009. // Define alias to the config data: `chart.data === chart.config.data`
  8010. Object.defineProperty(me, 'data', {
  8011. get: function() {
  8012. return me.config.data;
  8013. },
  8014. set: function(value) {
  8015. me.config.data = value;
  8016. }
  8017. });
  8018. if (!context || !canvas) {
  8019. // The given item is not a compatible context2d element, let's return before finalizing
  8020. // the chart initialization but after setting basic chart / controller properties that
  8021. // can help to figure out that the chart is not valid (e.g chart.canvas !== null);
  8022. // https://github.com/chartjs/Chart.js/issues/2807
  8023. console.error("Failed to create chart: can't acquire context from the given item");
  8024. return;
  8025. }
  8026. me.initialize();
  8027. me.update();
  8028. },
  8029. /**
  8030. * @private
  8031. */
  8032. initialize: function() {
  8033. var me = this;
  8034. // Before init plugin notification
  8035. core_plugins.notify(me, 'beforeInit');
  8036. helpers$1.retinaScale(me, me.options.devicePixelRatio);
  8037. me.bindEvents();
  8038. if (me.options.responsive) {
  8039. // Initial resize before chart draws (must be silent to preserve initial animations).
  8040. me.resize(true);
  8041. }
  8042. me.initToolTip();
  8043. // After init plugin notification
  8044. core_plugins.notify(me, 'afterInit');
  8045. return me;
  8046. },
  8047. clear: function() {
  8048. helpers$1.canvas.clear(this);
  8049. return this;
  8050. },
  8051. stop: function() {
  8052. // Stops any current animation loop occurring
  8053. core_animations.cancelAnimation(this);
  8054. return this;
  8055. },
  8056. resize: function(silent) {
  8057. var me = this;
  8058. var options = me.options;
  8059. var canvas = me.canvas;
  8060. var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null;
  8061. // the canvas render width and height will be casted to integers so make sure that
  8062. // the canvas display style uses the same integer values to avoid blurring effect.
  8063. // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collapsed
  8064. var newWidth = Math.max(0, Math.floor(helpers$1.getMaximumWidth(canvas)));
  8065. var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers$1.getMaximumHeight(canvas)));
  8066. if (me.width === newWidth && me.height === newHeight) {
  8067. return;
  8068. }
  8069. canvas.width = me.width = newWidth;
  8070. canvas.height = me.height = newHeight;
  8071. canvas.style.width = newWidth + 'px';
  8072. canvas.style.height = newHeight + 'px';
  8073. helpers$1.retinaScale(me, options.devicePixelRatio);
  8074. if (!silent) {
  8075. // Notify any plugins about the resize
  8076. var newSize = {width: newWidth, height: newHeight};
  8077. core_plugins.notify(me, 'resize', [newSize]);
  8078. // Notify of resize
  8079. if (options.onResize) {
  8080. options.onResize(me, newSize);
  8081. }
  8082. me.stop();
  8083. me.update({
  8084. duration: options.responsiveAnimationDuration
  8085. });
  8086. }
  8087. },
  8088. ensureScalesHaveIDs: function() {
  8089. var options = this.options;
  8090. var scalesOptions = options.scales || {};
  8091. var scaleOptions = options.scale;
  8092. helpers$1.each(scalesOptions.xAxes, function(xAxisOptions, index) {
  8093. if (!xAxisOptions.id) {
  8094. xAxisOptions.id = nextAvailableScaleId(scalesOptions.xAxes, 'x-axis-', index);
  8095. }
  8096. });
  8097. helpers$1.each(scalesOptions.yAxes, function(yAxisOptions, index) {
  8098. if (!yAxisOptions.id) {
  8099. yAxisOptions.id = nextAvailableScaleId(scalesOptions.yAxes, 'y-axis-', index);
  8100. }
  8101. });
  8102. if (scaleOptions) {
  8103. scaleOptions.id = scaleOptions.id || 'scale';
  8104. }
  8105. },
  8106. /**
  8107. * Builds a map of scale ID to scale object for future lookup.
  8108. */
  8109. buildOrUpdateScales: function() {
  8110. var me = this;
  8111. var options = me.options;
  8112. var scales = me.scales || {};
  8113. var items = [];
  8114. var updated = Object.keys(scales).reduce(function(obj, id) {
  8115. obj[id] = false;
  8116. return obj;
  8117. }, {});
  8118. if (options.scales) {
  8119. items = items.concat(
  8120. (options.scales.xAxes || []).map(function(xAxisOptions) {
  8121. return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'};
  8122. }),
  8123. (options.scales.yAxes || []).map(function(yAxisOptions) {
  8124. return {options: yAxisOptions, dtype: 'linear', dposition: 'left'};
  8125. })
  8126. );
  8127. }
  8128. if (options.scale) {
  8129. items.push({
  8130. options: options.scale,
  8131. dtype: 'radialLinear',
  8132. isDefault: true,
  8133. dposition: 'chartArea'
  8134. });
  8135. }
  8136. helpers$1.each(items, function(item) {
  8137. var scaleOptions = item.options;
  8138. var id = scaleOptions.id;
  8139. var scaleType = valueOrDefault$9(scaleOptions.type, item.dtype);
  8140. if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) {
  8141. scaleOptions.position = item.dposition;
  8142. }
  8143. updated[id] = true;
  8144. var scale = null;
  8145. if (id in scales && scales[id].type === scaleType) {
  8146. scale = scales[id];
  8147. scale.options = scaleOptions;
  8148. scale.ctx = me.ctx;
  8149. scale.chart = me;
  8150. } else {
  8151. var scaleClass = core_scaleService.getScaleConstructor(scaleType);
  8152. if (!scaleClass) {
  8153. return;
  8154. }
  8155. scale = new scaleClass({
  8156. id: id,
  8157. type: scaleType,
  8158. options: scaleOptions,
  8159. ctx: me.ctx,
  8160. chart: me
  8161. });
  8162. scales[scale.id] = scale;
  8163. }
  8164. scale.mergeTicksOptions();
  8165. // TODO(SB): I think we should be able to remove this custom case (options.scale)
  8166. // and consider it as a regular scale part of the "scales"" map only! This would
  8167. // make the logic easier and remove some useless? custom code.
  8168. if (item.isDefault) {
  8169. me.scale = scale;
  8170. }
  8171. });
  8172. // clear up discarded scales
  8173. helpers$1.each(updated, function(hasUpdated, id) {
  8174. if (!hasUpdated) {
  8175. delete scales[id];
  8176. }
  8177. });
  8178. me.scales = scales;
  8179. core_scaleService.addScalesToLayout(this);
  8180. },
  8181. buildOrUpdateControllers: function() {
  8182. var me = this;
  8183. var newControllers = [];
  8184. var datasets = me.data.datasets;
  8185. var i, ilen;
  8186. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  8187. var dataset = datasets[i];
  8188. var meta = me.getDatasetMeta(i);
  8189. var type = dataset.type || me.config.type;
  8190. if (meta.type && meta.type !== type) {
  8191. me.destroyDatasetMeta(i);
  8192. meta = me.getDatasetMeta(i);
  8193. }
  8194. meta.type = type;
  8195. meta.order = dataset.order || 0;
  8196. meta.index = i;
  8197. if (meta.controller) {
  8198. meta.controller.updateIndex(i);
  8199. meta.controller.linkScales();
  8200. } else {
  8201. var ControllerClass = controllers[meta.type];
  8202. if (ControllerClass === undefined) {
  8203. throw new Error('"' + meta.type + '" is not a chart type.');
  8204. }
  8205. meta.controller = new ControllerClass(me, i);
  8206. newControllers.push(meta.controller);
  8207. }
  8208. }
  8209. return newControllers;
  8210. },
  8211. /**
  8212. * Reset the elements of all datasets
  8213. * @private
  8214. */
  8215. resetElements: function() {
  8216. var me = this;
  8217. helpers$1.each(me.data.datasets, function(dataset, datasetIndex) {
  8218. me.getDatasetMeta(datasetIndex).controller.reset();
  8219. }, me);
  8220. },
  8221. /**
  8222. * Resets the chart back to it's state before the initial animation
  8223. */
  8224. reset: function() {
  8225. this.resetElements();
  8226. this.tooltip.initialize();
  8227. },
  8228. update: function(config) {
  8229. var me = this;
  8230. var i, ilen;
  8231. if (!config || typeof config !== 'object') {
  8232. // backwards compatibility
  8233. config = {
  8234. duration: config,
  8235. lazy: arguments[1]
  8236. };
  8237. }
  8238. updateConfig(me);
  8239. // plugins options references might have change, let's invalidate the cache
  8240. // https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
  8241. core_plugins._invalidate(me);
  8242. if (core_plugins.notify(me, 'beforeUpdate') === false) {
  8243. return;
  8244. }
  8245. // In case the entire data object changed
  8246. me.tooltip._data = me.data;
  8247. // Make sure dataset controllers are updated and new controllers are reset
  8248. var newControllers = me.buildOrUpdateControllers();
  8249. // Make sure all dataset controllers have correct meta data counts
  8250. for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
  8251. me.getDatasetMeta(i).controller.buildOrUpdateElements();
  8252. }
  8253. me.updateLayout();
  8254. // Can only reset the new controllers after the scales have been updated
  8255. if (me.options.animation && me.options.animation.duration) {
  8256. helpers$1.each(newControllers, function(controller) {
  8257. controller.reset();
  8258. });
  8259. }
  8260. me.updateDatasets();
  8261. // Need to reset tooltip in case it is displayed with elements that are removed
  8262. // after update.
  8263. me.tooltip.initialize();
  8264. // Last active contains items that were previously in the tooltip.
  8265. // When we reset the tooltip, we need to clear it
  8266. me.lastActive = [];
  8267. // Do this before render so that any plugins that need final scale updates can use it
  8268. core_plugins.notify(me, 'afterUpdate');
  8269. me._layers.sort(compare2Level('z', '_idx'));
  8270. if (me._bufferedRender) {
  8271. me._bufferedRequest = {
  8272. duration: config.duration,
  8273. easing: config.easing,
  8274. lazy: config.lazy
  8275. };
  8276. } else {
  8277. me.render(config);
  8278. }
  8279. },
  8280. /**
  8281. * Updates the chart layout unless a plugin returns `false` to the `beforeLayout`
  8282. * hook, in which case, plugins will not be called on `afterLayout`.
  8283. * @private
  8284. */
  8285. updateLayout: function() {
  8286. var me = this;
  8287. if (core_plugins.notify(me, 'beforeLayout') === false) {
  8288. return;
  8289. }
  8290. core_layouts.update(this, this.width, this.height);
  8291. me._layers = [];
  8292. helpers$1.each(me.boxes, function(box) {
  8293. // _configure is called twice, once in core.scale.update and once here.
  8294. // Here the boxes are fully updated and at their final positions.
  8295. if (box._configure) {
  8296. box._configure();
  8297. }
  8298. me._layers.push.apply(me._layers, box._layers());
  8299. }, me);
  8300. me._layers.forEach(function(item, index) {
  8301. item._idx = index;
  8302. });
  8303. /**
  8304. * Provided for backward compatibility, use `afterLayout` instead.
  8305. * @method IPlugin#afterScaleUpdate
  8306. * @deprecated since version 2.5.0
  8307. * @todo remove at version 3
  8308. * @private
  8309. */
  8310. core_plugins.notify(me, 'afterScaleUpdate');
  8311. core_plugins.notify(me, 'afterLayout');
  8312. },
  8313. /**
  8314. * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate`
  8315. * hook, in which case, plugins will not be called on `afterDatasetsUpdate`.
  8316. * @private
  8317. */
  8318. updateDatasets: function() {
  8319. var me = this;
  8320. if (core_plugins.notify(me, 'beforeDatasetsUpdate') === false) {
  8321. return;
  8322. }
  8323. for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8324. me.updateDataset(i);
  8325. }
  8326. core_plugins.notify(me, 'afterDatasetsUpdate');
  8327. },
  8328. /**
  8329. * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate`
  8330. * hook, in which case, plugins will not be called on `afterDatasetUpdate`.
  8331. * @private
  8332. */
  8333. updateDataset: function(index) {
  8334. var me = this;
  8335. var meta = me.getDatasetMeta(index);
  8336. var args = {
  8337. meta: meta,
  8338. index: index
  8339. };
  8340. if (core_plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) {
  8341. return;
  8342. }
  8343. meta.controller._update();
  8344. core_plugins.notify(me, 'afterDatasetUpdate', [args]);
  8345. },
  8346. render: function(config) {
  8347. var me = this;
  8348. if (!config || typeof config !== 'object') {
  8349. // backwards compatibility
  8350. config = {
  8351. duration: config,
  8352. lazy: arguments[1]
  8353. };
  8354. }
  8355. var animationOptions = me.options.animation;
  8356. var duration = valueOrDefault$9(config.duration, animationOptions && animationOptions.duration);
  8357. var lazy = config.lazy;
  8358. if (core_plugins.notify(me, 'beforeRender') === false) {
  8359. return;
  8360. }
  8361. var onComplete = function(animation) {
  8362. core_plugins.notify(me, 'afterRender');
  8363. helpers$1.callback(animationOptions && animationOptions.onComplete, [animation], me);
  8364. };
  8365. if (animationOptions && duration) {
  8366. var animation = new core_animation({
  8367. numSteps: duration / 16.66, // 60 fps
  8368. easing: config.easing || animationOptions.easing,
  8369. render: function(chart, animationObject) {
  8370. var easingFunction = helpers$1.easing.effects[animationObject.easing];
  8371. var currentStep = animationObject.currentStep;
  8372. var stepDecimal = currentStep / animationObject.numSteps;
  8373. chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep);
  8374. },
  8375. onAnimationProgress: animationOptions.onProgress,
  8376. onAnimationComplete: onComplete
  8377. });
  8378. core_animations.addAnimation(me, animation, duration, lazy);
  8379. } else {
  8380. me.draw();
  8381. // See https://github.com/chartjs/Chart.js/issues/3781
  8382. onComplete(new core_animation({numSteps: 0, chart: me}));
  8383. }
  8384. return me;
  8385. },
  8386. draw: function(easingValue) {
  8387. var me = this;
  8388. var i, layers;
  8389. me.clear();
  8390. if (helpers$1.isNullOrUndef(easingValue)) {
  8391. easingValue = 1;
  8392. }
  8393. me.transition(easingValue);
  8394. if (me.width <= 0 || me.height <= 0) {
  8395. return;
  8396. }
  8397. if (core_plugins.notify(me, 'beforeDraw', [easingValue]) === false) {
  8398. return;
  8399. }
  8400. // Because of plugin hooks (before/afterDatasetsDraw), datasets can't
  8401. // currently be part of layers. Instead, we draw
  8402. // layers <= 0 before(default, backward compat), and the rest after
  8403. layers = me._layers;
  8404. for (i = 0; i < layers.length && layers[i].z <= 0; ++i) {
  8405. layers[i].draw(me.chartArea);
  8406. }
  8407. me.drawDatasets(easingValue);
  8408. // Rest of layers
  8409. for (; i < layers.length; ++i) {
  8410. layers[i].draw(me.chartArea);
  8411. }
  8412. me._drawTooltip(easingValue);
  8413. core_plugins.notify(me, 'afterDraw', [easingValue]);
  8414. },
  8415. /**
  8416. * @private
  8417. */
  8418. transition: function(easingValue) {
  8419. var me = this;
  8420. for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) {
  8421. if (me.isDatasetVisible(i)) {
  8422. me.getDatasetMeta(i).controller.transition(easingValue);
  8423. }
  8424. }
  8425. me.tooltip.transition(easingValue);
  8426. },
  8427. /**
  8428. * @private
  8429. */
  8430. _getSortedDatasetMetas: function(filterVisible) {
  8431. var me = this;
  8432. var datasets = me.data.datasets || [];
  8433. var result = [];
  8434. var i, ilen;
  8435. for (i = 0, ilen = datasets.length; i < ilen; ++i) {
  8436. if (!filterVisible || me.isDatasetVisible(i)) {
  8437. result.push(me.getDatasetMeta(i));
  8438. }
  8439. }
  8440. result.sort(compare2Level('order', 'index'));
  8441. return result;
  8442. },
  8443. /**
  8444. * @private
  8445. */
  8446. _getSortedVisibleDatasetMetas: function() {
  8447. return this._getSortedDatasetMetas(true);
  8448. },
  8449. /**
  8450. * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw`
  8451. * hook, in which case, plugins will not be called on `afterDatasetsDraw`.
  8452. * @private
  8453. */
  8454. drawDatasets: function(easingValue) {
  8455. var me = this;
  8456. var metasets, i;
  8457. if (core_plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) {
  8458. return;
  8459. }
  8460. metasets = me._getSortedVisibleDatasetMetas();
  8461. for (i = metasets.length - 1; i >= 0; --i) {
  8462. me.drawDataset(metasets[i], easingValue);
  8463. }
  8464. core_plugins.notify(me, 'afterDatasetsDraw', [easingValue]);
  8465. },
  8466. /**
  8467. * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw`
  8468. * hook, in which case, plugins will not be called on `afterDatasetDraw`.
  8469. * @private
  8470. */
  8471. drawDataset: function(meta, easingValue) {
  8472. var me = this;
  8473. var args = {
  8474. meta: meta,
  8475. index: meta.index,
  8476. easingValue: easingValue
  8477. };
  8478. if (core_plugins.notify(me, 'beforeDatasetDraw', [args]) === false) {
  8479. return;
  8480. }
  8481. meta.controller.draw(easingValue);
  8482. core_plugins.notify(me, 'afterDatasetDraw', [args]);
  8483. },
  8484. /**
  8485. * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw`
  8486. * hook, in which case, plugins will not be called on `afterTooltipDraw`.
  8487. * @private
  8488. */
  8489. _drawTooltip: function(easingValue) {
  8490. var me = this;
  8491. var tooltip = me.tooltip;
  8492. var args = {
  8493. tooltip: tooltip,
  8494. easingValue: easingValue
  8495. };
  8496. if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) {
  8497. return;
  8498. }
  8499. tooltip.draw();
  8500. core_plugins.notify(me, 'afterTooltipDraw', [args]);
  8501. },
  8502. /**
  8503. * Get the single element that was clicked on
  8504. * @return An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw
  8505. */
  8506. getElementAtEvent: function(e) {
  8507. return core_interaction.modes.single(this, e);
  8508. },
  8509. getElementsAtEvent: function(e) {
  8510. return core_interaction.modes.label(this, e, {intersect: true});
  8511. },
  8512. getElementsAtXAxis: function(e) {
  8513. return core_interaction.modes['x-axis'](this, e, {intersect: true});
  8514. },
  8515. getElementsAtEventForMode: function(e, mode, options) {
  8516. var method = core_interaction.modes[mode];
  8517. if (typeof method === 'function') {
  8518. return method(this, e, options);
  8519. }
  8520. return [];
  8521. },
  8522. getDatasetAtEvent: function(e) {
  8523. return core_interaction.modes.dataset(this, e, {intersect: true});
  8524. },
  8525. getDatasetMeta: function(datasetIndex) {
  8526. var me = this;
  8527. var dataset = me.data.datasets[datasetIndex];
  8528. if (!dataset._meta) {
  8529. dataset._meta = {};
  8530. }
  8531. var meta = dataset._meta[me.id];
  8532. if (!meta) {
  8533. meta = dataset._meta[me.id] = {
  8534. type: null,
  8535. data: [],
  8536. dataset: null,
  8537. controller: null,
  8538. hidden: null, // See isDatasetVisible() comment
  8539. xAxisID: null,
  8540. yAxisID: null,
  8541. order: dataset.order || 0,
  8542. index: datasetIndex
  8543. };
  8544. }
  8545. return meta;
  8546. },
  8547. getVisibleDatasetCount: function() {
  8548. var count = 0;
  8549. for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) {
  8550. if (this.isDatasetVisible(i)) {
  8551. count++;
  8552. }
  8553. }
  8554. return count;
  8555. },
  8556. isDatasetVisible: function(datasetIndex) {
  8557. var meta = this.getDatasetMeta(datasetIndex);
  8558. // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false,
  8559. // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned.
  8560. return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden;
  8561. },
  8562. generateLegend: function() {
  8563. return this.options.legendCallback(this);
  8564. },
  8565. /**
  8566. * @private
  8567. */
  8568. destroyDatasetMeta: function(datasetIndex) {
  8569. var id = this.id;
  8570. var dataset = this.data.datasets[datasetIndex];
  8571. var meta = dataset._meta && dataset._meta[id];
  8572. if (meta) {
  8573. meta.controller.destroy();
  8574. delete dataset._meta[id];
  8575. }
  8576. },
  8577. destroy: function() {
  8578. var me = this;
  8579. var canvas = me.canvas;
  8580. var i, ilen;
  8581. me.stop();
  8582. // dataset controllers need to cleanup associated data
  8583. for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) {
  8584. me.destroyDatasetMeta(i);
  8585. }
  8586. if (canvas) {
  8587. me.unbindEvents();
  8588. helpers$1.canvas.clear(me);
  8589. platform.releaseContext(me.ctx);
  8590. me.canvas = null;
  8591. me.ctx = null;
  8592. }
  8593. core_plugins.notify(me, 'destroy');
  8594. delete Chart.instances[me.id];
  8595. },
  8596. toBase64Image: function() {
  8597. return this.canvas.toDataURL.apply(this.canvas, arguments);
  8598. },
  8599. initToolTip: function() {
  8600. var me = this;
  8601. me.tooltip = new core_tooltip({
  8602. _chart: me,
  8603. _chartInstance: me, // deprecated, backward compatibility
  8604. _data: me.data,
  8605. _options: me.options.tooltips
  8606. }, me);
  8607. },
  8608. /**
  8609. * @private
  8610. */
  8611. bindEvents: function() {
  8612. var me = this;
  8613. var listeners = me._listeners = {};
  8614. var listener = function() {
  8615. me.eventHandler.apply(me, arguments);
  8616. };
  8617. helpers$1.each(me.options.events, function(type) {
  8618. platform.addEventListener(me, type, listener);
  8619. listeners[type] = listener;
  8620. });
  8621. // Elements used to detect size change should not be injected for non responsive charts.
  8622. // See https://github.com/chartjs/Chart.js/issues/2210
  8623. if (me.options.responsive) {
  8624. listener = function() {
  8625. me.resize();
  8626. };
  8627. platform.addEventListener(me, 'resize', listener);
  8628. listeners.resize = listener;
  8629. }
  8630. },
  8631. /**
  8632. * @private
  8633. */
  8634. unbindEvents: function() {
  8635. var me = this;
  8636. var listeners = me._listeners;
  8637. if (!listeners) {
  8638. return;
  8639. }
  8640. delete me._listeners;
  8641. helpers$1.each(listeners, function(listener, type) {
  8642. platform.removeEventListener(me, type, listener);
  8643. });
  8644. },
  8645. updateHoverStyle: function(elements, mode, enabled) {
  8646. var prefix = enabled ? 'set' : 'remove';
  8647. var element, i, ilen;
  8648. for (i = 0, ilen = elements.length; i < ilen; ++i) {
  8649. element = elements[i];
  8650. if (element) {
  8651. this.getDatasetMeta(element._datasetIndex).controller[prefix + 'HoverStyle'](element);
  8652. }
  8653. }
  8654. if (mode === 'dataset') {
  8655. this.getDatasetMeta(elements[0]._datasetIndex).controller['_' + prefix + 'DatasetHoverStyle']();
  8656. }
  8657. },
  8658. /**
  8659. * @private
  8660. */
  8661. eventHandler: function(e) {
  8662. var me = this;
  8663. var tooltip = me.tooltip;
  8664. if (core_plugins.notify(me, 'beforeEvent', [e]) === false) {
  8665. return;
  8666. }
  8667. // Buffer any update calls so that renders do not occur
  8668. me._bufferedRender = true;
  8669. me._bufferedRequest = null;
  8670. var changed = me.handleEvent(e);
  8671. // for smooth tooltip animations issue #4989
  8672. // the tooltip should be the source of change
  8673. // Animation check workaround:
  8674. // tooltip._start will be null when tooltip isn't animating
  8675. if (tooltip) {
  8676. changed = tooltip._start
  8677. ? tooltip.handleEvent(e)
  8678. : changed | tooltip.handleEvent(e);
  8679. }
  8680. core_plugins.notify(me, 'afterEvent', [e]);
  8681. var bufferedRequest = me._bufferedRequest;
  8682. if (bufferedRequest) {
  8683. // If we have an update that was triggered, we need to do a normal render
  8684. me.render(bufferedRequest);
  8685. } else if (changed && !me.animating) {
  8686. // If entering, leaving, or changing elements, animate the change via pivot
  8687. me.stop();
  8688. // We only need to render at this point. Updating will cause scales to be
  8689. // recomputed generating flicker & using more memory than necessary.
  8690. me.render({
  8691. duration: me.options.hover.animationDuration,
  8692. lazy: true
  8693. });
  8694. }
  8695. me._bufferedRender = false;
  8696. me._bufferedRequest = null;
  8697. return me;
  8698. },
  8699. /**
  8700. * Handle an event
  8701. * @private
  8702. * @param {IEvent} event the event to handle
  8703. * @return {boolean} true if the chart needs to re-render
  8704. */
  8705. handleEvent: function(e) {
  8706. var me = this;
  8707. var options = me.options || {};
  8708. var hoverOptions = options.hover;
  8709. var changed = false;
  8710. me.lastActive = me.lastActive || [];
  8711. // Find Active Elements for hover and tooltips
  8712. if (e.type === 'mouseout') {
  8713. me.active = [];
  8714. } else {
  8715. me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions);
  8716. }
  8717. // Invoke onHover hook
  8718. // Need to call with native event here to not break backwards compatibility
  8719. helpers$1.callback(options.onHover || options.hover.onHover, [e.native, me.active], me);
  8720. if (e.type === 'mouseup' || e.type === 'click') {
  8721. if (options.onClick) {
  8722. // Use e.native here for backwards compatibility
  8723. options.onClick.call(me, e.native, me.active);
  8724. }
  8725. }
  8726. // Remove styling for last active (even if it may still be active)
  8727. if (me.lastActive.length) {
  8728. me.updateHoverStyle(me.lastActive, hoverOptions.mode, false);
  8729. }
  8730. // Built in hover styling
  8731. if (me.active.length && hoverOptions.mode) {
  8732. me.updateHoverStyle(me.active, hoverOptions.mode, true);
  8733. }
  8734. changed = !helpers$1.arrayEquals(me.active, me.lastActive);
  8735. // Remember Last Actives
  8736. me.lastActive = me.active;
  8737. return changed;
  8738. }
  8739. });
  8740. /**
  8741. * NOTE(SB) We actually don't use this container anymore but we need to keep it
  8742. * for backward compatibility. Though, it can still be useful for plugins that
  8743. * would need to work on multiple charts?!
  8744. */
  8745. Chart.instances = {};
  8746. var core_controller = Chart;
  8747. // DEPRECATIONS
  8748. /**
  8749. * Provided for backward compatibility, use Chart instead.
  8750. * @class Chart.Controller
  8751. * @deprecated since version 2.6
  8752. * @todo remove at version 3
  8753. * @private
  8754. */
  8755. Chart.Controller = Chart;
  8756. /**
  8757. * Provided for backward compatibility, not available anymore.
  8758. * @namespace Chart
  8759. * @deprecated since version 2.8
  8760. * @todo remove at version 3
  8761. * @private
  8762. */
  8763. Chart.types = {};
  8764. /**
  8765. * Provided for backward compatibility, not available anymore.
  8766. * @namespace Chart.helpers.configMerge
  8767. * @deprecated since version 2.8.0
  8768. * @todo remove at version 3
  8769. * @private
  8770. */
  8771. helpers$1.configMerge = mergeConfig;
  8772. /**
  8773. * Provided for backward compatibility, not available anymore.
  8774. * @namespace Chart.helpers.scaleMerge
  8775. * @deprecated since version 2.8.0
  8776. * @todo remove at version 3
  8777. * @private
  8778. */
  8779. helpers$1.scaleMerge = mergeScaleConfig;
  8780. var core_helpers = function() {
  8781. // -- Basic js utility methods
  8782. helpers$1.where = function(collection, filterCallback) {
  8783. if (helpers$1.isArray(collection) && Array.prototype.filter) {
  8784. return collection.filter(filterCallback);
  8785. }
  8786. var filtered = [];
  8787. helpers$1.each(collection, function(item) {
  8788. if (filterCallback(item)) {
  8789. filtered.push(item);
  8790. }
  8791. });
  8792. return filtered;
  8793. };
  8794. helpers$1.findIndex = Array.prototype.findIndex ?
  8795. function(array, callback, scope) {
  8796. return array.findIndex(callback, scope);
  8797. } :
  8798. function(array, callback, scope) {
  8799. scope = scope === undefined ? array : scope;
  8800. for (var i = 0, ilen = array.length; i < ilen; ++i) {
  8801. if (callback.call(scope, array[i], i, array)) {
  8802. return i;
  8803. }
  8804. }
  8805. return -1;
  8806. };
  8807. helpers$1.findNextWhere = function(arrayToSearch, filterCallback, startIndex) {
  8808. // Default to start of the array
  8809. if (helpers$1.isNullOrUndef(startIndex)) {
  8810. startIndex = -1;
  8811. }
  8812. for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
  8813. var currentItem = arrayToSearch[i];
  8814. if (filterCallback(currentItem)) {
  8815. return currentItem;
  8816. }
  8817. }
  8818. };
  8819. helpers$1.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) {
  8820. // Default to end of the array
  8821. if (helpers$1.isNullOrUndef(startIndex)) {
  8822. startIndex = arrayToSearch.length;
  8823. }
  8824. for (var i = startIndex - 1; i >= 0; i--) {
  8825. var currentItem = arrayToSearch[i];
  8826. if (filterCallback(currentItem)) {
  8827. return currentItem;
  8828. }
  8829. }
  8830. };
  8831. // -- Math methods
  8832. helpers$1.isNumber = function(n) {
  8833. return !isNaN(parseFloat(n)) && isFinite(n);
  8834. };
  8835. helpers$1.almostEquals = function(x, y, epsilon) {
  8836. return Math.abs(x - y) < epsilon;
  8837. };
  8838. helpers$1.almostWhole = function(x, epsilon) {
  8839. var rounded = Math.round(x);
  8840. return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x);
  8841. };
  8842. helpers$1.max = function(array) {
  8843. return array.reduce(function(max, value) {
  8844. if (!isNaN(value)) {
  8845. return Math.max(max, value);
  8846. }
  8847. return max;
  8848. }, Number.NEGATIVE_INFINITY);
  8849. };
  8850. helpers$1.min = function(array) {
  8851. return array.reduce(function(min, value) {
  8852. if (!isNaN(value)) {
  8853. return Math.min(min, value);
  8854. }
  8855. return min;
  8856. }, Number.POSITIVE_INFINITY);
  8857. };
  8858. helpers$1.sign = Math.sign ?
  8859. function(x) {
  8860. return Math.sign(x);
  8861. } :
  8862. function(x) {
  8863. x = +x; // convert to a number
  8864. if (x === 0 || isNaN(x)) {
  8865. return x;
  8866. }
  8867. return x > 0 ? 1 : -1;
  8868. };
  8869. helpers$1.toRadians = function(degrees) {
  8870. return degrees * (Math.PI / 180);
  8871. };
  8872. helpers$1.toDegrees = function(radians) {
  8873. return radians * (180 / Math.PI);
  8874. };
  8875. /**
  8876. * Returns the number of decimal places
  8877. * i.e. the number of digits after the decimal point, of the value of this Number.
  8878. * @param {number} x - A number.
  8879. * @returns {number} The number of decimal places.
  8880. * @private
  8881. */
  8882. helpers$1._decimalPlaces = function(x) {
  8883. if (!helpers$1.isFinite(x)) {
  8884. return;
  8885. }
  8886. var e = 1;
  8887. var p = 0;
  8888. while (Math.round(x * e) / e !== x) {
  8889. e *= 10;
  8890. p++;
  8891. }
  8892. return p;
  8893. };
  8894. // Gets the angle from vertical upright to the point about a centre.
  8895. helpers$1.getAngleFromPoint = function(centrePoint, anglePoint) {
  8896. var distanceFromXCenter = anglePoint.x - centrePoint.x;
  8897. var distanceFromYCenter = anglePoint.y - centrePoint.y;
  8898. var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
  8899. var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter);
  8900. if (angle < (-0.5 * Math.PI)) {
  8901. angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2]
  8902. }
  8903. return {
  8904. angle: angle,
  8905. distance: radialDistanceFromCenter
  8906. };
  8907. };
  8908. helpers$1.distanceBetweenPoints = function(pt1, pt2) {
  8909. return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2));
  8910. };
  8911. /**
  8912. * Provided for backward compatibility, not available anymore
  8913. * @function Chart.helpers.aliasPixel
  8914. * @deprecated since version 2.8.0
  8915. * @todo remove at version 3
  8916. */
  8917. helpers$1.aliasPixel = function(pixelWidth) {
  8918. return (pixelWidth % 2 === 0) ? 0 : 0.5;
  8919. };
  8920. /**
  8921. * Returns the aligned pixel value to avoid anti-aliasing blur
  8922. * @param {Chart} chart - The chart instance.
  8923. * @param {number} pixel - A pixel value.
  8924. * @param {number} width - The width of the element.
  8925. * @returns {number} The aligned pixel value.
  8926. * @private
  8927. */
  8928. helpers$1._alignPixel = function(chart, pixel, width) {
  8929. var devicePixelRatio = chart.currentDevicePixelRatio;
  8930. var halfWidth = width / 2;
  8931. return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth;
  8932. };
  8933. helpers$1.splineCurve = function(firstPoint, middlePoint, afterPoint, t) {
  8934. // Props to Rob Spencer at scaled innovation for his post on splining between points
  8935. // http://scaledinnovation.com/analytics/splines/aboutSplines.html
  8936. // This function must also respect "skipped" points
  8937. var previous = firstPoint.skip ? middlePoint : firstPoint;
  8938. var current = middlePoint;
  8939. var next = afterPoint.skip ? middlePoint : afterPoint;
  8940. var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2));
  8941. var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2));
  8942. var s01 = d01 / (d01 + d12);
  8943. var s12 = d12 / (d01 + d12);
  8944. // If all points are the same, s01 & s02 will be inf
  8945. s01 = isNaN(s01) ? 0 : s01;
  8946. s12 = isNaN(s12) ? 0 : s12;
  8947. var fa = t * s01; // scaling factor for triangle Ta
  8948. var fb = t * s12;
  8949. return {
  8950. previous: {
  8951. x: current.x - fa * (next.x - previous.x),
  8952. y: current.y - fa * (next.y - previous.y)
  8953. },
  8954. next: {
  8955. x: current.x + fb * (next.x - previous.x),
  8956. y: current.y + fb * (next.y - previous.y)
  8957. }
  8958. };
  8959. };
  8960. helpers$1.EPSILON = Number.EPSILON || 1e-14;
  8961. helpers$1.splineCurveMonotone = function(points) {
  8962. // This function calculates Bézier control points in a similar way than |splineCurve|,
  8963. // but preserves monotonicity of the provided data and ensures no local extremums are added
  8964. // between the dataset discrete points due to the interpolation.
  8965. // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
  8966. var pointsWithTangents = (points || []).map(function(point) {
  8967. return {
  8968. model: point._model,
  8969. deltaK: 0,
  8970. mK: 0
  8971. };
  8972. });
  8973. // Calculate slopes (deltaK) and initialize tangents (mK)
  8974. var pointsLen = pointsWithTangents.length;
  8975. var i, pointBefore, pointCurrent, pointAfter;
  8976. for (i = 0; i < pointsLen; ++i) {
  8977. pointCurrent = pointsWithTangents[i];
  8978. if (pointCurrent.model.skip) {
  8979. continue;
  8980. }
  8981. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  8982. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  8983. if (pointAfter && !pointAfter.model.skip) {
  8984. var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x);
  8985. // In the case of two points that appear at the same x pixel, slopeDeltaX is 0
  8986. pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0;
  8987. }
  8988. if (!pointBefore || pointBefore.model.skip) {
  8989. pointCurrent.mK = pointCurrent.deltaK;
  8990. } else if (!pointAfter || pointAfter.model.skip) {
  8991. pointCurrent.mK = pointBefore.deltaK;
  8992. } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) {
  8993. pointCurrent.mK = 0;
  8994. } else {
  8995. pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2;
  8996. }
  8997. }
  8998. // Adjust tangents to ensure monotonic properties
  8999. var alphaK, betaK, tauK, squaredMagnitude;
  9000. for (i = 0; i < pointsLen - 1; ++i) {
  9001. pointCurrent = pointsWithTangents[i];
  9002. pointAfter = pointsWithTangents[i + 1];
  9003. if (pointCurrent.model.skip || pointAfter.model.skip) {
  9004. continue;
  9005. }
  9006. if (helpers$1.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) {
  9007. pointCurrent.mK = pointAfter.mK = 0;
  9008. continue;
  9009. }
  9010. alphaK = pointCurrent.mK / pointCurrent.deltaK;
  9011. betaK = pointAfter.mK / pointCurrent.deltaK;
  9012. squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
  9013. if (squaredMagnitude <= 9) {
  9014. continue;
  9015. }
  9016. tauK = 3 / Math.sqrt(squaredMagnitude);
  9017. pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK;
  9018. pointAfter.mK = betaK * tauK * pointCurrent.deltaK;
  9019. }
  9020. // Compute control points
  9021. var deltaX;
  9022. for (i = 0; i < pointsLen; ++i) {
  9023. pointCurrent = pointsWithTangents[i];
  9024. if (pointCurrent.model.skip) {
  9025. continue;
  9026. }
  9027. pointBefore = i > 0 ? pointsWithTangents[i - 1] : null;
  9028. pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null;
  9029. if (pointBefore && !pointBefore.model.skip) {
  9030. deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3;
  9031. pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX;
  9032. pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK;
  9033. }
  9034. if (pointAfter && !pointAfter.model.skip) {
  9035. deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3;
  9036. pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX;
  9037. pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK;
  9038. }
  9039. }
  9040. };
  9041. helpers$1.nextItem = function(collection, index, loop) {
  9042. if (loop) {
  9043. return index >= collection.length - 1 ? collection[0] : collection[index + 1];
  9044. }
  9045. return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1];
  9046. };
  9047. helpers$1.previousItem = function(collection, index, loop) {
  9048. if (loop) {
  9049. return index <= 0 ? collection[collection.length - 1] : collection[index - 1];
  9050. }
  9051. return index <= 0 ? collection[0] : collection[index - 1];
  9052. };
  9053. // Implementation of the nice number algorithm used in determining where axis labels will go
  9054. helpers$1.niceNum = function(range, round) {
  9055. var exponent = Math.floor(helpers$1.log10(range));
  9056. var fraction = range / Math.pow(10, exponent);
  9057. var niceFraction;
  9058. if (round) {
  9059. if (fraction < 1.5) {
  9060. niceFraction = 1;
  9061. } else if (fraction < 3) {
  9062. niceFraction = 2;
  9063. } else if (fraction < 7) {
  9064. niceFraction = 5;
  9065. } else {
  9066. niceFraction = 10;
  9067. }
  9068. } else if (fraction <= 1.0) {
  9069. niceFraction = 1;
  9070. } else if (fraction <= 2) {
  9071. niceFraction = 2;
  9072. } else if (fraction <= 5) {
  9073. niceFraction = 5;
  9074. } else {
  9075. niceFraction = 10;
  9076. }
  9077. return niceFraction * Math.pow(10, exponent);
  9078. };
  9079. // Request animation polyfill - https://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  9080. helpers$1.requestAnimFrame = (function() {
  9081. if (typeof window === 'undefined') {
  9082. return function(callback) {
  9083. callback();
  9084. };
  9085. }
  9086. return window.requestAnimationFrame ||
  9087. window.webkitRequestAnimationFrame ||
  9088. window.mozRequestAnimationFrame ||
  9089. window.oRequestAnimationFrame ||
  9090. window.msRequestAnimationFrame ||
  9091. function(callback) {
  9092. return window.setTimeout(callback, 1000 / 60);
  9093. };
  9094. }());
  9095. // -- DOM methods
  9096. helpers$1.getRelativePosition = function(evt, chart) {
  9097. var mouseX, mouseY;
  9098. var e = evt.originalEvent || evt;
  9099. var canvas = evt.target || evt.srcElement;
  9100. var boundingRect = canvas.getBoundingClientRect();
  9101. var touches = e.touches;
  9102. if (touches && touches.length > 0) {
  9103. mouseX = touches[0].clientX;
  9104. mouseY = touches[0].clientY;
  9105. } else {
  9106. mouseX = e.clientX;
  9107. mouseY = e.clientY;
  9108. }
  9109. // Scale mouse coordinates into canvas coordinates
  9110. // by following the pattern laid out by 'jerryj' in the comments of
  9111. // https://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/
  9112. var paddingLeft = parseFloat(helpers$1.getStyle(canvas, 'padding-left'));
  9113. var paddingTop = parseFloat(helpers$1.getStyle(canvas, 'padding-top'));
  9114. var paddingRight = parseFloat(helpers$1.getStyle(canvas, 'padding-right'));
  9115. var paddingBottom = parseFloat(helpers$1.getStyle(canvas, 'padding-bottom'));
  9116. var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight;
  9117. var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom;
  9118. // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However
  9119. // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here
  9120. mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio);
  9121. mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio);
  9122. return {
  9123. x: mouseX,
  9124. y: mouseY
  9125. };
  9126. };
  9127. // Private helper function to convert max-width/max-height values that may be percentages into a number
  9128. function parseMaxStyle(styleValue, node, parentProperty) {
  9129. var valueInPixels;
  9130. if (typeof styleValue === 'string') {
  9131. valueInPixels = parseInt(styleValue, 10);
  9132. if (styleValue.indexOf('%') !== -1) {
  9133. // percentage * size in dimension
  9134. valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty];
  9135. }
  9136. } else {
  9137. valueInPixels = styleValue;
  9138. }
  9139. return valueInPixels;
  9140. }
  9141. /**
  9142. * Returns if the given value contains an effective constraint.
  9143. * @private
  9144. */
  9145. function isConstrainedValue(value) {
  9146. return value !== undefined && value !== null && value !== 'none';
  9147. }
  9148. /**
  9149. * Returns the max width or height of the given DOM node in a cross-browser compatible fashion
  9150. * @param {HTMLElement} domNode - the node to check the constraint on
  9151. * @param {string} maxStyle - the style that defines the maximum for the direction we are using ('max-width' / 'max-height')
  9152. * @param {string} percentageProperty - property of parent to use when calculating width as a percentage
  9153. * @see {@link https://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser}
  9154. */
  9155. function getConstraintDimension(domNode, maxStyle, percentageProperty) {
  9156. var view = document.defaultView;
  9157. var parentNode = helpers$1._getParentNode(domNode);
  9158. var constrainedNode = view.getComputedStyle(domNode)[maxStyle];
  9159. var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle];
  9160. var hasCNode = isConstrainedValue(constrainedNode);
  9161. var hasCContainer = isConstrainedValue(constrainedContainer);
  9162. var infinity = Number.POSITIVE_INFINITY;
  9163. if (hasCNode || hasCContainer) {
  9164. return Math.min(
  9165. hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity,
  9166. hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity);
  9167. }
  9168. return 'none';
  9169. }
  9170. // returns Number or undefined if no constraint
  9171. helpers$1.getConstraintWidth = function(domNode) {
  9172. return getConstraintDimension(domNode, 'max-width', 'clientWidth');
  9173. };
  9174. // returns Number or undefined if no constraint
  9175. helpers$1.getConstraintHeight = function(domNode) {
  9176. return getConstraintDimension(domNode, 'max-height', 'clientHeight');
  9177. };
  9178. /**
  9179. * @private
  9180. */
  9181. helpers$1._calculatePadding = function(container, padding, parentDimension) {
  9182. padding = helpers$1.getStyle(container, padding);
  9183. return padding.indexOf('%') > -1 ? parentDimension * parseInt(padding, 10) / 100 : parseInt(padding, 10);
  9184. };
  9185. /**
  9186. * @private
  9187. */
  9188. helpers$1._getParentNode = function(domNode) {
  9189. var parent = domNode.parentNode;
  9190. if (parent && parent.toString() === '[object ShadowRoot]') {
  9191. parent = parent.host;
  9192. }
  9193. return parent;
  9194. };
  9195. helpers$1.getMaximumWidth = function(domNode) {
  9196. var container = helpers$1._getParentNode(domNode);
  9197. if (!container) {
  9198. return domNode.clientWidth;
  9199. }
  9200. var clientWidth = container.clientWidth;
  9201. var paddingLeft = helpers$1._calculatePadding(container, 'padding-left', clientWidth);
  9202. var paddingRight = helpers$1._calculatePadding(container, 'padding-right', clientWidth);
  9203. var w = clientWidth - paddingLeft - paddingRight;
  9204. var cw = helpers$1.getConstraintWidth(domNode);
  9205. return isNaN(cw) ? w : Math.min(w, cw);
  9206. };
  9207. helpers$1.getMaximumHeight = function(domNode) {
  9208. var container = helpers$1._getParentNode(domNode);
  9209. if (!container) {
  9210. return domNode.clientHeight;
  9211. }
  9212. var clientHeight = container.clientHeight;
  9213. var paddingTop = helpers$1._calculatePadding(container, 'padding-top', clientHeight);
  9214. var paddingBottom = helpers$1._calculatePadding(container, 'padding-bottom', clientHeight);
  9215. var h = clientHeight - paddingTop - paddingBottom;
  9216. var ch = helpers$1.getConstraintHeight(domNode);
  9217. return isNaN(ch) ? h : Math.min(h, ch);
  9218. };
  9219. helpers$1.getStyle = function(el, property) {
  9220. return el.currentStyle ?
  9221. el.currentStyle[property] :
  9222. document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
  9223. };
  9224. helpers$1.retinaScale = function(chart, forceRatio) {
  9225. var pixelRatio = chart.currentDevicePixelRatio = forceRatio || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
  9226. if (pixelRatio === 1) {
  9227. return;
  9228. }
  9229. var canvas = chart.canvas;
  9230. var height = chart.height;
  9231. var width = chart.width;
  9232. canvas.height = height * pixelRatio;
  9233. canvas.width = width * pixelRatio;
  9234. chart.ctx.scale(pixelRatio, pixelRatio);
  9235. // If no style has been set on the canvas, the render size is used as display size,
  9236. // making the chart visually bigger, so let's enforce it to the "correct" values.
  9237. // See https://github.com/chartjs/Chart.js/issues/3575
  9238. if (!canvas.style.height && !canvas.style.width) {
  9239. canvas.style.height = height + 'px';
  9240. canvas.style.width = width + 'px';
  9241. }
  9242. };
  9243. // -- Canvas methods
  9244. helpers$1.fontString = function(pixelSize, fontStyle, fontFamily) {
  9245. return fontStyle + ' ' + pixelSize + 'px ' + fontFamily;
  9246. };
  9247. helpers$1.longestText = function(ctx, font, arrayOfThings, cache) {
  9248. cache = cache || {};
  9249. var data = cache.data = cache.data || {};
  9250. var gc = cache.garbageCollect = cache.garbageCollect || [];
  9251. if (cache.font !== font) {
  9252. data = cache.data = {};
  9253. gc = cache.garbageCollect = [];
  9254. cache.font = font;
  9255. }
  9256. ctx.font = font;
  9257. var longest = 0;
  9258. var ilen = arrayOfThings.length;
  9259. var i, j, jlen, thing, nestedThing;
  9260. for (i = 0; i < ilen; i++) {
  9261. thing = arrayOfThings[i];
  9262. // Undefined strings and arrays should not be measured
  9263. if (thing !== undefined && thing !== null && helpers$1.isArray(thing) !== true) {
  9264. longest = helpers$1.measureText(ctx, data, gc, longest, thing);
  9265. } else if (helpers$1.isArray(thing)) {
  9266. // if it is an array lets measure each element
  9267. // to do maybe simplify this function a bit so we can do this more recursively?
  9268. for (j = 0, jlen = thing.length; j < jlen; j++) {
  9269. nestedThing = thing[j];
  9270. // Undefined strings and arrays should not be measured
  9271. if (nestedThing !== undefined && nestedThing !== null && !helpers$1.isArray(nestedThing)) {
  9272. longest = helpers$1.measureText(ctx, data, gc, longest, nestedThing);
  9273. }
  9274. }
  9275. }
  9276. }
  9277. var gcLen = gc.length / 2;
  9278. if (gcLen > arrayOfThings.length) {
  9279. for (i = 0; i < gcLen; i++) {
  9280. delete data[gc[i]];
  9281. }
  9282. gc.splice(0, gcLen);
  9283. }
  9284. return longest;
  9285. };
  9286. helpers$1.measureText = function(ctx, data, gc, longest, string) {
  9287. var textWidth = data[string];
  9288. if (!textWidth) {
  9289. textWidth = data[string] = ctx.measureText(string).width;
  9290. gc.push(string);
  9291. }
  9292. if (textWidth > longest) {
  9293. longest = textWidth;
  9294. }
  9295. return longest;
  9296. };
  9297. /**
  9298. * @deprecated
  9299. */
  9300. helpers$1.numberOfLabelLines = function(arrayOfThings) {
  9301. var numberOfLines = 1;
  9302. helpers$1.each(arrayOfThings, function(thing) {
  9303. if (helpers$1.isArray(thing)) {
  9304. if (thing.length > numberOfLines) {
  9305. numberOfLines = thing.length;
  9306. }
  9307. }
  9308. });
  9309. return numberOfLines;
  9310. };
  9311. helpers$1.color = !chartjsColor ?
  9312. function(value) {
  9313. console.error('Color.js not found!');
  9314. return value;
  9315. } :
  9316. function(value) {
  9317. /* global CanvasGradient */
  9318. if (value instanceof CanvasGradient) {
  9319. value = core_defaults.global.defaultColor;
  9320. }
  9321. return chartjsColor(value);
  9322. };
  9323. helpers$1.getHoverColor = function(colorValue) {
  9324. /* global CanvasPattern */
  9325. return (colorValue instanceof CanvasPattern || colorValue instanceof CanvasGradient) ?
  9326. colorValue :
  9327. helpers$1.color(colorValue).saturate(0.5).darken(0.1).rgbString();
  9328. };
  9329. };
  9330. function abstract() {
  9331. throw new Error(
  9332. 'This method is not implemented: either no adapter can ' +
  9333. 'be found or an incomplete integration was provided.'
  9334. );
  9335. }
  9336. /**
  9337. * Date adapter (current used by the time scale)
  9338. * @namespace Chart._adapters._date
  9339. * @memberof Chart._adapters
  9340. * @private
  9341. */
  9342. /**
  9343. * Currently supported unit string values.
  9344. * @typedef {('millisecond'|'second'|'minute'|'hour'|'day'|'week'|'month'|'quarter'|'year')}
  9345. * @memberof Chart._adapters._date
  9346. * @name Unit
  9347. */
  9348. /**
  9349. * @class
  9350. */
  9351. function DateAdapter(options) {
  9352. this.options = options || {};
  9353. }
  9354. helpers$1.extend(DateAdapter.prototype, /** @lends DateAdapter */ {
  9355. /**
  9356. * Returns a map of time formats for the supported formatting units defined
  9357. * in Unit as well as 'datetime' representing a detailed date/time string.
  9358. * @returns {{string: string}}
  9359. */
  9360. formats: abstract,
  9361. /**
  9362. * Parses the given `value` and return the associated timestamp.
  9363. * @param {any} value - the value to parse (usually comes from the data)
  9364. * @param {string} [format] - the expected data format
  9365. * @returns {(number|null)}
  9366. * @function
  9367. */
  9368. parse: abstract,
  9369. /**
  9370. * Returns the formatted date in the specified `format` for a given `timestamp`.
  9371. * @param {number} timestamp - the timestamp to format
  9372. * @param {string} format - the date/time token
  9373. * @return {string}
  9374. * @function
  9375. */
  9376. format: abstract,
  9377. /**
  9378. * Adds the specified `amount` of `unit` to the given `timestamp`.
  9379. * @param {number} timestamp - the input timestamp
  9380. * @param {number} amount - the amount to add
  9381. * @param {Unit} unit - the unit as string
  9382. * @return {number}
  9383. * @function
  9384. */
  9385. add: abstract,
  9386. /**
  9387. * Returns the number of `unit` between the given timestamps.
  9388. * @param {number} max - the input timestamp (reference)
  9389. * @param {number} min - the timestamp to substract
  9390. * @param {Unit} unit - the unit as string
  9391. * @return {number}
  9392. * @function
  9393. */
  9394. diff: abstract,
  9395. /**
  9396. * Returns start of `unit` for the given `timestamp`.
  9397. * @param {number} timestamp - the input timestamp
  9398. * @param {Unit} unit - the unit as string
  9399. * @param {number} [weekday] - the ISO day of the week with 1 being Monday
  9400. * and 7 being Sunday (only needed if param *unit* is `isoWeek`).
  9401. * @function
  9402. */
  9403. startOf: abstract,
  9404. /**
  9405. * Returns end of `unit` for the given `timestamp`.
  9406. * @param {number} timestamp - the input timestamp
  9407. * @param {Unit} unit - the unit as string
  9408. * @function
  9409. */
  9410. endOf: abstract,
  9411. // DEPRECATIONS
  9412. /**
  9413. * Provided for backward compatibility for scale.getValueForPixel(),
  9414. * this method should be overridden only by the moment adapter.
  9415. * @deprecated since version 2.8.0
  9416. * @todo remove at version 3
  9417. * @private
  9418. */
  9419. _create: function(value) {
  9420. return value;
  9421. }
  9422. });
  9423. DateAdapter.override = function(members) {
  9424. helpers$1.extend(DateAdapter.prototype, members);
  9425. };
  9426. var _date = DateAdapter;
  9427. var core_adapters = {
  9428. _date: _date
  9429. };
  9430. /**
  9431. * Namespace to hold static tick generation functions
  9432. * @namespace Chart.Ticks
  9433. */
  9434. var core_ticks = {
  9435. /**
  9436. * Namespace to hold formatters for different types of ticks
  9437. * @namespace Chart.Ticks.formatters
  9438. */
  9439. formatters: {
  9440. /**
  9441. * Formatter for value labels
  9442. * @method Chart.Ticks.formatters.values
  9443. * @param value the value to display
  9444. * @return {string|string[]} the label to display
  9445. */
  9446. values: function(value) {
  9447. return helpers$1.isArray(value) ? value : '' + value;
  9448. },
  9449. /**
  9450. * Formatter for linear numeric ticks
  9451. * @method Chart.Ticks.formatters.linear
  9452. * @param tickValue {number} the value to be formatted
  9453. * @param index {number} the position of the tickValue parameter in the ticks array
  9454. * @param ticks {number[]} the list of ticks being converted
  9455. * @return {string} string representation of the tickValue parameter
  9456. */
  9457. linear: function(tickValue, index, ticks) {
  9458. // If we have lots of ticks, don't use the ones
  9459. var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0];
  9460. // If we have a number like 2.5 as the delta, figure out how many decimal places we need
  9461. if (Math.abs(delta) > 1) {
  9462. if (tickValue !== Math.floor(tickValue)) {
  9463. // not an integer
  9464. delta = tickValue - Math.floor(tickValue);
  9465. }
  9466. }
  9467. var logDelta = helpers$1.log10(Math.abs(delta));
  9468. var tickString = '';
  9469. if (tickValue !== 0) {
  9470. var maxTick = Math.max(Math.abs(ticks[0]), Math.abs(ticks[ticks.length - 1]));
  9471. if (maxTick < 1e-4) { // all ticks are small numbers; use scientific notation
  9472. var logTick = helpers$1.log10(Math.abs(tickValue));
  9473. var numExponential = Math.floor(logTick) - Math.floor(logDelta);
  9474. numExponential = Math.max(Math.min(numExponential, 20), 0);
  9475. tickString = tickValue.toExponential(numExponential);
  9476. } else {
  9477. var numDecimal = -1 * Math.floor(logDelta);
  9478. numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places
  9479. tickString = tickValue.toFixed(numDecimal);
  9480. }
  9481. } else {
  9482. tickString = '0'; // never show decimal places for 0
  9483. }
  9484. return tickString;
  9485. },
  9486. logarithmic: function(tickValue, index, ticks) {
  9487. var remain = tickValue / (Math.pow(10, Math.floor(helpers$1.log10(tickValue))));
  9488. if (tickValue === 0) {
  9489. return '0';
  9490. } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) {
  9491. return tickValue.toExponential();
  9492. }
  9493. return '';
  9494. }
  9495. }
  9496. };
  9497. var isArray = helpers$1.isArray;
  9498. var isNullOrUndef = helpers$1.isNullOrUndef;
  9499. var valueOrDefault$a = helpers$1.valueOrDefault;
  9500. var valueAtIndexOrDefault = helpers$1.valueAtIndexOrDefault;
  9501. core_defaults._set('scale', {
  9502. display: true,
  9503. position: 'left',
  9504. offset: false,
  9505. // grid line settings
  9506. gridLines: {
  9507. display: true,
  9508. color: 'rgba(0,0,0,0.1)',
  9509. lineWidth: 1,
  9510. drawBorder: true,
  9511. drawOnChartArea: true,
  9512. drawTicks: true,
  9513. tickMarkLength: 10,
  9514. zeroLineWidth: 1,
  9515. zeroLineColor: 'rgba(0,0,0,0.25)',
  9516. zeroLineBorderDash: [],
  9517. zeroLineBorderDashOffset: 0.0,
  9518. offsetGridLines: false,
  9519. borderDash: [],
  9520. borderDashOffset: 0.0
  9521. },
  9522. // scale label
  9523. scaleLabel: {
  9524. // display property
  9525. display: false,
  9526. // actual label
  9527. labelString: '',
  9528. // top/bottom padding
  9529. padding: {
  9530. top: 4,
  9531. bottom: 4
  9532. }
  9533. },
  9534. // label settings
  9535. ticks: {
  9536. beginAtZero: false,
  9537. minRotation: 0,
  9538. maxRotation: 50,
  9539. mirror: false,
  9540. padding: 0,
  9541. reverse: false,
  9542. display: true,
  9543. autoSkip: true,
  9544. autoSkipPadding: 0,
  9545. labelOffset: 0,
  9546. // We pass through arrays to be rendered as multiline labels, we convert Others to strings here.
  9547. callback: core_ticks.formatters.values,
  9548. minor: {},
  9549. major: {}
  9550. }
  9551. });
  9552. /** Returns a new array containing numItems from arr */
  9553. function sample(arr, numItems) {
  9554. var result = [];
  9555. var increment = arr.length / numItems;
  9556. var i = 0;
  9557. var len = arr.length;
  9558. for (; i < len; i += increment) {
  9559. result.push(arr[Math.floor(i)]);
  9560. }
  9561. return result;
  9562. }
  9563. function getPixelForGridLine(scale, index, offsetGridLines) {
  9564. var length = scale.getTicks().length;
  9565. var validIndex = Math.min(index, length - 1);
  9566. var lineValue = scale.getPixelForTick(validIndex);
  9567. var start = scale._startPixel;
  9568. var end = scale._endPixel;
  9569. var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error.
  9570. var offset;
  9571. if (offsetGridLines) {
  9572. if (length === 1) {
  9573. offset = Math.max(lineValue - start, end - lineValue);
  9574. } else if (index === 0) {
  9575. offset = (scale.getPixelForTick(1) - lineValue) / 2;
  9576. } else {
  9577. offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2;
  9578. }
  9579. lineValue += validIndex < index ? offset : -offset;
  9580. // Return undefined if the pixel is out of the range
  9581. if (lineValue < start - epsilon || lineValue > end + epsilon) {
  9582. return;
  9583. }
  9584. }
  9585. return lineValue;
  9586. }
  9587. function garbageCollect(caches, length) {
  9588. helpers$1.each(caches, function(cache) {
  9589. var gc = cache.gc;
  9590. var gcLen = gc.length / 2;
  9591. var i;
  9592. if (gcLen > length) {
  9593. for (i = 0; i < gcLen; ++i) {
  9594. delete cache.data[gc[i]];
  9595. }
  9596. gc.splice(0, gcLen);
  9597. }
  9598. });
  9599. }
  9600. /**
  9601. * Returns {width, height, offset} objects for the first, last, widest, highest tick
  9602. * labels where offset indicates the anchor point offset from the top in pixels.
  9603. */
  9604. function computeLabelSizes(ctx, tickFonts, ticks, caches) {
  9605. var length = ticks.length;
  9606. var widths = [];
  9607. var heights = [];
  9608. var offsets = [];
  9609. var i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel, widest, highest;
  9610. for (i = 0; i < length; ++i) {
  9611. label = ticks[i].label;
  9612. tickFont = ticks[i].major ? tickFonts.major : tickFonts.minor;
  9613. ctx.font = fontString = tickFont.string;
  9614. cache = caches[fontString] = caches[fontString] || {data: {}, gc: []};
  9615. lineHeight = tickFont.lineHeight;
  9616. width = height = 0;
  9617. // Undefined labels and arrays should not be measured
  9618. if (!isNullOrUndef(label) && !isArray(label)) {
  9619. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, label);
  9620. height = lineHeight;
  9621. } else if (isArray(label)) {
  9622. // if it is an array let's measure each element
  9623. for (j = 0, jlen = label.length; j < jlen; ++j) {
  9624. nestedLabel = label[j];
  9625. // Undefined labels and arrays should not be measured
  9626. if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) {
  9627. width = helpers$1.measureText(ctx, cache.data, cache.gc, width, nestedLabel);
  9628. height += lineHeight;
  9629. }
  9630. }
  9631. }
  9632. widths.push(width);
  9633. heights.push(height);
  9634. offsets.push(lineHeight / 2);
  9635. }
  9636. garbageCollect(caches, length);
  9637. widest = widths.indexOf(Math.max.apply(null, widths));
  9638. highest = heights.indexOf(Math.max.apply(null, heights));
  9639. function valueAt(idx) {
  9640. return {
  9641. width: widths[idx] || 0,
  9642. height: heights[idx] || 0,
  9643. offset: offsets[idx] || 0
  9644. };
  9645. }
  9646. return {
  9647. first: valueAt(0),
  9648. last: valueAt(length - 1),
  9649. widest: valueAt(widest),
  9650. highest: valueAt(highest)
  9651. };
  9652. }
  9653. function getTickMarkLength(options) {
  9654. return options.drawTicks ? options.tickMarkLength : 0;
  9655. }
  9656. function getScaleLabelHeight(options) {
  9657. var font, padding;
  9658. if (!options.display) {
  9659. return 0;
  9660. }
  9661. font = helpers$1.options._parseFont(options);
  9662. padding = helpers$1.options.toPadding(options.padding);
  9663. return font.lineHeight + padding.height;
  9664. }
  9665. function parseFontOptions(options, nestedOpts) {
  9666. return helpers$1.extend(helpers$1.options._parseFont({
  9667. fontFamily: valueOrDefault$a(nestedOpts.fontFamily, options.fontFamily),
  9668. fontSize: valueOrDefault$a(nestedOpts.fontSize, options.fontSize),
  9669. fontStyle: valueOrDefault$a(nestedOpts.fontStyle, options.fontStyle),
  9670. lineHeight: valueOrDefault$a(nestedOpts.lineHeight, options.lineHeight)
  9671. }), {
  9672. color: helpers$1.options.resolve([nestedOpts.fontColor, options.fontColor, core_defaults.global.defaultFontColor])
  9673. });
  9674. }
  9675. function parseTickFontOptions(options) {
  9676. var minor = parseFontOptions(options, options.minor);
  9677. var major = options.major.enabled ? parseFontOptions(options, options.major) : minor;
  9678. return {minor: minor, major: major};
  9679. }
  9680. function nonSkipped(ticksToFilter) {
  9681. var filtered = [];
  9682. var item, index, len;
  9683. for (index = 0, len = ticksToFilter.length; index < len; ++index) {
  9684. item = ticksToFilter[index];
  9685. if (typeof item._index !== 'undefined') {
  9686. filtered.push(item);
  9687. }
  9688. }
  9689. return filtered;
  9690. }
  9691. function getEvenSpacing(arr) {
  9692. var len = arr.length;
  9693. var i, diff;
  9694. if (len < 2) {
  9695. return false;
  9696. }
  9697. for (diff = arr[0], i = 1; i < len; ++i) {
  9698. if (arr[i] - arr[i - 1] !== diff) {
  9699. return false;
  9700. }
  9701. }
  9702. return diff;
  9703. }
  9704. function calculateSpacing(majorIndices, ticks, axisLength, ticksLimit) {
  9705. var evenMajorSpacing = getEvenSpacing(majorIndices);
  9706. var spacing = (ticks.length - 1) / ticksLimit;
  9707. var factors, factor, i, ilen;
  9708. // If the major ticks are evenly spaced apart, place the minor ticks
  9709. // so that they divide the major ticks into even chunks
  9710. if (!evenMajorSpacing) {
  9711. return Math.max(spacing, 1);
  9712. }
  9713. factors = helpers$1.math._factorize(evenMajorSpacing);
  9714. for (i = 0, ilen = factors.length - 1; i < ilen; i++) {
  9715. factor = factors[i];
  9716. if (factor > spacing) {
  9717. return factor;
  9718. }
  9719. }
  9720. return Math.max(spacing, 1);
  9721. }
  9722. function getMajorIndices(ticks) {
  9723. var result = [];
  9724. var i, ilen;
  9725. for (i = 0, ilen = ticks.length; i < ilen; i++) {
  9726. if (ticks[i].major) {
  9727. result.push(i);
  9728. }
  9729. }
  9730. return result;
  9731. }
  9732. function skipMajors(ticks, majorIndices, spacing) {
  9733. var count = 0;
  9734. var next = majorIndices[0];
  9735. var i, tick;
  9736. spacing = Math.ceil(spacing);
  9737. for (i = 0; i < ticks.length; i++) {
  9738. tick = ticks[i];
  9739. if (i === next) {
  9740. tick._index = i;
  9741. count++;
  9742. next = majorIndices[count * spacing];
  9743. } else {
  9744. delete tick.label;
  9745. }
  9746. }
  9747. }
  9748. function skip(ticks, spacing, majorStart, majorEnd) {
  9749. var start = valueOrDefault$a(majorStart, 0);
  9750. var end = Math.min(valueOrDefault$a(majorEnd, ticks.length), ticks.length);
  9751. var count = 0;
  9752. var length, i, tick, next;
  9753. spacing = Math.ceil(spacing);
  9754. if (majorEnd) {
  9755. length = majorEnd - majorStart;
  9756. spacing = length / Math.floor(length / spacing);
  9757. }
  9758. next = start;
  9759. while (next < 0) {
  9760. count++;
  9761. next = Math.round(start + count * spacing);
  9762. }
  9763. for (i = Math.max(start, 0); i < end; i++) {
  9764. tick = ticks[i];
  9765. if (i === next) {
  9766. tick._index = i;
  9767. count++;
  9768. next = Math.round(start + count * spacing);
  9769. } else {
  9770. delete tick.label;
  9771. }
  9772. }
  9773. }
  9774. var Scale = core_element.extend({
  9775. zeroLineIndex: 0,
  9776. /**
  9777. * Get the padding needed for the scale
  9778. * @method getPadding
  9779. * @private
  9780. * @returns {Padding} the necessary padding
  9781. */
  9782. getPadding: function() {
  9783. var me = this;
  9784. return {
  9785. left: me.paddingLeft || 0,
  9786. top: me.paddingTop || 0,
  9787. right: me.paddingRight || 0,
  9788. bottom: me.paddingBottom || 0
  9789. };
  9790. },
  9791. /**
  9792. * Returns the scale tick objects ({label, major})
  9793. * @since 2.7
  9794. */
  9795. getTicks: function() {
  9796. return this._ticks;
  9797. },
  9798. /**
  9799. * @private
  9800. */
  9801. _getLabels: function() {
  9802. var data = this.chart.data;
  9803. return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || [];
  9804. },
  9805. // These methods are ordered by lifecyle. Utilities then follow.
  9806. // Any function defined here is inherited by all scale types.
  9807. // Any function can be extended by the scale type
  9808. /**
  9809. * Provided for backward compatibility, not available anymore
  9810. * @function Chart.Scale.mergeTicksOptions
  9811. * @deprecated since version 2.8.0
  9812. * @todo remove at version 3
  9813. */
  9814. mergeTicksOptions: function() {
  9815. // noop
  9816. },
  9817. beforeUpdate: function() {
  9818. helpers$1.callback(this.options.beforeUpdate, [this]);
  9819. },
  9820. /**
  9821. * @param {number} maxWidth - the max width in pixels
  9822. * @param {number} maxHeight - the max height in pixels
  9823. * @param {object} margins - the space between the edge of the other scales and edge of the chart
  9824. * This space comes from two sources:
  9825. * - padding - space that's required to show the labels at the edges of the scale
  9826. * - thickness of scales or legends in another orientation
  9827. */
  9828. update: function(maxWidth, maxHeight, margins) {
  9829. var me = this;
  9830. var tickOpts = me.options.ticks;
  9831. var sampleSize = tickOpts.sampleSize;
  9832. var i, ilen, labels, ticks, samplingEnabled;
  9833. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  9834. me.beforeUpdate();
  9835. // Absorb the master measurements
  9836. me.maxWidth = maxWidth;
  9837. me.maxHeight = maxHeight;
  9838. me.margins = helpers$1.extend({
  9839. left: 0,
  9840. right: 0,
  9841. top: 0,
  9842. bottom: 0
  9843. }, margins);
  9844. me._ticks = null;
  9845. me.ticks = null;
  9846. me._labelSizes = null;
  9847. me._maxLabelLines = 0;
  9848. me.longestLabelWidth = 0;
  9849. me.longestTextCache = me.longestTextCache || {};
  9850. me._gridLineItems = null;
  9851. me._labelItems = null;
  9852. // Dimensions
  9853. me.beforeSetDimensions();
  9854. me.setDimensions();
  9855. me.afterSetDimensions();
  9856. // Data min/max
  9857. me.beforeDataLimits();
  9858. me.determineDataLimits();
  9859. me.afterDataLimits();
  9860. // Ticks - `this.ticks` is now DEPRECATED!
  9861. // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member
  9862. // and must not be accessed directly from outside this class. `this.ticks` being
  9863. // around for long time and not marked as private, we can't change its structure
  9864. // without unexpected breaking changes. If you need to access the scale ticks,
  9865. // use scale.getTicks() instead.
  9866. me.beforeBuildTicks();
  9867. // New implementations should return an array of objects but for BACKWARD COMPAT,
  9868. // we still support no return (`this.ticks` internally set by calling this method).
  9869. ticks = me.buildTicks() || [];
  9870. // Allow modification of ticks in callback.
  9871. ticks = me.afterBuildTicks(ticks) || ticks;
  9872. // Ensure ticks contains ticks in new tick format
  9873. if ((!ticks || !ticks.length) && me.ticks) {
  9874. ticks = [];
  9875. for (i = 0, ilen = me.ticks.length; i < ilen; ++i) {
  9876. ticks.push({
  9877. value: me.ticks[i],
  9878. major: false
  9879. });
  9880. }
  9881. }
  9882. me._ticks = ticks;
  9883. // Compute tick rotation and fit using a sampled subset of labels
  9884. // We generally don't need to compute the size of every single label for determining scale size
  9885. samplingEnabled = sampleSize < ticks.length;
  9886. labels = me._convertTicksToLabels(samplingEnabled ? sample(ticks, sampleSize) : ticks);
  9887. // _configure is called twice, once here, once from core.controller.updateLayout.
  9888. // Here we haven't been positioned yet, but dimensions are correct.
  9889. // Variables set in _configure are needed for calculateTickRotation, and
  9890. // it's ok that coordinates are not correct there, only dimensions matter.
  9891. me._configure();
  9892. // Tick Rotation
  9893. me.beforeCalculateTickRotation();
  9894. me.calculateTickRotation();
  9895. me.afterCalculateTickRotation();
  9896. me.beforeFit();
  9897. me.fit();
  9898. me.afterFit();
  9899. // Auto-skip
  9900. me._ticksToDraw = tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto') ? me._autoSkip(ticks) : ticks;
  9901. if (samplingEnabled) {
  9902. // Generate labels using all non-skipped ticks
  9903. labels = me._convertTicksToLabels(me._ticksToDraw);
  9904. }
  9905. me.ticks = labels; // BACKWARD COMPATIBILITY
  9906. // IMPORTANT: after this point, we consider that `this.ticks` will NEVER change!
  9907. me.afterUpdate();
  9908. // TODO(v3): remove minSize as a public property and return value from all layout boxes. It is unused
  9909. // make maxWidth and maxHeight private
  9910. return me.minSize;
  9911. },
  9912. /**
  9913. * @private
  9914. */
  9915. _configure: function() {
  9916. var me = this;
  9917. var reversePixels = me.options.ticks.reverse;
  9918. var startPixel, endPixel;
  9919. if (me.isHorizontal()) {
  9920. startPixel = me.left;
  9921. endPixel = me.right;
  9922. } else {
  9923. startPixel = me.top;
  9924. endPixel = me.bottom;
  9925. // by default vertical scales are from bottom to top, so pixels are reversed
  9926. reversePixels = !reversePixels;
  9927. }
  9928. me._startPixel = startPixel;
  9929. me._endPixel = endPixel;
  9930. me._reversePixels = reversePixels;
  9931. me._length = endPixel - startPixel;
  9932. },
  9933. afterUpdate: function() {
  9934. helpers$1.callback(this.options.afterUpdate, [this]);
  9935. },
  9936. //
  9937. beforeSetDimensions: function() {
  9938. helpers$1.callback(this.options.beforeSetDimensions, [this]);
  9939. },
  9940. setDimensions: function() {
  9941. var me = this;
  9942. // Set the unconstrained dimension before label rotation
  9943. if (me.isHorizontal()) {
  9944. // Reset position before calculating rotation
  9945. me.width = me.maxWidth;
  9946. me.left = 0;
  9947. me.right = me.width;
  9948. } else {
  9949. me.height = me.maxHeight;
  9950. // Reset position before calculating rotation
  9951. me.top = 0;
  9952. me.bottom = me.height;
  9953. }
  9954. // Reset padding
  9955. me.paddingLeft = 0;
  9956. me.paddingTop = 0;
  9957. me.paddingRight = 0;
  9958. me.paddingBottom = 0;
  9959. },
  9960. afterSetDimensions: function() {
  9961. helpers$1.callback(this.options.afterSetDimensions, [this]);
  9962. },
  9963. // Data limits
  9964. beforeDataLimits: function() {
  9965. helpers$1.callback(this.options.beforeDataLimits, [this]);
  9966. },
  9967. determineDataLimits: helpers$1.noop,
  9968. afterDataLimits: function() {
  9969. helpers$1.callback(this.options.afterDataLimits, [this]);
  9970. },
  9971. //
  9972. beforeBuildTicks: function() {
  9973. helpers$1.callback(this.options.beforeBuildTicks, [this]);
  9974. },
  9975. buildTicks: helpers$1.noop,
  9976. afterBuildTicks: function(ticks) {
  9977. var me = this;
  9978. // ticks is empty for old axis implementations here
  9979. if (isArray(ticks) && ticks.length) {
  9980. return helpers$1.callback(me.options.afterBuildTicks, [me, ticks]);
  9981. }
  9982. // Support old implementations (that modified `this.ticks` directly in buildTicks)
  9983. me.ticks = helpers$1.callback(me.options.afterBuildTicks, [me, me.ticks]) || me.ticks;
  9984. return ticks;
  9985. },
  9986. beforeTickToLabelConversion: function() {
  9987. helpers$1.callback(this.options.beforeTickToLabelConversion, [this]);
  9988. },
  9989. convertTicksToLabels: function() {
  9990. var me = this;
  9991. // Convert ticks to strings
  9992. var tickOpts = me.options.ticks;
  9993. me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this);
  9994. },
  9995. afterTickToLabelConversion: function() {
  9996. helpers$1.callback(this.options.afterTickToLabelConversion, [this]);
  9997. },
  9998. //
  9999. beforeCalculateTickRotation: function() {
  10000. helpers$1.callback(this.options.beforeCalculateTickRotation, [this]);
  10001. },
  10002. calculateTickRotation: function() {
  10003. var me = this;
  10004. var options = me.options;
  10005. var tickOpts = options.ticks;
  10006. var numTicks = me.getTicks().length;
  10007. var minRotation = tickOpts.minRotation || 0;
  10008. var maxRotation = tickOpts.maxRotation;
  10009. var labelRotation = minRotation;
  10010. var labelSizes, maxLabelWidth, maxLabelHeight, maxWidth, tickWidth, maxHeight, maxLabelDiagonal;
  10011. if (!me._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !me.isHorizontal()) {
  10012. me.labelRotation = minRotation;
  10013. return;
  10014. }
  10015. labelSizes = me._getLabelSizes();
  10016. maxLabelWidth = labelSizes.widest.width;
  10017. maxLabelHeight = labelSizes.highest.height - labelSizes.highest.offset;
  10018. // Estimate the width of each grid based on the canvas width, the maximum
  10019. // label width and the number of tick intervals
  10020. maxWidth = Math.min(me.maxWidth, me.chart.width - maxLabelWidth);
  10021. tickWidth = options.offset ? me.maxWidth / numTicks : maxWidth / (numTicks - 1);
  10022. // Allow 3 pixels x2 padding either side for label readability
  10023. if (maxLabelWidth + 6 > tickWidth) {
  10024. tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1));
  10025. maxHeight = me.maxHeight - getTickMarkLength(options.gridLines)
  10026. - tickOpts.padding - getScaleLabelHeight(options.scaleLabel);
  10027. maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
  10028. labelRotation = helpers$1.toDegrees(Math.min(
  10029. Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
  10030. Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
  10031. ));
  10032. labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
  10033. }
  10034. me.labelRotation = labelRotation;
  10035. },
  10036. afterCalculateTickRotation: function() {
  10037. helpers$1.callback(this.options.afterCalculateTickRotation, [this]);
  10038. },
  10039. //
  10040. beforeFit: function() {
  10041. helpers$1.callback(this.options.beforeFit, [this]);
  10042. },
  10043. fit: function() {
  10044. var me = this;
  10045. // Reset
  10046. var minSize = me.minSize = {
  10047. width: 0,
  10048. height: 0
  10049. };
  10050. var chart = me.chart;
  10051. var opts = me.options;
  10052. var tickOpts = opts.ticks;
  10053. var scaleLabelOpts = opts.scaleLabel;
  10054. var gridLineOpts = opts.gridLines;
  10055. var display = me._isVisible();
  10056. var isBottom = opts.position === 'bottom';
  10057. var isHorizontal = me.isHorizontal();
  10058. // Width
  10059. if (isHorizontal) {
  10060. minSize.width = me.maxWidth;
  10061. } else if (display) {
  10062. minSize.width = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10063. }
  10064. // height
  10065. if (!isHorizontal) {
  10066. minSize.height = me.maxHeight; // fill all the height
  10067. } else if (display) {
  10068. minSize.height = getTickMarkLength(gridLineOpts) + getScaleLabelHeight(scaleLabelOpts);
  10069. }
  10070. // Don't bother fitting the ticks if we are not showing the labels
  10071. if (tickOpts.display && display) {
  10072. var tickFonts = parseTickFontOptions(tickOpts);
  10073. var labelSizes = me._getLabelSizes();
  10074. var firstLabelSize = labelSizes.first;
  10075. var lastLabelSize = labelSizes.last;
  10076. var widestLabelSize = labelSizes.widest;
  10077. var highestLabelSize = labelSizes.highest;
  10078. var lineSpace = tickFonts.minor.lineHeight * 0.4;
  10079. var tickPadding = tickOpts.padding;
  10080. if (isHorizontal) {
  10081. // A horizontal axis is more constrained by the height.
  10082. var isRotated = me.labelRotation !== 0;
  10083. var angleRadians = helpers$1.toRadians(me.labelRotation);
  10084. var cosRotation = Math.cos(angleRadians);
  10085. var sinRotation = Math.sin(angleRadians);
  10086. var labelHeight = sinRotation * widestLabelSize.width
  10087. + cosRotation * (highestLabelSize.height - (isRotated ? highestLabelSize.offset : 0))
  10088. + (isRotated ? 0 : lineSpace); // padding
  10089. minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding);
  10090. var offsetLeft = me.getPixelForTick(0) - me.left;
  10091. var offsetRight = me.right - me.getPixelForTick(me.getTicks().length - 1);
  10092. var paddingLeft, paddingRight;
  10093. // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned
  10094. // which means that the right padding is dominated by the font height
  10095. if (isRotated) {
  10096. paddingLeft = isBottom ?
  10097. cosRotation * firstLabelSize.width + sinRotation * firstLabelSize.offset :
  10098. sinRotation * (firstLabelSize.height - firstLabelSize.offset);
  10099. paddingRight = isBottom ?
  10100. sinRotation * (lastLabelSize.height - lastLabelSize.offset) :
  10101. cosRotation * lastLabelSize.width + sinRotation * lastLabelSize.offset;
  10102. } else {
  10103. paddingLeft = firstLabelSize.width / 2;
  10104. paddingRight = lastLabelSize.width / 2;
  10105. }
  10106. // Adjust padding taking into account changes in offsets
  10107. // and add 3 px to move away from canvas edges
  10108. me.paddingLeft = Math.max((paddingLeft - offsetLeft) * me.width / (me.width - offsetLeft), 0) + 3;
  10109. me.paddingRight = Math.max((paddingRight - offsetRight) * me.width / (me.width - offsetRight), 0) + 3;
  10110. } else {
  10111. // A vertical axis is more constrained by the width. Labels are the
  10112. // dominant factor here, so get that length first and account for padding
  10113. var labelWidth = tickOpts.mirror ? 0 :
  10114. // use lineSpace for consistency with horizontal axis
  10115. // tickPadding is not implemented for horizontal
  10116. widestLabelSize.width + tickPadding + lineSpace;
  10117. minSize.width = Math.min(me.maxWidth, minSize.width + labelWidth);
  10118. me.paddingTop = firstLabelSize.height / 2;
  10119. me.paddingBottom = lastLabelSize.height / 2;
  10120. }
  10121. }
  10122. me.handleMargins();
  10123. if (isHorizontal) {
  10124. me.width = me._length = chart.width - me.margins.left - me.margins.right;
  10125. me.height = minSize.height;
  10126. } else {
  10127. me.width = minSize.width;
  10128. me.height = me._length = chart.height - me.margins.top - me.margins.bottom;
  10129. }
  10130. },
  10131. /**
  10132. * Handle margins and padding interactions
  10133. * @private
  10134. */
  10135. handleMargins: function() {
  10136. var me = this;
  10137. if (me.margins) {
  10138. me.margins.left = Math.max(me.paddingLeft, me.margins.left);
  10139. me.margins.top = Math.max(me.paddingTop, me.margins.top);
  10140. me.margins.right = Math.max(me.paddingRight, me.margins.right);
  10141. me.margins.bottom = Math.max(me.paddingBottom, me.margins.bottom);
  10142. }
  10143. },
  10144. afterFit: function() {
  10145. helpers$1.callback(this.options.afterFit, [this]);
  10146. },
  10147. // Shared Methods
  10148. isHorizontal: function() {
  10149. var pos = this.options.position;
  10150. return pos === 'top' || pos === 'bottom';
  10151. },
  10152. isFullWidth: function() {
  10153. return this.options.fullWidth;
  10154. },
  10155. // 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
  10156. getRightValue: function(rawValue) {
  10157. // Null and undefined values first
  10158. if (isNullOrUndef(rawValue)) {
  10159. return NaN;
  10160. }
  10161. // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values
  10162. if ((typeof rawValue === 'number' || rawValue instanceof Number) && !isFinite(rawValue)) {
  10163. return NaN;
  10164. }
  10165. // If it is in fact an object, dive in one more level
  10166. if (rawValue) {
  10167. if (this.isHorizontal()) {
  10168. if (rawValue.x !== undefined) {
  10169. return this.getRightValue(rawValue.x);
  10170. }
  10171. } else if (rawValue.y !== undefined) {
  10172. return this.getRightValue(rawValue.y);
  10173. }
  10174. }
  10175. // Value is good, return it
  10176. return rawValue;
  10177. },
  10178. _convertTicksToLabels: function(ticks) {
  10179. var me = this;
  10180. var labels, i, ilen;
  10181. me.ticks = ticks.map(function(tick) {
  10182. return tick.value;
  10183. });
  10184. me.beforeTickToLabelConversion();
  10185. // New implementations should return the formatted tick labels but for BACKWARD
  10186. // COMPAT, we still support no return (`this.ticks` internally changed by calling
  10187. // this method and supposed to contain only string values).
  10188. labels = me.convertTicksToLabels(ticks) || me.ticks;
  10189. me.afterTickToLabelConversion();
  10190. // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`)
  10191. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10192. ticks[i].label = labels[i];
  10193. }
  10194. return labels;
  10195. },
  10196. /**
  10197. * @private
  10198. */
  10199. _getLabelSizes: function() {
  10200. var me = this;
  10201. var labelSizes = me._labelSizes;
  10202. if (!labelSizes) {
  10203. me._labelSizes = labelSizes = computeLabelSizes(me.ctx, parseTickFontOptions(me.options.ticks), me.getTicks(), me.longestTextCache);
  10204. me.longestLabelWidth = labelSizes.widest.width;
  10205. }
  10206. return labelSizes;
  10207. },
  10208. /**
  10209. * @private
  10210. */
  10211. _parseValue: function(value) {
  10212. var start, end, min, max;
  10213. if (isArray(value)) {
  10214. start = +this.getRightValue(value[0]);
  10215. end = +this.getRightValue(value[1]);
  10216. min = Math.min(start, end);
  10217. max = Math.max(start, end);
  10218. } else {
  10219. value = +this.getRightValue(value);
  10220. start = undefined;
  10221. end = value;
  10222. min = value;
  10223. max = value;
  10224. }
  10225. return {
  10226. min: min,
  10227. max: max,
  10228. start: start,
  10229. end: end
  10230. };
  10231. },
  10232. /**
  10233. * @private
  10234. */
  10235. _getScaleLabel: function(rawValue) {
  10236. var v = this._parseValue(rawValue);
  10237. if (v.start !== undefined) {
  10238. return '[' + v.start + ', ' + v.end + ']';
  10239. }
  10240. return +this.getRightValue(rawValue);
  10241. },
  10242. /**
  10243. * Used to get the value to display in the tooltip for the data at the given index
  10244. * @param index
  10245. * @param datasetIndex
  10246. */
  10247. getLabelForIndex: helpers$1.noop,
  10248. /**
  10249. * Returns the location of the given data point. Value can either be an index or a numerical value
  10250. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10251. * @param value
  10252. * @param index
  10253. * @param datasetIndex
  10254. */
  10255. getPixelForValue: helpers$1.noop,
  10256. /**
  10257. * Used to get the data value from a given pixel. This is the inverse of getPixelForValue
  10258. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10259. * @param pixel
  10260. */
  10261. getValueForPixel: helpers$1.noop,
  10262. /**
  10263. * Returns the location of the tick at the given index
  10264. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10265. */
  10266. getPixelForTick: function(index) {
  10267. var me = this;
  10268. var offset = me.options.offset;
  10269. var numTicks = me._ticks.length;
  10270. var tickWidth = 1 / Math.max(numTicks - (offset ? 0 : 1), 1);
  10271. return index < 0 || index > numTicks - 1
  10272. ? null
  10273. : me.getPixelForDecimal(index * tickWidth + (offset ? tickWidth / 2 : 0));
  10274. },
  10275. /**
  10276. * Utility for getting the pixel location of a percentage of scale
  10277. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10278. */
  10279. getPixelForDecimal: function(decimal) {
  10280. var me = this;
  10281. if (me._reversePixels) {
  10282. decimal = 1 - decimal;
  10283. }
  10284. return me._startPixel + decimal * me._length;
  10285. },
  10286. getDecimalForPixel: function(pixel) {
  10287. var decimal = (pixel - this._startPixel) / this._length;
  10288. return this._reversePixels ? 1 - decimal : decimal;
  10289. },
  10290. /**
  10291. * Returns the pixel for the minimum chart value
  10292. * The coordinate (0, 0) is at the upper-left corner of the canvas
  10293. */
  10294. getBasePixel: function() {
  10295. return this.getPixelForValue(this.getBaseValue());
  10296. },
  10297. getBaseValue: function() {
  10298. var me = this;
  10299. var min = me.min;
  10300. var max = me.max;
  10301. return me.beginAtZero ? 0 :
  10302. min < 0 && max < 0 ? max :
  10303. min > 0 && max > 0 ? min :
  10304. 0;
  10305. },
  10306. /**
  10307. * Returns a subset of ticks to be plotted to avoid overlapping labels.
  10308. * @private
  10309. */
  10310. _autoSkip: function(ticks) {
  10311. var me = this;
  10312. var tickOpts = me.options.ticks;
  10313. var axisLength = me._length;
  10314. var ticksLimit = tickOpts.maxTicksLimit || axisLength / me._tickSize() + 1;
  10315. var majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : [];
  10316. var numMajorIndices = majorIndices.length;
  10317. var first = majorIndices[0];
  10318. var last = majorIndices[numMajorIndices - 1];
  10319. var i, ilen, spacing, avgMajorSpacing;
  10320. // If there are too many major ticks to display them all
  10321. if (numMajorIndices > ticksLimit) {
  10322. skipMajors(ticks, majorIndices, numMajorIndices / ticksLimit);
  10323. return nonSkipped(ticks);
  10324. }
  10325. spacing = calculateSpacing(majorIndices, ticks, axisLength, ticksLimit);
  10326. if (numMajorIndices > 0) {
  10327. for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) {
  10328. skip(ticks, spacing, majorIndices[i], majorIndices[i + 1]);
  10329. }
  10330. avgMajorSpacing = numMajorIndices > 1 ? (last - first) / (numMajorIndices - 1) : null;
  10331. skip(ticks, spacing, helpers$1.isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first);
  10332. skip(ticks, spacing, last, helpers$1.isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing);
  10333. return nonSkipped(ticks);
  10334. }
  10335. skip(ticks, spacing);
  10336. return nonSkipped(ticks);
  10337. },
  10338. /**
  10339. * @private
  10340. */
  10341. _tickSize: function() {
  10342. var me = this;
  10343. var optionTicks = me.options.ticks;
  10344. // Calculate space needed by label in axis direction.
  10345. var rot = helpers$1.toRadians(me.labelRotation);
  10346. var cos = Math.abs(Math.cos(rot));
  10347. var sin = Math.abs(Math.sin(rot));
  10348. var labelSizes = me._getLabelSizes();
  10349. var padding = optionTicks.autoSkipPadding || 0;
  10350. var w = labelSizes ? labelSizes.widest.width + padding : 0;
  10351. var h = labelSizes ? labelSizes.highest.height + padding : 0;
  10352. // Calculate space needed for 1 tick in axis direction.
  10353. return me.isHorizontal()
  10354. ? h * cos > w * sin ? w / cos : h / sin
  10355. : h * sin < w * cos ? h / cos : w / sin;
  10356. },
  10357. /**
  10358. * @private
  10359. */
  10360. _isVisible: function() {
  10361. var me = this;
  10362. var chart = me.chart;
  10363. var display = me.options.display;
  10364. var i, ilen, meta;
  10365. if (display !== 'auto') {
  10366. return !!display;
  10367. }
  10368. // When 'auto', the scale is visible if at least one associated dataset is visible.
  10369. for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) {
  10370. if (chart.isDatasetVisible(i)) {
  10371. meta = chart.getDatasetMeta(i);
  10372. if (meta.xAxisID === me.id || meta.yAxisID === me.id) {
  10373. return true;
  10374. }
  10375. }
  10376. }
  10377. return false;
  10378. },
  10379. /**
  10380. * @private
  10381. */
  10382. _computeGridLineItems: function(chartArea) {
  10383. var me = this;
  10384. var chart = me.chart;
  10385. var options = me.options;
  10386. var gridLines = options.gridLines;
  10387. var position = options.position;
  10388. var offsetGridLines = gridLines.offsetGridLines;
  10389. var isHorizontal = me.isHorizontal();
  10390. var ticks = me._ticksToDraw;
  10391. var ticksLength = ticks.length + (offsetGridLines ? 1 : 0);
  10392. var tl = getTickMarkLength(gridLines);
  10393. var items = [];
  10394. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10395. var axisHalfWidth = axisWidth / 2;
  10396. var alignPixel = helpers$1._alignPixel;
  10397. var alignBorderValue = function(pixel) {
  10398. return alignPixel(chart, pixel, axisWidth);
  10399. };
  10400. var borderValue, i, tick, lineValue, alignedLineValue;
  10401. var tx1, ty1, tx2, ty2, x1, y1, x2, y2, lineWidth, lineColor, borderDash, borderDashOffset;
  10402. if (position === 'top') {
  10403. borderValue = alignBorderValue(me.bottom);
  10404. ty1 = me.bottom - tl;
  10405. ty2 = borderValue - axisHalfWidth;
  10406. y1 = alignBorderValue(chartArea.top) + axisHalfWidth;
  10407. y2 = chartArea.bottom;
  10408. } else if (position === 'bottom') {
  10409. borderValue = alignBorderValue(me.top);
  10410. y1 = chartArea.top;
  10411. y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth;
  10412. ty1 = borderValue + axisHalfWidth;
  10413. ty2 = me.top + tl;
  10414. } else if (position === 'left') {
  10415. borderValue = alignBorderValue(me.right);
  10416. tx1 = me.right - tl;
  10417. tx2 = borderValue - axisHalfWidth;
  10418. x1 = alignBorderValue(chartArea.left) + axisHalfWidth;
  10419. x2 = chartArea.right;
  10420. } else {
  10421. borderValue = alignBorderValue(me.left);
  10422. x1 = chartArea.left;
  10423. x2 = alignBorderValue(chartArea.right) - axisHalfWidth;
  10424. tx1 = borderValue + axisHalfWidth;
  10425. tx2 = me.left + tl;
  10426. }
  10427. for (i = 0; i < ticksLength; ++i) {
  10428. tick = ticks[i] || {};
  10429. // autoskipper skipped this tick (#4635)
  10430. if (isNullOrUndef(tick.label) && i < ticks.length) {
  10431. continue;
  10432. }
  10433. if (i === me.zeroLineIndex && options.offset === offsetGridLines) {
  10434. // Draw the first index specially
  10435. lineWidth = gridLines.zeroLineWidth;
  10436. lineColor = gridLines.zeroLineColor;
  10437. borderDash = gridLines.zeroLineBorderDash || [];
  10438. borderDashOffset = gridLines.zeroLineBorderDashOffset || 0.0;
  10439. } else {
  10440. lineWidth = valueAtIndexOrDefault(gridLines.lineWidth, i, 1);
  10441. lineColor = valueAtIndexOrDefault(gridLines.color, i, 'rgba(0,0,0,0.1)');
  10442. borderDash = gridLines.borderDash || [];
  10443. borderDashOffset = gridLines.borderDashOffset || 0.0;
  10444. }
  10445. lineValue = getPixelForGridLine(me, tick._index || i, offsetGridLines);
  10446. // Skip if the pixel is out of the range
  10447. if (lineValue === undefined) {
  10448. continue;
  10449. }
  10450. alignedLineValue = alignPixel(chart, lineValue, lineWidth);
  10451. if (isHorizontal) {
  10452. tx1 = tx2 = x1 = x2 = alignedLineValue;
  10453. } else {
  10454. ty1 = ty2 = y1 = y2 = alignedLineValue;
  10455. }
  10456. items.push({
  10457. tx1: tx1,
  10458. ty1: ty1,
  10459. tx2: tx2,
  10460. ty2: ty2,
  10461. x1: x1,
  10462. y1: y1,
  10463. x2: x2,
  10464. y2: y2,
  10465. width: lineWidth,
  10466. color: lineColor,
  10467. borderDash: borderDash,
  10468. borderDashOffset: borderDashOffset,
  10469. });
  10470. }
  10471. items.ticksLength = ticksLength;
  10472. items.borderValue = borderValue;
  10473. return items;
  10474. },
  10475. /**
  10476. * @private
  10477. */
  10478. _computeLabelItems: function() {
  10479. var me = this;
  10480. var options = me.options;
  10481. var optionTicks = options.ticks;
  10482. var position = options.position;
  10483. var isMirrored = optionTicks.mirror;
  10484. var isHorizontal = me.isHorizontal();
  10485. var ticks = me._ticksToDraw;
  10486. var fonts = parseTickFontOptions(optionTicks);
  10487. var tickPadding = optionTicks.padding;
  10488. var tl = getTickMarkLength(options.gridLines);
  10489. var rotation = -helpers$1.toRadians(me.labelRotation);
  10490. var items = [];
  10491. var i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset;
  10492. if (position === 'top') {
  10493. y = me.bottom - tl - tickPadding;
  10494. textAlign = !rotation ? 'center' : 'left';
  10495. } else if (position === 'bottom') {
  10496. y = me.top + tl + tickPadding;
  10497. textAlign = !rotation ? 'center' : 'right';
  10498. } else if (position === 'left') {
  10499. x = me.right - (isMirrored ? 0 : tl) - tickPadding;
  10500. textAlign = isMirrored ? 'left' : 'right';
  10501. } else {
  10502. x = me.left + (isMirrored ? 0 : tl) + tickPadding;
  10503. textAlign = isMirrored ? 'right' : 'left';
  10504. }
  10505. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  10506. tick = ticks[i];
  10507. label = tick.label;
  10508. // autoskipper skipped this tick (#4635)
  10509. if (isNullOrUndef(label)) {
  10510. continue;
  10511. }
  10512. pixel = me.getPixelForTick(tick._index || i) + optionTicks.labelOffset;
  10513. font = tick.major ? fonts.major : fonts.minor;
  10514. lineHeight = font.lineHeight;
  10515. lineCount = isArray(label) ? label.length : 1;
  10516. if (isHorizontal) {
  10517. x = pixel;
  10518. textOffset = position === 'top'
  10519. ? ((!rotation ? 0.5 : 1) - lineCount) * lineHeight
  10520. : (!rotation ? 0.5 : 0) * lineHeight;
  10521. } else {
  10522. y = pixel;
  10523. textOffset = (1 - lineCount) * lineHeight / 2;
  10524. }
  10525. items.push({
  10526. x: x,
  10527. y: y,
  10528. rotation: rotation,
  10529. label: label,
  10530. font: font,
  10531. textOffset: textOffset,
  10532. textAlign: textAlign
  10533. });
  10534. }
  10535. return items;
  10536. },
  10537. /**
  10538. * @private
  10539. */
  10540. _drawGrid: function(chartArea) {
  10541. var me = this;
  10542. var gridLines = me.options.gridLines;
  10543. if (!gridLines.display) {
  10544. return;
  10545. }
  10546. var ctx = me.ctx;
  10547. var chart = me.chart;
  10548. var alignPixel = helpers$1._alignPixel;
  10549. var axisWidth = gridLines.drawBorder ? valueAtIndexOrDefault(gridLines.lineWidth, 0, 0) : 0;
  10550. var items = me._gridLineItems || (me._gridLineItems = me._computeGridLineItems(chartArea));
  10551. var width, color, i, ilen, item;
  10552. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10553. item = items[i];
  10554. width = item.width;
  10555. color = item.color;
  10556. if (width && color) {
  10557. ctx.save();
  10558. ctx.lineWidth = width;
  10559. ctx.strokeStyle = color;
  10560. if (ctx.setLineDash) {
  10561. ctx.setLineDash(item.borderDash);
  10562. ctx.lineDashOffset = item.borderDashOffset;
  10563. }
  10564. ctx.beginPath();
  10565. if (gridLines.drawTicks) {
  10566. ctx.moveTo(item.tx1, item.ty1);
  10567. ctx.lineTo(item.tx2, item.ty2);
  10568. }
  10569. if (gridLines.drawOnChartArea) {
  10570. ctx.moveTo(item.x1, item.y1);
  10571. ctx.lineTo(item.x2, item.y2);
  10572. }
  10573. ctx.stroke();
  10574. ctx.restore();
  10575. }
  10576. }
  10577. if (axisWidth) {
  10578. // Draw the line at the edge of the axis
  10579. var firstLineWidth = axisWidth;
  10580. var lastLineWidth = valueAtIndexOrDefault(gridLines.lineWidth, items.ticksLength - 1, 1);
  10581. var borderValue = items.borderValue;
  10582. var x1, x2, y1, y2;
  10583. if (me.isHorizontal()) {
  10584. x1 = alignPixel(chart, me.left, firstLineWidth) - firstLineWidth / 2;
  10585. x2 = alignPixel(chart, me.right, lastLineWidth) + lastLineWidth / 2;
  10586. y1 = y2 = borderValue;
  10587. } else {
  10588. y1 = alignPixel(chart, me.top, firstLineWidth) - firstLineWidth / 2;
  10589. y2 = alignPixel(chart, me.bottom, lastLineWidth) + lastLineWidth / 2;
  10590. x1 = x2 = borderValue;
  10591. }
  10592. ctx.lineWidth = axisWidth;
  10593. ctx.strokeStyle = valueAtIndexOrDefault(gridLines.color, 0);
  10594. ctx.beginPath();
  10595. ctx.moveTo(x1, y1);
  10596. ctx.lineTo(x2, y2);
  10597. ctx.stroke();
  10598. }
  10599. },
  10600. /**
  10601. * @private
  10602. */
  10603. _drawLabels: function() {
  10604. var me = this;
  10605. var optionTicks = me.options.ticks;
  10606. if (!optionTicks.display) {
  10607. return;
  10608. }
  10609. var ctx = me.ctx;
  10610. var items = me._labelItems || (me._labelItems = me._computeLabelItems());
  10611. var i, j, ilen, jlen, item, tickFont, label, y;
  10612. for (i = 0, ilen = items.length; i < ilen; ++i) {
  10613. item = items[i];
  10614. tickFont = item.font;
  10615. // Make sure we draw text in the correct color and font
  10616. ctx.save();
  10617. ctx.translate(item.x, item.y);
  10618. ctx.rotate(item.rotation);
  10619. ctx.font = tickFont.string;
  10620. ctx.fillStyle = tickFont.color;
  10621. ctx.textBaseline = 'middle';
  10622. ctx.textAlign = item.textAlign;
  10623. label = item.label;
  10624. y = item.textOffset;
  10625. if (isArray(label)) {
  10626. for (j = 0, jlen = label.length; j < jlen; ++j) {
  10627. // We just make sure the multiline element is a string here..
  10628. ctx.fillText('' + label[j], 0, y);
  10629. y += tickFont.lineHeight;
  10630. }
  10631. } else {
  10632. ctx.fillText(label, 0, y);
  10633. }
  10634. ctx.restore();
  10635. }
  10636. },
  10637. /**
  10638. * @private
  10639. */
  10640. _drawTitle: function() {
  10641. var me = this;
  10642. var ctx = me.ctx;
  10643. var options = me.options;
  10644. var scaleLabel = options.scaleLabel;
  10645. if (!scaleLabel.display) {
  10646. return;
  10647. }
  10648. var scaleLabelFontColor = valueOrDefault$a(scaleLabel.fontColor, core_defaults.global.defaultFontColor);
  10649. var scaleLabelFont = helpers$1.options._parseFont(scaleLabel);
  10650. var scaleLabelPadding = helpers$1.options.toPadding(scaleLabel.padding);
  10651. var halfLineHeight = scaleLabelFont.lineHeight / 2;
  10652. var position = options.position;
  10653. var rotation = 0;
  10654. var scaleLabelX, scaleLabelY;
  10655. if (me.isHorizontal()) {
  10656. scaleLabelX = me.left + me.width / 2; // midpoint of the width
  10657. scaleLabelY = position === 'bottom'
  10658. ? me.bottom - halfLineHeight - scaleLabelPadding.bottom
  10659. : me.top + halfLineHeight + scaleLabelPadding.top;
  10660. } else {
  10661. var isLeft = position === 'left';
  10662. scaleLabelX = isLeft
  10663. ? me.left + halfLineHeight + scaleLabelPadding.top
  10664. : me.right - halfLineHeight - scaleLabelPadding.top;
  10665. scaleLabelY = me.top + me.height / 2;
  10666. rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI;
  10667. }
  10668. ctx.save();
  10669. ctx.translate(scaleLabelX, scaleLabelY);
  10670. ctx.rotate(rotation);
  10671. ctx.textAlign = 'center';
  10672. ctx.textBaseline = 'middle';
  10673. ctx.fillStyle = scaleLabelFontColor; // render in correct colour
  10674. ctx.font = scaleLabelFont.string;
  10675. ctx.fillText(scaleLabel.labelString, 0, 0);
  10676. ctx.restore();
  10677. },
  10678. draw: function(chartArea) {
  10679. var me = this;
  10680. if (!me._isVisible()) {
  10681. return;
  10682. }
  10683. me._drawGrid(chartArea);
  10684. me._drawTitle();
  10685. me._drawLabels();
  10686. },
  10687. /**
  10688. * @private
  10689. */
  10690. _layers: function() {
  10691. var me = this;
  10692. var opts = me.options;
  10693. var tz = opts.ticks && opts.ticks.z || 0;
  10694. var gz = opts.gridLines && opts.gridLines.z || 0;
  10695. if (!me._isVisible() || tz === gz || me.draw !== me._draw) {
  10696. // backward compatibility: draw has been overridden by custom scale
  10697. return [{
  10698. z: tz,
  10699. draw: function() {
  10700. me.draw.apply(me, arguments);
  10701. }
  10702. }];
  10703. }
  10704. return [{
  10705. z: gz,
  10706. draw: function() {
  10707. me._drawGrid.apply(me, arguments);
  10708. me._drawTitle.apply(me, arguments);
  10709. }
  10710. }, {
  10711. z: tz,
  10712. draw: function() {
  10713. me._drawLabels.apply(me, arguments);
  10714. }
  10715. }];
  10716. },
  10717. /**
  10718. * @private
  10719. */
  10720. _getMatchingVisibleMetas: function(type) {
  10721. var me = this;
  10722. var isHorizontal = me.isHorizontal();
  10723. return me.chart._getSortedVisibleDatasetMetas()
  10724. .filter(function(meta) {
  10725. return (!type || meta.type === type)
  10726. && (isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id);
  10727. });
  10728. }
  10729. });
  10730. Scale.prototype._draw = Scale.prototype.draw;
  10731. var core_scale = Scale;
  10732. var isNullOrUndef$1 = helpers$1.isNullOrUndef;
  10733. var defaultConfig = {
  10734. position: 'bottom'
  10735. };
  10736. var scale_category = core_scale.extend({
  10737. determineDataLimits: function() {
  10738. var me = this;
  10739. var labels = me._getLabels();
  10740. var ticksOpts = me.options.ticks;
  10741. var min = ticksOpts.min;
  10742. var max = ticksOpts.max;
  10743. var minIndex = 0;
  10744. var maxIndex = labels.length - 1;
  10745. var findIndex;
  10746. if (min !== undefined) {
  10747. // user specified min value
  10748. findIndex = labels.indexOf(min);
  10749. if (findIndex >= 0) {
  10750. minIndex = findIndex;
  10751. }
  10752. }
  10753. if (max !== undefined) {
  10754. // user specified max value
  10755. findIndex = labels.indexOf(max);
  10756. if (findIndex >= 0) {
  10757. maxIndex = findIndex;
  10758. }
  10759. }
  10760. me.minIndex = minIndex;
  10761. me.maxIndex = maxIndex;
  10762. me.min = labels[minIndex];
  10763. me.max = labels[maxIndex];
  10764. },
  10765. buildTicks: function() {
  10766. var me = this;
  10767. var labels = me._getLabels();
  10768. var minIndex = me.minIndex;
  10769. var maxIndex = me.maxIndex;
  10770. // If we are viewing some subset of labels, slice the original array
  10771. me.ticks = (minIndex === 0 && maxIndex === labels.length - 1) ? labels : labels.slice(minIndex, maxIndex + 1);
  10772. },
  10773. getLabelForIndex: function(index, datasetIndex) {
  10774. var me = this;
  10775. var chart = me.chart;
  10776. if (chart.getDatasetMeta(datasetIndex).controller._getValueScaleId() === me.id) {
  10777. return me.getRightValue(chart.data.datasets[datasetIndex].data[index]);
  10778. }
  10779. return me._getLabels()[index];
  10780. },
  10781. _configure: function() {
  10782. var me = this;
  10783. var offset = me.options.offset;
  10784. var ticks = me.ticks;
  10785. core_scale.prototype._configure.call(me);
  10786. if (!me.isHorizontal()) {
  10787. // For backward compatibility, vertical category scale reverse is inverted.
  10788. me._reversePixels = !me._reversePixels;
  10789. }
  10790. if (!ticks) {
  10791. return;
  10792. }
  10793. me._startValue = me.minIndex - (offset ? 0.5 : 0);
  10794. me._valueRange = Math.max(ticks.length - (offset ? 0 : 1), 1);
  10795. },
  10796. // Used to get data value locations. Value can either be an index or a numerical value
  10797. getPixelForValue: function(value, index, datasetIndex) {
  10798. var me = this;
  10799. var valueCategory, labels, idx;
  10800. if (!isNullOrUndef$1(index) && !isNullOrUndef$1(datasetIndex)) {
  10801. value = me.chart.data.datasets[datasetIndex].data[index];
  10802. }
  10803. // If value is a data object, then index is the index in the data array,
  10804. // not the index of the scale. We need to change that.
  10805. if (!isNullOrUndef$1(value)) {
  10806. valueCategory = me.isHorizontal() ? value.x : value.y;
  10807. }
  10808. if (valueCategory !== undefined || (value !== undefined && isNaN(index))) {
  10809. labels = me._getLabels();
  10810. value = helpers$1.valueOrDefault(valueCategory, value);
  10811. idx = labels.indexOf(value);
  10812. index = idx !== -1 ? idx : index;
  10813. if (isNaN(index)) {
  10814. index = value;
  10815. }
  10816. }
  10817. return me.getPixelForDecimal((index - me._startValue) / me._valueRange);
  10818. },
  10819. getPixelForTick: function(index) {
  10820. var ticks = this.ticks;
  10821. return index < 0 || index > ticks.length - 1
  10822. ? null
  10823. : this.getPixelForValue(ticks[index], index + this.minIndex);
  10824. },
  10825. getValueForPixel: function(pixel) {
  10826. var me = this;
  10827. var value = Math.round(me._startValue + me.getDecimalForPixel(pixel) * me._valueRange);
  10828. return Math.min(Math.max(value, 0), me.ticks.length - 1);
  10829. },
  10830. getBasePixel: function() {
  10831. return this.bottom;
  10832. }
  10833. });
  10834. // INTERNAL: static default options, registered in src/index.js
  10835. var _defaults = defaultConfig;
  10836. scale_category._defaults = _defaults;
  10837. var noop = helpers$1.noop;
  10838. var isNullOrUndef$2 = helpers$1.isNullOrUndef;
  10839. /**
  10840. * Generate a set of linear ticks
  10841. * @param generationOptions the options used to generate the ticks
  10842. * @param dataRange the range of the data
  10843. * @returns {number[]} array of tick values
  10844. */
  10845. function generateTicks(generationOptions, dataRange) {
  10846. var ticks = [];
  10847. // To get a "nice" value for the tick spacing, we will use the appropriately named
  10848. // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks
  10849. // for details.
  10850. var MIN_SPACING = 1e-14;
  10851. var stepSize = generationOptions.stepSize;
  10852. var unit = stepSize || 1;
  10853. var maxNumSpaces = generationOptions.maxTicks - 1;
  10854. var min = generationOptions.min;
  10855. var max = generationOptions.max;
  10856. var precision = generationOptions.precision;
  10857. var rmin = dataRange.min;
  10858. var rmax = dataRange.max;
  10859. var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit;
  10860. var factor, niceMin, niceMax, numSpaces;
  10861. // Beyond MIN_SPACING floating point numbers being to lose precision
  10862. // such that we can't do the math necessary to generate ticks
  10863. if (spacing < MIN_SPACING && isNullOrUndef$2(min) && isNullOrUndef$2(max)) {
  10864. return [rmin, rmax];
  10865. }
  10866. numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing);
  10867. if (numSpaces > maxNumSpaces) {
  10868. // If the calculated num of spaces exceeds maxNumSpaces, recalculate it
  10869. spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit;
  10870. }
  10871. if (stepSize || isNullOrUndef$2(precision)) {
  10872. // If a precision is not specified, calculate factor based on spacing
  10873. factor = Math.pow(10, helpers$1._decimalPlaces(spacing));
  10874. } else {
  10875. // If the user specified a precision, round to that number of decimal places
  10876. factor = Math.pow(10, precision);
  10877. spacing = Math.ceil(spacing * factor) / factor;
  10878. }
  10879. niceMin = Math.floor(rmin / spacing) * spacing;
  10880. niceMax = Math.ceil(rmax / spacing) * spacing;
  10881. // If min, max and stepSize is set and they make an evenly spaced scale use it.
  10882. if (stepSize) {
  10883. // If very close to our whole number, use it.
  10884. if (!isNullOrUndef$2(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) {
  10885. niceMin = min;
  10886. }
  10887. if (!isNullOrUndef$2(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) {
  10888. niceMax = max;
  10889. }
  10890. }
  10891. numSpaces = (niceMax - niceMin) / spacing;
  10892. // If very close to our rounded value, use it.
  10893. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
  10894. numSpaces = Math.round(numSpaces);
  10895. } else {
  10896. numSpaces = Math.ceil(numSpaces);
  10897. }
  10898. niceMin = Math.round(niceMin * factor) / factor;
  10899. niceMax = Math.round(niceMax * factor) / factor;
  10900. ticks.push(isNullOrUndef$2(min) ? niceMin : min);
  10901. for (var j = 1; j < numSpaces; ++j) {
  10902. ticks.push(Math.round((niceMin + j * spacing) * factor) / factor);
  10903. }
  10904. ticks.push(isNullOrUndef$2(max) ? niceMax : max);
  10905. return ticks;
  10906. }
  10907. var scale_linearbase = core_scale.extend({
  10908. getRightValue: function(value) {
  10909. if (typeof value === 'string') {
  10910. return +value;
  10911. }
  10912. return core_scale.prototype.getRightValue.call(this, value);
  10913. },
  10914. handleTickRangeOptions: function() {
  10915. var me = this;
  10916. var opts = me.options;
  10917. var tickOpts = opts.ticks;
  10918. // If we are forcing it to begin at 0, but 0 will already be rendered on the chart,
  10919. // do nothing since that would make the chart weird. If the user really wants a weird chart
  10920. // axis, they can manually override it
  10921. if (tickOpts.beginAtZero) {
  10922. var minSign = helpers$1.sign(me.min);
  10923. var maxSign = helpers$1.sign(me.max);
  10924. if (minSign < 0 && maxSign < 0) {
  10925. // move the top up to 0
  10926. me.max = 0;
  10927. } else if (minSign > 0 && maxSign > 0) {
  10928. // move the bottom down to 0
  10929. me.min = 0;
  10930. }
  10931. }
  10932. var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined;
  10933. var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined;
  10934. if (tickOpts.min !== undefined) {
  10935. me.min = tickOpts.min;
  10936. } else if (tickOpts.suggestedMin !== undefined) {
  10937. if (me.min === null) {
  10938. me.min = tickOpts.suggestedMin;
  10939. } else {
  10940. me.min = Math.min(me.min, tickOpts.suggestedMin);
  10941. }
  10942. }
  10943. if (tickOpts.max !== undefined) {
  10944. me.max = tickOpts.max;
  10945. } else if (tickOpts.suggestedMax !== undefined) {
  10946. if (me.max === null) {
  10947. me.max = tickOpts.suggestedMax;
  10948. } else {
  10949. me.max = Math.max(me.max, tickOpts.suggestedMax);
  10950. }
  10951. }
  10952. if (setMin !== setMax) {
  10953. // We set the min or the max but not both.
  10954. // So ensure that our range is good
  10955. // Inverted or 0 length range can happen when
  10956. // ticks.min is set, and no datasets are visible
  10957. if (me.min >= me.max) {
  10958. if (setMin) {
  10959. me.max = me.min + 1;
  10960. } else {
  10961. me.min = me.max - 1;
  10962. }
  10963. }
  10964. }
  10965. if (me.min === me.max) {
  10966. me.max++;
  10967. if (!tickOpts.beginAtZero) {
  10968. me.min--;
  10969. }
  10970. }
  10971. },
  10972. getTickLimit: function() {
  10973. var me = this;
  10974. var tickOpts = me.options.ticks;
  10975. var stepSize = tickOpts.stepSize;
  10976. var maxTicksLimit = tickOpts.maxTicksLimit;
  10977. var maxTicks;
  10978. if (stepSize) {
  10979. maxTicks = Math.ceil(me.max / stepSize) - Math.floor(me.min / stepSize) + 1;
  10980. } else {
  10981. maxTicks = me._computeTickLimit();
  10982. maxTicksLimit = maxTicksLimit || 11;
  10983. }
  10984. if (maxTicksLimit) {
  10985. maxTicks = Math.min(maxTicksLimit, maxTicks);
  10986. }
  10987. return maxTicks;
  10988. },
  10989. _computeTickLimit: function() {
  10990. return Number.POSITIVE_INFINITY;
  10991. },
  10992. handleDirectionalChanges: noop,
  10993. buildTicks: function() {
  10994. var me = this;
  10995. var opts = me.options;
  10996. var tickOpts = opts.ticks;
  10997. // Figure out what the max number of ticks we can support it is based on the size of
  10998. // the axis area. For now, we say that the minimum tick spacing in pixels must be 40
  10999. // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
  11000. // the graph. Make sure we always have at least 2 ticks
  11001. var maxTicks = me.getTickLimit();
  11002. maxTicks = Math.max(2, maxTicks);
  11003. var numericGeneratorOptions = {
  11004. maxTicks: maxTicks,
  11005. min: tickOpts.min,
  11006. max: tickOpts.max,
  11007. precision: tickOpts.precision,
  11008. stepSize: helpers$1.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize)
  11009. };
  11010. var ticks = me.ticks = generateTicks(numericGeneratorOptions, me);
  11011. me.handleDirectionalChanges();
  11012. // At this point, we need to update our max and min given the tick values since we have expanded the
  11013. // range of the scale
  11014. me.max = helpers$1.max(ticks);
  11015. me.min = helpers$1.min(ticks);
  11016. if (tickOpts.reverse) {
  11017. ticks.reverse();
  11018. me.start = me.max;
  11019. me.end = me.min;
  11020. } else {
  11021. me.start = me.min;
  11022. me.end = me.max;
  11023. }
  11024. },
  11025. convertTicksToLabels: function() {
  11026. var me = this;
  11027. me.ticksAsNumbers = me.ticks.slice();
  11028. me.zeroLineIndex = me.ticks.indexOf(0);
  11029. core_scale.prototype.convertTicksToLabels.call(me);
  11030. },
  11031. _configure: function() {
  11032. var me = this;
  11033. var ticks = me.getTicks();
  11034. var start = me.min;
  11035. var end = me.max;
  11036. var offset;
  11037. core_scale.prototype._configure.call(me);
  11038. if (me.options.offset && ticks.length) {
  11039. offset = (end - start) / Math.max(ticks.length - 1, 1) / 2;
  11040. start -= offset;
  11041. end += offset;
  11042. }
  11043. me._startValue = start;
  11044. me._endValue = end;
  11045. me._valueRange = end - start;
  11046. }
  11047. });
  11048. var defaultConfig$1 = {
  11049. position: 'left',
  11050. ticks: {
  11051. callback: core_ticks.formatters.linear
  11052. }
  11053. };
  11054. var DEFAULT_MIN = 0;
  11055. var DEFAULT_MAX = 1;
  11056. function getOrCreateStack(stacks, stacked, meta) {
  11057. var key = [
  11058. meta.type,
  11059. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11060. stacked === undefined && meta.stack === undefined ? meta.index : '',
  11061. meta.stack
  11062. ].join('.');
  11063. if (stacks[key] === undefined) {
  11064. stacks[key] = {
  11065. pos: [],
  11066. neg: []
  11067. };
  11068. }
  11069. return stacks[key];
  11070. }
  11071. function stackData(scale, stacks, meta, data) {
  11072. var opts = scale.options;
  11073. var stacked = opts.stacked;
  11074. var stack = getOrCreateStack(stacks, stacked, meta);
  11075. var pos = stack.pos;
  11076. var neg = stack.neg;
  11077. var ilen = data.length;
  11078. var i, value;
  11079. for (i = 0; i < ilen; ++i) {
  11080. value = scale._parseValue(data[i]);
  11081. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11082. continue;
  11083. }
  11084. pos[i] = pos[i] || 0;
  11085. neg[i] = neg[i] || 0;
  11086. if (opts.relativePoints) {
  11087. pos[i] = 100;
  11088. } else if (value.min < 0 || value.max < 0) {
  11089. neg[i] += value.min;
  11090. } else {
  11091. pos[i] += value.max;
  11092. }
  11093. }
  11094. }
  11095. function updateMinMax(scale, meta, data) {
  11096. var ilen = data.length;
  11097. var i, value;
  11098. for (i = 0; i < ilen; ++i) {
  11099. value = scale._parseValue(data[i]);
  11100. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden) {
  11101. continue;
  11102. }
  11103. scale.min = Math.min(scale.min, value.min);
  11104. scale.max = Math.max(scale.max, value.max);
  11105. }
  11106. }
  11107. var scale_linear = scale_linearbase.extend({
  11108. determineDataLimits: function() {
  11109. var me = this;
  11110. var opts = me.options;
  11111. var chart = me.chart;
  11112. var datasets = chart.data.datasets;
  11113. var metasets = me._getMatchingVisibleMetas();
  11114. var hasStacks = opts.stacked;
  11115. var stacks = {};
  11116. var ilen = metasets.length;
  11117. var i, meta, data, values;
  11118. me.min = Number.POSITIVE_INFINITY;
  11119. me.max = Number.NEGATIVE_INFINITY;
  11120. if (hasStacks === undefined) {
  11121. for (i = 0; !hasStacks && i < ilen; ++i) {
  11122. meta = metasets[i];
  11123. hasStacks = meta.stack !== undefined;
  11124. }
  11125. }
  11126. for (i = 0; i < ilen; ++i) {
  11127. meta = metasets[i];
  11128. data = datasets[meta.index].data;
  11129. if (hasStacks) {
  11130. stackData(me, stacks, meta, data);
  11131. } else {
  11132. updateMinMax(me, meta, data);
  11133. }
  11134. }
  11135. helpers$1.each(stacks, function(stackValues) {
  11136. values = stackValues.pos.concat(stackValues.neg);
  11137. me.min = Math.min(me.min, helpers$1.min(values));
  11138. me.max = Math.max(me.max, helpers$1.max(values));
  11139. });
  11140. me.min = helpers$1.isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN;
  11141. me.max = helpers$1.isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX;
  11142. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11143. me.handleTickRangeOptions();
  11144. },
  11145. // Returns the maximum number of ticks based on the scale dimension
  11146. _computeTickLimit: function() {
  11147. var me = this;
  11148. var tickFont;
  11149. if (me.isHorizontal()) {
  11150. return Math.ceil(me.width / 40);
  11151. }
  11152. tickFont = helpers$1.options._parseFont(me.options.ticks);
  11153. return Math.ceil(me.height / tickFont.lineHeight);
  11154. },
  11155. // Called after the ticks are built. We need
  11156. handleDirectionalChanges: function() {
  11157. if (!this.isHorizontal()) {
  11158. // We are in a vertical orientation. The top value is the highest. So reverse the array
  11159. this.ticks.reverse();
  11160. }
  11161. },
  11162. getLabelForIndex: function(index, datasetIndex) {
  11163. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11164. },
  11165. // Utils
  11166. getPixelForValue: function(value) {
  11167. var me = this;
  11168. return me.getPixelForDecimal((+me.getRightValue(value) - me._startValue) / me._valueRange);
  11169. },
  11170. getValueForPixel: function(pixel) {
  11171. return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange;
  11172. },
  11173. getPixelForTick: function(index) {
  11174. var ticks = this.ticksAsNumbers;
  11175. if (index < 0 || index > ticks.length - 1) {
  11176. return null;
  11177. }
  11178. return this.getPixelForValue(ticks[index]);
  11179. }
  11180. });
  11181. // INTERNAL: static default options, registered in src/index.js
  11182. var _defaults$1 = defaultConfig$1;
  11183. scale_linear._defaults = _defaults$1;
  11184. var valueOrDefault$b = helpers$1.valueOrDefault;
  11185. var log10 = helpers$1.math.log10;
  11186. /**
  11187. * Generate a set of logarithmic ticks
  11188. * @param generationOptions the options used to generate the ticks
  11189. * @param dataRange the range of the data
  11190. * @returns {number[]} array of tick values
  11191. */
  11192. function generateTicks$1(generationOptions, dataRange) {
  11193. var ticks = [];
  11194. var tickVal = valueOrDefault$b(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min))));
  11195. var endExp = Math.floor(log10(dataRange.max));
  11196. var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp));
  11197. var exp, significand;
  11198. if (tickVal === 0) {
  11199. exp = Math.floor(log10(dataRange.minNotZero));
  11200. significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp));
  11201. ticks.push(tickVal);
  11202. tickVal = significand * Math.pow(10, exp);
  11203. } else {
  11204. exp = Math.floor(log10(tickVal));
  11205. significand = Math.floor(tickVal / Math.pow(10, exp));
  11206. }
  11207. var precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1;
  11208. do {
  11209. ticks.push(tickVal);
  11210. ++significand;
  11211. if (significand === 10) {
  11212. significand = 1;
  11213. ++exp;
  11214. precision = exp >= 0 ? 1 : precision;
  11215. }
  11216. tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision;
  11217. } while (exp < endExp || (exp === endExp && significand < endSignificand));
  11218. var lastTick = valueOrDefault$b(generationOptions.max, tickVal);
  11219. ticks.push(lastTick);
  11220. return ticks;
  11221. }
  11222. var defaultConfig$2 = {
  11223. position: 'left',
  11224. // label settings
  11225. ticks: {
  11226. callback: core_ticks.formatters.logarithmic
  11227. }
  11228. };
  11229. // TODO(v3): change this to positiveOrDefault
  11230. function nonNegativeOrDefault(value, defaultValue) {
  11231. return helpers$1.isFinite(value) && value >= 0 ? value : defaultValue;
  11232. }
  11233. var scale_logarithmic = core_scale.extend({
  11234. determineDataLimits: function() {
  11235. var me = this;
  11236. var opts = me.options;
  11237. var chart = me.chart;
  11238. var datasets = chart.data.datasets;
  11239. var isHorizontal = me.isHorizontal();
  11240. function IDMatches(meta) {
  11241. return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
  11242. }
  11243. var datasetIndex, meta, value, data, i, ilen;
  11244. // Calculate Range
  11245. me.min = Number.POSITIVE_INFINITY;
  11246. me.max = Number.NEGATIVE_INFINITY;
  11247. me.minNotZero = Number.POSITIVE_INFINITY;
  11248. var hasStacks = opts.stacked;
  11249. if (hasStacks === undefined) {
  11250. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11251. meta = chart.getDatasetMeta(datasetIndex);
  11252. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) &&
  11253. meta.stack !== undefined) {
  11254. hasStacks = true;
  11255. break;
  11256. }
  11257. }
  11258. }
  11259. if (opts.stacked || hasStacks) {
  11260. var valuesPerStack = {};
  11261. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11262. meta = chart.getDatasetMeta(datasetIndex);
  11263. var key = [
  11264. meta.type,
  11265. // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined
  11266. ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''),
  11267. meta.stack
  11268. ].join('.');
  11269. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11270. if (valuesPerStack[key] === undefined) {
  11271. valuesPerStack[key] = [];
  11272. }
  11273. data = datasets[datasetIndex].data;
  11274. for (i = 0, ilen = data.length; i < ilen; i++) {
  11275. var values = valuesPerStack[key];
  11276. value = me._parseValue(data[i]);
  11277. // invalid, hidden and negative values are ignored
  11278. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11279. continue;
  11280. }
  11281. values[i] = values[i] || 0;
  11282. values[i] += value.max;
  11283. }
  11284. }
  11285. }
  11286. helpers$1.each(valuesPerStack, function(valuesForType) {
  11287. if (valuesForType.length > 0) {
  11288. var minVal = helpers$1.min(valuesForType);
  11289. var maxVal = helpers$1.max(valuesForType);
  11290. me.min = Math.min(me.min, minVal);
  11291. me.max = Math.max(me.max, maxVal);
  11292. }
  11293. });
  11294. } else {
  11295. for (datasetIndex = 0; datasetIndex < datasets.length; datasetIndex++) {
  11296. meta = chart.getDatasetMeta(datasetIndex);
  11297. if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
  11298. data = datasets[datasetIndex].data;
  11299. for (i = 0, ilen = data.length; i < ilen; i++) {
  11300. value = me._parseValue(data[i]);
  11301. // invalid, hidden and negative values are ignored
  11302. if (isNaN(value.min) || isNaN(value.max) || meta.data[i].hidden || value.min < 0 || value.max < 0) {
  11303. continue;
  11304. }
  11305. me.min = Math.min(value.min, me.min);
  11306. me.max = Math.max(value.max, me.max);
  11307. if (value.min !== 0) {
  11308. me.minNotZero = Math.min(value.min, me.minNotZero);
  11309. }
  11310. }
  11311. }
  11312. }
  11313. }
  11314. me.min = helpers$1.isFinite(me.min) ? me.min : null;
  11315. me.max = helpers$1.isFinite(me.max) ? me.max : null;
  11316. me.minNotZero = helpers$1.isFinite(me.minNotZero) ? me.minNotZero : null;
  11317. // Common base implementation to handle ticks.min, ticks.max
  11318. this.handleTickRangeOptions();
  11319. },
  11320. handleTickRangeOptions: function() {
  11321. var me = this;
  11322. var tickOpts = me.options.ticks;
  11323. var DEFAULT_MIN = 1;
  11324. var DEFAULT_MAX = 10;
  11325. me.min = nonNegativeOrDefault(tickOpts.min, me.min);
  11326. me.max = nonNegativeOrDefault(tickOpts.max, me.max);
  11327. if (me.min === me.max) {
  11328. if (me.min !== 0 && me.min !== null) {
  11329. me.min = Math.pow(10, Math.floor(log10(me.min)) - 1);
  11330. me.max = Math.pow(10, Math.floor(log10(me.max)) + 1);
  11331. } else {
  11332. me.min = DEFAULT_MIN;
  11333. me.max = DEFAULT_MAX;
  11334. }
  11335. }
  11336. if (me.min === null) {
  11337. me.min = Math.pow(10, Math.floor(log10(me.max)) - 1);
  11338. }
  11339. if (me.max === null) {
  11340. me.max = me.min !== 0
  11341. ? Math.pow(10, Math.floor(log10(me.min)) + 1)
  11342. : DEFAULT_MAX;
  11343. }
  11344. if (me.minNotZero === null) {
  11345. if (me.min > 0) {
  11346. me.minNotZero = me.min;
  11347. } else if (me.max < 1) {
  11348. me.minNotZero = Math.pow(10, Math.floor(log10(me.max)));
  11349. } else {
  11350. me.minNotZero = DEFAULT_MIN;
  11351. }
  11352. }
  11353. },
  11354. buildTicks: function() {
  11355. var me = this;
  11356. var tickOpts = me.options.ticks;
  11357. var reverse = !me.isHorizontal();
  11358. var generationOptions = {
  11359. min: nonNegativeOrDefault(tickOpts.min),
  11360. max: nonNegativeOrDefault(tickOpts.max)
  11361. };
  11362. var ticks = me.ticks = generateTicks$1(generationOptions, me);
  11363. // At this point, we need to update our max and min given the tick values since we have expanded the
  11364. // range of the scale
  11365. me.max = helpers$1.max(ticks);
  11366. me.min = helpers$1.min(ticks);
  11367. if (tickOpts.reverse) {
  11368. reverse = !reverse;
  11369. me.start = me.max;
  11370. me.end = me.min;
  11371. } else {
  11372. me.start = me.min;
  11373. me.end = me.max;
  11374. }
  11375. if (reverse) {
  11376. ticks.reverse();
  11377. }
  11378. },
  11379. convertTicksToLabels: function() {
  11380. this.tickValues = this.ticks.slice();
  11381. core_scale.prototype.convertTicksToLabels.call(this);
  11382. },
  11383. // Get the correct tooltip label
  11384. getLabelForIndex: function(index, datasetIndex) {
  11385. return this._getScaleLabel(this.chart.data.datasets[datasetIndex].data[index]);
  11386. },
  11387. getPixelForTick: function(index) {
  11388. var ticks = this.tickValues;
  11389. if (index < 0 || index > ticks.length - 1) {
  11390. return null;
  11391. }
  11392. return this.getPixelForValue(ticks[index]);
  11393. },
  11394. /**
  11395. * Returns the value of the first tick.
  11396. * @param {number} value - The minimum not zero value.
  11397. * @return {number} The first tick value.
  11398. * @private
  11399. */
  11400. _getFirstTickValue: function(value) {
  11401. var exp = Math.floor(log10(value));
  11402. var significand = Math.floor(value / Math.pow(10, exp));
  11403. return significand * Math.pow(10, exp);
  11404. },
  11405. _configure: function() {
  11406. var me = this;
  11407. var start = me.min;
  11408. var offset = 0;
  11409. core_scale.prototype._configure.call(me);
  11410. if (start === 0) {
  11411. start = me._getFirstTickValue(me.minNotZero);
  11412. offset = valueOrDefault$b(me.options.ticks.fontSize, core_defaults.global.defaultFontSize) / me._length;
  11413. }
  11414. me._startValue = log10(start);
  11415. me._valueOffset = offset;
  11416. me._valueRange = (log10(me.max) - log10(start)) / (1 - offset);
  11417. },
  11418. getPixelForValue: function(value) {
  11419. var me = this;
  11420. var decimal = 0;
  11421. value = +me.getRightValue(value);
  11422. if (value > me.min && value > 0) {
  11423. decimal = (log10(value) - me._startValue) / me._valueRange + me._valueOffset;
  11424. }
  11425. return me.getPixelForDecimal(decimal);
  11426. },
  11427. getValueForPixel: function(pixel) {
  11428. var me = this;
  11429. var decimal = me.getDecimalForPixel(pixel);
  11430. return decimal === 0 && me.min === 0
  11431. ? 0
  11432. : Math.pow(10, me._startValue + (decimal - me._valueOffset) * me._valueRange);
  11433. }
  11434. });
  11435. // INTERNAL: static default options, registered in src/index.js
  11436. var _defaults$2 = defaultConfig$2;
  11437. scale_logarithmic._defaults = _defaults$2;
  11438. var valueOrDefault$c = helpers$1.valueOrDefault;
  11439. var valueAtIndexOrDefault$1 = helpers$1.valueAtIndexOrDefault;
  11440. var resolve$4 = helpers$1.options.resolve;
  11441. var defaultConfig$3 = {
  11442. display: true,
  11443. // Boolean - Whether to animate scaling the chart from the centre
  11444. animate: true,
  11445. position: 'chartArea',
  11446. angleLines: {
  11447. display: true,
  11448. color: 'rgba(0,0,0,0.1)',
  11449. lineWidth: 1,
  11450. borderDash: [],
  11451. borderDashOffset: 0.0
  11452. },
  11453. gridLines: {
  11454. circular: false
  11455. },
  11456. // label settings
  11457. ticks: {
  11458. // Boolean - Show a backdrop to the scale label
  11459. showLabelBackdrop: true,
  11460. // String - The colour of the label backdrop
  11461. backdropColor: 'rgba(255,255,255,0.75)',
  11462. // Number - The backdrop padding above & below the label in pixels
  11463. backdropPaddingY: 2,
  11464. // Number - The backdrop padding to the side of the label in pixels
  11465. backdropPaddingX: 2,
  11466. callback: core_ticks.formatters.linear
  11467. },
  11468. pointLabels: {
  11469. // Boolean - if true, show point labels
  11470. display: true,
  11471. // Number - Point label font size in pixels
  11472. fontSize: 10,
  11473. // Function - Used to convert point labels
  11474. callback: function(label) {
  11475. return label;
  11476. }
  11477. }
  11478. };
  11479. function getTickBackdropHeight(opts) {
  11480. var tickOpts = opts.ticks;
  11481. if (tickOpts.display && opts.display) {
  11482. return valueOrDefault$c(tickOpts.fontSize, core_defaults.global.defaultFontSize) + tickOpts.backdropPaddingY * 2;
  11483. }
  11484. return 0;
  11485. }
  11486. function measureLabelSize(ctx, lineHeight, label) {
  11487. if (helpers$1.isArray(label)) {
  11488. return {
  11489. w: helpers$1.longestText(ctx, ctx.font, label),
  11490. h: label.length * lineHeight
  11491. };
  11492. }
  11493. return {
  11494. w: ctx.measureText(label).width,
  11495. h: lineHeight
  11496. };
  11497. }
  11498. function determineLimits(angle, pos, size, min, max) {
  11499. if (angle === min || angle === max) {
  11500. return {
  11501. start: pos - (size / 2),
  11502. end: pos + (size / 2)
  11503. };
  11504. } else if (angle < min || angle > max) {
  11505. return {
  11506. start: pos - size,
  11507. end: pos
  11508. };
  11509. }
  11510. return {
  11511. start: pos,
  11512. end: pos + size
  11513. };
  11514. }
  11515. /**
  11516. * Helper function to fit a radial linear scale with point labels
  11517. */
  11518. function fitWithPointLabels(scale) {
  11519. // Right, this is really confusing and there is a lot of maths going on here
  11520. // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
  11521. //
  11522. // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
  11523. //
  11524. // Solution:
  11525. //
  11526. // We assume the radius of the polygon is half the size of the canvas at first
  11527. // at each index we check if the text overlaps.
  11528. //
  11529. // Where it does, we store that angle and that index.
  11530. //
  11531. // After finding the largest index and angle we calculate how much we need to remove
  11532. // from the shape radius to move the point inwards by that x.
  11533. //
  11534. // We average the left and right distances to get the maximum shape radius that can fit in the box
  11535. // along with labels.
  11536. //
  11537. // Once we have that, we can find the centre point for the chart, by taking the x text protrusion
  11538. // on each side, removing that from the size, halving it and adding the left x protrusion width.
  11539. //
  11540. // This will mean we have a shape fitted to the canvas, as large as it can be with the labels
  11541. // and position it in the most space efficient manner
  11542. //
  11543. // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
  11544. var plFont = helpers$1.options._parseFont(scale.options.pointLabels);
  11545. // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
  11546. // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
  11547. var furthestLimits = {
  11548. l: 0,
  11549. r: scale.width,
  11550. t: 0,
  11551. b: scale.height - scale.paddingTop
  11552. };
  11553. var furthestAngles = {};
  11554. var i, textSize, pointPosition;
  11555. scale.ctx.font = plFont.string;
  11556. scale._pointLabelSizes = [];
  11557. var valueCount = scale.chart.data.labels.length;
  11558. for (i = 0; i < valueCount; i++) {
  11559. pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);
  11560. textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i]);
  11561. scale._pointLabelSizes[i] = textSize;
  11562. // Add quarter circle to make degree 0 mean top of circle
  11563. var angleRadians = scale.getIndexAngle(i);
  11564. var angle = helpers$1.toDegrees(angleRadians) % 360;
  11565. var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);
  11566. var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);
  11567. if (hLimits.start < furthestLimits.l) {
  11568. furthestLimits.l = hLimits.start;
  11569. furthestAngles.l = angleRadians;
  11570. }
  11571. if (hLimits.end > furthestLimits.r) {
  11572. furthestLimits.r = hLimits.end;
  11573. furthestAngles.r = angleRadians;
  11574. }
  11575. if (vLimits.start < furthestLimits.t) {
  11576. furthestLimits.t = vLimits.start;
  11577. furthestAngles.t = angleRadians;
  11578. }
  11579. if (vLimits.end > furthestLimits.b) {
  11580. furthestLimits.b = vLimits.end;
  11581. furthestAngles.b = angleRadians;
  11582. }
  11583. }
  11584. scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);
  11585. }
  11586. function getTextAlignForAngle(angle) {
  11587. if (angle === 0 || angle === 180) {
  11588. return 'center';
  11589. } else if (angle < 180) {
  11590. return 'left';
  11591. }
  11592. return 'right';
  11593. }
  11594. function fillText(ctx, text, position, lineHeight) {
  11595. var y = position.y + lineHeight / 2;
  11596. var i, ilen;
  11597. if (helpers$1.isArray(text)) {
  11598. for (i = 0, ilen = text.length; i < ilen; ++i) {
  11599. ctx.fillText(text[i], position.x, y);
  11600. y += lineHeight;
  11601. }
  11602. } else {
  11603. ctx.fillText(text, position.x, y);
  11604. }
  11605. }
  11606. function adjustPointPositionForLabelHeight(angle, textSize, position) {
  11607. if (angle === 90 || angle === 270) {
  11608. position.y -= (textSize.h / 2);
  11609. } else if (angle > 270 || angle < 90) {
  11610. position.y -= textSize.h;
  11611. }
  11612. }
  11613. function drawPointLabels(scale) {
  11614. var ctx = scale.ctx;
  11615. var opts = scale.options;
  11616. var pointLabelOpts = opts.pointLabels;
  11617. var tickBackdropHeight = getTickBackdropHeight(opts);
  11618. var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max);
  11619. var plFont = helpers$1.options._parseFont(pointLabelOpts);
  11620. ctx.save();
  11621. ctx.font = plFont.string;
  11622. ctx.textBaseline = 'middle';
  11623. for (var i = scale.chart.data.labels.length - 1; i >= 0; i--) {
  11624. // Extra pixels out for some label spacing
  11625. var extra = (i === 0 ? tickBackdropHeight / 2 : 0);
  11626. var pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + 5);
  11627. // Keep this in loop since we may support array properties here
  11628. var pointLabelFontColor = valueAtIndexOrDefault$1(pointLabelOpts.fontColor, i, core_defaults.global.defaultFontColor);
  11629. ctx.fillStyle = pointLabelFontColor;
  11630. var angleRadians = scale.getIndexAngle(i);
  11631. var angle = helpers$1.toDegrees(angleRadians);
  11632. ctx.textAlign = getTextAlignForAngle(angle);
  11633. adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition);
  11634. fillText(ctx, scale.pointLabels[i], pointLabelPosition, plFont.lineHeight);
  11635. }
  11636. ctx.restore();
  11637. }
  11638. function drawRadiusLine(scale, gridLineOpts, radius, index) {
  11639. var ctx = scale.ctx;
  11640. var circular = gridLineOpts.circular;
  11641. var valueCount = scale.chart.data.labels.length;
  11642. var lineColor = valueAtIndexOrDefault$1(gridLineOpts.color, index - 1);
  11643. var lineWidth = valueAtIndexOrDefault$1(gridLineOpts.lineWidth, index - 1);
  11644. var pointPosition;
  11645. if ((!circular && !valueCount) || !lineColor || !lineWidth) {
  11646. return;
  11647. }
  11648. ctx.save();
  11649. ctx.strokeStyle = lineColor;
  11650. ctx.lineWidth = lineWidth;
  11651. if (ctx.setLineDash) {
  11652. ctx.setLineDash(gridLineOpts.borderDash || []);
  11653. ctx.lineDashOffset = gridLineOpts.borderDashOffset || 0.0;
  11654. }
  11655. ctx.beginPath();
  11656. if (circular) {
  11657. // Draw circular arcs between the points
  11658. ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2);
  11659. } else {
  11660. // Draw straight lines connecting each index
  11661. pointPosition = scale.getPointPosition(0, radius);
  11662. ctx.moveTo(pointPosition.x, pointPosition.y);
  11663. for (var i = 1; i < valueCount; i++) {
  11664. pointPosition = scale.getPointPosition(i, radius);
  11665. ctx.lineTo(pointPosition.x, pointPosition.y);
  11666. }
  11667. }
  11668. ctx.closePath();
  11669. ctx.stroke();
  11670. ctx.restore();
  11671. }
  11672. function numberOrZero(param) {
  11673. return helpers$1.isNumber(param) ? param : 0;
  11674. }
  11675. var scale_radialLinear = scale_linearbase.extend({
  11676. setDimensions: function() {
  11677. var me = this;
  11678. // Set the unconstrained dimension before label rotation
  11679. me.width = me.maxWidth;
  11680. me.height = me.maxHeight;
  11681. me.paddingTop = getTickBackdropHeight(me.options) / 2;
  11682. me.xCenter = Math.floor(me.width / 2);
  11683. me.yCenter = Math.floor((me.height - me.paddingTop) / 2);
  11684. me.drawingArea = Math.min(me.height - me.paddingTop, me.width) / 2;
  11685. },
  11686. determineDataLimits: function() {
  11687. var me = this;
  11688. var chart = me.chart;
  11689. var min = Number.POSITIVE_INFINITY;
  11690. var max = Number.NEGATIVE_INFINITY;
  11691. helpers$1.each(chart.data.datasets, function(dataset, datasetIndex) {
  11692. if (chart.isDatasetVisible(datasetIndex)) {
  11693. var meta = chart.getDatasetMeta(datasetIndex);
  11694. helpers$1.each(dataset.data, function(rawValue, index) {
  11695. var value = +me.getRightValue(rawValue);
  11696. if (isNaN(value) || meta.data[index].hidden) {
  11697. return;
  11698. }
  11699. min = Math.min(value, min);
  11700. max = Math.max(value, max);
  11701. });
  11702. }
  11703. });
  11704. me.min = (min === Number.POSITIVE_INFINITY ? 0 : min);
  11705. me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max);
  11706. // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero
  11707. me.handleTickRangeOptions();
  11708. },
  11709. // Returns the maximum number of ticks based on the scale dimension
  11710. _computeTickLimit: function() {
  11711. return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options));
  11712. },
  11713. convertTicksToLabels: function() {
  11714. var me = this;
  11715. scale_linearbase.prototype.convertTicksToLabels.call(me);
  11716. // Point labels
  11717. me.pointLabels = me.chart.data.labels.map(function() {
  11718. var label = helpers$1.callback(me.options.pointLabels.callback, arguments, me);
  11719. return label || label === 0 ? label : '';
  11720. });
  11721. },
  11722. getLabelForIndex: function(index, datasetIndex) {
  11723. return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
  11724. },
  11725. fit: function() {
  11726. var me = this;
  11727. var opts = me.options;
  11728. if (opts.display && opts.pointLabels.display) {
  11729. fitWithPointLabels(me);
  11730. } else {
  11731. me.setCenterPoint(0, 0, 0, 0);
  11732. }
  11733. },
  11734. /**
  11735. * Set radius reductions and determine new radius and center point
  11736. * @private
  11737. */
  11738. setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) {
  11739. var me = this;
  11740. var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l);
  11741. var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r);
  11742. var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t);
  11743. var radiusReductionBottom = -Math.max(furthestLimits.b - (me.height - me.paddingTop), 0) / Math.cos(furthestAngles.b);
  11744. radiusReductionLeft = numberOrZero(radiusReductionLeft);
  11745. radiusReductionRight = numberOrZero(radiusReductionRight);
  11746. radiusReductionTop = numberOrZero(radiusReductionTop);
  11747. radiusReductionBottom = numberOrZero(radiusReductionBottom);
  11748. me.drawingArea = Math.min(
  11749. Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2),
  11750. Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2));
  11751. me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom);
  11752. },
  11753. setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) {
  11754. var me = this;
  11755. var maxRight = me.width - rightMovement - me.drawingArea;
  11756. var maxLeft = leftMovement + me.drawingArea;
  11757. var maxTop = topMovement + me.drawingArea;
  11758. var maxBottom = (me.height - me.paddingTop) - bottomMovement - me.drawingArea;
  11759. me.xCenter = Math.floor(((maxLeft + maxRight) / 2) + me.left);
  11760. me.yCenter = Math.floor(((maxTop + maxBottom) / 2) + me.top + me.paddingTop);
  11761. },
  11762. getIndexAngle: function(index) {
  11763. var chart = this.chart;
  11764. var angleMultiplier = 360 / chart.data.labels.length;
  11765. var options = chart.options || {};
  11766. var startAngle = options.startAngle || 0;
  11767. // Start from the top instead of right, so remove a quarter of the circle
  11768. var angle = (index * angleMultiplier + startAngle) % 360;
  11769. return (angle < 0 ? angle + 360 : angle) * Math.PI * 2 / 360;
  11770. },
  11771. getDistanceFromCenterForValue: function(value) {
  11772. var me = this;
  11773. if (helpers$1.isNullOrUndef(value)) {
  11774. return NaN;
  11775. }
  11776. // Take into account half font size + the yPadding of the top value
  11777. var scalingFactor = me.drawingArea / (me.max - me.min);
  11778. if (me.options.ticks.reverse) {
  11779. return (me.max - value) * scalingFactor;
  11780. }
  11781. return (value - me.min) * scalingFactor;
  11782. },
  11783. getPointPosition: function(index, distanceFromCenter) {
  11784. var me = this;
  11785. var thisAngle = me.getIndexAngle(index) - (Math.PI / 2);
  11786. return {
  11787. x: Math.cos(thisAngle) * distanceFromCenter + me.xCenter,
  11788. y: Math.sin(thisAngle) * distanceFromCenter + me.yCenter
  11789. };
  11790. },
  11791. getPointPositionForValue: function(index, value) {
  11792. return this.getPointPosition(index, this.getDistanceFromCenterForValue(value));
  11793. },
  11794. getBasePosition: function(index) {
  11795. var me = this;
  11796. var min = me.min;
  11797. var max = me.max;
  11798. return me.getPointPositionForValue(index || 0,
  11799. me.beginAtZero ? 0 :
  11800. min < 0 && max < 0 ? max :
  11801. min > 0 && max > 0 ? min :
  11802. 0);
  11803. },
  11804. /**
  11805. * @private
  11806. */
  11807. _drawGrid: function() {
  11808. var me = this;
  11809. var ctx = me.ctx;
  11810. var opts = me.options;
  11811. var gridLineOpts = opts.gridLines;
  11812. var angleLineOpts = opts.angleLines;
  11813. var lineWidth = valueOrDefault$c(angleLineOpts.lineWidth, gridLineOpts.lineWidth);
  11814. var lineColor = valueOrDefault$c(angleLineOpts.color, gridLineOpts.color);
  11815. var i, offset, position;
  11816. if (opts.pointLabels.display) {
  11817. drawPointLabels(me);
  11818. }
  11819. if (gridLineOpts.display) {
  11820. helpers$1.each(me.ticks, function(label, index) {
  11821. if (index !== 0) {
  11822. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11823. drawRadiusLine(me, gridLineOpts, offset, index);
  11824. }
  11825. });
  11826. }
  11827. if (angleLineOpts.display && lineWidth && lineColor) {
  11828. ctx.save();
  11829. ctx.lineWidth = lineWidth;
  11830. ctx.strokeStyle = lineColor;
  11831. if (ctx.setLineDash) {
  11832. ctx.setLineDash(resolve$4([angleLineOpts.borderDash, gridLineOpts.borderDash, []]));
  11833. ctx.lineDashOffset = resolve$4([angleLineOpts.borderDashOffset, gridLineOpts.borderDashOffset, 0.0]);
  11834. }
  11835. for (i = me.chart.data.labels.length - 1; i >= 0; i--) {
  11836. offset = me.getDistanceFromCenterForValue(opts.ticks.reverse ? me.min : me.max);
  11837. position = me.getPointPosition(i, offset);
  11838. ctx.beginPath();
  11839. ctx.moveTo(me.xCenter, me.yCenter);
  11840. ctx.lineTo(position.x, position.y);
  11841. ctx.stroke();
  11842. }
  11843. ctx.restore();
  11844. }
  11845. },
  11846. /**
  11847. * @private
  11848. */
  11849. _drawLabels: function() {
  11850. var me = this;
  11851. var ctx = me.ctx;
  11852. var opts = me.options;
  11853. var tickOpts = opts.ticks;
  11854. if (!tickOpts.display) {
  11855. return;
  11856. }
  11857. var startAngle = me.getIndexAngle(0);
  11858. var tickFont = helpers$1.options._parseFont(tickOpts);
  11859. var tickFontColor = valueOrDefault$c(tickOpts.fontColor, core_defaults.global.defaultFontColor);
  11860. var offset, width;
  11861. ctx.save();
  11862. ctx.font = tickFont.string;
  11863. ctx.translate(me.xCenter, me.yCenter);
  11864. ctx.rotate(startAngle);
  11865. ctx.textAlign = 'center';
  11866. ctx.textBaseline = 'middle';
  11867. helpers$1.each(me.ticks, function(label, index) {
  11868. if (index === 0 && !tickOpts.reverse) {
  11869. return;
  11870. }
  11871. offset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]);
  11872. if (tickOpts.showLabelBackdrop) {
  11873. width = ctx.measureText(label).width;
  11874. ctx.fillStyle = tickOpts.backdropColor;
  11875. ctx.fillRect(
  11876. -width / 2 - tickOpts.backdropPaddingX,
  11877. -offset - tickFont.size / 2 - tickOpts.backdropPaddingY,
  11878. width + tickOpts.backdropPaddingX * 2,
  11879. tickFont.size + tickOpts.backdropPaddingY * 2
  11880. );
  11881. }
  11882. ctx.fillStyle = tickFontColor;
  11883. ctx.fillText(label, 0, -offset);
  11884. });
  11885. ctx.restore();
  11886. },
  11887. /**
  11888. * @private
  11889. */
  11890. _drawTitle: helpers$1.noop
  11891. });
  11892. // INTERNAL: static default options, registered in src/index.js
  11893. var _defaults$3 = defaultConfig$3;
  11894. scale_radialLinear._defaults = _defaults$3;
  11895. var deprecated$1 = helpers$1._deprecated;
  11896. var resolve$5 = helpers$1.options.resolve;
  11897. var valueOrDefault$d = helpers$1.valueOrDefault;
  11898. // Integer constants are from the ES6 spec.
  11899. var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
  11900. var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
  11901. var INTERVALS = {
  11902. millisecond: {
  11903. common: true,
  11904. size: 1,
  11905. steps: 1000
  11906. },
  11907. second: {
  11908. common: true,
  11909. size: 1000,
  11910. steps: 60
  11911. },
  11912. minute: {
  11913. common: true,
  11914. size: 60000,
  11915. steps: 60
  11916. },
  11917. hour: {
  11918. common: true,
  11919. size: 3600000,
  11920. steps: 24
  11921. },
  11922. day: {
  11923. common: true,
  11924. size: 86400000,
  11925. steps: 30
  11926. },
  11927. week: {
  11928. common: false,
  11929. size: 604800000,
  11930. steps: 4
  11931. },
  11932. month: {
  11933. common: true,
  11934. size: 2.628e9,
  11935. steps: 12
  11936. },
  11937. quarter: {
  11938. common: false,
  11939. size: 7.884e9,
  11940. steps: 4
  11941. },
  11942. year: {
  11943. common: true,
  11944. size: 3.154e10
  11945. }
  11946. };
  11947. var UNITS = Object.keys(INTERVALS);
  11948. function sorter(a, b) {
  11949. return a - b;
  11950. }
  11951. function arrayUnique(items) {
  11952. var hash = {};
  11953. var out = [];
  11954. var i, ilen, item;
  11955. for (i = 0, ilen = items.length; i < ilen; ++i) {
  11956. item = items[i];
  11957. if (!hash[item]) {
  11958. hash[item] = true;
  11959. out.push(item);
  11960. }
  11961. }
  11962. return out;
  11963. }
  11964. function getMin(options) {
  11965. return helpers$1.valueOrDefault(options.time.min, options.ticks.min);
  11966. }
  11967. function getMax(options) {
  11968. return helpers$1.valueOrDefault(options.time.max, options.ticks.max);
  11969. }
  11970. /**
  11971. * Returns an array of {time, pos} objects used to interpolate a specific `time` or position
  11972. * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is
  11973. * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other
  11974. * extremity (left + width or top + height). Note that it would be more optimized to directly
  11975. * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need
  11976. * to create the lookup table. The table ALWAYS contains at least two items: min and max.
  11977. *
  11978. * @param {number[]} timestamps - timestamps sorted from lowest to highest.
  11979. * @param {string} distribution - If 'linear', timestamps will be spread linearly along the min
  11980. * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}.
  11981. * If 'series', timestamps will be positioned at the same distance from each other. In this
  11982. * case, only timestamps that break the time linearity are registered, meaning that in the
  11983. * best case, all timestamps are linear, the table contains only min and max.
  11984. */
  11985. function buildLookupTable(timestamps, min, max, distribution) {
  11986. if (distribution === 'linear' || !timestamps.length) {
  11987. return [
  11988. {time: min, pos: 0},
  11989. {time: max, pos: 1}
  11990. ];
  11991. }
  11992. var table = [];
  11993. var items = [min];
  11994. var i, ilen, prev, curr, next;
  11995. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  11996. curr = timestamps[i];
  11997. if (curr > min && curr < max) {
  11998. items.push(curr);
  11999. }
  12000. }
  12001. items.push(max);
  12002. for (i = 0, ilen = items.length; i < ilen; ++i) {
  12003. next = items[i + 1];
  12004. prev = items[i - 1];
  12005. curr = items[i];
  12006. // only add points that breaks the scale linearity
  12007. if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) {
  12008. table.push({time: curr, pos: i / (ilen - 1)});
  12009. }
  12010. }
  12011. return table;
  12012. }
  12013. // @see adapted from https://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/
  12014. function lookup(table, key, value) {
  12015. var lo = 0;
  12016. var hi = table.length - 1;
  12017. var mid, i0, i1;
  12018. while (lo >= 0 && lo <= hi) {
  12019. mid = (lo + hi) >> 1;
  12020. i0 = table[mid - 1] || null;
  12021. i1 = table[mid];
  12022. if (!i0) {
  12023. // given value is outside table (before first item)
  12024. return {lo: null, hi: i1};
  12025. } else if (i1[key] < value) {
  12026. lo = mid + 1;
  12027. } else if (i0[key] > value) {
  12028. hi = mid - 1;
  12029. } else {
  12030. return {lo: i0, hi: i1};
  12031. }
  12032. }
  12033. // given value is outside table (after last item)
  12034. return {lo: i1, hi: null};
  12035. }
  12036. /**
  12037. * Linearly interpolates the given source `value` using the table items `skey` values and
  12038. * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos')
  12039. * returns the position for a timestamp equal to 42. If value is out of bounds, values at
  12040. * index [0, 1] or [n - 1, n] are used for the interpolation.
  12041. */
  12042. function interpolate$1(table, skey, sval, tkey) {
  12043. var range = lookup(table, skey, sval);
  12044. // Note: the lookup table ALWAYS contains at least 2 items (min and max)
  12045. var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo;
  12046. var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi;
  12047. var span = next[skey] - prev[skey];
  12048. var ratio = span ? (sval - prev[skey]) / span : 0;
  12049. var offset = (next[tkey] - prev[tkey]) * ratio;
  12050. return prev[tkey] + offset;
  12051. }
  12052. function toTimestamp(scale, input) {
  12053. var adapter = scale._adapter;
  12054. var options = scale.options.time;
  12055. var parser = options.parser;
  12056. var format = parser || options.format;
  12057. var value = input;
  12058. if (typeof parser === 'function') {
  12059. value = parser(value);
  12060. }
  12061. // Only parse if its not a timestamp already
  12062. if (!helpers$1.isFinite(value)) {
  12063. value = typeof format === 'string'
  12064. ? adapter.parse(value, format)
  12065. : adapter.parse(value);
  12066. }
  12067. if (value !== null) {
  12068. return +value;
  12069. }
  12070. // Labels are in an incompatible format and no `parser` has been provided.
  12071. // The user might still use the deprecated `format` option for parsing.
  12072. if (!parser && typeof format === 'function') {
  12073. value = format(input);
  12074. // `format` could return something else than a timestamp, if so, parse it
  12075. if (!helpers$1.isFinite(value)) {
  12076. value = adapter.parse(value);
  12077. }
  12078. }
  12079. return value;
  12080. }
  12081. function parse(scale, input) {
  12082. if (helpers$1.isNullOrUndef(input)) {
  12083. return null;
  12084. }
  12085. var options = scale.options.time;
  12086. var value = toTimestamp(scale, scale.getRightValue(input));
  12087. if (value === null) {
  12088. return value;
  12089. }
  12090. if (options.round) {
  12091. value = +scale._adapter.startOf(value, options.round);
  12092. }
  12093. return value;
  12094. }
  12095. /**
  12096. * Figures out what unit results in an appropriate number of auto-generated ticks
  12097. */
  12098. function determineUnitForAutoTicks(minUnit, min, max, capacity) {
  12099. var ilen = UNITS.length;
  12100. var i, interval, factor;
  12101. for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) {
  12102. interval = INTERVALS[UNITS[i]];
  12103. factor = interval.steps ? interval.steps : MAX_INTEGER;
  12104. if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) {
  12105. return UNITS[i];
  12106. }
  12107. }
  12108. return UNITS[ilen - 1];
  12109. }
  12110. /**
  12111. * Figures out what unit to format a set of ticks with
  12112. */
  12113. function determineUnitForFormatting(scale, numTicks, minUnit, min, max) {
  12114. var i, unit;
  12115. for (i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) {
  12116. unit = UNITS[i];
  12117. if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) {
  12118. return unit;
  12119. }
  12120. }
  12121. return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0];
  12122. }
  12123. function determineMajorUnit(unit) {
  12124. for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) {
  12125. if (INTERVALS[UNITS[i]].common) {
  12126. return UNITS[i];
  12127. }
  12128. }
  12129. }
  12130. /**
  12131. * Generates a maximum of `capacity` timestamps between min and max, rounded to the
  12132. * `minor` unit using the given scale time `options`.
  12133. * Important: this method can return ticks outside the min and max range, it's the
  12134. * responsibility of the calling code to clamp values if needed.
  12135. */
  12136. function generate(scale, min, max, capacity) {
  12137. var adapter = scale._adapter;
  12138. var options = scale.options;
  12139. var timeOpts = options.time;
  12140. var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity);
  12141. var stepSize = resolve$5([timeOpts.stepSize, timeOpts.unitStepSize, 1]);
  12142. var weekday = minor === 'week' ? timeOpts.isoWeekday : false;
  12143. var first = min;
  12144. var ticks = [];
  12145. var time;
  12146. // For 'week' unit, handle the first day of week option
  12147. if (weekday) {
  12148. first = +adapter.startOf(first, 'isoWeek', weekday);
  12149. }
  12150. // Align first ticks on unit
  12151. first = +adapter.startOf(first, weekday ? 'day' : minor);
  12152. // Prevent browser from freezing in case user options request millions of milliseconds
  12153. if (adapter.diff(max, min, minor) > 100000 * stepSize) {
  12154. throw min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor;
  12155. }
  12156. for (time = first; time < max; time = +adapter.add(time, stepSize, minor)) {
  12157. ticks.push(time);
  12158. }
  12159. if (time === max || options.bounds === 'ticks') {
  12160. ticks.push(time);
  12161. }
  12162. return ticks;
  12163. }
  12164. /**
  12165. * Returns the start and end offsets from edges in the form of {start, end}
  12166. * where each value is a relative width to the scale and ranges between 0 and 1.
  12167. * They add extra margins on the both sides by scaling down the original scale.
  12168. * Offsets are added when the `offset` option is true.
  12169. */
  12170. function computeOffsets(table, ticks, min, max, options) {
  12171. var start = 0;
  12172. var end = 0;
  12173. var first, last;
  12174. if (options.offset && ticks.length) {
  12175. first = interpolate$1(table, 'time', ticks[0], 'pos');
  12176. if (ticks.length === 1) {
  12177. start = 1 - first;
  12178. } else {
  12179. start = (interpolate$1(table, 'time', ticks[1], 'pos') - first) / 2;
  12180. }
  12181. last = interpolate$1(table, 'time', ticks[ticks.length - 1], 'pos');
  12182. if (ticks.length === 1) {
  12183. end = last;
  12184. } else {
  12185. end = (last - interpolate$1(table, 'time', ticks[ticks.length - 2], 'pos')) / 2;
  12186. }
  12187. }
  12188. return {start: start, end: end, factor: 1 / (start + 1 + end)};
  12189. }
  12190. function setMajorTicks(scale, ticks, map, majorUnit) {
  12191. var adapter = scale._adapter;
  12192. var first = +adapter.startOf(ticks[0].value, majorUnit);
  12193. var last = ticks[ticks.length - 1].value;
  12194. var major, index;
  12195. for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) {
  12196. index = map[major];
  12197. if (index >= 0) {
  12198. ticks[index].major = true;
  12199. }
  12200. }
  12201. return ticks;
  12202. }
  12203. function ticksFromTimestamps(scale, values, majorUnit) {
  12204. var ticks = [];
  12205. var map = {};
  12206. var ilen = values.length;
  12207. var i, value;
  12208. for (i = 0; i < ilen; ++i) {
  12209. value = values[i];
  12210. map[value] = i;
  12211. ticks.push({
  12212. value: value,
  12213. major: false
  12214. });
  12215. }
  12216. // We set the major ticks separately from the above loop because calling startOf for every tick
  12217. // is expensive when there is a large number of ticks
  12218. return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit);
  12219. }
  12220. var defaultConfig$4 = {
  12221. position: 'bottom',
  12222. /**
  12223. * Data distribution along the scale:
  12224. * - 'linear': data are spread according to their time (distances can vary),
  12225. * - 'series': data are spread at the same distance from each other.
  12226. * @see https://github.com/chartjs/Chart.js/pull/4507
  12227. * @since 2.7.0
  12228. */
  12229. distribution: 'linear',
  12230. /**
  12231. * Scale boundary strategy (bypassed by min/max time options)
  12232. * - `data`: make sure data are fully visible, ticks outside are removed
  12233. * - `ticks`: make sure ticks are fully visible, data outside are truncated
  12234. * @see https://github.com/chartjs/Chart.js/pull/4556
  12235. * @since 2.7.0
  12236. */
  12237. bounds: 'data',
  12238. adapters: {},
  12239. time: {
  12240. 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
  12241. unit: false, // false == automatic or override with week, month, year, etc.
  12242. round: false, // none, or override with week, month, year, etc.
  12243. displayFormat: false, // DEPRECATED
  12244. isoWeekday: false, // override week start day - see https://momentjs.com/docs/#/get-set/iso-weekday/
  12245. minUnit: 'millisecond',
  12246. displayFormats: {}
  12247. },
  12248. ticks: {
  12249. autoSkip: false,
  12250. /**
  12251. * Ticks generation input values:
  12252. * - 'auto': generates "optimal" ticks based on scale size and time options.
  12253. * - 'data': generates ticks from data (including labels from data {t|x|y} objects).
  12254. * - 'labels': generates ticks from user given `data.labels` values ONLY.
  12255. * @see https://github.com/chartjs/Chart.js/pull/4507
  12256. * @since 2.7.0
  12257. */
  12258. source: 'auto',
  12259. major: {
  12260. enabled: false
  12261. }
  12262. }
  12263. };
  12264. var scale_time = core_scale.extend({
  12265. initialize: function() {
  12266. this.mergeTicksOptions();
  12267. core_scale.prototype.initialize.call(this);
  12268. },
  12269. update: function() {
  12270. var me = this;
  12271. var options = me.options;
  12272. var time = options.time || (options.time = {});
  12273. var adapter = me._adapter = new core_adapters._date(options.adapters.date);
  12274. // DEPRECATIONS: output a message only one time per update
  12275. deprecated$1('time scale', time.format, 'time.format', 'time.parser');
  12276. deprecated$1('time scale', time.min, 'time.min', 'ticks.min');
  12277. deprecated$1('time scale', time.max, 'time.max', 'ticks.max');
  12278. // Backward compatibility: before introducing adapter, `displayFormats` was
  12279. // supposed to contain *all* unit/string pairs but this can't be resolved
  12280. // when loading the scale (adapters are loaded afterward), so let's populate
  12281. // missing formats on update
  12282. helpers$1.mergeIf(time.displayFormats, adapter.formats());
  12283. return core_scale.prototype.update.apply(me, arguments);
  12284. },
  12285. /**
  12286. * Allows data to be referenced via 't' attribute
  12287. */
  12288. getRightValue: function(rawValue) {
  12289. if (rawValue && rawValue.t !== undefined) {
  12290. rawValue = rawValue.t;
  12291. }
  12292. return core_scale.prototype.getRightValue.call(this, rawValue);
  12293. },
  12294. determineDataLimits: function() {
  12295. var me = this;
  12296. var chart = me.chart;
  12297. var adapter = me._adapter;
  12298. var options = me.options;
  12299. var unit = options.time.unit || 'day';
  12300. var min = MAX_INTEGER;
  12301. var max = MIN_INTEGER;
  12302. var timestamps = [];
  12303. var datasets = [];
  12304. var labels = [];
  12305. var i, j, ilen, jlen, data, timestamp, labelsAdded;
  12306. var dataLabels = me._getLabels();
  12307. for (i = 0, ilen = dataLabels.length; i < ilen; ++i) {
  12308. labels.push(parse(me, dataLabels[i]));
  12309. }
  12310. for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) {
  12311. if (chart.isDatasetVisible(i)) {
  12312. data = chart.data.datasets[i].data;
  12313. // Let's consider that all data have the same format.
  12314. if (helpers$1.isObject(data[0])) {
  12315. datasets[i] = [];
  12316. for (j = 0, jlen = data.length; j < jlen; ++j) {
  12317. timestamp = parse(me, data[j]);
  12318. timestamps.push(timestamp);
  12319. datasets[i][j] = timestamp;
  12320. }
  12321. } else {
  12322. datasets[i] = labels.slice(0);
  12323. if (!labelsAdded) {
  12324. timestamps = timestamps.concat(labels);
  12325. labelsAdded = true;
  12326. }
  12327. }
  12328. } else {
  12329. datasets[i] = [];
  12330. }
  12331. }
  12332. if (labels.length) {
  12333. min = Math.min(min, labels[0]);
  12334. max = Math.max(max, labels[labels.length - 1]);
  12335. }
  12336. if (timestamps.length) {
  12337. timestamps = ilen > 1 ? arrayUnique(timestamps).sort(sorter) : timestamps.sort(sorter);
  12338. min = Math.min(min, timestamps[0]);
  12339. max = Math.max(max, timestamps[timestamps.length - 1]);
  12340. }
  12341. min = parse(me, getMin(options)) || min;
  12342. max = parse(me, getMax(options)) || max;
  12343. // In case there is no valid min/max, set limits based on unit time option
  12344. min = min === MAX_INTEGER ? +adapter.startOf(Date.now(), unit) : min;
  12345. max = max === MIN_INTEGER ? +adapter.endOf(Date.now(), unit) + 1 : max;
  12346. // Make sure that max is strictly higher than min (required by the lookup table)
  12347. me.min = Math.min(min, max);
  12348. me.max = Math.max(min + 1, max);
  12349. // PRIVATE
  12350. me._table = [];
  12351. me._timestamps = {
  12352. data: timestamps,
  12353. datasets: datasets,
  12354. labels: labels
  12355. };
  12356. },
  12357. buildTicks: function() {
  12358. var me = this;
  12359. var min = me.min;
  12360. var max = me.max;
  12361. var options = me.options;
  12362. var tickOpts = options.ticks;
  12363. var timeOpts = options.time;
  12364. var timestamps = me._timestamps;
  12365. var ticks = [];
  12366. var capacity = me.getLabelCapacity(min);
  12367. var source = tickOpts.source;
  12368. var distribution = options.distribution;
  12369. var i, ilen, timestamp;
  12370. if (source === 'data' || (source === 'auto' && distribution === 'series')) {
  12371. timestamps = timestamps.data;
  12372. } else if (source === 'labels') {
  12373. timestamps = timestamps.labels;
  12374. } else {
  12375. timestamps = generate(me, min, max, capacity);
  12376. }
  12377. if (options.bounds === 'ticks' && timestamps.length) {
  12378. min = timestamps[0];
  12379. max = timestamps[timestamps.length - 1];
  12380. }
  12381. // Enforce limits with user min/max options
  12382. min = parse(me, getMin(options)) || min;
  12383. max = parse(me, getMax(options)) || max;
  12384. // Remove ticks outside the min/max range
  12385. for (i = 0, ilen = timestamps.length; i < ilen; ++i) {
  12386. timestamp = timestamps[i];
  12387. if (timestamp >= min && timestamp <= max) {
  12388. ticks.push(timestamp);
  12389. }
  12390. }
  12391. me.min = min;
  12392. me.max = max;
  12393. // PRIVATE
  12394. // determineUnitForFormatting relies on the number of ticks so we don't use it when
  12395. // autoSkip is enabled because we don't yet know what the final number of ticks will be
  12396. me._unit = timeOpts.unit || (tickOpts.autoSkip
  12397. ? determineUnitForAutoTicks(timeOpts.minUnit, me.min, me.max, capacity)
  12398. : determineUnitForFormatting(me, ticks.length, timeOpts.minUnit, me.min, me.max));
  12399. me._majorUnit = !tickOpts.major.enabled || me._unit === 'year' ? undefined
  12400. : determineMajorUnit(me._unit);
  12401. me._table = buildLookupTable(me._timestamps.data, min, max, distribution);
  12402. me._offsets = computeOffsets(me._table, ticks, min, max, options);
  12403. if (tickOpts.reverse) {
  12404. ticks.reverse();
  12405. }
  12406. return ticksFromTimestamps(me, ticks, me._majorUnit);
  12407. },
  12408. getLabelForIndex: function(index, datasetIndex) {
  12409. var me = this;
  12410. var adapter = me._adapter;
  12411. var data = me.chart.data;
  12412. var timeOpts = me.options.time;
  12413. var label = data.labels && index < data.labels.length ? data.labels[index] : '';
  12414. var value = data.datasets[datasetIndex].data[index];
  12415. if (helpers$1.isObject(value)) {
  12416. label = me.getRightValue(value);
  12417. }
  12418. if (timeOpts.tooltipFormat) {
  12419. return adapter.format(toTimestamp(me, label), timeOpts.tooltipFormat);
  12420. }
  12421. if (typeof label === 'string') {
  12422. return label;
  12423. }
  12424. return adapter.format(toTimestamp(me, label), timeOpts.displayFormats.datetime);
  12425. },
  12426. /**
  12427. * Function to format an individual tick mark
  12428. * @private
  12429. */
  12430. tickFormatFunction: function(time, index, ticks, format) {
  12431. var me = this;
  12432. var adapter = me._adapter;
  12433. var options = me.options;
  12434. var formats = options.time.displayFormats;
  12435. var minorFormat = formats[me._unit];
  12436. var majorUnit = me._majorUnit;
  12437. var majorFormat = formats[majorUnit];
  12438. var tick = ticks[index];
  12439. var tickOpts = options.ticks;
  12440. var major = majorUnit && majorFormat && tick && tick.major;
  12441. var label = adapter.format(time, format ? format : major ? majorFormat : minorFormat);
  12442. var nestedTickOpts = major ? tickOpts.major : tickOpts.minor;
  12443. var formatter = resolve$5([
  12444. nestedTickOpts.callback,
  12445. nestedTickOpts.userCallback,
  12446. tickOpts.callback,
  12447. tickOpts.userCallback
  12448. ]);
  12449. return formatter ? formatter(label, index, ticks) : label;
  12450. },
  12451. convertTicksToLabels: function(ticks) {
  12452. var labels = [];
  12453. var i, ilen;
  12454. for (i = 0, ilen = ticks.length; i < ilen; ++i) {
  12455. labels.push(this.tickFormatFunction(ticks[i].value, i, ticks));
  12456. }
  12457. return labels;
  12458. },
  12459. /**
  12460. * @private
  12461. */
  12462. getPixelForOffset: function(time) {
  12463. var me = this;
  12464. var offsets = me._offsets;
  12465. var pos = interpolate$1(me._table, 'time', time, 'pos');
  12466. return me.getPixelForDecimal((offsets.start + pos) * offsets.factor);
  12467. },
  12468. getPixelForValue: function(value, index, datasetIndex) {
  12469. var me = this;
  12470. var time = null;
  12471. if (index !== undefined && datasetIndex !== undefined) {
  12472. time = me._timestamps.datasets[datasetIndex][index];
  12473. }
  12474. if (time === null) {
  12475. time = parse(me, value);
  12476. }
  12477. if (time !== null) {
  12478. return me.getPixelForOffset(time);
  12479. }
  12480. },
  12481. getPixelForTick: function(index) {
  12482. var ticks = this.getTicks();
  12483. return index >= 0 && index < ticks.length ?
  12484. this.getPixelForOffset(ticks[index].value) :
  12485. null;
  12486. },
  12487. getValueForPixel: function(pixel) {
  12488. var me = this;
  12489. var offsets = me._offsets;
  12490. var pos = me.getDecimalForPixel(pixel) / offsets.factor - offsets.end;
  12491. var time = interpolate$1(me._table, 'pos', pos, 'time');
  12492. // DEPRECATION, we should return time directly
  12493. return me._adapter._create(time);
  12494. },
  12495. /**
  12496. * @private
  12497. */
  12498. _getLabelSize: function(label) {
  12499. var me = this;
  12500. var ticksOpts = me.options.ticks;
  12501. var tickLabelWidth = me.ctx.measureText(label).width;
  12502. var angle = helpers$1.toRadians(me.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation);
  12503. var cosRotation = Math.cos(angle);
  12504. var sinRotation = Math.sin(angle);
  12505. var tickFontSize = valueOrDefault$d(ticksOpts.fontSize, core_defaults.global.defaultFontSize);
  12506. return {
  12507. w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation),
  12508. h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation)
  12509. };
  12510. },
  12511. /**
  12512. * Crude approximation of what the label width might be
  12513. * @private
  12514. */
  12515. getLabelWidth: function(label) {
  12516. return this._getLabelSize(label).w;
  12517. },
  12518. /**
  12519. * @private
  12520. */
  12521. getLabelCapacity: function(exampleTime) {
  12522. var me = this;
  12523. var timeOpts = me.options.time;
  12524. var displayFormats = timeOpts.displayFormats;
  12525. // pick the longest format (milliseconds) for guestimation
  12526. var format = displayFormats[timeOpts.unit] || displayFormats.millisecond;
  12527. var exampleLabel = me.tickFormatFunction(exampleTime, 0, ticksFromTimestamps(me, [exampleTime], me._majorUnit), format);
  12528. var size = me._getLabelSize(exampleLabel);
  12529. var capacity = Math.floor(me.isHorizontal() ? me.width / size.w : me.height / size.h);
  12530. if (me.options.offset) {
  12531. capacity--;
  12532. }
  12533. return capacity > 0 ? capacity : 1;
  12534. }
  12535. });
  12536. // INTERNAL: static default options, registered in src/index.js
  12537. var _defaults$4 = defaultConfig$4;
  12538. scale_time._defaults = _defaults$4;
  12539. var scales = {
  12540. category: scale_category,
  12541. linear: scale_linear,
  12542. logarithmic: scale_logarithmic,
  12543. radialLinear: scale_radialLinear,
  12544. time: scale_time
  12545. };
  12546. var moment = createCommonjsModule(function (module, exports) {
  12547. (function (global, factory) {
  12548. module.exports = factory() ;
  12549. }(commonjsGlobal, (function () {
  12550. var hookCallback;
  12551. function hooks () {
  12552. return hookCallback.apply(null, arguments);
  12553. }
  12554. // This is done to register the method called with moment()
  12555. // without creating circular dependencies.
  12556. function setHookCallback (callback) {
  12557. hookCallback = callback;
  12558. }
  12559. function isArray(input) {
  12560. return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]';
  12561. }
  12562. function isObject(input) {
  12563. // IE8 will treat undefined and null as object if it wasn't for
  12564. // input != null
  12565. return input != null && Object.prototype.toString.call(input) === '[object Object]';
  12566. }
  12567. function isObjectEmpty(obj) {
  12568. if (Object.getOwnPropertyNames) {
  12569. return (Object.getOwnPropertyNames(obj).length === 0);
  12570. } else {
  12571. var k;
  12572. for (k in obj) {
  12573. if (obj.hasOwnProperty(k)) {
  12574. return false;
  12575. }
  12576. }
  12577. return true;
  12578. }
  12579. }
  12580. function isUndefined(input) {
  12581. return input === void 0;
  12582. }
  12583. function isNumber(input) {
  12584. return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]';
  12585. }
  12586. function isDate(input) {
  12587. return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]';
  12588. }
  12589. function map(arr, fn) {
  12590. var res = [], i;
  12591. for (i = 0; i < arr.length; ++i) {
  12592. res.push(fn(arr[i], i));
  12593. }
  12594. return res;
  12595. }
  12596. function hasOwnProp(a, b) {
  12597. return Object.prototype.hasOwnProperty.call(a, b);
  12598. }
  12599. function extend(a, b) {
  12600. for (var i in b) {
  12601. if (hasOwnProp(b, i)) {
  12602. a[i] = b[i];
  12603. }
  12604. }
  12605. if (hasOwnProp(b, 'toString')) {
  12606. a.toString = b.toString;
  12607. }
  12608. if (hasOwnProp(b, 'valueOf')) {
  12609. a.valueOf = b.valueOf;
  12610. }
  12611. return a;
  12612. }
  12613. function createUTC (input, format, locale, strict) {
  12614. return createLocalOrUTC(input, format, locale, strict, true).utc();
  12615. }
  12616. function defaultParsingFlags() {
  12617. // We need to deep clone this object.
  12618. return {
  12619. empty : false,
  12620. unusedTokens : [],
  12621. unusedInput : [],
  12622. overflow : -2,
  12623. charsLeftOver : 0,
  12624. nullInput : false,
  12625. invalidMonth : null,
  12626. invalidFormat : false,
  12627. userInvalidated : false,
  12628. iso : false,
  12629. parsedDateParts : [],
  12630. meridiem : null,
  12631. rfc2822 : false,
  12632. weekdayMismatch : false
  12633. };
  12634. }
  12635. function getParsingFlags(m) {
  12636. if (m._pf == null) {
  12637. m._pf = defaultParsingFlags();
  12638. }
  12639. return m._pf;
  12640. }
  12641. var some;
  12642. if (Array.prototype.some) {
  12643. some = Array.prototype.some;
  12644. } else {
  12645. some = function (fun) {
  12646. var t = Object(this);
  12647. var len = t.length >>> 0;
  12648. for (var i = 0; i < len; i++) {
  12649. if (i in t && fun.call(this, t[i], i, t)) {
  12650. return true;
  12651. }
  12652. }
  12653. return false;
  12654. };
  12655. }
  12656. function isValid(m) {
  12657. if (m._isValid == null) {
  12658. var flags = getParsingFlags(m);
  12659. var parsedParts = some.call(flags.parsedDateParts, function (i) {
  12660. return i != null;
  12661. });
  12662. var isNowValid = !isNaN(m._d.getTime()) &&
  12663. flags.overflow < 0 &&
  12664. !flags.empty &&
  12665. !flags.invalidMonth &&
  12666. !flags.invalidWeekday &&
  12667. !flags.weekdayMismatch &&
  12668. !flags.nullInput &&
  12669. !flags.invalidFormat &&
  12670. !flags.userInvalidated &&
  12671. (!flags.meridiem || (flags.meridiem && parsedParts));
  12672. if (m._strict) {
  12673. isNowValid = isNowValid &&
  12674. flags.charsLeftOver === 0 &&
  12675. flags.unusedTokens.length === 0 &&
  12676. flags.bigHour === undefined;
  12677. }
  12678. if (Object.isFrozen == null || !Object.isFrozen(m)) {
  12679. m._isValid = isNowValid;
  12680. }
  12681. else {
  12682. return isNowValid;
  12683. }
  12684. }
  12685. return m._isValid;
  12686. }
  12687. function createInvalid (flags) {
  12688. var m = createUTC(NaN);
  12689. if (flags != null) {
  12690. extend(getParsingFlags(m), flags);
  12691. }
  12692. else {
  12693. getParsingFlags(m).userInvalidated = true;
  12694. }
  12695. return m;
  12696. }
  12697. // Plugins that add properties should also add the key here (null value),
  12698. // so we can properly clone ourselves.
  12699. var momentProperties = hooks.momentProperties = [];
  12700. function copyConfig(to, from) {
  12701. var i, prop, val;
  12702. if (!isUndefined(from._isAMomentObject)) {
  12703. to._isAMomentObject = from._isAMomentObject;
  12704. }
  12705. if (!isUndefined(from._i)) {
  12706. to._i = from._i;
  12707. }
  12708. if (!isUndefined(from._f)) {
  12709. to._f = from._f;
  12710. }
  12711. if (!isUndefined(from._l)) {
  12712. to._l = from._l;
  12713. }
  12714. if (!isUndefined(from._strict)) {
  12715. to._strict = from._strict;
  12716. }
  12717. if (!isUndefined(from._tzm)) {
  12718. to._tzm = from._tzm;
  12719. }
  12720. if (!isUndefined(from._isUTC)) {
  12721. to._isUTC = from._isUTC;
  12722. }
  12723. if (!isUndefined(from._offset)) {
  12724. to._offset = from._offset;
  12725. }
  12726. if (!isUndefined(from._pf)) {
  12727. to._pf = getParsingFlags(from);
  12728. }
  12729. if (!isUndefined(from._locale)) {
  12730. to._locale = from._locale;
  12731. }
  12732. if (momentProperties.length > 0) {
  12733. for (i = 0; i < momentProperties.length; i++) {
  12734. prop = momentProperties[i];
  12735. val = from[prop];
  12736. if (!isUndefined(val)) {
  12737. to[prop] = val;
  12738. }
  12739. }
  12740. }
  12741. return to;
  12742. }
  12743. var updateInProgress = false;
  12744. // Moment prototype object
  12745. function Moment(config) {
  12746. copyConfig(this, config);
  12747. this._d = new Date(config._d != null ? config._d.getTime() : NaN);
  12748. if (!this.isValid()) {
  12749. this._d = new Date(NaN);
  12750. }
  12751. // Prevent infinite loop in case updateOffset creates new moment
  12752. // objects.
  12753. if (updateInProgress === false) {
  12754. updateInProgress = true;
  12755. hooks.updateOffset(this);
  12756. updateInProgress = false;
  12757. }
  12758. }
  12759. function isMoment (obj) {
  12760. return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
  12761. }
  12762. function absFloor (number) {
  12763. if (number < 0) {
  12764. // -0 -> 0
  12765. return Math.ceil(number) || 0;
  12766. } else {
  12767. return Math.floor(number);
  12768. }
  12769. }
  12770. function toInt(argumentForCoercion) {
  12771. var coercedNumber = +argumentForCoercion,
  12772. value = 0;
  12773. if (coercedNumber !== 0 && isFinite(coercedNumber)) {
  12774. value = absFloor(coercedNumber);
  12775. }
  12776. return value;
  12777. }
  12778. // compare two arrays, return the number of differences
  12779. function compareArrays(array1, array2, dontConvert) {
  12780. var len = Math.min(array1.length, array2.length),
  12781. lengthDiff = Math.abs(array1.length - array2.length),
  12782. diffs = 0,
  12783. i;
  12784. for (i = 0; i < len; i++) {
  12785. if ((dontConvert && array1[i] !== array2[i]) ||
  12786. (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) {
  12787. diffs++;
  12788. }
  12789. }
  12790. return diffs + lengthDiff;
  12791. }
  12792. function warn(msg) {
  12793. if (hooks.suppressDeprecationWarnings === false &&
  12794. (typeof console !== 'undefined') && console.warn) {
  12795. console.warn('Deprecation warning: ' + msg);
  12796. }
  12797. }
  12798. function deprecate(msg, fn) {
  12799. var firstTime = true;
  12800. return extend(function () {
  12801. if (hooks.deprecationHandler != null) {
  12802. hooks.deprecationHandler(null, msg);
  12803. }
  12804. if (firstTime) {
  12805. var args = [];
  12806. var arg;
  12807. for (var i = 0; i < arguments.length; i++) {
  12808. arg = '';
  12809. if (typeof arguments[i] === 'object') {
  12810. arg += '\n[' + i + '] ';
  12811. for (var key in arguments[0]) {
  12812. arg += key + ': ' + arguments[0][key] + ', ';
  12813. }
  12814. arg = arg.slice(0, -2); // Remove trailing comma and space
  12815. } else {
  12816. arg = arguments[i];
  12817. }
  12818. args.push(arg);
  12819. }
  12820. warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack);
  12821. firstTime = false;
  12822. }
  12823. return fn.apply(this, arguments);
  12824. }, fn);
  12825. }
  12826. var deprecations = {};
  12827. function deprecateSimple(name, msg) {
  12828. if (hooks.deprecationHandler != null) {
  12829. hooks.deprecationHandler(name, msg);
  12830. }
  12831. if (!deprecations[name]) {
  12832. warn(msg);
  12833. deprecations[name] = true;
  12834. }
  12835. }
  12836. hooks.suppressDeprecationWarnings = false;
  12837. hooks.deprecationHandler = null;
  12838. function isFunction(input) {
  12839. return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]';
  12840. }
  12841. function set (config) {
  12842. var prop, i;
  12843. for (i in config) {
  12844. prop = config[i];
  12845. if (isFunction(prop)) {
  12846. this[i] = prop;
  12847. } else {
  12848. this['_' + i] = prop;
  12849. }
  12850. }
  12851. this._config = config;
  12852. // Lenient ordinal parsing accepts just a number in addition to
  12853. // number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
  12854. // TODO: Remove "ordinalParse" fallback in next major release.
  12855. this._dayOfMonthOrdinalParseLenient = new RegExp(
  12856. (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
  12857. '|' + (/\d{1,2}/).source);
  12858. }
  12859. function mergeConfigs(parentConfig, childConfig) {
  12860. var res = extend({}, parentConfig), prop;
  12861. for (prop in childConfig) {
  12862. if (hasOwnProp(childConfig, prop)) {
  12863. if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) {
  12864. res[prop] = {};
  12865. extend(res[prop], parentConfig[prop]);
  12866. extend(res[prop], childConfig[prop]);
  12867. } else if (childConfig[prop] != null) {
  12868. res[prop] = childConfig[prop];
  12869. } else {
  12870. delete res[prop];
  12871. }
  12872. }
  12873. }
  12874. for (prop in parentConfig) {
  12875. if (hasOwnProp(parentConfig, prop) &&
  12876. !hasOwnProp(childConfig, prop) &&
  12877. isObject(parentConfig[prop])) {
  12878. // make sure changes to properties don't modify parent config
  12879. res[prop] = extend({}, res[prop]);
  12880. }
  12881. }
  12882. return res;
  12883. }
  12884. function Locale(config) {
  12885. if (config != null) {
  12886. this.set(config);
  12887. }
  12888. }
  12889. var keys;
  12890. if (Object.keys) {
  12891. keys = Object.keys;
  12892. } else {
  12893. keys = function (obj) {
  12894. var i, res = [];
  12895. for (i in obj) {
  12896. if (hasOwnProp(obj, i)) {
  12897. res.push(i);
  12898. }
  12899. }
  12900. return res;
  12901. };
  12902. }
  12903. var defaultCalendar = {
  12904. sameDay : '[Today at] LT',
  12905. nextDay : '[Tomorrow at] LT',
  12906. nextWeek : 'dddd [at] LT',
  12907. lastDay : '[Yesterday at] LT',
  12908. lastWeek : '[Last] dddd [at] LT',
  12909. sameElse : 'L'
  12910. };
  12911. function calendar (key, mom, now) {
  12912. var output = this._calendar[key] || this._calendar['sameElse'];
  12913. return isFunction(output) ? output.call(mom, now) : output;
  12914. }
  12915. var defaultLongDateFormat = {
  12916. LTS : 'h:mm:ss A',
  12917. LT : 'h:mm A',
  12918. L : 'MM/DD/YYYY',
  12919. LL : 'MMMM D, YYYY',
  12920. LLL : 'MMMM D, YYYY h:mm A',
  12921. LLLL : 'dddd, MMMM D, YYYY h:mm A'
  12922. };
  12923. function longDateFormat (key) {
  12924. var format = this._longDateFormat[key],
  12925. formatUpper = this._longDateFormat[key.toUpperCase()];
  12926. if (format || !formatUpper) {
  12927. return format;
  12928. }
  12929. this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) {
  12930. return val.slice(1);
  12931. });
  12932. return this._longDateFormat[key];
  12933. }
  12934. var defaultInvalidDate = 'Invalid date';
  12935. function invalidDate () {
  12936. return this._invalidDate;
  12937. }
  12938. var defaultOrdinal = '%d';
  12939. var defaultDayOfMonthOrdinalParse = /\d{1,2}/;
  12940. function ordinal (number) {
  12941. return this._ordinal.replace('%d', number);
  12942. }
  12943. var defaultRelativeTime = {
  12944. future : 'in %s',
  12945. past : '%s ago',
  12946. s : 'a few seconds',
  12947. ss : '%d seconds',
  12948. m : 'a minute',
  12949. mm : '%d minutes',
  12950. h : 'an hour',
  12951. hh : '%d hours',
  12952. d : 'a day',
  12953. dd : '%d days',
  12954. M : 'a month',
  12955. MM : '%d months',
  12956. y : 'a year',
  12957. yy : '%d years'
  12958. };
  12959. function relativeTime (number, withoutSuffix, string, isFuture) {
  12960. var output = this._relativeTime[string];
  12961. return (isFunction(output)) ?
  12962. output(number, withoutSuffix, string, isFuture) :
  12963. output.replace(/%d/i, number);
  12964. }
  12965. function pastFuture (diff, output) {
  12966. var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
  12967. return isFunction(format) ? format(output) : format.replace(/%s/i, output);
  12968. }
  12969. var aliases = {};
  12970. function addUnitAlias (unit, shorthand) {
  12971. var lowerCase = unit.toLowerCase();
  12972. aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
  12973. }
  12974. function normalizeUnits(units) {
  12975. return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
  12976. }
  12977. function normalizeObjectUnits(inputObject) {
  12978. var normalizedInput = {},
  12979. normalizedProp,
  12980. prop;
  12981. for (prop in inputObject) {
  12982. if (hasOwnProp(inputObject, prop)) {
  12983. normalizedProp = normalizeUnits(prop);
  12984. if (normalizedProp) {
  12985. normalizedInput[normalizedProp] = inputObject[prop];
  12986. }
  12987. }
  12988. }
  12989. return normalizedInput;
  12990. }
  12991. var priorities = {};
  12992. function addUnitPriority(unit, priority) {
  12993. priorities[unit] = priority;
  12994. }
  12995. function getPrioritizedUnits(unitsObj) {
  12996. var units = [];
  12997. for (var u in unitsObj) {
  12998. units.push({unit: u, priority: priorities[u]});
  12999. }
  13000. units.sort(function (a, b) {
  13001. return a.priority - b.priority;
  13002. });
  13003. return units;
  13004. }
  13005. function zeroFill(number, targetLength, forceSign) {
  13006. var absNumber = '' + Math.abs(number),
  13007. zerosToFill = targetLength - absNumber.length,
  13008. sign = number >= 0;
  13009. return (sign ? (forceSign ? '+' : '') : '-') +
  13010. Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber;
  13011. }
  13012. var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g;
  13013. var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
  13014. var formatFunctions = {};
  13015. var formatTokenFunctions = {};
  13016. // token: 'M'
  13017. // padded: ['MM', 2]
  13018. // ordinal: 'Mo'
  13019. // callback: function () { this.month() + 1 }
  13020. function addFormatToken (token, padded, ordinal, callback) {
  13021. var func = callback;
  13022. if (typeof callback === 'string') {
  13023. func = function () {
  13024. return this[callback]();
  13025. };
  13026. }
  13027. if (token) {
  13028. formatTokenFunctions[token] = func;
  13029. }
  13030. if (padded) {
  13031. formatTokenFunctions[padded[0]] = function () {
  13032. return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
  13033. };
  13034. }
  13035. if (ordinal) {
  13036. formatTokenFunctions[ordinal] = function () {
  13037. return this.localeData().ordinal(func.apply(this, arguments), token);
  13038. };
  13039. }
  13040. }
  13041. function removeFormattingTokens(input) {
  13042. if (input.match(/\[[\s\S]/)) {
  13043. return input.replace(/^\[|\]$/g, '');
  13044. }
  13045. return input.replace(/\\/g, '');
  13046. }
  13047. function makeFormatFunction(format) {
  13048. var array = format.match(formattingTokens), i, length;
  13049. for (i = 0, length = array.length; i < length; i++) {
  13050. if (formatTokenFunctions[array[i]]) {
  13051. array[i] = formatTokenFunctions[array[i]];
  13052. } else {
  13053. array[i] = removeFormattingTokens(array[i]);
  13054. }
  13055. }
  13056. return function (mom) {
  13057. var output = '', i;
  13058. for (i = 0; i < length; i++) {
  13059. output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
  13060. }
  13061. return output;
  13062. };
  13063. }
  13064. // format date using native date object
  13065. function formatMoment(m, format) {
  13066. if (!m.isValid()) {
  13067. return m.localeData().invalidDate();
  13068. }
  13069. format = expandFormat(format, m.localeData());
  13070. formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
  13071. return formatFunctions[format](m);
  13072. }
  13073. function expandFormat(format, locale) {
  13074. var i = 5;
  13075. function replaceLongDateFormatTokens(input) {
  13076. return locale.longDateFormat(input) || input;
  13077. }
  13078. localFormattingTokens.lastIndex = 0;
  13079. while (i >= 0 && localFormattingTokens.test(format)) {
  13080. format = format.replace(localFormattingTokens, replaceLongDateFormatTokens);
  13081. localFormattingTokens.lastIndex = 0;
  13082. i -= 1;
  13083. }
  13084. return format;
  13085. }
  13086. var match1 = /\d/; // 0 - 9
  13087. var match2 = /\d\d/; // 00 - 99
  13088. var match3 = /\d{3}/; // 000 - 999
  13089. var match4 = /\d{4}/; // 0000 - 9999
  13090. var match6 = /[+-]?\d{6}/; // -999999 - 999999
  13091. var match1to2 = /\d\d?/; // 0 - 99
  13092. var match3to4 = /\d\d\d\d?/; // 999 - 9999
  13093. var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999
  13094. var match1to3 = /\d{1,3}/; // 0 - 999
  13095. var match1to4 = /\d{1,4}/; // 0 - 9999
  13096. var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999
  13097. var matchUnsigned = /\d+/; // 0 - inf
  13098. var matchSigned = /[+-]?\d+/; // -inf - inf
  13099. var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z
  13100. var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z
  13101. var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123
  13102. // any word (or two) characters or numbers including two/three word month in arabic.
  13103. // includes scottish gaelic two word and hyphenated months
  13104. var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;
  13105. var regexes = {};
  13106. function addRegexToken (token, regex, strictRegex) {
  13107. regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) {
  13108. return (isStrict && strictRegex) ? strictRegex : regex;
  13109. };
  13110. }
  13111. function getParseRegexForToken (token, config) {
  13112. if (!hasOwnProp(regexes, token)) {
  13113. return new RegExp(unescapeFormat(token));
  13114. }
  13115. return regexes[token](config._strict, config._locale);
  13116. }
  13117. // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  13118. function unescapeFormat(s) {
  13119. return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) {
  13120. return p1 || p2 || p3 || p4;
  13121. }));
  13122. }
  13123. function regexEscape(s) {
  13124. return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  13125. }
  13126. var tokens = {};
  13127. function addParseToken (token, callback) {
  13128. var i, func = callback;
  13129. if (typeof token === 'string') {
  13130. token = [token];
  13131. }
  13132. if (isNumber(callback)) {
  13133. func = function (input, array) {
  13134. array[callback] = toInt(input);
  13135. };
  13136. }
  13137. for (i = 0; i < token.length; i++) {
  13138. tokens[token[i]] = func;
  13139. }
  13140. }
  13141. function addWeekParseToken (token, callback) {
  13142. addParseToken(token, function (input, array, config, token) {
  13143. config._w = config._w || {};
  13144. callback(input, config._w, config, token);
  13145. });
  13146. }
  13147. function addTimeToArrayFromToken(token, input, config) {
  13148. if (input != null && hasOwnProp(tokens, token)) {
  13149. tokens[token](input, config._a, config, token);
  13150. }
  13151. }
  13152. var YEAR = 0;
  13153. var MONTH = 1;
  13154. var DATE = 2;
  13155. var HOUR = 3;
  13156. var MINUTE = 4;
  13157. var SECOND = 5;
  13158. var MILLISECOND = 6;
  13159. var WEEK = 7;
  13160. var WEEKDAY = 8;
  13161. // FORMATTING
  13162. addFormatToken('Y', 0, 0, function () {
  13163. var y = this.year();
  13164. return y <= 9999 ? '' + y : '+' + y;
  13165. });
  13166. addFormatToken(0, ['YY', 2], 0, function () {
  13167. return this.year() % 100;
  13168. });
  13169. addFormatToken(0, ['YYYY', 4], 0, 'year');
  13170. addFormatToken(0, ['YYYYY', 5], 0, 'year');
  13171. addFormatToken(0, ['YYYYYY', 6, true], 0, 'year');
  13172. // ALIASES
  13173. addUnitAlias('year', 'y');
  13174. // PRIORITIES
  13175. addUnitPriority('year', 1);
  13176. // PARSING
  13177. addRegexToken('Y', matchSigned);
  13178. addRegexToken('YY', match1to2, match2);
  13179. addRegexToken('YYYY', match1to4, match4);
  13180. addRegexToken('YYYYY', match1to6, match6);
  13181. addRegexToken('YYYYYY', match1to6, match6);
  13182. addParseToken(['YYYYY', 'YYYYYY'], YEAR);
  13183. addParseToken('YYYY', function (input, array) {
  13184. array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
  13185. });
  13186. addParseToken('YY', function (input, array) {
  13187. array[YEAR] = hooks.parseTwoDigitYear(input);
  13188. });
  13189. addParseToken('Y', function (input, array) {
  13190. array[YEAR] = parseInt(input, 10);
  13191. });
  13192. // HELPERS
  13193. function daysInYear(year) {
  13194. return isLeapYear(year) ? 366 : 365;
  13195. }
  13196. function isLeapYear(year) {
  13197. return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  13198. }
  13199. // HOOKS
  13200. hooks.parseTwoDigitYear = function (input) {
  13201. return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
  13202. };
  13203. // MOMENTS
  13204. var getSetYear = makeGetSet('FullYear', true);
  13205. function getIsLeapYear () {
  13206. return isLeapYear(this.year());
  13207. }
  13208. function makeGetSet (unit, keepTime) {
  13209. return function (value) {
  13210. if (value != null) {
  13211. set$1(this, unit, value);
  13212. hooks.updateOffset(this, keepTime);
  13213. return this;
  13214. } else {
  13215. return get(this, unit);
  13216. }
  13217. };
  13218. }
  13219. function get (mom, unit) {
  13220. return mom.isValid() ?
  13221. mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
  13222. }
  13223. function set$1 (mom, unit, value) {
  13224. if (mom.isValid() && !isNaN(value)) {
  13225. if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) {
  13226. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()));
  13227. }
  13228. else {
  13229. mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value);
  13230. }
  13231. }
  13232. }
  13233. // MOMENTS
  13234. function stringGet (units) {
  13235. units = normalizeUnits(units);
  13236. if (isFunction(this[units])) {
  13237. return this[units]();
  13238. }
  13239. return this;
  13240. }
  13241. function stringSet (units, value) {
  13242. if (typeof units === 'object') {
  13243. units = normalizeObjectUnits(units);
  13244. var prioritized = getPrioritizedUnits(units);
  13245. for (var i = 0; i < prioritized.length; i++) {
  13246. this[prioritized[i].unit](units[prioritized[i].unit]);
  13247. }
  13248. } else {
  13249. units = normalizeUnits(units);
  13250. if (isFunction(this[units])) {
  13251. return this[units](value);
  13252. }
  13253. }
  13254. return this;
  13255. }
  13256. function mod(n, x) {
  13257. return ((n % x) + x) % x;
  13258. }
  13259. var indexOf;
  13260. if (Array.prototype.indexOf) {
  13261. indexOf = Array.prototype.indexOf;
  13262. } else {
  13263. indexOf = function (o) {
  13264. // I know
  13265. var i;
  13266. for (i = 0; i < this.length; ++i) {
  13267. if (this[i] === o) {
  13268. return i;
  13269. }
  13270. }
  13271. return -1;
  13272. };
  13273. }
  13274. function daysInMonth(year, month) {
  13275. if (isNaN(year) || isNaN(month)) {
  13276. return NaN;
  13277. }
  13278. var modMonth = mod(month, 12);
  13279. year += (month - modMonth) / 12;
  13280. return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2);
  13281. }
  13282. // FORMATTING
  13283. addFormatToken('M', ['MM', 2], 'Mo', function () {
  13284. return this.month() + 1;
  13285. });
  13286. addFormatToken('MMM', 0, 0, function (format) {
  13287. return this.localeData().monthsShort(this, format);
  13288. });
  13289. addFormatToken('MMMM', 0, 0, function (format) {
  13290. return this.localeData().months(this, format);
  13291. });
  13292. // ALIASES
  13293. addUnitAlias('month', 'M');
  13294. // PRIORITY
  13295. addUnitPriority('month', 8);
  13296. // PARSING
  13297. addRegexToken('M', match1to2);
  13298. addRegexToken('MM', match1to2, match2);
  13299. addRegexToken('MMM', function (isStrict, locale) {
  13300. return locale.monthsShortRegex(isStrict);
  13301. });
  13302. addRegexToken('MMMM', function (isStrict, locale) {
  13303. return locale.monthsRegex(isStrict);
  13304. });
  13305. addParseToken(['M', 'MM'], function (input, array) {
  13306. array[MONTH] = toInt(input) - 1;
  13307. });
  13308. addParseToken(['MMM', 'MMMM'], function (input, array, config, token) {
  13309. var month = config._locale.monthsParse(input, token, config._strict);
  13310. // if we didn't find a month name, mark the date as invalid.
  13311. if (month != null) {
  13312. array[MONTH] = month;
  13313. } else {
  13314. getParsingFlags(config).invalidMonth = input;
  13315. }
  13316. });
  13317. // LOCALES
  13318. var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
  13319. var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_');
  13320. function localeMonths (m, format) {
  13321. if (!m) {
  13322. return isArray(this._months) ? this._months :
  13323. this._months['standalone'];
  13324. }
  13325. return isArray(this._months) ? this._months[m.month()] :
  13326. this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()];
  13327. }
  13328. var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_');
  13329. function localeMonthsShort (m, format) {
  13330. if (!m) {
  13331. return isArray(this._monthsShort) ? this._monthsShort :
  13332. this._monthsShort['standalone'];
  13333. }
  13334. return isArray(this._monthsShort) ? this._monthsShort[m.month()] :
  13335. this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()];
  13336. }
  13337. function handleStrictParse(monthName, format, strict) {
  13338. var i, ii, mom, llc = monthName.toLocaleLowerCase();
  13339. if (!this._monthsParse) {
  13340. // this is not used
  13341. this._monthsParse = [];
  13342. this._longMonthsParse = [];
  13343. this._shortMonthsParse = [];
  13344. for (i = 0; i < 12; ++i) {
  13345. mom = createUTC([2000, i]);
  13346. this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase();
  13347. this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
  13348. }
  13349. }
  13350. if (strict) {
  13351. if (format === 'MMM') {
  13352. ii = indexOf.call(this._shortMonthsParse, llc);
  13353. return ii !== -1 ? ii : null;
  13354. } else {
  13355. ii = indexOf.call(this._longMonthsParse, llc);
  13356. return ii !== -1 ? ii : null;
  13357. }
  13358. } else {
  13359. if (format === 'MMM') {
  13360. ii = indexOf.call(this._shortMonthsParse, llc);
  13361. if (ii !== -1) {
  13362. return ii;
  13363. }
  13364. ii = indexOf.call(this._longMonthsParse, llc);
  13365. return ii !== -1 ? ii : null;
  13366. } else {
  13367. ii = indexOf.call(this._longMonthsParse, llc);
  13368. if (ii !== -1) {
  13369. return ii;
  13370. }
  13371. ii = indexOf.call(this._shortMonthsParse, llc);
  13372. return ii !== -1 ? ii : null;
  13373. }
  13374. }
  13375. }
  13376. function localeMonthsParse (monthName, format, strict) {
  13377. var i, mom, regex;
  13378. if (this._monthsParseExact) {
  13379. return handleStrictParse.call(this, monthName, format, strict);
  13380. }
  13381. if (!this._monthsParse) {
  13382. this._monthsParse = [];
  13383. this._longMonthsParse = [];
  13384. this._shortMonthsParse = [];
  13385. }
  13386. // TODO: add sorting
  13387. // Sorting makes sure if one month (or abbr) is a prefix of another
  13388. // see sorting in computeMonthsParse
  13389. for (i = 0; i < 12; i++) {
  13390. // make the regex if we don't have it already
  13391. mom = createUTC([2000, i]);
  13392. if (strict && !this._longMonthsParse[i]) {
  13393. this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i');
  13394. this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i');
  13395. }
  13396. if (!strict && !this._monthsParse[i]) {
  13397. regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, '');
  13398. this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i');
  13399. }
  13400. // test the regex
  13401. if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) {
  13402. return i;
  13403. } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) {
  13404. return i;
  13405. } else if (!strict && this._monthsParse[i].test(monthName)) {
  13406. return i;
  13407. }
  13408. }
  13409. }
  13410. // MOMENTS
  13411. function setMonth (mom, value) {
  13412. var dayOfMonth;
  13413. if (!mom.isValid()) {
  13414. // No op
  13415. return mom;
  13416. }
  13417. if (typeof value === 'string') {
  13418. if (/^\d+$/.test(value)) {
  13419. value = toInt(value);
  13420. } else {
  13421. value = mom.localeData().monthsParse(value);
  13422. // TODO: Another silent failure?
  13423. if (!isNumber(value)) {
  13424. return mom;
  13425. }
  13426. }
  13427. }
  13428. dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
  13429. mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth);
  13430. return mom;
  13431. }
  13432. function getSetMonth (value) {
  13433. if (value != null) {
  13434. setMonth(this, value);
  13435. hooks.updateOffset(this, true);
  13436. return this;
  13437. } else {
  13438. return get(this, 'Month');
  13439. }
  13440. }
  13441. function getDaysInMonth () {
  13442. return daysInMonth(this.year(), this.month());
  13443. }
  13444. var defaultMonthsShortRegex = matchWord;
  13445. function monthsShortRegex (isStrict) {
  13446. if (this._monthsParseExact) {
  13447. if (!hasOwnProp(this, '_monthsRegex')) {
  13448. computeMonthsParse.call(this);
  13449. }
  13450. if (isStrict) {
  13451. return this._monthsShortStrictRegex;
  13452. } else {
  13453. return this._monthsShortRegex;
  13454. }
  13455. } else {
  13456. if (!hasOwnProp(this, '_monthsShortRegex')) {
  13457. this._monthsShortRegex = defaultMonthsShortRegex;
  13458. }
  13459. return this._monthsShortStrictRegex && isStrict ?
  13460. this._monthsShortStrictRegex : this._monthsShortRegex;
  13461. }
  13462. }
  13463. var defaultMonthsRegex = matchWord;
  13464. function monthsRegex (isStrict) {
  13465. if (this._monthsParseExact) {
  13466. if (!hasOwnProp(this, '_monthsRegex')) {
  13467. computeMonthsParse.call(this);
  13468. }
  13469. if (isStrict) {
  13470. return this._monthsStrictRegex;
  13471. } else {
  13472. return this._monthsRegex;
  13473. }
  13474. } else {
  13475. if (!hasOwnProp(this, '_monthsRegex')) {
  13476. this._monthsRegex = defaultMonthsRegex;
  13477. }
  13478. return this._monthsStrictRegex && isStrict ?
  13479. this._monthsStrictRegex : this._monthsRegex;
  13480. }
  13481. }
  13482. function computeMonthsParse () {
  13483. function cmpLenRev(a, b) {
  13484. return b.length - a.length;
  13485. }
  13486. var shortPieces = [], longPieces = [], mixedPieces = [],
  13487. i, mom;
  13488. for (i = 0; i < 12; i++) {
  13489. // make the regex if we don't have it already
  13490. mom = createUTC([2000, i]);
  13491. shortPieces.push(this.monthsShort(mom, ''));
  13492. longPieces.push(this.months(mom, ''));
  13493. mixedPieces.push(this.months(mom, ''));
  13494. mixedPieces.push(this.monthsShort(mom, ''));
  13495. }
  13496. // Sorting makes sure if one month (or abbr) is a prefix of another it
  13497. // will match the longer piece.
  13498. shortPieces.sort(cmpLenRev);
  13499. longPieces.sort(cmpLenRev);
  13500. mixedPieces.sort(cmpLenRev);
  13501. for (i = 0; i < 12; i++) {
  13502. shortPieces[i] = regexEscape(shortPieces[i]);
  13503. longPieces[i] = regexEscape(longPieces[i]);
  13504. }
  13505. for (i = 0; i < 24; i++) {
  13506. mixedPieces[i] = regexEscape(mixedPieces[i]);
  13507. }
  13508. this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  13509. this._monthsShortRegex = this._monthsRegex;
  13510. this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  13511. this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  13512. }
  13513. function createDate (y, m, d, h, M, s, ms) {
  13514. // can't just apply() to create a date:
  13515. // https://stackoverflow.com/q/181348
  13516. var date;
  13517. // the date constructor remaps years 0-99 to 1900-1999
  13518. if (y < 100 && y >= 0) {
  13519. // preserve leap years using a full 400 year cycle, then reset
  13520. date = new Date(y + 400, m, d, h, M, s, ms);
  13521. if (isFinite(date.getFullYear())) {
  13522. date.setFullYear(y);
  13523. }
  13524. } else {
  13525. date = new Date(y, m, d, h, M, s, ms);
  13526. }
  13527. return date;
  13528. }
  13529. function createUTCDate (y) {
  13530. var date;
  13531. // the Date.UTC function remaps years 0-99 to 1900-1999
  13532. if (y < 100 && y >= 0) {
  13533. var args = Array.prototype.slice.call(arguments);
  13534. // preserve leap years using a full 400 year cycle, then reset
  13535. args[0] = y + 400;
  13536. date = new Date(Date.UTC.apply(null, args));
  13537. if (isFinite(date.getUTCFullYear())) {
  13538. date.setUTCFullYear(y);
  13539. }
  13540. } else {
  13541. date = new Date(Date.UTC.apply(null, arguments));
  13542. }
  13543. return date;
  13544. }
  13545. // start-of-first-week - start-of-year
  13546. function firstWeekOffset(year, dow, doy) {
  13547. var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
  13548. fwd = 7 + dow - doy,
  13549. // first-week day local weekday -- which local weekday is fwd
  13550. fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
  13551. return -fwdlw + fwd - 1;
  13552. }
  13553. // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
  13554. function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
  13555. var localWeekday = (7 + weekday - dow) % 7,
  13556. weekOffset = firstWeekOffset(year, dow, doy),
  13557. dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
  13558. resYear, resDayOfYear;
  13559. if (dayOfYear <= 0) {
  13560. resYear = year - 1;
  13561. resDayOfYear = daysInYear(resYear) + dayOfYear;
  13562. } else if (dayOfYear > daysInYear(year)) {
  13563. resYear = year + 1;
  13564. resDayOfYear = dayOfYear - daysInYear(year);
  13565. } else {
  13566. resYear = year;
  13567. resDayOfYear = dayOfYear;
  13568. }
  13569. return {
  13570. year: resYear,
  13571. dayOfYear: resDayOfYear
  13572. };
  13573. }
  13574. function weekOfYear(mom, dow, doy) {
  13575. var weekOffset = firstWeekOffset(mom.year(), dow, doy),
  13576. week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
  13577. resWeek, resYear;
  13578. if (week < 1) {
  13579. resYear = mom.year() - 1;
  13580. resWeek = week + weeksInYear(resYear, dow, doy);
  13581. } else if (week > weeksInYear(mom.year(), dow, doy)) {
  13582. resWeek = week - weeksInYear(mom.year(), dow, doy);
  13583. resYear = mom.year() + 1;
  13584. } else {
  13585. resYear = mom.year();
  13586. resWeek = week;
  13587. }
  13588. return {
  13589. week: resWeek,
  13590. year: resYear
  13591. };
  13592. }
  13593. function weeksInYear(year, dow, doy) {
  13594. var weekOffset = firstWeekOffset(year, dow, doy),
  13595. weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
  13596. return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
  13597. }
  13598. // FORMATTING
  13599. addFormatToken('w', ['ww', 2], 'wo', 'week');
  13600. addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek');
  13601. // ALIASES
  13602. addUnitAlias('week', 'w');
  13603. addUnitAlias('isoWeek', 'W');
  13604. // PRIORITIES
  13605. addUnitPriority('week', 5);
  13606. addUnitPriority('isoWeek', 5);
  13607. // PARSING
  13608. addRegexToken('w', match1to2);
  13609. addRegexToken('ww', match1to2, match2);
  13610. addRegexToken('W', match1to2);
  13611. addRegexToken('WW', match1to2, match2);
  13612. addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) {
  13613. week[token.substr(0, 1)] = toInt(input);
  13614. });
  13615. // HELPERS
  13616. // LOCALES
  13617. function localeWeek (mom) {
  13618. return weekOfYear(mom, this._week.dow, this._week.doy).week;
  13619. }
  13620. var defaultLocaleWeek = {
  13621. dow : 0, // Sunday is the first day of the week.
  13622. doy : 6 // The week that contains Jan 6th is the first week of the year.
  13623. };
  13624. function localeFirstDayOfWeek () {
  13625. return this._week.dow;
  13626. }
  13627. function localeFirstDayOfYear () {
  13628. return this._week.doy;
  13629. }
  13630. // MOMENTS
  13631. function getSetWeek (input) {
  13632. var week = this.localeData().week(this);
  13633. return input == null ? week : this.add((input - week) * 7, 'd');
  13634. }
  13635. function getSetISOWeek (input) {
  13636. var week = weekOfYear(this, 1, 4).week;
  13637. return input == null ? week : this.add((input - week) * 7, 'd');
  13638. }
  13639. // FORMATTING
  13640. addFormatToken('d', 0, 'do', 'day');
  13641. addFormatToken('dd', 0, 0, function (format) {
  13642. return this.localeData().weekdaysMin(this, format);
  13643. });
  13644. addFormatToken('ddd', 0, 0, function (format) {
  13645. return this.localeData().weekdaysShort(this, format);
  13646. });
  13647. addFormatToken('dddd', 0, 0, function (format) {
  13648. return this.localeData().weekdays(this, format);
  13649. });
  13650. addFormatToken('e', 0, 0, 'weekday');
  13651. addFormatToken('E', 0, 0, 'isoWeekday');
  13652. // ALIASES
  13653. addUnitAlias('day', 'd');
  13654. addUnitAlias('weekday', 'e');
  13655. addUnitAlias('isoWeekday', 'E');
  13656. // PRIORITY
  13657. addUnitPriority('day', 11);
  13658. addUnitPriority('weekday', 11);
  13659. addUnitPriority('isoWeekday', 11);
  13660. // PARSING
  13661. addRegexToken('d', match1to2);
  13662. addRegexToken('e', match1to2);
  13663. addRegexToken('E', match1to2);
  13664. addRegexToken('dd', function (isStrict, locale) {
  13665. return locale.weekdaysMinRegex(isStrict);
  13666. });
  13667. addRegexToken('ddd', function (isStrict, locale) {
  13668. return locale.weekdaysShortRegex(isStrict);
  13669. });
  13670. addRegexToken('dddd', function (isStrict, locale) {
  13671. return locale.weekdaysRegex(isStrict);
  13672. });
  13673. addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) {
  13674. var weekday = config._locale.weekdaysParse(input, token, config._strict);
  13675. // if we didn't get a weekday name, mark the date as invalid
  13676. if (weekday != null) {
  13677. week.d = weekday;
  13678. } else {
  13679. getParsingFlags(config).invalidWeekday = input;
  13680. }
  13681. });
  13682. addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
  13683. week[token] = toInt(input);
  13684. });
  13685. // HELPERS
  13686. function parseWeekday(input, locale) {
  13687. if (typeof input !== 'string') {
  13688. return input;
  13689. }
  13690. if (!isNaN(input)) {
  13691. return parseInt(input, 10);
  13692. }
  13693. input = locale.weekdaysParse(input);
  13694. if (typeof input === 'number') {
  13695. return input;
  13696. }
  13697. return null;
  13698. }
  13699. function parseIsoWeekday(input, locale) {
  13700. if (typeof input === 'string') {
  13701. return locale.weekdaysParse(input) % 7 || 7;
  13702. }
  13703. return isNaN(input) ? null : input;
  13704. }
  13705. // LOCALES
  13706. function shiftWeekdays (ws, n) {
  13707. return ws.slice(n, 7).concat(ws.slice(0, n));
  13708. }
  13709. var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_');
  13710. function localeWeekdays (m, format) {
  13711. var weekdays = isArray(this._weekdays) ? this._weekdays :
  13712. this._weekdays[(m && m !== true && this._weekdays.isFormat.test(format)) ? 'format' : 'standalone'];
  13713. return (m === true) ? shiftWeekdays(weekdays, this._week.dow)
  13714. : (m) ? weekdays[m.day()] : weekdays;
  13715. }
  13716. var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
  13717. function localeWeekdaysShort (m) {
  13718. return (m === true) ? shiftWeekdays(this._weekdaysShort, this._week.dow)
  13719. : (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort;
  13720. }
  13721. var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_');
  13722. function localeWeekdaysMin (m) {
  13723. return (m === true) ? shiftWeekdays(this._weekdaysMin, this._week.dow)
  13724. : (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin;
  13725. }
  13726. function handleStrictParse$1(weekdayName, format, strict) {
  13727. var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
  13728. if (!this._weekdaysParse) {
  13729. this._weekdaysParse = [];
  13730. this._shortWeekdaysParse = [];
  13731. this._minWeekdaysParse = [];
  13732. for (i = 0; i < 7; ++i) {
  13733. mom = createUTC([2000, 1]).day(i);
  13734. this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase();
  13735. this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase();
  13736. this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
  13737. }
  13738. }
  13739. if (strict) {
  13740. if (format === 'dddd') {
  13741. ii = indexOf.call(this._weekdaysParse, llc);
  13742. return ii !== -1 ? ii : null;
  13743. } else if (format === 'ddd') {
  13744. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13745. return ii !== -1 ? ii : null;
  13746. } else {
  13747. ii = indexOf.call(this._minWeekdaysParse, llc);
  13748. return ii !== -1 ? ii : null;
  13749. }
  13750. } else {
  13751. if (format === 'dddd') {
  13752. ii = indexOf.call(this._weekdaysParse, llc);
  13753. if (ii !== -1) {
  13754. return ii;
  13755. }
  13756. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13757. if (ii !== -1) {
  13758. return ii;
  13759. }
  13760. ii = indexOf.call(this._minWeekdaysParse, llc);
  13761. return ii !== -1 ? ii : null;
  13762. } else if (format === 'ddd') {
  13763. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13764. if (ii !== -1) {
  13765. return ii;
  13766. }
  13767. ii = indexOf.call(this._weekdaysParse, llc);
  13768. if (ii !== -1) {
  13769. return ii;
  13770. }
  13771. ii = indexOf.call(this._minWeekdaysParse, llc);
  13772. return ii !== -1 ? ii : null;
  13773. } else {
  13774. ii = indexOf.call(this._minWeekdaysParse, llc);
  13775. if (ii !== -1) {
  13776. return ii;
  13777. }
  13778. ii = indexOf.call(this._weekdaysParse, llc);
  13779. if (ii !== -1) {
  13780. return ii;
  13781. }
  13782. ii = indexOf.call(this._shortWeekdaysParse, llc);
  13783. return ii !== -1 ? ii : null;
  13784. }
  13785. }
  13786. }
  13787. function localeWeekdaysParse (weekdayName, format, strict) {
  13788. var i, mom, regex;
  13789. if (this._weekdaysParseExact) {
  13790. return handleStrictParse$1.call(this, weekdayName, format, strict);
  13791. }
  13792. if (!this._weekdaysParse) {
  13793. this._weekdaysParse = [];
  13794. this._minWeekdaysParse = [];
  13795. this._shortWeekdaysParse = [];
  13796. this._fullWeekdaysParse = [];
  13797. }
  13798. for (i = 0; i < 7; i++) {
  13799. // make the regex if we don't have it already
  13800. mom = createUTC([2000, 1]).day(i);
  13801. if (strict && !this._fullWeekdaysParse[i]) {
  13802. this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i');
  13803. this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i');
  13804. this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i');
  13805. }
  13806. if (!this._weekdaysParse[i]) {
  13807. regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, '');
  13808. this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i');
  13809. }
  13810. // test the regex
  13811. if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) {
  13812. return i;
  13813. } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) {
  13814. return i;
  13815. } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) {
  13816. return i;
  13817. } else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
  13818. return i;
  13819. }
  13820. }
  13821. }
  13822. // MOMENTS
  13823. function getSetDayOfWeek (input) {
  13824. if (!this.isValid()) {
  13825. return input != null ? this : NaN;
  13826. }
  13827. var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
  13828. if (input != null) {
  13829. input = parseWeekday(input, this.localeData());
  13830. return this.add(input - day, 'd');
  13831. } else {
  13832. return day;
  13833. }
  13834. }
  13835. function getSetLocaleDayOfWeek (input) {
  13836. if (!this.isValid()) {
  13837. return input != null ? this : NaN;
  13838. }
  13839. var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
  13840. return input == null ? weekday : this.add(input - weekday, 'd');
  13841. }
  13842. function getSetISODayOfWeek (input) {
  13843. if (!this.isValid()) {
  13844. return input != null ? this : NaN;
  13845. }
  13846. // behaves the same as moment#day except
  13847. // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
  13848. // as a setter, sunday should belong to the previous week.
  13849. if (input != null) {
  13850. var weekday = parseIsoWeekday(input, this.localeData());
  13851. return this.day(this.day() % 7 ? weekday : weekday - 7);
  13852. } else {
  13853. return this.day() || 7;
  13854. }
  13855. }
  13856. var defaultWeekdaysRegex = matchWord;
  13857. function weekdaysRegex (isStrict) {
  13858. if (this._weekdaysParseExact) {
  13859. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13860. computeWeekdaysParse.call(this);
  13861. }
  13862. if (isStrict) {
  13863. return this._weekdaysStrictRegex;
  13864. } else {
  13865. return this._weekdaysRegex;
  13866. }
  13867. } else {
  13868. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13869. this._weekdaysRegex = defaultWeekdaysRegex;
  13870. }
  13871. return this._weekdaysStrictRegex && isStrict ?
  13872. this._weekdaysStrictRegex : this._weekdaysRegex;
  13873. }
  13874. }
  13875. var defaultWeekdaysShortRegex = matchWord;
  13876. function weekdaysShortRegex (isStrict) {
  13877. if (this._weekdaysParseExact) {
  13878. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13879. computeWeekdaysParse.call(this);
  13880. }
  13881. if (isStrict) {
  13882. return this._weekdaysShortStrictRegex;
  13883. } else {
  13884. return this._weekdaysShortRegex;
  13885. }
  13886. } else {
  13887. if (!hasOwnProp(this, '_weekdaysShortRegex')) {
  13888. this._weekdaysShortRegex = defaultWeekdaysShortRegex;
  13889. }
  13890. return this._weekdaysShortStrictRegex && isStrict ?
  13891. this._weekdaysShortStrictRegex : this._weekdaysShortRegex;
  13892. }
  13893. }
  13894. var defaultWeekdaysMinRegex = matchWord;
  13895. function weekdaysMinRegex (isStrict) {
  13896. if (this._weekdaysParseExact) {
  13897. if (!hasOwnProp(this, '_weekdaysRegex')) {
  13898. computeWeekdaysParse.call(this);
  13899. }
  13900. if (isStrict) {
  13901. return this._weekdaysMinStrictRegex;
  13902. } else {
  13903. return this._weekdaysMinRegex;
  13904. }
  13905. } else {
  13906. if (!hasOwnProp(this, '_weekdaysMinRegex')) {
  13907. this._weekdaysMinRegex = defaultWeekdaysMinRegex;
  13908. }
  13909. return this._weekdaysMinStrictRegex && isStrict ?
  13910. this._weekdaysMinStrictRegex : this._weekdaysMinRegex;
  13911. }
  13912. }
  13913. function computeWeekdaysParse () {
  13914. function cmpLenRev(a, b) {
  13915. return b.length - a.length;
  13916. }
  13917. var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [],
  13918. i, mom, minp, shortp, longp;
  13919. for (i = 0; i < 7; i++) {
  13920. // make the regex if we don't have it already
  13921. mom = createUTC([2000, 1]).day(i);
  13922. minp = this.weekdaysMin(mom, '');
  13923. shortp = this.weekdaysShort(mom, '');
  13924. longp = this.weekdays(mom, '');
  13925. minPieces.push(minp);
  13926. shortPieces.push(shortp);
  13927. longPieces.push(longp);
  13928. mixedPieces.push(minp);
  13929. mixedPieces.push(shortp);
  13930. mixedPieces.push(longp);
  13931. }
  13932. // Sorting makes sure if one weekday (or abbr) is a prefix of another it
  13933. // will match the longer piece.
  13934. minPieces.sort(cmpLenRev);
  13935. shortPieces.sort(cmpLenRev);
  13936. longPieces.sort(cmpLenRev);
  13937. mixedPieces.sort(cmpLenRev);
  13938. for (i = 0; i < 7; i++) {
  13939. shortPieces[i] = regexEscape(shortPieces[i]);
  13940. longPieces[i] = regexEscape(longPieces[i]);
  13941. mixedPieces[i] = regexEscape(mixedPieces[i]);
  13942. }
  13943. this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i');
  13944. this._weekdaysShortRegex = this._weekdaysRegex;
  13945. this._weekdaysMinRegex = this._weekdaysRegex;
  13946. this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i');
  13947. this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i');
  13948. this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i');
  13949. }
  13950. // FORMATTING
  13951. function hFormat() {
  13952. return this.hours() % 12 || 12;
  13953. }
  13954. function kFormat() {
  13955. return this.hours() || 24;
  13956. }
  13957. addFormatToken('H', ['HH', 2], 0, 'hour');
  13958. addFormatToken('h', ['hh', 2], 0, hFormat);
  13959. addFormatToken('k', ['kk', 2], 0, kFormat);
  13960. addFormatToken('hmm', 0, 0, function () {
  13961. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
  13962. });
  13963. addFormatToken('hmmss', 0, 0, function () {
  13964. return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) +
  13965. zeroFill(this.seconds(), 2);
  13966. });
  13967. addFormatToken('Hmm', 0, 0, function () {
  13968. return '' + this.hours() + zeroFill(this.minutes(), 2);
  13969. });
  13970. addFormatToken('Hmmss', 0, 0, function () {
  13971. return '' + this.hours() + zeroFill(this.minutes(), 2) +
  13972. zeroFill(this.seconds(), 2);
  13973. });
  13974. function meridiem (token, lowercase) {
  13975. addFormatToken(token, 0, 0, function () {
  13976. return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
  13977. });
  13978. }
  13979. meridiem('a', true);
  13980. meridiem('A', false);
  13981. // ALIASES
  13982. addUnitAlias('hour', 'h');
  13983. // PRIORITY
  13984. addUnitPriority('hour', 13);
  13985. // PARSING
  13986. function matchMeridiem (isStrict, locale) {
  13987. return locale._meridiemParse;
  13988. }
  13989. addRegexToken('a', matchMeridiem);
  13990. addRegexToken('A', matchMeridiem);
  13991. addRegexToken('H', match1to2);
  13992. addRegexToken('h', match1to2);
  13993. addRegexToken('k', match1to2);
  13994. addRegexToken('HH', match1to2, match2);
  13995. addRegexToken('hh', match1to2, match2);
  13996. addRegexToken('kk', match1to2, match2);
  13997. addRegexToken('hmm', match3to4);
  13998. addRegexToken('hmmss', match5to6);
  13999. addRegexToken('Hmm', match3to4);
  14000. addRegexToken('Hmmss', match5to6);
  14001. addParseToken(['H', 'HH'], HOUR);
  14002. addParseToken(['k', 'kk'], function (input, array, config) {
  14003. var kInput = toInt(input);
  14004. array[HOUR] = kInput === 24 ? 0 : kInput;
  14005. });
  14006. addParseToken(['a', 'A'], function (input, array, config) {
  14007. config._isPm = config._locale.isPM(input);
  14008. config._meridiem = input;
  14009. });
  14010. addParseToken(['h', 'hh'], function (input, array, config) {
  14011. array[HOUR] = toInt(input);
  14012. getParsingFlags(config).bigHour = true;
  14013. });
  14014. addParseToken('hmm', function (input, array, config) {
  14015. var pos = input.length - 2;
  14016. array[HOUR] = toInt(input.substr(0, pos));
  14017. array[MINUTE] = toInt(input.substr(pos));
  14018. getParsingFlags(config).bigHour = true;
  14019. });
  14020. addParseToken('hmmss', function (input, array, config) {
  14021. var pos1 = input.length - 4;
  14022. var pos2 = input.length - 2;
  14023. array[HOUR] = toInt(input.substr(0, pos1));
  14024. array[MINUTE] = toInt(input.substr(pos1, 2));
  14025. array[SECOND] = toInt(input.substr(pos2));
  14026. getParsingFlags(config).bigHour = true;
  14027. });
  14028. addParseToken('Hmm', function (input, array, config) {
  14029. var pos = input.length - 2;
  14030. array[HOUR] = toInt(input.substr(0, pos));
  14031. array[MINUTE] = toInt(input.substr(pos));
  14032. });
  14033. addParseToken('Hmmss', function (input, array, config) {
  14034. var pos1 = input.length - 4;
  14035. var pos2 = input.length - 2;
  14036. array[HOUR] = toInt(input.substr(0, pos1));
  14037. array[MINUTE] = toInt(input.substr(pos1, 2));
  14038. array[SECOND] = toInt(input.substr(pos2));
  14039. });
  14040. // LOCALES
  14041. function localeIsPM (input) {
  14042. // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
  14043. // Using charAt should be more compatible.
  14044. return ((input + '').toLowerCase().charAt(0) === 'p');
  14045. }
  14046. var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i;
  14047. function localeMeridiem (hours, minutes, isLower) {
  14048. if (hours > 11) {
  14049. return isLower ? 'pm' : 'PM';
  14050. } else {
  14051. return isLower ? 'am' : 'AM';
  14052. }
  14053. }
  14054. // MOMENTS
  14055. // Setting the hour should keep the time, because the user explicitly
  14056. // specified which hour they want. So trying to maintain the same hour (in
  14057. // a new timezone) makes sense. Adding/subtracting hours does not follow
  14058. // this rule.
  14059. var getSetHour = makeGetSet('Hours', true);
  14060. var baseConfig = {
  14061. calendar: defaultCalendar,
  14062. longDateFormat: defaultLongDateFormat,
  14063. invalidDate: defaultInvalidDate,
  14064. ordinal: defaultOrdinal,
  14065. dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
  14066. relativeTime: defaultRelativeTime,
  14067. months: defaultLocaleMonths,
  14068. monthsShort: defaultLocaleMonthsShort,
  14069. week: defaultLocaleWeek,
  14070. weekdays: defaultLocaleWeekdays,
  14071. weekdaysMin: defaultLocaleWeekdaysMin,
  14072. weekdaysShort: defaultLocaleWeekdaysShort,
  14073. meridiemParse: defaultLocaleMeridiemParse
  14074. };
  14075. // internal storage for locale config files
  14076. var locales = {};
  14077. var localeFamilies = {};
  14078. var globalLocale;
  14079. function normalizeLocale(key) {
  14080. return key ? key.toLowerCase().replace('_', '-') : key;
  14081. }
  14082. // pick the locale from the array
  14083. // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
  14084. // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
  14085. function chooseLocale(names) {
  14086. var i = 0, j, next, locale, split;
  14087. while (i < names.length) {
  14088. split = normalizeLocale(names[i]).split('-');
  14089. j = split.length;
  14090. next = normalizeLocale(names[i + 1]);
  14091. next = next ? next.split('-') : null;
  14092. while (j > 0) {
  14093. locale = loadLocale(split.slice(0, j).join('-'));
  14094. if (locale) {
  14095. return locale;
  14096. }
  14097. if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) {
  14098. //the next array item is better than a shallower substring of this one
  14099. break;
  14100. }
  14101. j--;
  14102. }
  14103. i++;
  14104. }
  14105. return globalLocale;
  14106. }
  14107. function loadLocale(name) {
  14108. var oldLocale = null;
  14109. // TODO: Find a better way to register and load all the locales in Node
  14110. if (!locales[name] && ('object' !== 'undefined') &&
  14111. module && module.exports) {
  14112. try {
  14113. oldLocale = globalLocale._abbr;
  14114. var aliasedRequire = commonjsRequire;
  14115. aliasedRequire('./locale/' + name);
  14116. getSetGlobalLocale(oldLocale);
  14117. } catch (e) {}
  14118. }
  14119. return locales[name];
  14120. }
  14121. // This function will load locale and then set the global locale. If
  14122. // no arguments are passed in, it will simply return the current global
  14123. // locale key.
  14124. function getSetGlobalLocale (key, values) {
  14125. var data;
  14126. if (key) {
  14127. if (isUndefined(values)) {
  14128. data = getLocale(key);
  14129. }
  14130. else {
  14131. data = defineLocale(key, values);
  14132. }
  14133. if (data) {
  14134. // moment.duration._locale = moment._locale = data;
  14135. globalLocale = data;
  14136. }
  14137. else {
  14138. if ((typeof console !== 'undefined') && console.warn) {
  14139. //warn user if arguments are passed but the locale could not be set
  14140. console.warn('Locale ' + key + ' not found. Did you forget to load it?');
  14141. }
  14142. }
  14143. }
  14144. return globalLocale._abbr;
  14145. }
  14146. function defineLocale (name, config) {
  14147. if (config !== null) {
  14148. var locale, parentConfig = baseConfig;
  14149. config.abbr = name;
  14150. if (locales[name] != null) {
  14151. deprecateSimple('defineLocaleOverride',
  14152. 'use moment.updateLocale(localeName, config) to change ' +
  14153. 'an existing locale. moment.defineLocale(localeName, ' +
  14154. 'config) should only be used for creating a new locale ' +
  14155. 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.');
  14156. parentConfig = locales[name]._config;
  14157. } else if (config.parentLocale != null) {
  14158. if (locales[config.parentLocale] != null) {
  14159. parentConfig = locales[config.parentLocale]._config;
  14160. } else {
  14161. locale = loadLocale(config.parentLocale);
  14162. if (locale != null) {
  14163. parentConfig = locale._config;
  14164. } else {
  14165. if (!localeFamilies[config.parentLocale]) {
  14166. localeFamilies[config.parentLocale] = [];
  14167. }
  14168. localeFamilies[config.parentLocale].push({
  14169. name: name,
  14170. config: config
  14171. });
  14172. return null;
  14173. }
  14174. }
  14175. }
  14176. locales[name] = new Locale(mergeConfigs(parentConfig, config));
  14177. if (localeFamilies[name]) {
  14178. localeFamilies[name].forEach(function (x) {
  14179. defineLocale(x.name, x.config);
  14180. });
  14181. }
  14182. // backwards compat for now: also set the locale
  14183. // make sure we set the locale AFTER all child locales have been
  14184. // created, so we won't end up with the child locale set.
  14185. getSetGlobalLocale(name);
  14186. return locales[name];
  14187. } else {
  14188. // useful for testing
  14189. delete locales[name];
  14190. return null;
  14191. }
  14192. }
  14193. function updateLocale(name, config) {
  14194. if (config != null) {
  14195. var locale, tmpLocale, parentConfig = baseConfig;
  14196. // MERGE
  14197. tmpLocale = loadLocale(name);
  14198. if (tmpLocale != null) {
  14199. parentConfig = tmpLocale._config;
  14200. }
  14201. config = mergeConfigs(parentConfig, config);
  14202. locale = new Locale(config);
  14203. locale.parentLocale = locales[name];
  14204. locales[name] = locale;
  14205. // backwards compat for now: also set the locale
  14206. getSetGlobalLocale(name);
  14207. } else {
  14208. // pass null for config to unupdate, useful for tests
  14209. if (locales[name] != null) {
  14210. if (locales[name].parentLocale != null) {
  14211. locales[name] = locales[name].parentLocale;
  14212. } else if (locales[name] != null) {
  14213. delete locales[name];
  14214. }
  14215. }
  14216. }
  14217. return locales[name];
  14218. }
  14219. // returns locale data
  14220. function getLocale (key) {
  14221. var locale;
  14222. if (key && key._locale && key._locale._abbr) {
  14223. key = key._locale._abbr;
  14224. }
  14225. if (!key) {
  14226. return globalLocale;
  14227. }
  14228. if (!isArray(key)) {
  14229. //short-circuit everything else
  14230. locale = loadLocale(key);
  14231. if (locale) {
  14232. return locale;
  14233. }
  14234. key = [key];
  14235. }
  14236. return chooseLocale(key);
  14237. }
  14238. function listLocales() {
  14239. return keys(locales);
  14240. }
  14241. function checkOverflow (m) {
  14242. var overflow;
  14243. var a = m._a;
  14244. if (a && getParsingFlags(m).overflow === -2) {
  14245. overflow =
  14246. a[MONTH] < 0 || a[MONTH] > 11 ? MONTH :
  14247. a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE :
  14248. a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR :
  14249. a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE :
  14250. a[SECOND] < 0 || a[SECOND] > 59 ? SECOND :
  14251. a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND :
  14252. -1;
  14253. if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) {
  14254. overflow = DATE;
  14255. }
  14256. if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
  14257. overflow = WEEK;
  14258. }
  14259. if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
  14260. overflow = WEEKDAY;
  14261. }
  14262. getParsingFlags(m).overflow = overflow;
  14263. }
  14264. return m;
  14265. }
  14266. // Pick the first defined of two or three arguments.
  14267. function defaults(a, b, c) {
  14268. if (a != null) {
  14269. return a;
  14270. }
  14271. if (b != null) {
  14272. return b;
  14273. }
  14274. return c;
  14275. }
  14276. function currentDateArray(config) {
  14277. // hooks is actually the exported moment object
  14278. var nowValue = new Date(hooks.now());
  14279. if (config._useUTC) {
  14280. return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()];
  14281. }
  14282. return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()];
  14283. }
  14284. // convert an array to a date.
  14285. // the array should mirror the parameters below
  14286. // note: all values past the year are optional and will default to the lowest possible value.
  14287. // [year, month, day , hour, minute, second, millisecond]
  14288. function configFromArray (config) {
  14289. var i, date, input = [], currentDate, expectedWeekday, yearToUse;
  14290. if (config._d) {
  14291. return;
  14292. }
  14293. currentDate = currentDateArray(config);
  14294. //compute day of the year from weeks and weekdays
  14295. if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
  14296. dayOfYearFromWeekInfo(config);
  14297. }
  14298. //if the day of the year is set, figure out what it is
  14299. if (config._dayOfYear != null) {
  14300. yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
  14301. if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) {
  14302. getParsingFlags(config)._overflowDayOfYear = true;
  14303. }
  14304. date = createUTCDate(yearToUse, 0, config._dayOfYear);
  14305. config._a[MONTH] = date.getUTCMonth();
  14306. config._a[DATE] = date.getUTCDate();
  14307. }
  14308. // Default to current date.
  14309. // * if no year, month, day of month are given, default to today
  14310. // * if day of month is given, default month and year
  14311. // * if month is given, default only year
  14312. // * if year is given, don't default anything
  14313. for (i = 0; i < 3 && config._a[i] == null; ++i) {
  14314. config._a[i] = input[i] = currentDate[i];
  14315. }
  14316. // Zero out whatever was not defaulted, including time
  14317. for (; i < 7; i++) {
  14318. config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i];
  14319. }
  14320. // Check for 24:00:00.000
  14321. if (config._a[HOUR] === 24 &&
  14322. config._a[MINUTE] === 0 &&
  14323. config._a[SECOND] === 0 &&
  14324. config._a[MILLISECOND] === 0) {
  14325. config._nextDay = true;
  14326. config._a[HOUR] = 0;
  14327. }
  14328. config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input);
  14329. expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay();
  14330. // Apply timezone offset from input. The actual utcOffset can be changed
  14331. // with parseZone.
  14332. if (config._tzm != null) {
  14333. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  14334. }
  14335. if (config._nextDay) {
  14336. config._a[HOUR] = 24;
  14337. }
  14338. // check for mismatching day of week
  14339. if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) {
  14340. getParsingFlags(config).weekdayMismatch = true;
  14341. }
  14342. }
  14343. function dayOfYearFromWeekInfo(config) {
  14344. var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow;
  14345. w = config._w;
  14346. if (w.GG != null || w.W != null || w.E != null) {
  14347. dow = 1;
  14348. doy = 4;
  14349. // TODO: We need to take the current isoWeekYear, but that depends on
  14350. // how we interpret now (local, utc, fixed offset). So create
  14351. // a now version of current config (take local/utc/offset flags, and
  14352. // create now).
  14353. weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year);
  14354. week = defaults(w.W, 1);
  14355. weekday = defaults(w.E, 1);
  14356. if (weekday < 1 || weekday > 7) {
  14357. weekdayOverflow = true;
  14358. }
  14359. } else {
  14360. dow = config._locale._week.dow;
  14361. doy = config._locale._week.doy;
  14362. var curWeek = weekOfYear(createLocal(), dow, doy);
  14363. weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
  14364. // Default to current week.
  14365. week = defaults(w.w, curWeek.week);
  14366. if (w.d != null) {
  14367. // weekday -- low day numbers are considered next week
  14368. weekday = w.d;
  14369. if (weekday < 0 || weekday > 6) {
  14370. weekdayOverflow = true;
  14371. }
  14372. } else if (w.e != null) {
  14373. // local weekday -- counting starts from beginning of week
  14374. weekday = w.e + dow;
  14375. if (w.e < 0 || w.e > 6) {
  14376. weekdayOverflow = true;
  14377. }
  14378. } else {
  14379. // default to beginning of week
  14380. weekday = dow;
  14381. }
  14382. }
  14383. if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
  14384. getParsingFlags(config)._overflowWeeks = true;
  14385. } else if (weekdayOverflow != null) {
  14386. getParsingFlags(config)._overflowWeekday = true;
  14387. } else {
  14388. temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
  14389. config._a[YEAR] = temp.year;
  14390. config._dayOfYear = temp.dayOfYear;
  14391. }
  14392. }
  14393. // iso 8601 regex
  14394. // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
  14395. var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
  14396. var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/;
  14397. var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/;
  14398. var isoDates = [
  14399. ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/],
  14400. ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/],
  14401. ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/],
  14402. ['GGGG-[W]WW', /\d{4}-W\d\d/, false],
  14403. ['YYYY-DDD', /\d{4}-\d{3}/],
  14404. ['YYYY-MM', /\d{4}-\d\d/, false],
  14405. ['YYYYYYMMDD', /[+-]\d{10}/],
  14406. ['YYYYMMDD', /\d{8}/],
  14407. // YYYYMM is NOT allowed by the standard
  14408. ['GGGG[W]WWE', /\d{4}W\d{3}/],
  14409. ['GGGG[W]WW', /\d{4}W\d{2}/, false],
  14410. ['YYYYDDD', /\d{7}/]
  14411. ];
  14412. // iso time formats and regexes
  14413. var isoTimes = [
  14414. ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/],
  14415. ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/],
  14416. ['HH:mm:ss', /\d\d:\d\d:\d\d/],
  14417. ['HH:mm', /\d\d:\d\d/],
  14418. ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/],
  14419. ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/],
  14420. ['HHmmss', /\d\d\d\d\d\d/],
  14421. ['HHmm', /\d\d\d\d/],
  14422. ['HH', /\d\d/]
  14423. ];
  14424. var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
  14425. // date from iso format
  14426. function configFromISO(config) {
  14427. var i, l,
  14428. string = config._i,
  14429. match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
  14430. allowTime, dateFormat, timeFormat, tzFormat;
  14431. if (match) {
  14432. getParsingFlags(config).iso = true;
  14433. for (i = 0, l = isoDates.length; i < l; i++) {
  14434. if (isoDates[i][1].exec(match[1])) {
  14435. dateFormat = isoDates[i][0];
  14436. allowTime = isoDates[i][2] !== false;
  14437. break;
  14438. }
  14439. }
  14440. if (dateFormat == null) {
  14441. config._isValid = false;
  14442. return;
  14443. }
  14444. if (match[3]) {
  14445. for (i = 0, l = isoTimes.length; i < l; i++) {
  14446. if (isoTimes[i][1].exec(match[3])) {
  14447. // match[2] should be 'T' or space
  14448. timeFormat = (match[2] || ' ') + isoTimes[i][0];
  14449. break;
  14450. }
  14451. }
  14452. if (timeFormat == null) {
  14453. config._isValid = false;
  14454. return;
  14455. }
  14456. }
  14457. if (!allowTime && timeFormat != null) {
  14458. config._isValid = false;
  14459. return;
  14460. }
  14461. if (match[4]) {
  14462. if (tzRegex.exec(match[4])) {
  14463. tzFormat = 'Z';
  14464. } else {
  14465. config._isValid = false;
  14466. return;
  14467. }
  14468. }
  14469. config._f = dateFormat + (timeFormat || '') + (tzFormat || '');
  14470. configFromStringAndFormat(config);
  14471. } else {
  14472. config._isValid = false;
  14473. }
  14474. }
  14475. // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
  14476. var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/;
  14477. function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) {
  14478. var result = [
  14479. untruncateYear(yearStr),
  14480. defaultLocaleMonthsShort.indexOf(monthStr),
  14481. parseInt(dayStr, 10),
  14482. parseInt(hourStr, 10),
  14483. parseInt(minuteStr, 10)
  14484. ];
  14485. if (secondStr) {
  14486. result.push(parseInt(secondStr, 10));
  14487. }
  14488. return result;
  14489. }
  14490. function untruncateYear(yearStr) {
  14491. var year = parseInt(yearStr, 10);
  14492. if (year <= 49) {
  14493. return 2000 + year;
  14494. } else if (year <= 999) {
  14495. return 1900 + year;
  14496. }
  14497. return year;
  14498. }
  14499. function preprocessRFC2822(s) {
  14500. // Remove comments and folding whitespace and replace multiple-spaces with a single space
  14501. return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  14502. }
  14503. function checkWeekday(weekdayStr, parsedInput, config) {
  14504. if (weekdayStr) {
  14505. // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check.
  14506. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr),
  14507. weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay();
  14508. if (weekdayProvided !== weekdayActual) {
  14509. getParsingFlags(config).weekdayMismatch = true;
  14510. config._isValid = false;
  14511. return false;
  14512. }
  14513. }
  14514. return true;
  14515. }
  14516. var obsOffsets = {
  14517. UT: 0,
  14518. GMT: 0,
  14519. EDT: -4 * 60,
  14520. EST: -5 * 60,
  14521. CDT: -5 * 60,
  14522. CST: -6 * 60,
  14523. MDT: -6 * 60,
  14524. MST: -7 * 60,
  14525. PDT: -7 * 60,
  14526. PST: -8 * 60
  14527. };
  14528. function calculateOffset(obsOffset, militaryOffset, numOffset) {
  14529. if (obsOffset) {
  14530. return obsOffsets[obsOffset];
  14531. } else if (militaryOffset) {
  14532. // the only allowed military tz is Z
  14533. return 0;
  14534. } else {
  14535. var hm = parseInt(numOffset, 10);
  14536. var m = hm % 100, h = (hm - m) / 100;
  14537. return h * 60 + m;
  14538. }
  14539. }
  14540. // date and time from ref 2822 format
  14541. function configFromRFC2822(config) {
  14542. var match = rfc2822.exec(preprocessRFC2822(config._i));
  14543. if (match) {
  14544. var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]);
  14545. if (!checkWeekday(match[1], parsedArray, config)) {
  14546. return;
  14547. }
  14548. config._a = parsedArray;
  14549. config._tzm = calculateOffset(match[8], match[9], match[10]);
  14550. config._d = createUTCDate.apply(null, config._a);
  14551. config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
  14552. getParsingFlags(config).rfc2822 = true;
  14553. } else {
  14554. config._isValid = false;
  14555. }
  14556. }
  14557. // date from iso format or fallback
  14558. function configFromString(config) {
  14559. var matched = aspNetJsonRegex.exec(config._i);
  14560. if (matched !== null) {
  14561. config._d = new Date(+matched[1]);
  14562. return;
  14563. }
  14564. configFromISO(config);
  14565. if (config._isValid === false) {
  14566. delete config._isValid;
  14567. } else {
  14568. return;
  14569. }
  14570. configFromRFC2822(config);
  14571. if (config._isValid === false) {
  14572. delete config._isValid;
  14573. } else {
  14574. return;
  14575. }
  14576. // Final attempt, use Input Fallback
  14577. hooks.createFromInputFallback(config);
  14578. }
  14579. hooks.createFromInputFallback = deprecate(
  14580. 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' +
  14581. 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' +
  14582. 'discouraged and will be removed in an upcoming major release. Please refer to ' +
  14583. 'http://momentjs.com/guides/#/warnings/js-date/ for more info.',
  14584. function (config) {
  14585. config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
  14586. }
  14587. );
  14588. // constant that refers to the ISO standard
  14589. hooks.ISO_8601 = function () {};
  14590. // constant that refers to the RFC 2822 form
  14591. hooks.RFC_2822 = function () {};
  14592. // date from string and format string
  14593. function configFromStringAndFormat(config) {
  14594. // TODO: Move this to another part of the creation flow to prevent circular deps
  14595. if (config._f === hooks.ISO_8601) {
  14596. configFromISO(config);
  14597. return;
  14598. }
  14599. if (config._f === hooks.RFC_2822) {
  14600. configFromRFC2822(config);
  14601. return;
  14602. }
  14603. config._a = [];
  14604. getParsingFlags(config).empty = true;
  14605. // This array is used to make a Date, either with `new Date` or `Date.UTC`
  14606. var string = '' + config._i,
  14607. i, parsedInput, tokens, token, skipped,
  14608. stringLength = string.length,
  14609. totalParsedInputLength = 0;
  14610. tokens = expandFormat(config._f, config._locale).match(formattingTokens) || [];
  14611. for (i = 0; i < tokens.length; i++) {
  14612. token = tokens[i];
  14613. parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0];
  14614. // console.log('token', token, 'parsedInput', parsedInput,
  14615. // 'regex', getParseRegexForToken(token, config));
  14616. if (parsedInput) {
  14617. skipped = string.substr(0, string.indexOf(parsedInput));
  14618. if (skipped.length > 0) {
  14619. getParsingFlags(config).unusedInput.push(skipped);
  14620. }
  14621. string = string.slice(string.indexOf(parsedInput) + parsedInput.length);
  14622. totalParsedInputLength += parsedInput.length;
  14623. }
  14624. // don't parse if it's not a known token
  14625. if (formatTokenFunctions[token]) {
  14626. if (parsedInput) {
  14627. getParsingFlags(config).empty = false;
  14628. }
  14629. else {
  14630. getParsingFlags(config).unusedTokens.push(token);
  14631. }
  14632. addTimeToArrayFromToken(token, parsedInput, config);
  14633. }
  14634. else if (config._strict && !parsedInput) {
  14635. getParsingFlags(config).unusedTokens.push(token);
  14636. }
  14637. }
  14638. // add remaining unparsed input length to the string
  14639. getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength;
  14640. if (string.length > 0) {
  14641. getParsingFlags(config).unusedInput.push(string);
  14642. }
  14643. // clear _12h flag if hour is <= 12
  14644. if (config._a[HOUR] <= 12 &&
  14645. getParsingFlags(config).bigHour === true &&
  14646. config._a[HOUR] > 0) {
  14647. getParsingFlags(config).bigHour = undefined;
  14648. }
  14649. getParsingFlags(config).parsedDateParts = config._a.slice(0);
  14650. getParsingFlags(config).meridiem = config._meridiem;
  14651. // handle meridiem
  14652. config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem);
  14653. configFromArray(config);
  14654. checkOverflow(config);
  14655. }
  14656. function meridiemFixWrap (locale, hour, meridiem) {
  14657. var isPm;
  14658. if (meridiem == null) {
  14659. // nothing to do
  14660. return hour;
  14661. }
  14662. if (locale.meridiemHour != null) {
  14663. return locale.meridiemHour(hour, meridiem);
  14664. } else if (locale.isPM != null) {
  14665. // Fallback
  14666. isPm = locale.isPM(meridiem);
  14667. if (isPm && hour < 12) {
  14668. hour += 12;
  14669. }
  14670. if (!isPm && hour === 12) {
  14671. hour = 0;
  14672. }
  14673. return hour;
  14674. } else {
  14675. // this is not supposed to happen
  14676. return hour;
  14677. }
  14678. }
  14679. // date from string and array of format strings
  14680. function configFromStringAndArray(config) {
  14681. var tempConfig,
  14682. bestMoment,
  14683. scoreToBeat,
  14684. i,
  14685. currentScore;
  14686. if (config._f.length === 0) {
  14687. getParsingFlags(config).invalidFormat = true;
  14688. config._d = new Date(NaN);
  14689. return;
  14690. }
  14691. for (i = 0; i < config._f.length; i++) {
  14692. currentScore = 0;
  14693. tempConfig = copyConfig({}, config);
  14694. if (config._useUTC != null) {
  14695. tempConfig._useUTC = config._useUTC;
  14696. }
  14697. tempConfig._f = config._f[i];
  14698. configFromStringAndFormat(tempConfig);
  14699. if (!isValid(tempConfig)) {
  14700. continue;
  14701. }
  14702. // if there is any input that was not parsed add a penalty for that format
  14703. currentScore += getParsingFlags(tempConfig).charsLeftOver;
  14704. //or tokens
  14705. currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10;
  14706. getParsingFlags(tempConfig).score = currentScore;
  14707. if (scoreToBeat == null || currentScore < scoreToBeat) {
  14708. scoreToBeat = currentScore;
  14709. bestMoment = tempConfig;
  14710. }
  14711. }
  14712. extend(config, bestMoment || tempConfig);
  14713. }
  14714. function configFromObject(config) {
  14715. if (config._d) {
  14716. return;
  14717. }
  14718. var i = normalizeObjectUnits(config._i);
  14719. config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) {
  14720. return obj && parseInt(obj, 10);
  14721. });
  14722. configFromArray(config);
  14723. }
  14724. function createFromConfig (config) {
  14725. var res = new Moment(checkOverflow(prepareConfig(config)));
  14726. if (res._nextDay) {
  14727. // Adding is smart enough around DST
  14728. res.add(1, 'd');
  14729. res._nextDay = undefined;
  14730. }
  14731. return res;
  14732. }
  14733. function prepareConfig (config) {
  14734. var input = config._i,
  14735. format = config._f;
  14736. config._locale = config._locale || getLocale(config._l);
  14737. if (input === null || (format === undefined && input === '')) {
  14738. return createInvalid({nullInput: true});
  14739. }
  14740. if (typeof input === 'string') {
  14741. config._i = input = config._locale.preparse(input);
  14742. }
  14743. if (isMoment(input)) {
  14744. return new Moment(checkOverflow(input));
  14745. } else if (isDate(input)) {
  14746. config._d = input;
  14747. } else if (isArray(format)) {
  14748. configFromStringAndArray(config);
  14749. } else if (format) {
  14750. configFromStringAndFormat(config);
  14751. } else {
  14752. configFromInput(config);
  14753. }
  14754. if (!isValid(config)) {
  14755. config._d = null;
  14756. }
  14757. return config;
  14758. }
  14759. function configFromInput(config) {
  14760. var input = config._i;
  14761. if (isUndefined(input)) {
  14762. config._d = new Date(hooks.now());
  14763. } else if (isDate(input)) {
  14764. config._d = new Date(input.valueOf());
  14765. } else if (typeof input === 'string') {
  14766. configFromString(config);
  14767. } else if (isArray(input)) {
  14768. config._a = map(input.slice(0), function (obj) {
  14769. return parseInt(obj, 10);
  14770. });
  14771. configFromArray(config);
  14772. } else if (isObject(input)) {
  14773. configFromObject(config);
  14774. } else if (isNumber(input)) {
  14775. // from milliseconds
  14776. config._d = new Date(input);
  14777. } else {
  14778. hooks.createFromInputFallback(config);
  14779. }
  14780. }
  14781. function createLocalOrUTC (input, format, locale, strict, isUTC) {
  14782. var c = {};
  14783. if (locale === true || locale === false) {
  14784. strict = locale;
  14785. locale = undefined;
  14786. }
  14787. if ((isObject(input) && isObjectEmpty(input)) ||
  14788. (isArray(input) && input.length === 0)) {
  14789. input = undefined;
  14790. }
  14791. // object construction must be done this way.
  14792. // https://github.com/moment/moment/issues/1423
  14793. c._isAMomentObject = true;
  14794. c._useUTC = c._isUTC = isUTC;
  14795. c._l = locale;
  14796. c._i = input;
  14797. c._f = format;
  14798. c._strict = strict;
  14799. return createFromConfig(c);
  14800. }
  14801. function createLocal (input, format, locale, strict) {
  14802. return createLocalOrUTC(input, format, locale, strict, false);
  14803. }
  14804. var prototypeMin = deprecate(
  14805. 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/',
  14806. function () {
  14807. var other = createLocal.apply(null, arguments);
  14808. if (this.isValid() && other.isValid()) {
  14809. return other < this ? this : other;
  14810. } else {
  14811. return createInvalid();
  14812. }
  14813. }
  14814. );
  14815. var prototypeMax = deprecate(
  14816. 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/',
  14817. function () {
  14818. var other = createLocal.apply(null, arguments);
  14819. if (this.isValid() && other.isValid()) {
  14820. return other > this ? this : other;
  14821. } else {
  14822. return createInvalid();
  14823. }
  14824. }
  14825. );
  14826. // Pick a moment m from moments so that m[fn](other) is true for all
  14827. // other. This relies on the function fn to be transitive.
  14828. //
  14829. // moments should either be an array of moment objects or an array, whose
  14830. // first element is an array of moment objects.
  14831. function pickBy(fn, moments) {
  14832. var res, i;
  14833. if (moments.length === 1 && isArray(moments[0])) {
  14834. moments = moments[0];
  14835. }
  14836. if (!moments.length) {
  14837. return createLocal();
  14838. }
  14839. res = moments[0];
  14840. for (i = 1; i < moments.length; ++i) {
  14841. if (!moments[i].isValid() || moments[i][fn](res)) {
  14842. res = moments[i];
  14843. }
  14844. }
  14845. return res;
  14846. }
  14847. // TODO: Use [].sort instead?
  14848. function min () {
  14849. var args = [].slice.call(arguments, 0);
  14850. return pickBy('isBefore', args);
  14851. }
  14852. function max () {
  14853. var args = [].slice.call(arguments, 0);
  14854. return pickBy('isAfter', args);
  14855. }
  14856. var now = function () {
  14857. return Date.now ? Date.now() : +(new Date());
  14858. };
  14859. var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'];
  14860. function isDurationValid(m) {
  14861. for (var key in m) {
  14862. if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) {
  14863. return false;
  14864. }
  14865. }
  14866. var unitHasDecimal = false;
  14867. for (var i = 0; i < ordering.length; ++i) {
  14868. if (m[ordering[i]]) {
  14869. if (unitHasDecimal) {
  14870. return false; // only allow non-integers for smallest unit
  14871. }
  14872. if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
  14873. unitHasDecimal = true;
  14874. }
  14875. }
  14876. }
  14877. return true;
  14878. }
  14879. function isValid$1() {
  14880. return this._isValid;
  14881. }
  14882. function createInvalid$1() {
  14883. return createDuration(NaN);
  14884. }
  14885. function Duration (duration) {
  14886. var normalizedInput = normalizeObjectUnits(duration),
  14887. years = normalizedInput.year || 0,
  14888. quarters = normalizedInput.quarter || 0,
  14889. months = normalizedInput.month || 0,
  14890. weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
  14891. days = normalizedInput.day || 0,
  14892. hours = normalizedInput.hour || 0,
  14893. minutes = normalizedInput.minute || 0,
  14894. seconds = normalizedInput.second || 0,
  14895. milliseconds = normalizedInput.millisecond || 0;
  14896. this._isValid = isDurationValid(normalizedInput);
  14897. // representation for dateAddRemove
  14898. this._milliseconds = +milliseconds +
  14899. seconds * 1e3 + // 1000
  14900. minutes * 6e4 + // 1000 * 60
  14901. hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
  14902. // Because of dateAddRemove treats 24 hours as different from a
  14903. // day when working around DST, we need to store them separately
  14904. this._days = +days +
  14905. weeks * 7;
  14906. // It is impossible to translate months into days without knowing
  14907. // which months you are are talking about, so we have to store
  14908. // it separately.
  14909. this._months = +months +
  14910. quarters * 3 +
  14911. years * 12;
  14912. this._data = {};
  14913. this._locale = getLocale();
  14914. this._bubble();
  14915. }
  14916. function isDuration (obj) {
  14917. return obj instanceof Duration;
  14918. }
  14919. function absRound (number) {
  14920. if (number < 0) {
  14921. return Math.round(-1 * number) * -1;
  14922. } else {
  14923. return Math.round(number);
  14924. }
  14925. }
  14926. // FORMATTING
  14927. function offset (token, separator) {
  14928. addFormatToken(token, 0, 0, function () {
  14929. var offset = this.utcOffset();
  14930. var sign = '+';
  14931. if (offset < 0) {
  14932. offset = -offset;
  14933. sign = '-';
  14934. }
  14935. return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2);
  14936. });
  14937. }
  14938. offset('Z', ':');
  14939. offset('ZZ', '');
  14940. // PARSING
  14941. addRegexToken('Z', matchShortOffset);
  14942. addRegexToken('ZZ', matchShortOffset);
  14943. addParseToken(['Z', 'ZZ'], function (input, array, config) {
  14944. config._useUTC = true;
  14945. config._tzm = offsetFromString(matchShortOffset, input);
  14946. });
  14947. // HELPERS
  14948. // timezone chunker
  14949. // '+10:00' > ['10', '00']
  14950. // '-1530' > ['-15', '30']
  14951. var chunkOffset = /([\+\-]|\d\d)/gi;
  14952. function offsetFromString(matcher, string) {
  14953. var matches = (string || '').match(matcher);
  14954. if (matches === null) {
  14955. return null;
  14956. }
  14957. var chunk = matches[matches.length - 1] || [];
  14958. var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0];
  14959. var minutes = +(parts[1] * 60) + toInt(parts[2]);
  14960. return minutes === 0 ?
  14961. 0 :
  14962. parts[0] === '+' ? minutes : -minutes;
  14963. }
  14964. // Return a moment from input, that is local/utc/zone equivalent to model.
  14965. function cloneWithOffset(input, model) {
  14966. var res, diff;
  14967. if (model._isUTC) {
  14968. res = model.clone();
  14969. diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf();
  14970. // Use low-level api, because this fn is low-level api.
  14971. res._d.setTime(res._d.valueOf() + diff);
  14972. hooks.updateOffset(res, false);
  14973. return res;
  14974. } else {
  14975. return createLocal(input).local();
  14976. }
  14977. }
  14978. function getDateOffset (m) {
  14979. // On Firefox.24 Date#getTimezoneOffset returns a floating point.
  14980. // https://github.com/moment/moment/pull/1871
  14981. return -Math.round(m._d.getTimezoneOffset() / 15) * 15;
  14982. }
  14983. // HOOKS
  14984. // This function will be called whenever a moment is mutated.
  14985. // It is intended to keep the offset in sync with the timezone.
  14986. hooks.updateOffset = function () {};
  14987. // MOMENTS
  14988. // keepLocalTime = true means only change the timezone, without
  14989. // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
  14990. // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
  14991. // +0200, so we adjust the time as needed, to be valid.
  14992. //
  14993. // Keeping the time actually adds/subtracts (one hour)
  14994. // from the actual represented time. That is why we call updateOffset
  14995. // a second time. In case it wants us to change the offset again
  14996. // _changeInProgress == true case, then we have to adjust, because
  14997. // there is no such time in the given timezone.
  14998. function getSetOffset (input, keepLocalTime, keepMinutes) {
  14999. var offset = this._offset || 0,
  15000. localAdjust;
  15001. if (!this.isValid()) {
  15002. return input != null ? this : NaN;
  15003. }
  15004. if (input != null) {
  15005. if (typeof input === 'string') {
  15006. input = offsetFromString(matchShortOffset, input);
  15007. if (input === null) {
  15008. return this;
  15009. }
  15010. } else if (Math.abs(input) < 16 && !keepMinutes) {
  15011. input = input * 60;
  15012. }
  15013. if (!this._isUTC && keepLocalTime) {
  15014. localAdjust = getDateOffset(this);
  15015. }
  15016. this._offset = input;
  15017. this._isUTC = true;
  15018. if (localAdjust != null) {
  15019. this.add(localAdjust, 'm');
  15020. }
  15021. if (offset !== input) {
  15022. if (!keepLocalTime || this._changeInProgress) {
  15023. addSubtract(this, createDuration(input - offset, 'm'), 1, false);
  15024. } else if (!this._changeInProgress) {
  15025. this._changeInProgress = true;
  15026. hooks.updateOffset(this, true);
  15027. this._changeInProgress = null;
  15028. }
  15029. }
  15030. return this;
  15031. } else {
  15032. return this._isUTC ? offset : getDateOffset(this);
  15033. }
  15034. }
  15035. function getSetZone (input, keepLocalTime) {
  15036. if (input != null) {
  15037. if (typeof input !== 'string') {
  15038. input = -input;
  15039. }
  15040. this.utcOffset(input, keepLocalTime);
  15041. return this;
  15042. } else {
  15043. return -this.utcOffset();
  15044. }
  15045. }
  15046. function setOffsetToUTC (keepLocalTime) {
  15047. return this.utcOffset(0, keepLocalTime);
  15048. }
  15049. function setOffsetToLocal (keepLocalTime) {
  15050. if (this._isUTC) {
  15051. this.utcOffset(0, keepLocalTime);
  15052. this._isUTC = false;
  15053. if (keepLocalTime) {
  15054. this.subtract(getDateOffset(this), 'm');
  15055. }
  15056. }
  15057. return this;
  15058. }
  15059. function setOffsetToParsedOffset () {
  15060. if (this._tzm != null) {
  15061. this.utcOffset(this._tzm, false, true);
  15062. } else if (typeof this._i === 'string') {
  15063. var tZone = offsetFromString(matchOffset, this._i);
  15064. if (tZone != null) {
  15065. this.utcOffset(tZone);
  15066. }
  15067. else {
  15068. this.utcOffset(0, true);
  15069. }
  15070. }
  15071. return this;
  15072. }
  15073. function hasAlignedHourOffset (input) {
  15074. if (!this.isValid()) {
  15075. return false;
  15076. }
  15077. input = input ? createLocal(input).utcOffset() : 0;
  15078. return (this.utcOffset() - input) % 60 === 0;
  15079. }
  15080. function isDaylightSavingTime () {
  15081. return (
  15082. this.utcOffset() > this.clone().month(0).utcOffset() ||
  15083. this.utcOffset() > this.clone().month(5).utcOffset()
  15084. );
  15085. }
  15086. function isDaylightSavingTimeShifted () {
  15087. if (!isUndefined(this._isDSTShifted)) {
  15088. return this._isDSTShifted;
  15089. }
  15090. var c = {};
  15091. copyConfig(c, this);
  15092. c = prepareConfig(c);
  15093. if (c._a) {
  15094. var other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
  15095. this._isDSTShifted = this.isValid() &&
  15096. compareArrays(c._a, other.toArray()) > 0;
  15097. } else {
  15098. this._isDSTShifted = false;
  15099. }
  15100. return this._isDSTShifted;
  15101. }
  15102. function isLocal () {
  15103. return this.isValid() ? !this._isUTC : false;
  15104. }
  15105. function isUtcOffset () {
  15106. return this.isValid() ? this._isUTC : false;
  15107. }
  15108. function isUtc () {
  15109. return this.isValid() ? this._isUTC && this._offset === 0 : false;
  15110. }
  15111. // ASP.NET json date format regex
  15112. var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/;
  15113. // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
  15114. // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
  15115. // and further modified to allow for strings containing both week and day
  15116. var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  15117. function createDuration (input, key) {
  15118. var duration = input,
  15119. // matching against regexp is expensive, do it on demand
  15120. match = null,
  15121. sign,
  15122. ret,
  15123. diffRes;
  15124. if (isDuration(input)) {
  15125. duration = {
  15126. ms : input._milliseconds,
  15127. d : input._days,
  15128. M : input._months
  15129. };
  15130. } else if (isNumber(input)) {
  15131. duration = {};
  15132. if (key) {
  15133. duration[key] = input;
  15134. } else {
  15135. duration.milliseconds = input;
  15136. }
  15137. } else if (!!(match = aspNetRegex.exec(input))) {
  15138. sign = (match[1] === '-') ? -1 : 1;
  15139. duration = {
  15140. y : 0,
  15141. d : toInt(match[DATE]) * sign,
  15142. h : toInt(match[HOUR]) * sign,
  15143. m : toInt(match[MINUTE]) * sign,
  15144. s : toInt(match[SECOND]) * sign,
  15145. ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match
  15146. };
  15147. } else if (!!(match = isoRegex.exec(input))) {
  15148. sign = (match[1] === '-') ? -1 : 1;
  15149. duration = {
  15150. y : parseIso(match[2], sign),
  15151. M : parseIso(match[3], sign),
  15152. w : parseIso(match[4], sign),
  15153. d : parseIso(match[5], sign),
  15154. h : parseIso(match[6], sign),
  15155. m : parseIso(match[7], sign),
  15156. s : parseIso(match[8], sign)
  15157. };
  15158. } else if (duration == null) {// checks for null or undefined
  15159. duration = {};
  15160. } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) {
  15161. diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to));
  15162. duration = {};
  15163. duration.ms = diffRes.milliseconds;
  15164. duration.M = diffRes.months;
  15165. }
  15166. ret = new Duration(duration);
  15167. if (isDuration(input) && hasOwnProp(input, '_locale')) {
  15168. ret._locale = input._locale;
  15169. }
  15170. return ret;
  15171. }
  15172. createDuration.fn = Duration.prototype;
  15173. createDuration.invalid = createInvalid$1;
  15174. function parseIso (inp, sign) {
  15175. // We'd normally use ~~inp for this, but unfortunately it also
  15176. // converts floats to ints.
  15177. // inp may be undefined, so careful calling replace on it.
  15178. var res = inp && parseFloat(inp.replace(',', '.'));
  15179. // apply sign while we're at it
  15180. return (isNaN(res) ? 0 : res) * sign;
  15181. }
  15182. function positiveMomentsDifference(base, other) {
  15183. var res = {};
  15184. res.months = other.month() - base.month() +
  15185. (other.year() - base.year()) * 12;
  15186. if (base.clone().add(res.months, 'M').isAfter(other)) {
  15187. --res.months;
  15188. }
  15189. res.milliseconds = +other - +(base.clone().add(res.months, 'M'));
  15190. return res;
  15191. }
  15192. function momentsDifference(base, other) {
  15193. var res;
  15194. if (!(base.isValid() && other.isValid())) {
  15195. return {milliseconds: 0, months: 0};
  15196. }
  15197. other = cloneWithOffset(other, base);
  15198. if (base.isBefore(other)) {
  15199. res = positiveMomentsDifference(base, other);
  15200. } else {
  15201. res = positiveMomentsDifference(other, base);
  15202. res.milliseconds = -res.milliseconds;
  15203. res.months = -res.months;
  15204. }
  15205. return res;
  15206. }
  15207. // TODO: remove 'name' arg after deprecation is removed
  15208. function createAdder(direction, name) {
  15209. return function (val, period) {
  15210. var dur, tmp;
  15211. //invert the arguments, but complain about it
  15212. if (period !== null && !isNaN(+period)) {
  15213. deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' +
  15214. 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.');
  15215. tmp = val; val = period; period = tmp;
  15216. }
  15217. val = typeof val === 'string' ? +val : val;
  15218. dur = createDuration(val, period);
  15219. addSubtract(this, dur, direction);
  15220. return this;
  15221. };
  15222. }
  15223. function addSubtract (mom, duration, isAdding, updateOffset) {
  15224. var milliseconds = duration._milliseconds,
  15225. days = absRound(duration._days),
  15226. months = absRound(duration._months);
  15227. if (!mom.isValid()) {
  15228. // No op
  15229. return;
  15230. }
  15231. updateOffset = updateOffset == null ? true : updateOffset;
  15232. if (months) {
  15233. setMonth(mom, get(mom, 'Month') + months * isAdding);
  15234. }
  15235. if (days) {
  15236. set$1(mom, 'Date', get(mom, 'Date') + days * isAdding);
  15237. }
  15238. if (milliseconds) {
  15239. mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
  15240. }
  15241. if (updateOffset) {
  15242. hooks.updateOffset(mom, days || months);
  15243. }
  15244. }
  15245. var add = createAdder(1, 'add');
  15246. var subtract = createAdder(-1, 'subtract');
  15247. function getCalendarFormat(myMoment, now) {
  15248. var diff = myMoment.diff(now, 'days', true);
  15249. return diff < -6 ? 'sameElse' :
  15250. diff < -1 ? 'lastWeek' :
  15251. diff < 0 ? 'lastDay' :
  15252. diff < 1 ? 'sameDay' :
  15253. diff < 2 ? 'nextDay' :
  15254. diff < 7 ? 'nextWeek' : 'sameElse';
  15255. }
  15256. function calendar$1 (time, formats) {
  15257. // We want to compare the start of today, vs this.
  15258. // Getting start-of-today depends on whether we're local/utc/offset or not.
  15259. var now = time || createLocal(),
  15260. sod = cloneWithOffset(now, this).startOf('day'),
  15261. format = hooks.calendarFormat(this, sod) || 'sameElse';
  15262. var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
  15263. return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
  15264. }
  15265. function clone () {
  15266. return new Moment(this);
  15267. }
  15268. function isAfter (input, units) {
  15269. var localInput = isMoment(input) ? input : createLocal(input);
  15270. if (!(this.isValid() && localInput.isValid())) {
  15271. return false;
  15272. }
  15273. units = normalizeUnits(units) || 'millisecond';
  15274. if (units === 'millisecond') {
  15275. return this.valueOf() > localInput.valueOf();
  15276. } else {
  15277. return localInput.valueOf() < this.clone().startOf(units).valueOf();
  15278. }
  15279. }
  15280. function isBefore (input, units) {
  15281. var localInput = isMoment(input) ? input : createLocal(input);
  15282. if (!(this.isValid() && localInput.isValid())) {
  15283. return false;
  15284. }
  15285. units = normalizeUnits(units) || 'millisecond';
  15286. if (units === 'millisecond') {
  15287. return this.valueOf() < localInput.valueOf();
  15288. } else {
  15289. return this.clone().endOf(units).valueOf() < localInput.valueOf();
  15290. }
  15291. }
  15292. function isBetween (from, to, units, inclusivity) {
  15293. var localFrom = isMoment(from) ? from : createLocal(from),
  15294. localTo = isMoment(to) ? to : createLocal(to);
  15295. if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
  15296. return false;
  15297. }
  15298. inclusivity = inclusivity || '()';
  15299. return (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) &&
  15300. (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
  15301. }
  15302. function isSame (input, units) {
  15303. var localInput = isMoment(input) ? input : createLocal(input),
  15304. inputMs;
  15305. if (!(this.isValid() && localInput.isValid())) {
  15306. return false;
  15307. }
  15308. units = normalizeUnits(units) || 'millisecond';
  15309. if (units === 'millisecond') {
  15310. return this.valueOf() === localInput.valueOf();
  15311. } else {
  15312. inputMs = localInput.valueOf();
  15313. return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf();
  15314. }
  15315. }
  15316. function isSameOrAfter (input, units) {
  15317. return this.isSame(input, units) || this.isAfter(input, units);
  15318. }
  15319. function isSameOrBefore (input, units) {
  15320. return this.isSame(input, units) || this.isBefore(input, units);
  15321. }
  15322. function diff (input, units, asFloat) {
  15323. var that,
  15324. zoneDelta,
  15325. output;
  15326. if (!this.isValid()) {
  15327. return NaN;
  15328. }
  15329. that = cloneWithOffset(input, this);
  15330. if (!that.isValid()) {
  15331. return NaN;
  15332. }
  15333. zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
  15334. units = normalizeUnits(units);
  15335. switch (units) {
  15336. case 'year': output = monthDiff(this, that) / 12; break;
  15337. case 'month': output = monthDiff(this, that); break;
  15338. case 'quarter': output = monthDiff(this, that) / 3; break;
  15339. case 'second': output = (this - that) / 1e3; break; // 1000
  15340. case 'minute': output = (this - that) / 6e4; break; // 1000 * 60
  15341. case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60
  15342. case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst
  15343. case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst
  15344. default: output = this - that;
  15345. }
  15346. return asFloat ? output : absFloor(output);
  15347. }
  15348. function monthDiff (a, b) {
  15349. // difference in months
  15350. var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()),
  15351. // b is in (anchor - 1 month, anchor + 1 month)
  15352. anchor = a.clone().add(wholeMonthDiff, 'months'),
  15353. anchor2, adjust;
  15354. if (b - anchor < 0) {
  15355. anchor2 = a.clone().add(wholeMonthDiff - 1, 'months');
  15356. // linear across the month
  15357. adjust = (b - anchor) / (anchor - anchor2);
  15358. } else {
  15359. anchor2 = a.clone().add(wholeMonthDiff + 1, 'months');
  15360. // linear across the month
  15361. adjust = (b - anchor) / (anchor2 - anchor);
  15362. }
  15363. //check for negative zero, return zero if negative zero
  15364. return -(wholeMonthDiff + adjust) || 0;
  15365. }
  15366. hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ';
  15367. hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
  15368. function toString () {
  15369. return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
  15370. }
  15371. function toISOString(keepOffset) {
  15372. if (!this.isValid()) {
  15373. return null;
  15374. }
  15375. var utc = keepOffset !== true;
  15376. var m = utc ? this.clone().utc() : this;
  15377. if (m.year() < 0 || m.year() > 9999) {
  15378. return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ');
  15379. }
  15380. if (isFunction(Date.prototype.toISOString)) {
  15381. // native implementation is ~50x faster, use it when we can
  15382. if (utc) {
  15383. return this.toDate().toISOString();
  15384. } else {
  15385. return new Date(this.valueOf() + this.utcOffset() * 60 * 1000).toISOString().replace('Z', formatMoment(m, 'Z'));
  15386. }
  15387. }
  15388. return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
  15389. }
  15390. /**
  15391. * Return a human readable representation of a moment that can
  15392. * also be evaluated to get a new moment which is the same
  15393. *
  15394. * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
  15395. */
  15396. function inspect () {
  15397. if (!this.isValid()) {
  15398. return 'moment.invalid(/* ' + this._i + ' */)';
  15399. }
  15400. var func = 'moment';
  15401. var zone = '';
  15402. if (!this.isLocal()) {
  15403. func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone';
  15404. zone = 'Z';
  15405. }
  15406. var prefix = '[' + func + '("]';
  15407. var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY';
  15408. var datetime = '-MM-DD[T]HH:mm:ss.SSS';
  15409. var suffix = zone + '[")]';
  15410. return this.format(prefix + year + datetime + suffix);
  15411. }
  15412. function format (inputString) {
  15413. if (!inputString) {
  15414. inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat;
  15415. }
  15416. var output = formatMoment(this, inputString);
  15417. return this.localeData().postformat(output);
  15418. }
  15419. function from (time, withoutSuffix) {
  15420. if (this.isValid() &&
  15421. ((isMoment(time) && time.isValid()) ||
  15422. createLocal(time).isValid())) {
  15423. return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix);
  15424. } else {
  15425. return this.localeData().invalidDate();
  15426. }
  15427. }
  15428. function fromNow (withoutSuffix) {
  15429. return this.from(createLocal(), withoutSuffix);
  15430. }
  15431. function to (time, withoutSuffix) {
  15432. if (this.isValid() &&
  15433. ((isMoment(time) && time.isValid()) ||
  15434. createLocal(time).isValid())) {
  15435. return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix);
  15436. } else {
  15437. return this.localeData().invalidDate();
  15438. }
  15439. }
  15440. function toNow (withoutSuffix) {
  15441. return this.to(createLocal(), withoutSuffix);
  15442. }
  15443. // If passed a locale key, it will set the locale for this
  15444. // instance. Otherwise, it will return the locale configuration
  15445. // variables for this instance.
  15446. function locale (key) {
  15447. var newLocaleData;
  15448. if (key === undefined) {
  15449. return this._locale._abbr;
  15450. } else {
  15451. newLocaleData = getLocale(key);
  15452. if (newLocaleData != null) {
  15453. this._locale = newLocaleData;
  15454. }
  15455. return this;
  15456. }
  15457. }
  15458. var lang = deprecate(
  15459. 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.',
  15460. function (key) {
  15461. if (key === undefined) {
  15462. return this.localeData();
  15463. } else {
  15464. return this.locale(key);
  15465. }
  15466. }
  15467. );
  15468. function localeData () {
  15469. return this._locale;
  15470. }
  15471. var MS_PER_SECOND = 1000;
  15472. var MS_PER_MINUTE = 60 * MS_PER_SECOND;
  15473. var MS_PER_HOUR = 60 * MS_PER_MINUTE;
  15474. var MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
  15475. // actual modulo - handles negative numbers (for dates before 1970):
  15476. function mod$1(dividend, divisor) {
  15477. return (dividend % divisor + divisor) % divisor;
  15478. }
  15479. function localStartOfDate(y, m, d) {
  15480. // the date constructor remaps years 0-99 to 1900-1999
  15481. if (y < 100 && y >= 0) {
  15482. // preserve leap years using a full 400 year cycle, then reset
  15483. return new Date(y + 400, m, d) - MS_PER_400_YEARS;
  15484. } else {
  15485. return new Date(y, m, d).valueOf();
  15486. }
  15487. }
  15488. function utcStartOfDate(y, m, d) {
  15489. // Date.UTC remaps years 0-99 to 1900-1999
  15490. if (y < 100 && y >= 0) {
  15491. // preserve leap years using a full 400 year cycle, then reset
  15492. return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
  15493. } else {
  15494. return Date.UTC(y, m, d);
  15495. }
  15496. }
  15497. function startOf (units) {
  15498. var time;
  15499. units = normalizeUnits(units);
  15500. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  15501. return this;
  15502. }
  15503. var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  15504. switch (units) {
  15505. case 'year':
  15506. time = startOfDate(this.year(), 0, 1);
  15507. break;
  15508. case 'quarter':
  15509. time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
  15510. break;
  15511. case 'month':
  15512. time = startOfDate(this.year(), this.month(), 1);
  15513. break;
  15514. case 'week':
  15515. time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
  15516. break;
  15517. case 'isoWeek':
  15518. time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
  15519. break;
  15520. case 'day':
  15521. case 'date':
  15522. time = startOfDate(this.year(), this.month(), this.date());
  15523. break;
  15524. case 'hour':
  15525. time = this._d.valueOf();
  15526. time -= mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR);
  15527. break;
  15528. case 'minute':
  15529. time = this._d.valueOf();
  15530. time -= mod$1(time, MS_PER_MINUTE);
  15531. break;
  15532. case 'second':
  15533. time = this._d.valueOf();
  15534. time -= mod$1(time, MS_PER_SECOND);
  15535. break;
  15536. }
  15537. this._d.setTime(time);
  15538. hooks.updateOffset(this, true);
  15539. return this;
  15540. }
  15541. function endOf (units) {
  15542. var time;
  15543. units = normalizeUnits(units);
  15544. if (units === undefined || units === 'millisecond' || !this.isValid()) {
  15545. return this;
  15546. }
  15547. var startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
  15548. switch (units) {
  15549. case 'year':
  15550. time = startOfDate(this.year() + 1, 0, 1) - 1;
  15551. break;
  15552. case 'quarter':
  15553. time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
  15554. break;
  15555. case 'month':
  15556. time = startOfDate(this.year(), this.month() + 1, 1) - 1;
  15557. break;
  15558. case 'week':
  15559. time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
  15560. break;
  15561. case 'isoWeek':
  15562. time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
  15563. break;
  15564. case 'day':
  15565. case 'date':
  15566. time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
  15567. break;
  15568. case 'hour':
  15569. time = this._d.valueOf();
  15570. time += MS_PER_HOUR - mod$1(time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR) - 1;
  15571. break;
  15572. case 'minute':
  15573. time = this._d.valueOf();
  15574. time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
  15575. break;
  15576. case 'second':
  15577. time = this._d.valueOf();
  15578. time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
  15579. break;
  15580. }
  15581. this._d.setTime(time);
  15582. hooks.updateOffset(this, true);
  15583. return this;
  15584. }
  15585. function valueOf () {
  15586. return this._d.valueOf() - ((this._offset || 0) * 60000);
  15587. }
  15588. function unix () {
  15589. return Math.floor(this.valueOf() / 1000);
  15590. }
  15591. function toDate () {
  15592. return new Date(this.valueOf());
  15593. }
  15594. function toArray () {
  15595. var m = this;
  15596. return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()];
  15597. }
  15598. function toObject () {
  15599. var m = this;
  15600. return {
  15601. years: m.year(),
  15602. months: m.month(),
  15603. date: m.date(),
  15604. hours: m.hours(),
  15605. minutes: m.minutes(),
  15606. seconds: m.seconds(),
  15607. milliseconds: m.milliseconds()
  15608. };
  15609. }
  15610. function toJSON () {
  15611. // new Date(NaN).toJSON() === null
  15612. return this.isValid() ? this.toISOString() : null;
  15613. }
  15614. function isValid$2 () {
  15615. return isValid(this);
  15616. }
  15617. function parsingFlags () {
  15618. return extend({}, getParsingFlags(this));
  15619. }
  15620. function invalidAt () {
  15621. return getParsingFlags(this).overflow;
  15622. }
  15623. function creationData() {
  15624. return {
  15625. input: this._i,
  15626. format: this._f,
  15627. locale: this._locale,
  15628. isUTC: this._isUTC,
  15629. strict: this._strict
  15630. };
  15631. }
  15632. // FORMATTING
  15633. addFormatToken(0, ['gg', 2], 0, function () {
  15634. return this.weekYear() % 100;
  15635. });
  15636. addFormatToken(0, ['GG', 2], 0, function () {
  15637. return this.isoWeekYear() % 100;
  15638. });
  15639. function addWeekYearFormatToken (token, getter) {
  15640. addFormatToken(0, [token, token.length], 0, getter);
  15641. }
  15642. addWeekYearFormatToken('gggg', 'weekYear');
  15643. addWeekYearFormatToken('ggggg', 'weekYear');
  15644. addWeekYearFormatToken('GGGG', 'isoWeekYear');
  15645. addWeekYearFormatToken('GGGGG', 'isoWeekYear');
  15646. // ALIASES
  15647. addUnitAlias('weekYear', 'gg');
  15648. addUnitAlias('isoWeekYear', 'GG');
  15649. // PRIORITY
  15650. addUnitPriority('weekYear', 1);
  15651. addUnitPriority('isoWeekYear', 1);
  15652. // PARSING
  15653. addRegexToken('G', matchSigned);
  15654. addRegexToken('g', matchSigned);
  15655. addRegexToken('GG', match1to2, match2);
  15656. addRegexToken('gg', match1to2, match2);
  15657. addRegexToken('GGGG', match1to4, match4);
  15658. addRegexToken('gggg', match1to4, match4);
  15659. addRegexToken('GGGGG', match1to6, match6);
  15660. addRegexToken('ggggg', match1to6, match6);
  15661. addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) {
  15662. week[token.substr(0, 2)] = toInt(input);
  15663. });
  15664. addWeekParseToken(['gg', 'GG'], function (input, week, config, token) {
  15665. week[token] = hooks.parseTwoDigitYear(input);
  15666. });
  15667. // MOMENTS
  15668. function getSetWeekYear (input) {
  15669. return getSetWeekYearHelper.call(this,
  15670. input,
  15671. this.week(),
  15672. this.weekday(),
  15673. this.localeData()._week.dow,
  15674. this.localeData()._week.doy);
  15675. }
  15676. function getSetISOWeekYear (input) {
  15677. return getSetWeekYearHelper.call(this,
  15678. input, this.isoWeek(), this.isoWeekday(), 1, 4);
  15679. }
  15680. function getISOWeeksInYear () {
  15681. return weeksInYear(this.year(), 1, 4);
  15682. }
  15683. function getWeeksInYear () {
  15684. var weekInfo = this.localeData()._week;
  15685. return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
  15686. }
  15687. function getSetWeekYearHelper(input, week, weekday, dow, doy) {
  15688. var weeksTarget;
  15689. if (input == null) {
  15690. return weekOfYear(this, dow, doy).year;
  15691. } else {
  15692. weeksTarget = weeksInYear(input, dow, doy);
  15693. if (week > weeksTarget) {
  15694. week = weeksTarget;
  15695. }
  15696. return setWeekAll.call(this, input, week, weekday, dow, doy);
  15697. }
  15698. }
  15699. function setWeekAll(weekYear, week, weekday, dow, doy) {
  15700. var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy),
  15701. date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
  15702. this.year(date.getUTCFullYear());
  15703. this.month(date.getUTCMonth());
  15704. this.date(date.getUTCDate());
  15705. return this;
  15706. }
  15707. // FORMATTING
  15708. addFormatToken('Q', 0, 'Qo', 'quarter');
  15709. // ALIASES
  15710. addUnitAlias('quarter', 'Q');
  15711. // PRIORITY
  15712. addUnitPriority('quarter', 7);
  15713. // PARSING
  15714. addRegexToken('Q', match1);
  15715. addParseToken('Q', function (input, array) {
  15716. array[MONTH] = (toInt(input) - 1) * 3;
  15717. });
  15718. // MOMENTS
  15719. function getSetQuarter (input) {
  15720. return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
  15721. }
  15722. // FORMATTING
  15723. addFormatToken('D', ['DD', 2], 'Do', 'date');
  15724. // ALIASES
  15725. addUnitAlias('date', 'D');
  15726. // PRIORITY
  15727. addUnitPriority('date', 9);
  15728. // PARSING
  15729. addRegexToken('D', match1to2);
  15730. addRegexToken('DD', match1to2, match2);
  15731. addRegexToken('Do', function (isStrict, locale) {
  15732. // TODO: Remove "ordinalParse" fallback in next major release.
  15733. return isStrict ?
  15734. (locale._dayOfMonthOrdinalParse || locale._ordinalParse) :
  15735. locale._dayOfMonthOrdinalParseLenient;
  15736. });
  15737. addParseToken(['D', 'DD'], DATE);
  15738. addParseToken('Do', function (input, array) {
  15739. array[DATE] = toInt(input.match(match1to2)[0]);
  15740. });
  15741. // MOMENTS
  15742. var getSetDayOfMonth = makeGetSet('Date', true);
  15743. // FORMATTING
  15744. addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear');
  15745. // ALIASES
  15746. addUnitAlias('dayOfYear', 'DDD');
  15747. // PRIORITY
  15748. addUnitPriority('dayOfYear', 4);
  15749. // PARSING
  15750. addRegexToken('DDD', match1to3);
  15751. addRegexToken('DDDD', match3);
  15752. addParseToken(['DDD', 'DDDD'], function (input, array, config) {
  15753. config._dayOfYear = toInt(input);
  15754. });
  15755. // HELPERS
  15756. // MOMENTS
  15757. function getSetDayOfYear (input) {
  15758. var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
  15759. return input == null ? dayOfYear : this.add((input - dayOfYear), 'd');
  15760. }
  15761. // FORMATTING
  15762. addFormatToken('m', ['mm', 2], 0, 'minute');
  15763. // ALIASES
  15764. addUnitAlias('minute', 'm');
  15765. // PRIORITY
  15766. addUnitPriority('minute', 14);
  15767. // PARSING
  15768. addRegexToken('m', match1to2);
  15769. addRegexToken('mm', match1to2, match2);
  15770. addParseToken(['m', 'mm'], MINUTE);
  15771. // MOMENTS
  15772. var getSetMinute = makeGetSet('Minutes', false);
  15773. // FORMATTING
  15774. addFormatToken('s', ['ss', 2], 0, 'second');
  15775. // ALIASES
  15776. addUnitAlias('second', 's');
  15777. // PRIORITY
  15778. addUnitPriority('second', 15);
  15779. // PARSING
  15780. addRegexToken('s', match1to2);
  15781. addRegexToken('ss', match1to2, match2);
  15782. addParseToken(['s', 'ss'], SECOND);
  15783. // MOMENTS
  15784. var getSetSecond = makeGetSet('Seconds', false);
  15785. // FORMATTING
  15786. addFormatToken('S', 0, 0, function () {
  15787. return ~~(this.millisecond() / 100);
  15788. });
  15789. addFormatToken(0, ['SS', 2], 0, function () {
  15790. return ~~(this.millisecond() / 10);
  15791. });
  15792. addFormatToken(0, ['SSS', 3], 0, 'millisecond');
  15793. addFormatToken(0, ['SSSS', 4], 0, function () {
  15794. return this.millisecond() * 10;
  15795. });
  15796. addFormatToken(0, ['SSSSS', 5], 0, function () {
  15797. return this.millisecond() * 100;
  15798. });
  15799. addFormatToken(0, ['SSSSSS', 6], 0, function () {
  15800. return this.millisecond() * 1000;
  15801. });
  15802. addFormatToken(0, ['SSSSSSS', 7], 0, function () {
  15803. return this.millisecond() * 10000;
  15804. });
  15805. addFormatToken(0, ['SSSSSSSS', 8], 0, function () {
  15806. return this.millisecond() * 100000;
  15807. });
  15808. addFormatToken(0, ['SSSSSSSSS', 9], 0, function () {
  15809. return this.millisecond() * 1000000;
  15810. });
  15811. // ALIASES
  15812. addUnitAlias('millisecond', 'ms');
  15813. // PRIORITY
  15814. addUnitPriority('millisecond', 16);
  15815. // PARSING
  15816. addRegexToken('S', match1to3, match1);
  15817. addRegexToken('SS', match1to3, match2);
  15818. addRegexToken('SSS', match1to3, match3);
  15819. var token;
  15820. for (token = 'SSSS'; token.length <= 9; token += 'S') {
  15821. addRegexToken(token, matchUnsigned);
  15822. }
  15823. function parseMs(input, array) {
  15824. array[MILLISECOND] = toInt(('0.' + input) * 1000);
  15825. }
  15826. for (token = 'S'; token.length <= 9; token += 'S') {
  15827. addParseToken(token, parseMs);
  15828. }
  15829. // MOMENTS
  15830. var getSetMillisecond = makeGetSet('Milliseconds', false);
  15831. // FORMATTING
  15832. addFormatToken('z', 0, 0, 'zoneAbbr');
  15833. addFormatToken('zz', 0, 0, 'zoneName');
  15834. // MOMENTS
  15835. function getZoneAbbr () {
  15836. return this._isUTC ? 'UTC' : '';
  15837. }
  15838. function getZoneName () {
  15839. return this._isUTC ? 'Coordinated Universal Time' : '';
  15840. }
  15841. var proto = Moment.prototype;
  15842. proto.add = add;
  15843. proto.calendar = calendar$1;
  15844. proto.clone = clone;
  15845. proto.diff = diff;
  15846. proto.endOf = endOf;
  15847. proto.format = format;
  15848. proto.from = from;
  15849. proto.fromNow = fromNow;
  15850. proto.to = to;
  15851. proto.toNow = toNow;
  15852. proto.get = stringGet;
  15853. proto.invalidAt = invalidAt;
  15854. proto.isAfter = isAfter;
  15855. proto.isBefore = isBefore;
  15856. proto.isBetween = isBetween;
  15857. proto.isSame = isSame;
  15858. proto.isSameOrAfter = isSameOrAfter;
  15859. proto.isSameOrBefore = isSameOrBefore;
  15860. proto.isValid = isValid$2;
  15861. proto.lang = lang;
  15862. proto.locale = locale;
  15863. proto.localeData = localeData;
  15864. proto.max = prototypeMax;
  15865. proto.min = prototypeMin;
  15866. proto.parsingFlags = parsingFlags;
  15867. proto.set = stringSet;
  15868. proto.startOf = startOf;
  15869. proto.subtract = subtract;
  15870. proto.toArray = toArray;
  15871. proto.toObject = toObject;
  15872. proto.toDate = toDate;
  15873. proto.toISOString = toISOString;
  15874. proto.inspect = inspect;
  15875. proto.toJSON = toJSON;
  15876. proto.toString = toString;
  15877. proto.unix = unix;
  15878. proto.valueOf = valueOf;
  15879. proto.creationData = creationData;
  15880. proto.year = getSetYear;
  15881. proto.isLeapYear = getIsLeapYear;
  15882. proto.weekYear = getSetWeekYear;
  15883. proto.isoWeekYear = getSetISOWeekYear;
  15884. proto.quarter = proto.quarters = getSetQuarter;
  15885. proto.month = getSetMonth;
  15886. proto.daysInMonth = getDaysInMonth;
  15887. proto.week = proto.weeks = getSetWeek;
  15888. proto.isoWeek = proto.isoWeeks = getSetISOWeek;
  15889. proto.weeksInYear = getWeeksInYear;
  15890. proto.isoWeeksInYear = getISOWeeksInYear;
  15891. proto.date = getSetDayOfMonth;
  15892. proto.day = proto.days = getSetDayOfWeek;
  15893. proto.weekday = getSetLocaleDayOfWeek;
  15894. proto.isoWeekday = getSetISODayOfWeek;
  15895. proto.dayOfYear = getSetDayOfYear;
  15896. proto.hour = proto.hours = getSetHour;
  15897. proto.minute = proto.minutes = getSetMinute;
  15898. proto.second = proto.seconds = getSetSecond;
  15899. proto.millisecond = proto.milliseconds = getSetMillisecond;
  15900. proto.utcOffset = getSetOffset;
  15901. proto.utc = setOffsetToUTC;
  15902. proto.local = setOffsetToLocal;
  15903. proto.parseZone = setOffsetToParsedOffset;
  15904. proto.hasAlignedHourOffset = hasAlignedHourOffset;
  15905. proto.isDST = isDaylightSavingTime;
  15906. proto.isLocal = isLocal;
  15907. proto.isUtcOffset = isUtcOffset;
  15908. proto.isUtc = isUtc;
  15909. proto.isUTC = isUtc;
  15910. proto.zoneAbbr = getZoneAbbr;
  15911. proto.zoneName = getZoneName;
  15912. proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth);
  15913. proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth);
  15914. proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear);
  15915. proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone);
  15916. proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted);
  15917. function createUnix (input) {
  15918. return createLocal(input * 1000);
  15919. }
  15920. function createInZone () {
  15921. return createLocal.apply(null, arguments).parseZone();
  15922. }
  15923. function preParsePostFormat (string) {
  15924. return string;
  15925. }
  15926. var proto$1 = Locale.prototype;
  15927. proto$1.calendar = calendar;
  15928. proto$1.longDateFormat = longDateFormat;
  15929. proto$1.invalidDate = invalidDate;
  15930. proto$1.ordinal = ordinal;
  15931. proto$1.preparse = preParsePostFormat;
  15932. proto$1.postformat = preParsePostFormat;
  15933. proto$1.relativeTime = relativeTime;
  15934. proto$1.pastFuture = pastFuture;
  15935. proto$1.set = set;
  15936. proto$1.months = localeMonths;
  15937. proto$1.monthsShort = localeMonthsShort;
  15938. proto$1.monthsParse = localeMonthsParse;
  15939. proto$1.monthsRegex = monthsRegex;
  15940. proto$1.monthsShortRegex = monthsShortRegex;
  15941. proto$1.week = localeWeek;
  15942. proto$1.firstDayOfYear = localeFirstDayOfYear;
  15943. proto$1.firstDayOfWeek = localeFirstDayOfWeek;
  15944. proto$1.weekdays = localeWeekdays;
  15945. proto$1.weekdaysMin = localeWeekdaysMin;
  15946. proto$1.weekdaysShort = localeWeekdaysShort;
  15947. proto$1.weekdaysParse = localeWeekdaysParse;
  15948. proto$1.weekdaysRegex = weekdaysRegex;
  15949. proto$1.weekdaysShortRegex = weekdaysShortRegex;
  15950. proto$1.weekdaysMinRegex = weekdaysMinRegex;
  15951. proto$1.isPM = localeIsPM;
  15952. proto$1.meridiem = localeMeridiem;
  15953. function get$1 (format, index, field, setter) {
  15954. var locale = getLocale();
  15955. var utc = createUTC().set(setter, index);
  15956. return locale[field](utc, format);
  15957. }
  15958. function listMonthsImpl (format, index, field) {
  15959. if (isNumber(format)) {
  15960. index = format;
  15961. format = undefined;
  15962. }
  15963. format = format || '';
  15964. if (index != null) {
  15965. return get$1(format, index, field, 'month');
  15966. }
  15967. var i;
  15968. var out = [];
  15969. for (i = 0; i < 12; i++) {
  15970. out[i] = get$1(format, i, field, 'month');
  15971. }
  15972. return out;
  15973. }
  15974. // ()
  15975. // (5)
  15976. // (fmt, 5)
  15977. // (fmt)
  15978. // (true)
  15979. // (true, 5)
  15980. // (true, fmt, 5)
  15981. // (true, fmt)
  15982. function listWeekdaysImpl (localeSorted, format, index, field) {
  15983. if (typeof localeSorted === 'boolean') {
  15984. if (isNumber(format)) {
  15985. index = format;
  15986. format = undefined;
  15987. }
  15988. format = format || '';
  15989. } else {
  15990. format = localeSorted;
  15991. index = format;
  15992. localeSorted = false;
  15993. if (isNumber(format)) {
  15994. index = format;
  15995. format = undefined;
  15996. }
  15997. format = format || '';
  15998. }
  15999. var locale = getLocale(),
  16000. shift = localeSorted ? locale._week.dow : 0;
  16001. if (index != null) {
  16002. return get$1(format, (index + shift) % 7, field, 'day');
  16003. }
  16004. var i;
  16005. var out = [];
  16006. for (i = 0; i < 7; i++) {
  16007. out[i] = get$1(format, (i + shift) % 7, field, 'day');
  16008. }
  16009. return out;
  16010. }
  16011. function listMonths (format, index) {
  16012. return listMonthsImpl(format, index, 'months');
  16013. }
  16014. function listMonthsShort (format, index) {
  16015. return listMonthsImpl(format, index, 'monthsShort');
  16016. }
  16017. function listWeekdays (localeSorted, format, index) {
  16018. return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
  16019. }
  16020. function listWeekdaysShort (localeSorted, format, index) {
  16021. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
  16022. }
  16023. function listWeekdaysMin (localeSorted, format, index) {
  16024. return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
  16025. }
  16026. getSetGlobalLocale('en', {
  16027. dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
  16028. ordinal : function (number) {
  16029. var b = number % 10,
  16030. output = (toInt(number % 100 / 10) === 1) ? 'th' :
  16031. (b === 1) ? 'st' :
  16032. (b === 2) ? 'nd' :
  16033. (b === 3) ? 'rd' : 'th';
  16034. return number + output;
  16035. }
  16036. });
  16037. // Side effect imports
  16038. hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale);
  16039. hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
  16040. var mathAbs = Math.abs;
  16041. function abs () {
  16042. var data = this._data;
  16043. this._milliseconds = mathAbs(this._milliseconds);
  16044. this._days = mathAbs(this._days);
  16045. this._months = mathAbs(this._months);
  16046. data.milliseconds = mathAbs(data.milliseconds);
  16047. data.seconds = mathAbs(data.seconds);
  16048. data.minutes = mathAbs(data.minutes);
  16049. data.hours = mathAbs(data.hours);
  16050. data.months = mathAbs(data.months);
  16051. data.years = mathAbs(data.years);
  16052. return this;
  16053. }
  16054. function addSubtract$1 (duration, input, value, direction) {
  16055. var other = createDuration(input, value);
  16056. duration._milliseconds += direction * other._milliseconds;
  16057. duration._days += direction * other._days;
  16058. duration._months += direction * other._months;
  16059. return duration._bubble();
  16060. }
  16061. // supports only 2.0-style add(1, 's') or add(duration)
  16062. function add$1 (input, value) {
  16063. return addSubtract$1(this, input, value, 1);
  16064. }
  16065. // supports only 2.0-style subtract(1, 's') or subtract(duration)
  16066. function subtract$1 (input, value) {
  16067. return addSubtract$1(this, input, value, -1);
  16068. }
  16069. function absCeil (number) {
  16070. if (number < 0) {
  16071. return Math.floor(number);
  16072. } else {
  16073. return Math.ceil(number);
  16074. }
  16075. }
  16076. function bubble () {
  16077. var milliseconds = this._milliseconds;
  16078. var days = this._days;
  16079. var months = this._months;
  16080. var data = this._data;
  16081. var seconds, minutes, hours, years, monthsFromDays;
  16082. // if we have a mix of positive and negative values, bubble down first
  16083. // check: https://github.com/moment/moment/issues/2166
  16084. if (!((milliseconds >= 0 && days >= 0 && months >= 0) ||
  16085. (milliseconds <= 0 && days <= 0 && months <= 0))) {
  16086. milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
  16087. days = 0;
  16088. months = 0;
  16089. }
  16090. // The following code bubbles up values, see the tests for
  16091. // examples of what that means.
  16092. data.milliseconds = milliseconds % 1000;
  16093. seconds = absFloor(milliseconds / 1000);
  16094. data.seconds = seconds % 60;
  16095. minutes = absFloor(seconds / 60);
  16096. data.minutes = minutes % 60;
  16097. hours = absFloor(minutes / 60);
  16098. data.hours = hours % 24;
  16099. days += absFloor(hours / 24);
  16100. // convert days to months
  16101. monthsFromDays = absFloor(daysToMonths(days));
  16102. months += monthsFromDays;
  16103. days -= absCeil(monthsToDays(monthsFromDays));
  16104. // 12 months -> 1 year
  16105. years = absFloor(months / 12);
  16106. months %= 12;
  16107. data.days = days;
  16108. data.months = months;
  16109. data.years = years;
  16110. return this;
  16111. }
  16112. function daysToMonths (days) {
  16113. // 400 years have 146097 days (taking into account leap year rules)
  16114. // 400 years have 12 months === 4800
  16115. return days * 4800 / 146097;
  16116. }
  16117. function monthsToDays (months) {
  16118. // the reverse of daysToMonths
  16119. return months * 146097 / 4800;
  16120. }
  16121. function as (units) {
  16122. if (!this.isValid()) {
  16123. return NaN;
  16124. }
  16125. var days;
  16126. var months;
  16127. var milliseconds = this._milliseconds;
  16128. units = normalizeUnits(units);
  16129. if (units === 'month' || units === 'quarter' || units === 'year') {
  16130. days = this._days + milliseconds / 864e5;
  16131. months = this._months + daysToMonths(days);
  16132. switch (units) {
  16133. case 'month': return months;
  16134. case 'quarter': return months / 3;
  16135. case 'year': return months / 12;
  16136. }
  16137. } else {
  16138. // handle milliseconds separately because of floating point math errors (issue #1867)
  16139. days = this._days + Math.round(monthsToDays(this._months));
  16140. switch (units) {
  16141. case 'week' : return days / 7 + milliseconds / 6048e5;
  16142. case 'day' : return days + milliseconds / 864e5;
  16143. case 'hour' : return days * 24 + milliseconds / 36e5;
  16144. case 'minute' : return days * 1440 + milliseconds / 6e4;
  16145. case 'second' : return days * 86400 + milliseconds / 1000;
  16146. // Math.floor prevents floating point math errors here
  16147. case 'millisecond': return Math.floor(days * 864e5) + milliseconds;
  16148. default: throw new Error('Unknown unit ' + units);
  16149. }
  16150. }
  16151. }
  16152. // TODO: Use this.as('ms')?
  16153. function valueOf$1 () {
  16154. if (!this.isValid()) {
  16155. return NaN;
  16156. }
  16157. return (
  16158. this._milliseconds +
  16159. this._days * 864e5 +
  16160. (this._months % 12) * 2592e6 +
  16161. toInt(this._months / 12) * 31536e6
  16162. );
  16163. }
  16164. function makeAs (alias) {
  16165. return function () {
  16166. return this.as(alias);
  16167. };
  16168. }
  16169. var asMilliseconds = makeAs('ms');
  16170. var asSeconds = makeAs('s');
  16171. var asMinutes = makeAs('m');
  16172. var asHours = makeAs('h');
  16173. var asDays = makeAs('d');
  16174. var asWeeks = makeAs('w');
  16175. var asMonths = makeAs('M');
  16176. var asQuarters = makeAs('Q');
  16177. var asYears = makeAs('y');
  16178. function clone$1 () {
  16179. return createDuration(this);
  16180. }
  16181. function get$2 (units) {
  16182. units = normalizeUnits(units);
  16183. return this.isValid() ? this[units + 's']() : NaN;
  16184. }
  16185. function makeGetter(name) {
  16186. return function () {
  16187. return this.isValid() ? this._data[name] : NaN;
  16188. };
  16189. }
  16190. var milliseconds = makeGetter('milliseconds');
  16191. var seconds = makeGetter('seconds');
  16192. var minutes = makeGetter('minutes');
  16193. var hours = makeGetter('hours');
  16194. var days = makeGetter('days');
  16195. var months = makeGetter('months');
  16196. var years = makeGetter('years');
  16197. function weeks () {
  16198. return absFloor(this.days() / 7);
  16199. }
  16200. var round = Math.round;
  16201. var thresholds = {
  16202. ss: 44, // a few seconds to seconds
  16203. s : 45, // seconds to minute
  16204. m : 45, // minutes to hour
  16205. h : 22, // hours to day
  16206. d : 26, // days to month
  16207. M : 11 // months to year
  16208. };
  16209. // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
  16210. function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
  16211. return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
  16212. }
  16213. function relativeTime$1 (posNegDuration, withoutSuffix, locale) {
  16214. var duration = createDuration(posNegDuration).abs();
  16215. var seconds = round(duration.as('s'));
  16216. var minutes = round(duration.as('m'));
  16217. var hours = round(duration.as('h'));
  16218. var days = round(duration.as('d'));
  16219. var months = round(duration.as('M'));
  16220. var years = round(duration.as('y'));
  16221. var a = seconds <= thresholds.ss && ['s', seconds] ||
  16222. seconds < thresholds.s && ['ss', seconds] ||
  16223. minutes <= 1 && ['m'] ||
  16224. minutes < thresholds.m && ['mm', minutes] ||
  16225. hours <= 1 && ['h'] ||
  16226. hours < thresholds.h && ['hh', hours] ||
  16227. days <= 1 && ['d'] ||
  16228. days < thresholds.d && ['dd', days] ||
  16229. months <= 1 && ['M'] ||
  16230. months < thresholds.M && ['MM', months] ||
  16231. years <= 1 && ['y'] || ['yy', years];
  16232. a[2] = withoutSuffix;
  16233. a[3] = +posNegDuration > 0;
  16234. a[4] = locale;
  16235. return substituteTimeAgo.apply(null, a);
  16236. }
  16237. // This function allows you to set the rounding function for relative time strings
  16238. function getSetRelativeTimeRounding (roundingFunction) {
  16239. if (roundingFunction === undefined) {
  16240. return round;
  16241. }
  16242. if (typeof(roundingFunction) === 'function') {
  16243. round = roundingFunction;
  16244. return true;
  16245. }
  16246. return false;
  16247. }
  16248. // This function allows you to set a threshold for relative time strings
  16249. function getSetRelativeTimeThreshold (threshold, limit) {
  16250. if (thresholds[threshold] === undefined) {
  16251. return false;
  16252. }
  16253. if (limit === undefined) {
  16254. return thresholds[threshold];
  16255. }
  16256. thresholds[threshold] = limit;
  16257. if (threshold === 's') {
  16258. thresholds.ss = limit - 1;
  16259. }
  16260. return true;
  16261. }
  16262. function humanize (withSuffix) {
  16263. if (!this.isValid()) {
  16264. return this.localeData().invalidDate();
  16265. }
  16266. var locale = this.localeData();
  16267. var output = relativeTime$1(this, !withSuffix, locale);
  16268. if (withSuffix) {
  16269. output = locale.pastFuture(+this, output);
  16270. }
  16271. return locale.postformat(output);
  16272. }
  16273. var abs$1 = Math.abs;
  16274. function sign(x) {
  16275. return ((x > 0) - (x < 0)) || +x;
  16276. }
  16277. function toISOString$1() {
  16278. // for ISO strings we do not use the normal bubbling rules:
  16279. // * milliseconds bubble up until they become hours
  16280. // * days do not bubble at all
  16281. // * months bubble up until they become years
  16282. // This is because there is no context-free conversion between hours and days
  16283. // (think of clock changes)
  16284. // and also not between days and months (28-31 days per month)
  16285. if (!this.isValid()) {
  16286. return this.localeData().invalidDate();
  16287. }
  16288. var seconds = abs$1(this._milliseconds) / 1000;
  16289. var days = abs$1(this._days);
  16290. var months = abs$1(this._months);
  16291. var minutes, hours, years;
  16292. // 3600 seconds -> 60 minutes -> 1 hour
  16293. minutes = absFloor(seconds / 60);
  16294. hours = absFloor(minutes / 60);
  16295. seconds %= 60;
  16296. minutes %= 60;
  16297. // 12 months -> 1 year
  16298. years = absFloor(months / 12);
  16299. months %= 12;
  16300. // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
  16301. var Y = years;
  16302. var M = months;
  16303. var D = days;
  16304. var h = hours;
  16305. var m = minutes;
  16306. var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '';
  16307. var total = this.asSeconds();
  16308. if (!total) {
  16309. // this is the same as C#'s (Noda) and python (isodate)...
  16310. // but not other JS (goog.date)
  16311. return 'P0D';
  16312. }
  16313. var totalSign = total < 0 ? '-' : '';
  16314. var ymSign = sign(this._months) !== sign(total) ? '-' : '';
  16315. var daysSign = sign(this._days) !== sign(total) ? '-' : '';
  16316. var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '';
  16317. return totalSign + 'P' +
  16318. (Y ? ymSign + Y + 'Y' : '') +
  16319. (M ? ymSign + M + 'M' : '') +
  16320. (D ? daysSign + D + 'D' : '') +
  16321. ((h || m || s) ? 'T' : '') +
  16322. (h ? hmsSign + h + 'H' : '') +
  16323. (m ? hmsSign + m + 'M' : '') +
  16324. (s ? hmsSign + s + 'S' : '');
  16325. }
  16326. var proto$2 = Duration.prototype;
  16327. proto$2.isValid = isValid$1;
  16328. proto$2.abs = abs;
  16329. proto$2.add = add$1;
  16330. proto$2.subtract = subtract$1;
  16331. proto$2.as = as;
  16332. proto$2.asMilliseconds = asMilliseconds;
  16333. proto$2.asSeconds = asSeconds;
  16334. proto$2.asMinutes = asMinutes;
  16335. proto$2.asHours = asHours;
  16336. proto$2.asDays = asDays;
  16337. proto$2.asWeeks = asWeeks;
  16338. proto$2.asMonths = asMonths;
  16339. proto$2.asQuarters = asQuarters;
  16340. proto$2.asYears = asYears;
  16341. proto$2.valueOf = valueOf$1;
  16342. proto$2._bubble = bubble;
  16343. proto$2.clone = clone$1;
  16344. proto$2.get = get$2;
  16345. proto$2.milliseconds = milliseconds;
  16346. proto$2.seconds = seconds;
  16347. proto$2.minutes = minutes;
  16348. proto$2.hours = hours;
  16349. proto$2.days = days;
  16350. proto$2.weeks = weeks;
  16351. proto$2.months = months;
  16352. proto$2.years = years;
  16353. proto$2.humanize = humanize;
  16354. proto$2.toISOString = toISOString$1;
  16355. proto$2.toString = toISOString$1;
  16356. proto$2.toJSON = toISOString$1;
  16357. proto$2.locale = locale;
  16358. proto$2.localeData = localeData;
  16359. proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1);
  16360. proto$2.lang = lang;
  16361. // Side effect imports
  16362. // FORMATTING
  16363. addFormatToken('X', 0, 0, 'unix');
  16364. addFormatToken('x', 0, 0, 'valueOf');
  16365. // PARSING
  16366. addRegexToken('x', matchSigned);
  16367. addRegexToken('X', matchTimestamp);
  16368. addParseToken('X', function (input, array, config) {
  16369. config._d = new Date(parseFloat(input, 10) * 1000);
  16370. });
  16371. addParseToken('x', function (input, array, config) {
  16372. config._d = new Date(toInt(input));
  16373. });
  16374. // Side effect imports
  16375. hooks.version = '2.24.0';
  16376. setHookCallback(createLocal);
  16377. hooks.fn = proto;
  16378. hooks.min = min;
  16379. hooks.max = max;
  16380. hooks.now = now;
  16381. hooks.utc = createUTC;
  16382. hooks.unix = createUnix;
  16383. hooks.months = listMonths;
  16384. hooks.isDate = isDate;
  16385. hooks.locale = getSetGlobalLocale;
  16386. hooks.invalid = createInvalid;
  16387. hooks.duration = createDuration;
  16388. hooks.isMoment = isMoment;
  16389. hooks.weekdays = listWeekdays;
  16390. hooks.parseZone = createInZone;
  16391. hooks.localeData = getLocale;
  16392. hooks.isDuration = isDuration;
  16393. hooks.monthsShort = listMonthsShort;
  16394. hooks.weekdaysMin = listWeekdaysMin;
  16395. hooks.defineLocale = defineLocale;
  16396. hooks.updateLocale = updateLocale;
  16397. hooks.locales = listLocales;
  16398. hooks.weekdaysShort = listWeekdaysShort;
  16399. hooks.normalizeUnits = normalizeUnits;
  16400. hooks.relativeTimeRounding = getSetRelativeTimeRounding;
  16401. hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
  16402. hooks.calendarFormat = getCalendarFormat;
  16403. hooks.prototype = proto;
  16404. // currently HTML5 input type only supports 24-hour formats
  16405. hooks.HTML5_FMT = {
  16406. DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" />
  16407. DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" />
  16408. DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" />
  16409. DATE: 'YYYY-MM-DD', // <input type="date" />
  16410. TIME: 'HH:mm', // <input type="time" />
  16411. TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" />
  16412. TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" />
  16413. WEEK: 'GGGG-[W]WW', // <input type="week" />
  16414. MONTH: 'YYYY-MM' // <input type="month" />
  16415. };
  16416. return hooks;
  16417. })));
  16418. });
  16419. var FORMATS = {
  16420. datetime: 'MMM D, YYYY, h:mm:ss a',
  16421. millisecond: 'h:mm:ss.SSS a',
  16422. second: 'h:mm:ss a',
  16423. minute: 'h:mm a',
  16424. hour: 'hA',
  16425. day: 'MMM D',
  16426. week: 'll',
  16427. month: 'MMM YYYY',
  16428. quarter: '[Q]Q - YYYY',
  16429. year: 'YYYY'
  16430. };
  16431. core_adapters._date.override(typeof moment === 'function' ? {
  16432. _id: 'moment', // DEBUG ONLY
  16433. formats: function() {
  16434. return FORMATS;
  16435. },
  16436. parse: function(value, format) {
  16437. if (typeof value === 'string' && typeof format === 'string') {
  16438. value = moment(value, format);
  16439. } else if (!(value instanceof moment)) {
  16440. value = moment(value);
  16441. }
  16442. return value.isValid() ? value.valueOf() : null;
  16443. },
  16444. format: function(time, format) {
  16445. return moment(time).format(format);
  16446. },
  16447. add: function(time, amount, unit) {
  16448. return moment(time).add(amount, unit).valueOf();
  16449. },
  16450. diff: function(max, min, unit) {
  16451. return moment(max).diff(moment(min), unit);
  16452. },
  16453. startOf: function(time, unit, weekday) {
  16454. time = moment(time);
  16455. if (unit === 'isoWeek') {
  16456. return time.isoWeekday(weekday).valueOf();
  16457. }
  16458. return time.startOf(unit).valueOf();
  16459. },
  16460. endOf: function(time, unit) {
  16461. return moment(time).endOf(unit).valueOf();
  16462. },
  16463. // DEPRECATIONS
  16464. /**
  16465. * Provided for backward compatibility with scale.getValueForPixel().
  16466. * @deprecated since version 2.8.0
  16467. * @todo remove at version 3
  16468. * @private
  16469. */
  16470. _create: function(time) {
  16471. return moment(time);
  16472. },
  16473. } : {});
  16474. core_defaults._set('global', {
  16475. plugins: {
  16476. filler: {
  16477. propagate: true
  16478. }
  16479. }
  16480. });
  16481. var mappers = {
  16482. dataset: function(source) {
  16483. var index = source.fill;
  16484. var chart = source.chart;
  16485. var meta = chart.getDatasetMeta(index);
  16486. var visible = meta && chart.isDatasetVisible(index);
  16487. var points = (visible && meta.dataset._children) || [];
  16488. var length = points.length || 0;
  16489. return !length ? null : function(point, i) {
  16490. return (i < length && points[i]._view) || null;
  16491. };
  16492. },
  16493. boundary: function(source) {
  16494. var boundary = source.boundary;
  16495. var x = boundary ? boundary.x : null;
  16496. var y = boundary ? boundary.y : null;
  16497. if (helpers$1.isArray(boundary)) {
  16498. return function(point, i) {
  16499. return boundary[i];
  16500. };
  16501. }
  16502. return function(point) {
  16503. return {
  16504. x: x === null ? point.x : x,
  16505. y: y === null ? point.y : y,
  16506. };
  16507. };
  16508. }
  16509. };
  16510. // @todo if (fill[0] === '#')
  16511. function decodeFill(el, index, count) {
  16512. var model = el._model || {};
  16513. var fill = model.fill;
  16514. var target;
  16515. if (fill === undefined) {
  16516. fill = !!model.backgroundColor;
  16517. }
  16518. if (fill === false || fill === null) {
  16519. return false;
  16520. }
  16521. if (fill === true) {
  16522. return 'origin';
  16523. }
  16524. target = parseFloat(fill, 10);
  16525. if (isFinite(target) && Math.floor(target) === target) {
  16526. if (fill[0] === '-' || fill[0] === '+') {
  16527. target = index + target;
  16528. }
  16529. if (target === index || target < 0 || target >= count) {
  16530. return false;
  16531. }
  16532. return target;
  16533. }
  16534. switch (fill) {
  16535. // compatibility
  16536. case 'bottom':
  16537. return 'start';
  16538. case 'top':
  16539. return 'end';
  16540. case 'zero':
  16541. return 'origin';
  16542. // supported boundaries
  16543. case 'origin':
  16544. case 'start':
  16545. case 'end':
  16546. return fill;
  16547. // invalid fill values
  16548. default:
  16549. return false;
  16550. }
  16551. }
  16552. function computeLinearBoundary(source) {
  16553. var model = source.el._model || {};
  16554. var scale = source.el._scale || {};
  16555. var fill = source.fill;
  16556. var target = null;
  16557. var horizontal;
  16558. if (isFinite(fill)) {
  16559. return null;
  16560. }
  16561. // Backward compatibility: until v3, we still need to support boundary values set on
  16562. // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and
  16563. // controllers might still use it (e.g. the Smith chart).
  16564. if (fill === 'start') {
  16565. target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom;
  16566. } else if (fill === 'end') {
  16567. target = model.scaleTop === undefined ? scale.top : model.scaleTop;
  16568. } else if (model.scaleZero !== undefined) {
  16569. target = model.scaleZero;
  16570. } else if (scale.getBasePixel) {
  16571. target = scale.getBasePixel();
  16572. }
  16573. if (target !== undefined && target !== null) {
  16574. if (target.x !== undefined && target.y !== undefined) {
  16575. return target;
  16576. }
  16577. if (helpers$1.isFinite(target)) {
  16578. horizontal = scale.isHorizontal();
  16579. return {
  16580. x: horizontal ? target : null,
  16581. y: horizontal ? null : target
  16582. };
  16583. }
  16584. }
  16585. return null;
  16586. }
  16587. function computeCircularBoundary(source) {
  16588. var scale = source.el._scale;
  16589. var options = scale.options;
  16590. var length = scale.chart.data.labels.length;
  16591. var fill = source.fill;
  16592. var target = [];
  16593. var start, end, center, i, point;
  16594. if (!length) {
  16595. return null;
  16596. }
  16597. start = options.ticks.reverse ? scale.max : scale.min;
  16598. end = options.ticks.reverse ? scale.min : scale.max;
  16599. center = scale.getPointPositionForValue(0, start);
  16600. for (i = 0; i < length; ++i) {
  16601. point = fill === 'start' || fill === 'end'
  16602. ? scale.getPointPositionForValue(i, fill === 'start' ? start : end)
  16603. : scale.getBasePosition(i);
  16604. if (options.gridLines.circular) {
  16605. point.cx = center.x;
  16606. point.cy = center.y;
  16607. point.angle = scale.getIndexAngle(i) - Math.PI / 2;
  16608. }
  16609. target.push(point);
  16610. }
  16611. return target;
  16612. }
  16613. function computeBoundary(source) {
  16614. var scale = source.el._scale || {};
  16615. if (scale.getPointPositionForValue) {
  16616. return computeCircularBoundary(source);
  16617. }
  16618. return computeLinearBoundary(source);
  16619. }
  16620. function resolveTarget(sources, index, propagate) {
  16621. var source = sources[index];
  16622. var fill = source.fill;
  16623. var visited = [index];
  16624. var target;
  16625. if (!propagate) {
  16626. return fill;
  16627. }
  16628. while (fill !== false && visited.indexOf(fill) === -1) {
  16629. if (!isFinite(fill)) {
  16630. return fill;
  16631. }
  16632. target = sources[fill];
  16633. if (!target) {
  16634. return false;
  16635. }
  16636. if (target.visible) {
  16637. return fill;
  16638. }
  16639. visited.push(fill);
  16640. fill = target.fill;
  16641. }
  16642. return false;
  16643. }
  16644. function createMapper(source) {
  16645. var fill = source.fill;
  16646. var type = 'dataset';
  16647. if (fill === false) {
  16648. return null;
  16649. }
  16650. if (!isFinite(fill)) {
  16651. type = 'boundary';
  16652. }
  16653. return mappers[type](source);
  16654. }
  16655. function isDrawable(point) {
  16656. return point && !point.skip;
  16657. }
  16658. function drawArea(ctx, curve0, curve1, len0, len1) {
  16659. var i, cx, cy, r;
  16660. if (!len0 || !len1) {
  16661. return;
  16662. }
  16663. // building first area curve (normal)
  16664. ctx.moveTo(curve0[0].x, curve0[0].y);
  16665. for (i = 1; i < len0; ++i) {
  16666. helpers$1.canvas.lineTo(ctx, curve0[i - 1], curve0[i]);
  16667. }
  16668. if (curve1[0].angle !== undefined) {
  16669. cx = curve1[0].cx;
  16670. cy = curve1[0].cy;
  16671. r = Math.sqrt(Math.pow(curve1[0].x - cx, 2) + Math.pow(curve1[0].y - cy, 2));
  16672. for (i = len1 - 1; i > 0; --i) {
  16673. ctx.arc(cx, cy, r, curve1[i].angle, curve1[i - 1].angle, true);
  16674. }
  16675. return;
  16676. }
  16677. // joining the two area curves
  16678. ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y);
  16679. // building opposite area curve (reverse)
  16680. for (i = len1 - 1; i > 0; --i) {
  16681. helpers$1.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true);
  16682. }
  16683. }
  16684. function doFill(ctx, points, mapper, view, color, loop) {
  16685. var count = points.length;
  16686. var span = view.spanGaps;
  16687. var curve0 = [];
  16688. var curve1 = [];
  16689. var len0 = 0;
  16690. var len1 = 0;
  16691. var i, ilen, index, p0, p1, d0, d1, loopOffset;
  16692. ctx.beginPath();
  16693. for (i = 0, ilen = count; i < ilen; ++i) {
  16694. index = i % count;
  16695. p0 = points[index]._view;
  16696. p1 = mapper(p0, index, view);
  16697. d0 = isDrawable(p0);
  16698. d1 = isDrawable(p1);
  16699. if (loop && loopOffset === undefined && d0) {
  16700. loopOffset = i + 1;
  16701. ilen = count + loopOffset;
  16702. }
  16703. if (d0 && d1) {
  16704. len0 = curve0.push(p0);
  16705. len1 = curve1.push(p1);
  16706. } else if (len0 && len1) {
  16707. if (!span) {
  16708. drawArea(ctx, curve0, curve1, len0, len1);
  16709. len0 = len1 = 0;
  16710. curve0 = [];
  16711. curve1 = [];
  16712. } else {
  16713. if (d0) {
  16714. curve0.push(p0);
  16715. }
  16716. if (d1) {
  16717. curve1.push(p1);
  16718. }
  16719. }
  16720. }
  16721. }
  16722. drawArea(ctx, curve0, curve1, len0, len1);
  16723. ctx.closePath();
  16724. ctx.fillStyle = color;
  16725. ctx.fill();
  16726. }
  16727. var plugin_filler = {
  16728. id: 'filler',
  16729. afterDatasetsUpdate: function(chart, options) {
  16730. var count = (chart.data.datasets || []).length;
  16731. var propagate = options.propagate;
  16732. var sources = [];
  16733. var meta, i, el, source;
  16734. for (i = 0; i < count; ++i) {
  16735. meta = chart.getDatasetMeta(i);
  16736. el = meta.dataset;
  16737. source = null;
  16738. if (el && el._model && el instanceof elements.Line) {
  16739. source = {
  16740. visible: chart.isDatasetVisible(i),
  16741. fill: decodeFill(el, i, count),
  16742. chart: chart,
  16743. el: el
  16744. };
  16745. }
  16746. meta.$filler = source;
  16747. sources.push(source);
  16748. }
  16749. for (i = 0; i < count; ++i) {
  16750. source = sources[i];
  16751. if (!source) {
  16752. continue;
  16753. }
  16754. source.fill = resolveTarget(sources, i, propagate);
  16755. source.boundary = computeBoundary(source);
  16756. source.mapper = createMapper(source);
  16757. }
  16758. },
  16759. beforeDatasetsDraw: function(chart) {
  16760. var metasets = chart._getSortedVisibleDatasetMetas();
  16761. var ctx = chart.ctx;
  16762. var meta, i, el, view, points, mapper, color;
  16763. for (i = metasets.length - 1; i >= 0; --i) {
  16764. meta = metasets[i].$filler;
  16765. if (!meta || !meta.visible) {
  16766. continue;
  16767. }
  16768. el = meta.el;
  16769. view = el._view;
  16770. points = el._children || [];
  16771. mapper = meta.mapper;
  16772. color = view.backgroundColor || core_defaults.global.defaultColor;
  16773. if (mapper && color && points.length) {
  16774. helpers$1.canvas.clipArea(ctx, chart.chartArea);
  16775. doFill(ctx, points, mapper, view, color, el._loop);
  16776. helpers$1.canvas.unclipArea(ctx);
  16777. }
  16778. }
  16779. }
  16780. };
  16781. var getRtlHelper$1 = helpers$1.rtl.getRtlAdapter;
  16782. var noop$1 = helpers$1.noop;
  16783. var valueOrDefault$e = helpers$1.valueOrDefault;
  16784. core_defaults._set('global', {
  16785. legend: {
  16786. display: true,
  16787. position: 'top',
  16788. align: 'center',
  16789. fullWidth: true,
  16790. reverse: false,
  16791. weight: 1000,
  16792. // a callback that will handle
  16793. onClick: function(e, legendItem) {
  16794. var index = legendItem.datasetIndex;
  16795. var ci = this.chart;
  16796. var meta = ci.getDatasetMeta(index);
  16797. // See controller.isDatasetVisible comment
  16798. meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null;
  16799. // We hid a dataset ... rerender the chart
  16800. ci.update();
  16801. },
  16802. onHover: null,
  16803. onLeave: null,
  16804. labels: {
  16805. boxWidth: 40,
  16806. padding: 10,
  16807. // Generates labels shown in the legend
  16808. // Valid properties to return:
  16809. // text : text to display
  16810. // fillStyle : fill of coloured box
  16811. // strokeStyle: stroke of coloured box
  16812. // hidden : if this legend item refers to a hidden item
  16813. // lineCap : cap style for line
  16814. // lineDash
  16815. // lineDashOffset :
  16816. // lineJoin :
  16817. // lineWidth :
  16818. generateLabels: function(chart) {
  16819. var datasets = chart.data.datasets;
  16820. var options = chart.options.legend || {};
  16821. var usePointStyle = options.labels && options.labels.usePointStyle;
  16822. return chart._getSortedDatasetMetas().map(function(meta) {
  16823. var style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
  16824. return {
  16825. text: datasets[meta.index].label,
  16826. fillStyle: style.backgroundColor,
  16827. hidden: !chart.isDatasetVisible(meta.index),
  16828. lineCap: style.borderCapStyle,
  16829. lineDash: style.borderDash,
  16830. lineDashOffset: style.borderDashOffset,
  16831. lineJoin: style.borderJoinStyle,
  16832. lineWidth: style.borderWidth,
  16833. strokeStyle: style.borderColor,
  16834. pointStyle: style.pointStyle,
  16835. rotation: style.rotation,
  16836. // Below is extra data used for toggling the datasets
  16837. datasetIndex: meta.index
  16838. };
  16839. }, this);
  16840. }
  16841. }
  16842. },
  16843. legendCallback: function(chart) {
  16844. var list = document.createElement('ul');
  16845. var datasets = chart.data.datasets;
  16846. var i, ilen, listItem, listItemSpan;
  16847. list.setAttribute('class', chart.id + '-legend');
  16848. for (i = 0, ilen = datasets.length; i < ilen; i++) {
  16849. listItem = list.appendChild(document.createElement('li'));
  16850. listItemSpan = listItem.appendChild(document.createElement('span'));
  16851. listItemSpan.style.backgroundColor = datasets[i].backgroundColor;
  16852. if (datasets[i].label) {
  16853. listItem.appendChild(document.createTextNode(datasets[i].label));
  16854. }
  16855. }
  16856. return list.outerHTML;
  16857. }
  16858. });
  16859. /**
  16860. * Helper function to get the box width based on the usePointStyle option
  16861. * @param {object} labelopts - the label options on the legend
  16862. * @param {number} fontSize - the label font size
  16863. * @return {number} width of the color box area
  16864. */
  16865. function getBoxWidth(labelOpts, fontSize) {
  16866. return labelOpts.usePointStyle && labelOpts.boxWidth > fontSize ?
  16867. fontSize :
  16868. labelOpts.boxWidth;
  16869. }
  16870. /**
  16871. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  16872. */
  16873. var Legend = core_element.extend({
  16874. initialize: function(config) {
  16875. var me = this;
  16876. helpers$1.extend(me, config);
  16877. // Contains hit boxes for each dataset (in dataset order)
  16878. me.legendHitBoxes = [];
  16879. /**
  16880. * @private
  16881. */
  16882. me._hoveredItem = null;
  16883. // Are we in doughnut mode which has a different data type
  16884. me.doughnutMode = false;
  16885. },
  16886. // These methods are ordered by lifecycle. Utilities then follow.
  16887. // Any function defined here is inherited by all legend types.
  16888. // Any function can be extended by the legend type
  16889. beforeUpdate: noop$1,
  16890. update: function(maxWidth, maxHeight, margins) {
  16891. var me = this;
  16892. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  16893. me.beforeUpdate();
  16894. // Absorb the master measurements
  16895. me.maxWidth = maxWidth;
  16896. me.maxHeight = maxHeight;
  16897. me.margins = margins;
  16898. // Dimensions
  16899. me.beforeSetDimensions();
  16900. me.setDimensions();
  16901. me.afterSetDimensions();
  16902. // Labels
  16903. me.beforeBuildLabels();
  16904. me.buildLabels();
  16905. me.afterBuildLabels();
  16906. // Fit
  16907. me.beforeFit();
  16908. me.fit();
  16909. me.afterFit();
  16910. //
  16911. me.afterUpdate();
  16912. return me.minSize;
  16913. },
  16914. afterUpdate: noop$1,
  16915. //
  16916. beforeSetDimensions: noop$1,
  16917. setDimensions: function() {
  16918. var me = this;
  16919. // Set the unconstrained dimension before label rotation
  16920. if (me.isHorizontal()) {
  16921. // Reset position before calculating rotation
  16922. me.width = me.maxWidth;
  16923. me.left = 0;
  16924. me.right = me.width;
  16925. } else {
  16926. me.height = me.maxHeight;
  16927. // Reset position before calculating rotation
  16928. me.top = 0;
  16929. me.bottom = me.height;
  16930. }
  16931. // Reset padding
  16932. me.paddingLeft = 0;
  16933. me.paddingTop = 0;
  16934. me.paddingRight = 0;
  16935. me.paddingBottom = 0;
  16936. // Reset minSize
  16937. me.minSize = {
  16938. width: 0,
  16939. height: 0
  16940. };
  16941. },
  16942. afterSetDimensions: noop$1,
  16943. //
  16944. beforeBuildLabels: noop$1,
  16945. buildLabels: function() {
  16946. var me = this;
  16947. var labelOpts = me.options.labels || {};
  16948. var legendItems = helpers$1.callback(labelOpts.generateLabels, [me.chart], me) || [];
  16949. if (labelOpts.filter) {
  16950. legendItems = legendItems.filter(function(item) {
  16951. return labelOpts.filter(item, me.chart.data);
  16952. });
  16953. }
  16954. if (me.options.reverse) {
  16955. legendItems.reverse();
  16956. }
  16957. me.legendItems = legendItems;
  16958. },
  16959. afterBuildLabels: noop$1,
  16960. //
  16961. beforeFit: noop$1,
  16962. fit: function() {
  16963. var me = this;
  16964. var opts = me.options;
  16965. var labelOpts = opts.labels;
  16966. var display = opts.display;
  16967. var ctx = me.ctx;
  16968. var labelFont = helpers$1.options._parseFont(labelOpts);
  16969. var fontSize = labelFont.size;
  16970. // Reset hit boxes
  16971. var hitboxes = me.legendHitBoxes = [];
  16972. var minSize = me.minSize;
  16973. var isHorizontal = me.isHorizontal();
  16974. if (isHorizontal) {
  16975. minSize.width = me.maxWidth; // fill all the width
  16976. minSize.height = display ? 10 : 0;
  16977. } else {
  16978. minSize.width = display ? 10 : 0;
  16979. minSize.height = me.maxHeight; // fill all the height
  16980. }
  16981. // Increase sizes here
  16982. if (!display) {
  16983. me.width = minSize.width = me.height = minSize.height = 0;
  16984. return;
  16985. }
  16986. ctx.font = labelFont.string;
  16987. if (isHorizontal) {
  16988. // Labels
  16989. // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one
  16990. var lineWidths = me.lineWidths = [0];
  16991. var totalHeight = 0;
  16992. ctx.textAlign = 'left';
  16993. ctx.textBaseline = 'middle';
  16994. helpers$1.each(me.legendItems, function(legendItem, i) {
  16995. var boxWidth = getBoxWidth(labelOpts, fontSize);
  16996. var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  16997. if (i === 0 || lineWidths[lineWidths.length - 1] + width + 2 * labelOpts.padding > minSize.width) {
  16998. totalHeight += fontSize + labelOpts.padding;
  16999. lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0;
  17000. }
  17001. // Store the hitbox width and height here. Final position will be updated in `draw`
  17002. hitboxes[i] = {
  17003. left: 0,
  17004. top: 0,
  17005. width: width,
  17006. height: fontSize
  17007. };
  17008. lineWidths[lineWidths.length - 1] += width + labelOpts.padding;
  17009. });
  17010. minSize.height += totalHeight;
  17011. } else {
  17012. var vPadding = labelOpts.padding;
  17013. var columnWidths = me.columnWidths = [];
  17014. var columnHeights = me.columnHeights = [];
  17015. var totalWidth = labelOpts.padding;
  17016. var currentColWidth = 0;
  17017. var currentColHeight = 0;
  17018. helpers$1.each(me.legendItems, function(legendItem, i) {
  17019. var boxWidth = getBoxWidth(labelOpts, fontSize);
  17020. var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width;
  17021. // If too tall, go to new column
  17022. if (i > 0 && currentColHeight + fontSize + 2 * vPadding > minSize.height) {
  17023. totalWidth += currentColWidth + labelOpts.padding;
  17024. columnWidths.push(currentColWidth); // previous column width
  17025. columnHeights.push(currentColHeight);
  17026. currentColWidth = 0;
  17027. currentColHeight = 0;
  17028. }
  17029. // Get max width
  17030. currentColWidth = Math.max(currentColWidth, itemWidth);
  17031. currentColHeight += fontSize + vPadding;
  17032. // Store the hitbox width and height here. Final position will be updated in `draw`
  17033. hitboxes[i] = {
  17034. left: 0,
  17035. top: 0,
  17036. width: itemWidth,
  17037. height: fontSize
  17038. };
  17039. });
  17040. totalWidth += currentColWidth;
  17041. columnWidths.push(currentColWidth);
  17042. columnHeights.push(currentColHeight);
  17043. minSize.width += totalWidth;
  17044. }
  17045. me.width = minSize.width;
  17046. me.height = minSize.height;
  17047. },
  17048. afterFit: noop$1,
  17049. // Shared Methods
  17050. isHorizontal: function() {
  17051. return this.options.position === 'top' || this.options.position === 'bottom';
  17052. },
  17053. // Actually draw the legend on the canvas
  17054. draw: function() {
  17055. var me = this;
  17056. var opts = me.options;
  17057. var labelOpts = opts.labels;
  17058. var globalDefaults = core_defaults.global;
  17059. var defaultColor = globalDefaults.defaultColor;
  17060. var lineDefault = globalDefaults.elements.line;
  17061. var legendHeight = me.height;
  17062. var columnHeights = me.columnHeights;
  17063. var legendWidth = me.width;
  17064. var lineWidths = me.lineWidths;
  17065. if (!opts.display) {
  17066. return;
  17067. }
  17068. var rtlHelper = getRtlHelper$1(opts.rtl, me.left, me.minSize.width);
  17069. var ctx = me.ctx;
  17070. var fontColor = valueOrDefault$e(labelOpts.fontColor, globalDefaults.defaultFontColor);
  17071. var labelFont = helpers$1.options._parseFont(labelOpts);
  17072. var fontSize = labelFont.size;
  17073. var cursor;
  17074. // Canvas setup
  17075. ctx.textAlign = rtlHelper.textAlign('left');
  17076. ctx.textBaseline = 'middle';
  17077. ctx.lineWidth = 0.5;
  17078. ctx.strokeStyle = fontColor; // for strikethrough effect
  17079. ctx.fillStyle = fontColor; // render in correct colour
  17080. ctx.font = labelFont.string;
  17081. var boxWidth = getBoxWidth(labelOpts, fontSize);
  17082. var hitboxes = me.legendHitBoxes;
  17083. // current position
  17084. var drawLegendBox = function(x, y, legendItem) {
  17085. if (isNaN(boxWidth) || boxWidth <= 0) {
  17086. return;
  17087. }
  17088. // Set the ctx for the box
  17089. ctx.save();
  17090. var lineWidth = valueOrDefault$e(legendItem.lineWidth, lineDefault.borderWidth);
  17091. ctx.fillStyle = valueOrDefault$e(legendItem.fillStyle, defaultColor);
  17092. ctx.lineCap = valueOrDefault$e(legendItem.lineCap, lineDefault.borderCapStyle);
  17093. ctx.lineDashOffset = valueOrDefault$e(legendItem.lineDashOffset, lineDefault.borderDashOffset);
  17094. ctx.lineJoin = valueOrDefault$e(legendItem.lineJoin, lineDefault.borderJoinStyle);
  17095. ctx.lineWidth = lineWidth;
  17096. ctx.strokeStyle = valueOrDefault$e(legendItem.strokeStyle, defaultColor);
  17097. if (ctx.setLineDash) {
  17098. // IE 9 and 10 do not support line dash
  17099. ctx.setLineDash(valueOrDefault$e(legendItem.lineDash, lineDefault.borderDash));
  17100. }
  17101. if (labelOpts && labelOpts.usePointStyle) {
  17102. // Recalculate x and y for drawPoint() because its expecting
  17103. // x and y to be center of figure (instead of top left)
  17104. var radius = boxWidth * Math.SQRT2 / 2;
  17105. var centerX = rtlHelper.xPlus(x, boxWidth / 2);
  17106. var centerY = y + fontSize / 2;
  17107. // Draw pointStyle as legend symbol
  17108. helpers$1.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY, legendItem.rotation);
  17109. } else {
  17110. // Draw box as legend symbol
  17111. ctx.fillRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  17112. if (lineWidth !== 0) {
  17113. ctx.strokeRect(rtlHelper.leftForLtr(x, boxWidth), y, boxWidth, fontSize);
  17114. }
  17115. }
  17116. ctx.restore();
  17117. };
  17118. var fillText = function(x, y, legendItem, textWidth) {
  17119. var halfFontSize = fontSize / 2;
  17120. var xLeft = rtlHelper.xPlus(x, boxWidth + halfFontSize);
  17121. var yMiddle = y + halfFontSize;
  17122. ctx.fillText(legendItem.text, xLeft, yMiddle);
  17123. if (legendItem.hidden) {
  17124. // Strikethrough the text if hidden
  17125. ctx.beginPath();
  17126. ctx.lineWidth = 2;
  17127. ctx.moveTo(xLeft, yMiddle);
  17128. ctx.lineTo(rtlHelper.xPlus(xLeft, textWidth), yMiddle);
  17129. ctx.stroke();
  17130. }
  17131. };
  17132. var alignmentOffset = function(dimension, blockSize) {
  17133. switch (opts.align) {
  17134. case 'start':
  17135. return labelOpts.padding;
  17136. case 'end':
  17137. return dimension - blockSize;
  17138. default: // center
  17139. return (dimension - blockSize + labelOpts.padding) / 2;
  17140. }
  17141. };
  17142. // Horizontal
  17143. var isHorizontal = me.isHorizontal();
  17144. if (isHorizontal) {
  17145. cursor = {
  17146. x: me.left + alignmentOffset(legendWidth, lineWidths[0]),
  17147. y: me.top + labelOpts.padding,
  17148. line: 0
  17149. };
  17150. } else {
  17151. cursor = {
  17152. x: me.left + labelOpts.padding,
  17153. y: me.top + alignmentOffset(legendHeight, columnHeights[0]),
  17154. line: 0
  17155. };
  17156. }
  17157. helpers$1.rtl.overrideTextDirection(me.ctx, opts.textDirection);
  17158. var itemHeight = fontSize + labelOpts.padding;
  17159. helpers$1.each(me.legendItems, function(legendItem, i) {
  17160. var textWidth = ctx.measureText(legendItem.text).width;
  17161. var width = boxWidth + (fontSize / 2) + textWidth;
  17162. var x = cursor.x;
  17163. var y = cursor.y;
  17164. rtlHelper.setWidth(me.minSize.width);
  17165. // Use (me.left + me.minSize.width) and (me.top + me.minSize.height)
  17166. // instead of me.right and me.bottom because me.width and me.height
  17167. // may have been changed since me.minSize was calculated
  17168. if (isHorizontal) {
  17169. if (i > 0 && x + width + labelOpts.padding > me.left + me.minSize.width) {
  17170. y = cursor.y += itemHeight;
  17171. cursor.line++;
  17172. x = cursor.x = me.left + alignmentOffset(legendWidth, lineWidths[cursor.line]);
  17173. }
  17174. } else if (i > 0 && y + itemHeight > me.top + me.minSize.height) {
  17175. x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding;
  17176. cursor.line++;
  17177. y = cursor.y = me.top + alignmentOffset(legendHeight, columnHeights[cursor.line]);
  17178. }
  17179. var realX = rtlHelper.x(x);
  17180. drawLegendBox(realX, y, legendItem);
  17181. hitboxes[i].left = rtlHelper.leftForLtr(realX, hitboxes[i].width);
  17182. hitboxes[i].top = y;
  17183. // Fill the actual label
  17184. fillText(realX, y, legendItem, textWidth);
  17185. if (isHorizontal) {
  17186. cursor.x += width + labelOpts.padding;
  17187. } else {
  17188. cursor.y += itemHeight;
  17189. }
  17190. });
  17191. helpers$1.rtl.restoreTextDirection(me.ctx, opts.textDirection);
  17192. },
  17193. /**
  17194. * @private
  17195. */
  17196. _getLegendItemAt: function(x, y) {
  17197. var me = this;
  17198. var i, hitBox, lh;
  17199. if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) {
  17200. // See if we are touching one of the dataset boxes
  17201. lh = me.legendHitBoxes;
  17202. for (i = 0; i < lh.length; ++i) {
  17203. hitBox = lh[i];
  17204. if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) {
  17205. // Touching an element
  17206. return me.legendItems[i];
  17207. }
  17208. }
  17209. }
  17210. return null;
  17211. },
  17212. /**
  17213. * Handle an event
  17214. * @private
  17215. * @param {IEvent} event - The event to handle
  17216. */
  17217. handleEvent: function(e) {
  17218. var me = this;
  17219. var opts = me.options;
  17220. var type = e.type === 'mouseup' ? 'click' : e.type;
  17221. var hoveredItem;
  17222. if (type === 'mousemove') {
  17223. if (!opts.onHover && !opts.onLeave) {
  17224. return;
  17225. }
  17226. } else if (type === 'click') {
  17227. if (!opts.onClick) {
  17228. return;
  17229. }
  17230. } else {
  17231. return;
  17232. }
  17233. // Chart event already has relative position in it
  17234. hoveredItem = me._getLegendItemAt(e.x, e.y);
  17235. if (type === 'click') {
  17236. if (hoveredItem && opts.onClick) {
  17237. // use e.native for backwards compatibility
  17238. opts.onClick.call(me, e.native, hoveredItem);
  17239. }
  17240. } else {
  17241. if (opts.onLeave && hoveredItem !== me._hoveredItem) {
  17242. if (me._hoveredItem) {
  17243. opts.onLeave.call(me, e.native, me._hoveredItem);
  17244. }
  17245. me._hoveredItem = hoveredItem;
  17246. }
  17247. if (opts.onHover && hoveredItem) {
  17248. // use e.native for backwards compatibility
  17249. opts.onHover.call(me, e.native, hoveredItem);
  17250. }
  17251. }
  17252. }
  17253. });
  17254. function createNewLegendAndAttach(chart, legendOpts) {
  17255. var legend = new Legend({
  17256. ctx: chart.ctx,
  17257. options: legendOpts,
  17258. chart: chart
  17259. });
  17260. core_layouts.configure(chart, legend, legendOpts);
  17261. core_layouts.addBox(chart, legend);
  17262. chart.legend = legend;
  17263. }
  17264. var plugin_legend = {
  17265. id: 'legend',
  17266. /**
  17267. * Backward compatibility: since 2.1.5, the legend is registered as a plugin, making
  17268. * Chart.Legend obsolete. To avoid a breaking change, we export the Legend as part of
  17269. * the plugin, which one will be re-exposed in the chart.js file.
  17270. * https://github.com/chartjs/Chart.js/pull/2640
  17271. * @private
  17272. */
  17273. _element: Legend,
  17274. beforeInit: function(chart) {
  17275. var legendOpts = chart.options.legend;
  17276. if (legendOpts) {
  17277. createNewLegendAndAttach(chart, legendOpts);
  17278. }
  17279. },
  17280. beforeUpdate: function(chart) {
  17281. var legendOpts = chart.options.legend;
  17282. var legend = chart.legend;
  17283. if (legendOpts) {
  17284. helpers$1.mergeIf(legendOpts, core_defaults.global.legend);
  17285. if (legend) {
  17286. core_layouts.configure(chart, legend, legendOpts);
  17287. legend.options = legendOpts;
  17288. } else {
  17289. createNewLegendAndAttach(chart, legendOpts);
  17290. }
  17291. } else if (legend) {
  17292. core_layouts.removeBox(chart, legend);
  17293. delete chart.legend;
  17294. }
  17295. },
  17296. afterEvent: function(chart, e) {
  17297. var legend = chart.legend;
  17298. if (legend) {
  17299. legend.handleEvent(e);
  17300. }
  17301. }
  17302. };
  17303. var noop$2 = helpers$1.noop;
  17304. core_defaults._set('global', {
  17305. title: {
  17306. display: false,
  17307. fontStyle: 'bold',
  17308. fullWidth: true,
  17309. padding: 10,
  17310. position: 'top',
  17311. text: '',
  17312. weight: 2000 // by default greater than legend (1000) to be above
  17313. }
  17314. });
  17315. /**
  17316. * IMPORTANT: this class is exposed publicly as Chart.Legend, backward compatibility required!
  17317. */
  17318. var Title = core_element.extend({
  17319. initialize: function(config) {
  17320. var me = this;
  17321. helpers$1.extend(me, config);
  17322. // Contains hit boxes for each dataset (in dataset order)
  17323. me.legendHitBoxes = [];
  17324. },
  17325. // These methods are ordered by lifecycle. Utilities then follow.
  17326. beforeUpdate: noop$2,
  17327. update: function(maxWidth, maxHeight, margins) {
  17328. var me = this;
  17329. // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;)
  17330. me.beforeUpdate();
  17331. // Absorb the master measurements
  17332. me.maxWidth = maxWidth;
  17333. me.maxHeight = maxHeight;
  17334. me.margins = margins;
  17335. // Dimensions
  17336. me.beforeSetDimensions();
  17337. me.setDimensions();
  17338. me.afterSetDimensions();
  17339. // Labels
  17340. me.beforeBuildLabels();
  17341. me.buildLabels();
  17342. me.afterBuildLabels();
  17343. // Fit
  17344. me.beforeFit();
  17345. me.fit();
  17346. me.afterFit();
  17347. //
  17348. me.afterUpdate();
  17349. return me.minSize;
  17350. },
  17351. afterUpdate: noop$2,
  17352. //
  17353. beforeSetDimensions: noop$2,
  17354. setDimensions: function() {
  17355. var me = this;
  17356. // Set the unconstrained dimension before label rotation
  17357. if (me.isHorizontal()) {
  17358. // Reset position before calculating rotation
  17359. me.width = me.maxWidth;
  17360. me.left = 0;
  17361. me.right = me.width;
  17362. } else {
  17363. me.height = me.maxHeight;
  17364. // Reset position before calculating rotation
  17365. me.top = 0;
  17366. me.bottom = me.height;
  17367. }
  17368. // Reset padding
  17369. me.paddingLeft = 0;
  17370. me.paddingTop = 0;
  17371. me.paddingRight = 0;
  17372. me.paddingBottom = 0;
  17373. // Reset minSize
  17374. me.minSize = {
  17375. width: 0,
  17376. height: 0
  17377. };
  17378. },
  17379. afterSetDimensions: noop$2,
  17380. //
  17381. beforeBuildLabels: noop$2,
  17382. buildLabels: noop$2,
  17383. afterBuildLabels: noop$2,
  17384. //
  17385. beforeFit: noop$2,
  17386. fit: function() {
  17387. var me = this;
  17388. var opts = me.options;
  17389. var minSize = me.minSize = {};
  17390. var isHorizontal = me.isHorizontal();
  17391. var lineCount, textSize;
  17392. if (!opts.display) {
  17393. me.width = minSize.width = me.height = minSize.height = 0;
  17394. return;
  17395. }
  17396. lineCount = helpers$1.isArray(opts.text) ? opts.text.length : 1;
  17397. textSize = lineCount * helpers$1.options._parseFont(opts).lineHeight + opts.padding * 2;
  17398. me.width = minSize.width = isHorizontal ? me.maxWidth : textSize;
  17399. me.height = minSize.height = isHorizontal ? textSize : me.maxHeight;
  17400. },
  17401. afterFit: noop$2,
  17402. // Shared Methods
  17403. isHorizontal: function() {
  17404. var pos = this.options.position;
  17405. return pos === 'top' || pos === 'bottom';
  17406. },
  17407. // Actually draw the title block on the canvas
  17408. draw: function() {
  17409. var me = this;
  17410. var ctx = me.ctx;
  17411. var opts = me.options;
  17412. if (!opts.display) {
  17413. return;
  17414. }
  17415. var fontOpts = helpers$1.options._parseFont(opts);
  17416. var lineHeight = fontOpts.lineHeight;
  17417. var offset = lineHeight / 2 + opts.padding;
  17418. var rotation = 0;
  17419. var top = me.top;
  17420. var left = me.left;
  17421. var bottom = me.bottom;
  17422. var right = me.right;
  17423. var maxWidth, titleX, titleY;
  17424. ctx.fillStyle = helpers$1.valueOrDefault(opts.fontColor, core_defaults.global.defaultFontColor); // render in correct colour
  17425. ctx.font = fontOpts.string;
  17426. // Horizontal
  17427. if (me.isHorizontal()) {
  17428. titleX = left + ((right - left) / 2); // midpoint of the width
  17429. titleY = top + offset;
  17430. maxWidth = right - left;
  17431. } else {
  17432. titleX = opts.position === 'left' ? left + offset : right - offset;
  17433. titleY = top + ((bottom - top) / 2);
  17434. maxWidth = bottom - top;
  17435. rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5);
  17436. }
  17437. ctx.save();
  17438. ctx.translate(titleX, titleY);
  17439. ctx.rotate(rotation);
  17440. ctx.textAlign = 'center';
  17441. ctx.textBaseline = 'middle';
  17442. var text = opts.text;
  17443. if (helpers$1.isArray(text)) {
  17444. var y = 0;
  17445. for (var i = 0; i < text.length; ++i) {
  17446. ctx.fillText(text[i], 0, y, maxWidth);
  17447. y += lineHeight;
  17448. }
  17449. } else {
  17450. ctx.fillText(text, 0, 0, maxWidth);
  17451. }
  17452. ctx.restore();
  17453. }
  17454. });
  17455. function createNewTitleBlockAndAttach(chart, titleOpts) {
  17456. var title = new Title({
  17457. ctx: chart.ctx,
  17458. options: titleOpts,
  17459. chart: chart
  17460. });
  17461. core_layouts.configure(chart, title, titleOpts);
  17462. core_layouts.addBox(chart, title);
  17463. chart.titleBlock = title;
  17464. }
  17465. var plugin_title = {
  17466. id: 'title',
  17467. /**
  17468. * Backward compatibility: since 2.1.5, the title is registered as a plugin, making
  17469. * Chart.Title obsolete. To avoid a breaking change, we export the Title as part of
  17470. * the plugin, which one will be re-exposed in the chart.js file.
  17471. * https://github.com/chartjs/Chart.js/pull/2640
  17472. * @private
  17473. */
  17474. _element: Title,
  17475. beforeInit: function(chart) {
  17476. var titleOpts = chart.options.title;
  17477. if (titleOpts) {
  17478. createNewTitleBlockAndAttach(chart, titleOpts);
  17479. }
  17480. },
  17481. beforeUpdate: function(chart) {
  17482. var titleOpts = chart.options.title;
  17483. var titleBlock = chart.titleBlock;
  17484. if (titleOpts) {
  17485. helpers$1.mergeIf(titleOpts, core_defaults.global.title);
  17486. if (titleBlock) {
  17487. core_layouts.configure(chart, titleBlock, titleOpts);
  17488. titleBlock.options = titleOpts;
  17489. } else {
  17490. createNewTitleBlockAndAttach(chart, titleOpts);
  17491. }
  17492. } else if (titleBlock) {
  17493. core_layouts.removeBox(chart, titleBlock);
  17494. delete chart.titleBlock;
  17495. }
  17496. }
  17497. };
  17498. var plugins = {};
  17499. var filler = plugin_filler;
  17500. var legend = plugin_legend;
  17501. var title = plugin_title;
  17502. plugins.filler = filler;
  17503. plugins.legend = legend;
  17504. plugins.title = title;
  17505. /**
  17506. * @namespace Chart
  17507. */
  17508. core_controller.helpers = helpers$1;
  17509. // @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests!
  17510. core_helpers();
  17511. core_controller._adapters = core_adapters;
  17512. core_controller.Animation = core_animation;
  17513. core_controller.animationService = core_animations;
  17514. core_controller.controllers = controllers;
  17515. core_controller.DatasetController = core_datasetController;
  17516. core_controller.defaults = core_defaults;
  17517. core_controller.Element = core_element;
  17518. core_controller.elements = elements;
  17519. core_controller.Interaction = core_interaction;
  17520. core_controller.layouts = core_layouts;
  17521. core_controller.platform = platform;
  17522. core_controller.plugins = core_plugins;
  17523. core_controller.Scale = core_scale;
  17524. core_controller.scaleService = core_scaleService;
  17525. core_controller.Ticks = core_ticks;
  17526. core_controller.Tooltip = core_tooltip;
  17527. // Register built-in scales
  17528. core_controller.helpers.each(scales, function(scale, type) {
  17529. core_controller.scaleService.registerScaleType(type, scale, scale._defaults);
  17530. });
  17531. // Load to register built-in adapters (as side effects)
  17532. // Loading built-in plugins
  17533. for (var k in plugins) {
  17534. if (plugins.hasOwnProperty(k)) {
  17535. core_controller.plugins.register(plugins[k]);
  17536. }
  17537. }
  17538. core_controller.platform.initialize();
  17539. var src = core_controller;
  17540. if (typeof window !== 'undefined') {
  17541. window.Chart = core_controller;
  17542. }
  17543. // DEPRECATIONS
  17544. /**
  17545. * Provided for backward compatibility, not available anymore
  17546. * @namespace Chart.Chart
  17547. * @deprecated since version 2.8.0
  17548. * @todo remove at version 3
  17549. * @private
  17550. */
  17551. core_controller.Chart = core_controller;
  17552. /**
  17553. * Provided for backward compatibility, not available anymore
  17554. * @namespace Chart.Legend
  17555. * @deprecated since version 2.1.5
  17556. * @todo remove at version 3
  17557. * @private
  17558. */
  17559. core_controller.Legend = plugins.legend._element;
  17560. /**
  17561. * Provided for backward compatibility, not available anymore
  17562. * @namespace Chart.Title
  17563. * @deprecated since version 2.1.5
  17564. * @todo remove at version 3
  17565. * @private
  17566. */
  17567. core_controller.Title = plugins.title._element;
  17568. /**
  17569. * Provided for backward compatibility, use Chart.plugins instead
  17570. * @namespace Chart.pluginService
  17571. * @deprecated since version 2.1.5
  17572. * @todo remove at version 3
  17573. * @private
  17574. */
  17575. core_controller.pluginService = core_controller.plugins;
  17576. /**
  17577. * Provided for backward compatibility, inheriting from Chart.PlugingBase has no
  17578. * effect, instead simply create/register plugins via plain JavaScript objects.
  17579. * @interface Chart.PluginBase
  17580. * @deprecated since version 2.5.0
  17581. * @todo remove at version 3
  17582. * @private
  17583. */
  17584. core_controller.PluginBase = core_controller.Element.extend({});
  17585. /**
  17586. * Provided for backward compatibility, use Chart.helpers.canvas instead.
  17587. * @namespace Chart.canvasHelpers
  17588. * @deprecated since version 2.6.0
  17589. * @todo remove at version 3
  17590. * @private
  17591. */
  17592. core_controller.canvasHelpers = core_controller.helpers.canvas;
  17593. /**
  17594. * Provided for backward compatibility, use Chart.layouts instead.
  17595. * @namespace Chart.layoutService
  17596. * @deprecated since version 2.7.3
  17597. * @todo remove at version 3
  17598. * @private
  17599. */
  17600. core_controller.layoutService = core_controller.layouts;
  17601. /**
  17602. * Provided for backward compatibility, not available anymore.
  17603. * @namespace Chart.LinearScaleBase
  17604. * @deprecated since version 2.8
  17605. * @todo remove at version 3
  17606. * @private
  17607. */
  17608. core_controller.LinearScaleBase = scale_linearbase;
  17609. /**
  17610. * Provided for backward compatibility, instead we should create a new Chart
  17611. * by setting the type in the config (`new Chart(id, {type: '{chart-type}'}`).
  17612. * @deprecated since version 2.8.0
  17613. * @todo remove at version 3
  17614. */
  17615. core_controller.helpers.each(
  17616. [
  17617. 'Bar',
  17618. 'Bubble',
  17619. 'Doughnut',
  17620. 'Line',
  17621. 'PolarArea',
  17622. 'Radar',
  17623. 'Scatter'
  17624. ],
  17625. function(klass) {
  17626. core_controller[klass] = function(ctx, cfg) {
  17627. return new core_controller(ctx, core_controller.helpers.merge(cfg || {}, {
  17628. type: klass.charAt(0).toLowerCase() + klass.slice(1)
  17629. }));
  17630. };
  17631. }
  17632. );
  17633. return src;
  17634. })));